_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q8400
AESCipher
train
function AESCipher(key, iv, bits, mode) { if (!(this instanceof AESCipher)) return new AESCipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; }
javascript
{ "resource": "" }
q8401
AESDecipher
train
function AESDecipher(key, iv, bits, mode) { if (!(this instanceof AESDecipher)) return new AESDecipher(key, iv, mode); assert(mode === 'ecb' || mode === 'cbc', 'Unknown mode.'); this.key = new AESKey(key, bits); this.mode = mode; this.prev = iv; this.waiting = null; this.lastBlock = null; }
javascript
{ "resource": "" }
q8402
Miner
train
function Miner(options) { if (!(this instanceof Miner)) return new Miner(options); AsyncObject.call(this); this.options = new MinerOptions(options); this.network = this.options.network; this.logger = this.options.logger.context('miner'); this.workers = this.options.workers; this.chain = this.options.chain; this.mempool = this.options.mempool; this.addresses = this.options.addresses; this.locker = this.chain.locker; this.cpu = new CPUMiner(this); this.address = null; this.init(); }
javascript
{ "resource": "" }
q8403
Witness
train
function Witness(options) { if (!(this instanceof Witness)) return new Witness(options); Stack.call(this, []); if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8404
HostListOptions
train
function HostListOptions(options) { if (!(this instanceof HostListOptions)) return new HostListOptions(options); this.network = Network.primary; this.logger = Logger.global; this.resolve = dns.lookup; this.host = '0.0.0.0'; this.port = this.network.port; this.services = common.LOCAL_SERVICES; this.onion = false; this.banTime = common.BAN_TIME; this.address = new NetAddress(); this.address.services = this.services; this.address.time = this.network.now(); this.seeds = this.network.seeds; this.nodes = []; this.maxBuckets = 20; this.maxEntries = 50; this.prefix = null; this.filename = null; this.persistent = false; this.flushInterval = 120000; if (options) this.fromOptions(options); }
javascript
{ "resource": "" }
q8405
CPUMiner
train
function CPUMiner(miner) { if (!(this instanceof CPUMiner)) return new CPUMiner(miner); AsyncObject.call(this); this.miner = miner; this.network = this.miner.network; this.logger = this.miner.logger.context('cpuminer'); this.workers = this.miner.workers; this.chain = this.miner.chain; this.locker = new Lock(); this.locker2 = new Lock(); this.running = false; this.stopping = false; this.own = false; this.job = null; this.stopJob = null; this._init(); }
javascript
{ "resource": "" }
q8406
setAbsolutePath
train
function setAbsolutePath(file) { file.absolutePath = path.resolve(process.cwd(), file.fullPath); return file.absolutePath; }
javascript
{ "resource": "" }
q8407
watchFile
train
function watchFile(file, cb, partial) { setAbsolutePath(file); storeDirectory(file); if (!watched_files[file.fullPath]) { if (use_fs_watch) { (function() { watched_files[file.fullPath] = fs.watch(file.fullPath, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } else { (function(file, cb) { watched_files[file.fullPath] = true; fs.watchFile(file.fullPath, {interval: 150}, function() { typeof cb === "function" && cb(file); }); partial && cb(file); })(file, cb); } } }
javascript
{ "resource": "" }
q8408
storeDirectory
train
function storeDirectory(file) { var directory = file.fullParentDir; if (!watched_directories[directory]) { fs.stat(directory, function(err, stats) { if (err) { watched_directories[directory] = (new Date).getTime(); } else { watched_directories[directory] = (new Date(stats.mtime)).getTime(); } }); } }
javascript
{ "resource": "" }
q8409
distinguishPaths
train
function distinguishPaths(paths) { paths = Array.isArray(paths) ? paths : [paths]; var result = { directories: [], files: [] }; paths.forEach(function(name) { if (fs.statSync(name).isDirectory()) { result.directories.push(name); } else { result.files.push(name); } }); return result; }
javascript
{ "resource": "" }
q8410
extend
train
function extend(prototype, attributes) { var object = {}; Object.keys(prototype).forEach(function(key) { object[key] = prototype[key]; }); Object.keys(attributes).forEach(function(key) { object[key] = attributes[key]; }); return object; }
javascript
{ "resource": "" }
q8411
watchPaths
train
function watchPaths(args) { var result = distinguishPaths(args.path) if (result.directories.length) { result.directories.forEach(function(directory) { watchDirectory(extend(args, {root: directory})); }); } if (result.files.length) watchFiles(extend(args, {files: result.files})); }
javascript
{ "resource": "" }
q8412
siphash24
train
function siphash24(data, key, shift) { const blocks = Math.floor(data.length / 8); const c0 = U64(0x736f6d65, 0x70736575); const c1 = U64(0x646f7261, 0x6e646f6d); const c2 = U64(0x6c796765, 0x6e657261); const c3 = U64(0x74656462, 0x79746573); const f0 = U64(blocks << (shift - 32), 0); const f1 = U64(0, 0xff); const k0 = U64.fromRaw(key, 0); const k1 = U64.fromRaw(key, 8); // Init const v0 = c0.ixor(k0); const v1 = c1.ixor(k1); const v2 = c2.ixor(k0); const v3 = c3.ixor(k1); // Blocks let p = 0; for (let i = 0; i < blocks; i++) { const d = U64.fromRaw(data, p); p += 8; v3.ixor(d); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(d); } switch (data.length & 7) { case 7: f0.hi |= data[p + 6] << 16; case 6: f0.hi |= data[p + 5] << 8; case 5: f0.hi |= data[p + 4]; case 4: f0.lo |= data[p + 3] << 24; case 3: f0.lo |= data[p + 2] << 16; case 2: f0.lo |= data[p + 1] << 8; case 1: f0.lo |= data[p]; } // Finalization v3.ixor(f0); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(f0); v2.ixor(f1); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); sipround(v0, v1, v2, v3); v0.ixor(v1); v0.ixor(v2); v0.ixor(v3); return [v0.hi, v0.lo]; }
javascript
{ "resource": "" }
q8413
BufferReader
train
function BufferReader(data, zeroCopy) { if (!(this instanceof BufferReader)) return new BufferReader(data, zeroCopy); assert(Buffer.isBuffer(data), 'Must pass a Buffer.'); this.data = data; this.offset = 0; this.zeroCopy = zeroCopy || false; this.stack = []; }
javascript
{ "resource": "" }
q8414
updateSession
train
function updateSession(callback) { core.api({method: ''}, function(err, response) { var session; if (err) { core.log('error encountered updating session:', err); callback && callback(err, null); return; } if (!response.token.valid) { // Invalid token. Either it has expired or the user has // revoked permission, so clear out our stored data. logout(callback); return; } callback && callback(null, session); }); }
javascript
{ "resource": "" }
q8415
makeSession
train
function makeSession(session) { return { authenticated: !!session.token, token: session.token, scope: session.scope, error: session.error, errorDescription: session.errorDescription }; }
javascript
{ "resource": "" }
q8416
getStatus
train
function getStatus(options, callback) { if (typeof options === 'function') { callback = options; } if (typeof callback !== 'function') { callback = function() {}; } if (!core.session) { throw new Error('You must call init() before getStatus()'); } if (options && options.force) { updateSession(function(err, session) { callback(err, makeSession(session || core.session)); }); } else { callback(null, makeSession(core.session)); } }
javascript
{ "resource": "" }
q8417
login
train
function login(options) { if (!gui.isActive()) { throw new Error('Cannot login without a GUI.'); } if (!options.scope) { throw new Error('Must specify list of requested scopes'); } var params = { response_type: 'token', client_id: core.clientId, redirect_uri: 'https://api.twitch.tv/kraken/', scope: options.scope.join(' '), }; if(options.force_verify) { params.force_verify = true; } if (!params.client_id) { throw new Error('You must call init() before login()'); } gui.popupLogin(params); }
javascript
{ "resource": "" }
q8418
logout
train
function logout(callback) { // Reset the current session core.setSession({}); core.events.emit('auth.logout'); if (typeof callback === 'function') { callback(null); } }
javascript
{ "resource": "" }
q8419
initSession
train
function initSession(storedSession, callback) { if (typeof storedSession === "function") { callback = storedSession; } core.setSession((storedSession && makeSession(storedSession)) || {}); getStatus({ force: true }, function(err, status) { if (status.authenticated) { core.events.emit('auth.login', status); } if (typeof callback === "function") { callback(err, status); } }); }
javascript
{ "resource": "" }
q8420
runWebServerInProcess
train
function runWebServerInProcess(rawConfig, serverConfig, emitter) { var server = require('./server.js'); if (serverConfig.command == 'stop') { logger.info('stopping server'); return server.stop(); } var app = server.listen(rawConfig, serverConfig, function(err, newCommandName, newConfig, finalCallback) { if (err) { logger.error("Error: " + err); if (callback) callback(err); } else { emitter.emit(newCommandName, newConfig, finalCallback); } }); }
javascript
{ "resource": "" }
q8421
runWebServerAsWorker
train
function runWebServerAsWorker(rawConfig, serverConfig, emitter, callback) { if (serverConfig.command == 'stop') { logger.info('stopping server workers'); if (netServer) { netServer.close(); netServer = null; } for (var i=0;i<webservers.length;i++) { var webserver = webservers[i]; webserver.kill(); } webservers = []; return; } netServer = require('net').createServer().listen(serverConfig.options.port, function() { var numWorkers = require('os').cpus().length; var readyCount = 0; for (var i=0;i<numWorkers;i++) { var webserver = fork(__dirname + '/worker.js', [], {env: process.env}); webservers.push(webserver); webserver.send({message: 'start', rawConfig: rawConfig, serverConfig: serverConfig}, netServer._handle) webserver.on('message', function(m) { if (m == 'ready') { //this is a reply from the worker indicating that the server is ready. readyCount += 1; if (readyCount == numWorkers) { //all servers are ready logger.info('started server workers'); if (callback) callback(); } return; } var webserverWorker = this; var id = m.id; if (m.err) { logger.error("Error: " + m.err); if (callback) callback(m.err); } else { emitter.emit(m.commandName, m.config, function(err, result) { webserverWorker.send({message: 'result', err: err, result: result, id: id}) }); } }) } }); }
javascript
{ "resource": "" }
q8422
train
function(err, result) { if (err && !util.isError(err)) { err = new Error(err); } if (callback) callback(err, result); }
javascript
{ "resource": "" }
q8423
Peer
train
function Peer(options) { if (!(this instanceof Peer)) return new Peer(options); EventEmitter.call(this); this.options = options; this.network = this.options.network; this.logger = this.options.logger.context('peer'); this.locker = new Lock(); this.parser = new Parser(this.network); this.framer = new Framer(this.network); this.id = -1; this.socket = null; this.opened = false; this.outbound = false; this.loader = false; this.address = new NetAddress(); this.local = new NetAddress(); this.connected = false; this.destroyed = false; this.ack = false; this.handshake = false; this.time = 0; this.lastSend = 0; this.lastRecv = 0; this.drainSize = 0; this.drainQueue = []; this.banScore = 0; this.invQueue = []; this.onPacket = null; this.next = null; this.prev = null; this.version = -1; this.services = 0; this.height = -1; this.agent = null; this.noRelay = false; this.preferHeaders = false; this.hashContinue = null; this.spvFilter = null; this.feeRate = -1; this.bip151 = null; this.bip150 = null; this.compactMode = -1; this.compactWitness = false; this.merkleBlock = null; this.merkleTime = -1; this.merkleMatches = 0; this.merkleMap = null; this.syncing = false; this.sentAddr = false; this.sentGetAddr = false; this.challenge = null; this.lastPong = -1; this.lastPing = -1; this.minPing = -1; this.blockTime = -1; this.bestHash = null; this.bestHeight = -1; this.connectTimeout = null; this.pingTimer = null; this.invTimer = null; this.stallTimer = null; this.addrFilter = new RollingFilter(5000, 0.001); this.invFilter = new RollingFilter(50000, 0.000001); this.blockMap = new Map(); this.txMap = new Map(); this.responseMap = new Map(); this.compactBlocks = new Map(); this._init(); }
javascript
{ "resource": "" }
q8424
retrievePolicyArn
train
function retrievePolicyArn(identifier, context, searchParams) { if (/arn:aws:iam::\d{12}:policy\/?[a-zA-Z_0-9+=,.@\-_/]+]/.test(identifier)) { return Promise.resolve(identifier); } // @TODO make this code more beautiful // Try ENV_PolicyName_stage let policyIdentifier = context.environment + '_' + identifier + '_' + context.stage; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try ENV_PolicyName policyIdentifier = context.environment + '_' + identifier; return getPolicyByName(policyIdentifier, searchParams) .then(policy => { if (!policy) { // Try PolicyName return getPolicyByName(identifier, searchParams) .then(policy => { if (!policy) { return findAndDeployPolicy(identifier, context) .then(report => { if (!report) { throw new Error('The policy ' + identifier + ' could not be found.'); } return { Arn: report.arn }; }); } return policy; }); } return policy; }); } return policy; }) .then(policy => { return policy.Arn; }); }
javascript
{ "resource": "" }
q8425
retrieveRoleArn
train
function retrieveRoleArn(identifier, context) { const iam = new AWS.IAM(); // First check if the parameter already is an ARN if (/arn:aws:iam::\d{12}:role\/?[a-zA-Z_0-9+=,.@\-_\/]+/.test(identifier)) { return Promise.resolve(identifier); } // Then, we check if a role exists with a name "ENVIRONMENT_identifier_stage" return iam.getRole({ RoleName: context.environment + '_' + identifier + '_' + context.stage }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed, we check if a role exists with a name "ENVIRONMENT_identifier" return iam.getRole({ RoleName: context.environment + '_' + identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { // If it failed again, we check if a role exists with a name "identifier" return iam.getRole({ RoleName: identifier }).promise() .then((data) => { return Promise.resolve(data.Role.Arn); }) .catch(e => { const plugin = require('./index'); return plugin.findRoles([identifier]) .then(roles => { if (roles.length === 1) { return roles[0].deploy(context) .then(report => { return Promise.resolve(report.arn); }); } return Promise.reject(new Error('Could not find role ' + identifier)); }); }); }); }); }
javascript
{ "resource": "" }
q8426
fileName
train
function fileName(file) { let prefix = null let reference = null if (isPathSubDirOf(file, PROJECT_DIR)) { // Assets from the target project. prefix = [] reference = PROJECT_DIR } else if (isPathSubDirOf(file, TOOLBOX_DIR)) { // Assets from the Toolbox. prefix = ['__borela__'] reference = TOOLBOX_DIR } const RELATIVE = relative(reference, file) let nodes = RELATIVE.split(sep) if (nodes[0] === 'src') nodes.shift() if (prefix.length > 0) nodes = [...prefix, ...nodes] return `${nodes.join('/')}?[sha512:hash:base64:8]` }
javascript
{ "resource": "" }
q8427
train
function (commentObj, code, filepath, context, emitter) { var tagRegexp = tags.getTagRegexp(); var sym = new Symbol({file:filepath}); var comment = commentObj.comment, match = tagRegexp.exec(comment), description, l = comment.length, i; if (match && match[1]) { parseCode(code, commentObj.end, sym, context); i = match.index; sym.description = comment.substr(0, i); comment = comment.substr(i); i = 0; while (i < l) { var subComment = comment.substr(i), nextIndex; match = tagRegexp.exec(comment.substr(i + 2)); if (match && match[1]) { nextIndex = match.index; nextIndex += i + 1; parseTag(comment.substr(i, nextIndex - i), sym, context); i = nextIndex; } else { parseTag(subComment, sym, context); i = l; } } } else { parseCode(code, commentObj.end, sym, context); sym.description = comment; } sym.fullName = sym.memberof ? [sym.memberof, sym.name].join(".") : sym.name; return {symbol:sym, comment:comment}; }
javascript
{ "resource": "" }
q8428
getProjectRootDirectory
train
function getProjectRootDirectory() { // From the current directory, check if parent directories have a package.json file and if it contains // a reference to the @myrmex/core node_module let cwd = process.cwd(); let packageJson; let found = false; do { try { packageJson = require(path.join(cwd, 'package.json')); if ((packageJson.dependencies && packageJson.dependencies['@myrmex/core']) || (packageJson.devDependencies && packageJson.devDependencies['@myrmex/core'])) { found = true; } else { cwd = path.dirname(cwd); } } catch (e) { cwd = path.dirname(cwd); } } while (cwd !== path.dirname(cwd) && !found); if (found) { return cwd; } return false; }
javascript
{ "resource": "" }
q8429
getConfig
train
function getConfig() { // Load the myrmex main configuration file let config = {}; try { // try to load a myrmex.json or myrmex.js file config = require(path.join(process.cwd(), 'myrmex')); } catch (e) { // Silently ignore if there is no configuration file return config; } config.config = config.config || {}; // Load sub-configuration files config.configPath = config.configPath || './config'; const configPath = path.join(process.cwd(), config.configPath); let files = []; try { files = fs.readdirSync(configPath); } catch (e) { // Silently ignore if there is no configuration directory } files.forEach(file => { const parse = path.parse(file); // We load all .js and .json files in the configuration directory if (['.js', '.json'].indexOf(parse.ext) !== -1) { config.config[parse.name] = _.merge(config.config[parse.name] || {}, require(path.join(configPath, file))); } }); // Add configuration passed by environment variables Object.keys(process.env).forEach(key => { const prefix = 'MYRMEX_'; if (key.substring(0, prefix.length) === prefix) { // We transform // MYRMEX_myConfig_levels = value // into // { config: { myConfig: { levels: value } } } function addParts(config, parts, value) { const part = parts.shift(); if (parts.length === 0) { // Convert string values "true" and "false" to booleans if (value === 'false') { value = false; } if (value === 'true') { value = true; } config[part] = value; } else { if (config[part] === undefined) { config[part] = {}; } addParts(config[part], parts, value); } } addParts(config.config, key.substring(prefix.length).split('_'), process.env[key]); } }); return config; }
javascript
{ "resource": "" }
q8430
loadTemplate
train
function loadTemplate(templatePath, identifier) { return plugin.myrmex.fire('beforeTemplateLoad', templatePath, identifier) .spread((templatePath, name) => { const templateDoc = _.cloneDeep(require(path.join(templatePath))); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring the document const Template = require('./template'); const template = new Template(templateDoc, identifier); // This event allows to inject code to alter the template configuration return plugin.myrmex.fire('afterTemplateLoad', template); }) .spread(template => { return Promise.resolve(template); }); }
javascript
{ "resource": "" }
q8431
toggleFullscreen
train
function toggleFullscreen(element, callback) { if (callback && typeof callback === 'function') { if (!isFullscreen()) { var fn = function (e) { if (isFullscreen()) { callback(true); } else { callback(false); } }; fullscreenChange(fn); enterFullscreen(element); } else { exitFullscreen(); callback(false); } return Promise.resolve(); } return new Promise(function (resolve) { if (!isFullscreen()) { enterFullscreen(element); } else { exitFullscreen(); } resolve(); }); /** * enter fullscreen mode. * @param {Element} element */ function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } } /** * exit fullscreen mode. */ function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } } }
javascript
{ "resource": "" }
q8432
enterFullscreen
train
function enterFullscreen(element) { var userAgent = navigator.userAgent.toLowerCase(); if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else if (element.mozRequestFullScreen) { element.parentElement.mozRequestFullScreen(); } else if (userAgent.indexOf('edge') != -1) { element.parentElement.webkitRequestFullscreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } }
javascript
{ "resource": "" }
q8433
exitFullscreen
train
function exitFullscreen() { var _doument = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (_doument.msExitFullscreen) { _doument.msExitFullscreen(); } else if (_doument.mozCancelFullScreen) { _doument.mozCancelFullScreen(); } else if (_doument.webkitExitFullscreen) { _doument.webkitExitFullscreen(); } }
javascript
{ "resource": "" }
q8434
isFullscreen
train
function isFullscreen() { var _document = document; if (!_document.fullscreenElement && !_document.mozFullScreenElement && !_document.webkitFullscreenElement && !_document.msFullscreenElement) { return false; } return true; }
javascript
{ "resource": "" }
q8435
fullscreenChange
train
function fullscreenChange(callback) { var _document = document; return new Promise(function (resolve, reject) { if (document.fullscreenEnabled) { document.addEventListener('fullscreenchange', callback); } else if (_document.mozFullScreenEnabled) { _document.addEventListener('mozfullscreenchange', callback); } else if (_document.webkitFullscreenEnabled) { _document.addEventListener('webkitfullscreenchange', callback); //Safari _document.addEventListener('fullscreenChange', callback); // Edge } else if (_document.msFullscreenEnabled) { _document.addEventListener('MSFullscreenChange', callback); } else { reject(); } resolve(); }); }
javascript
{ "resource": "" }
q8436
timeInMs
train
function timeInMs(time) { var HOUR_IN_MS = 3.6e+6, DAY_IN_MS = HOUR_IN_MS * 24, WK_IN_MS = DAY_IN_MS * 7, MS_DICTIONARY = { 'weeks': WK_IN_MS, 'week': WK_IN_MS, 'w': WK_IN_MS, 'days': DAY_IN_MS, 'day': DAY_IN_MS, 'd': DAY_IN_MS, 'hours': HOUR_IN_MS, 'hour': HOUR_IN_MS, 'h': HOUR_IN_MS }; var duration = parseInt(time, 10); var interval = time.replace(/\d*[\d]/, '').trim(); if (Object.keys(MS_DICTIONARY).indexOf(interval) < 0) { throw new Error('Interval is invalid. The ttl must be of weeks, days, or hours'); } return MS_DICTIONARY[interval] * duration; }
javascript
{ "resource": "" }
q8437
loadApis
train
function loadApis() { // Shortcut if apis already have been loaded if (apis !== undefined) { return Promise.resolve(apis); } const apiSpecsPath = path.join(process.cwd(), plugin.config.apisPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeApisLoad') .then(() => { // Retrieve configuration path of all API specifications return Promise.promisify(fs.readdir)(apiSpecsPath); }) .then(subdirs => { // Load all the API specifications const apiPromises = []; _.forEach(subdirs, (subdir) => { const apiSpecPath = path.join(apiSpecsPath, subdir, 'spec'); // subdir is the identifier of the API, so we pass it as the second argument apiPromises.push(loadApi(apiSpecPath, subdir)); }); return Promise.all(apiPromises); }) .then(apis => { // This event allows to inject code to add or delete or alter API specifications return plugin.myrmex.fire('afterApisLoad', apis); }) .spread(loadedApis => { apis = loadedApis; return Promise.resolve(apis); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.apisPath)) { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
{ "resource": "" }
q8438
loadApi
train
function loadApi(apiSpecPath, identifier) { return plugin.myrmex.fire('beforeApiLoad', apiSpecPath, identifier) .spread((apiSpecPath, identifier) => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const apiSpec = _.cloneDeep(require(apiSpecPath)); apiSpec['x-myrmex'] = apiSpec['x-myrmex'] || {}; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./endpoint const Api = require('./api'); const api = new Api(apiSpec, identifier); // This event allows to inject code to alter the API specification return plugin.myrmex.fire('afterApiLoad', api); }) .spread(api => { return api.init(); }); }
javascript
{ "resource": "" }
q8439
loadEndpoints
train
function loadEndpoints() { // Shortcut if endpoints already have been loaded if (endpoints !== undefined) { return Promise.resolve(endpoints); } const endpointSpecsPath = path.join(process.cwd(), plugin.config.endpointsPath); return plugin.myrmex.fire('beforeEndpointsLoad') .spread(() => { const endpointPromises = []; file.walkSync(endpointSpecsPath, (dirPath, dirs, files) => { // We are looking for directories that have the name of an HTTP method const subPath = dirPath.substr(endpointSpecsPath.length); const resourcePathParts = subPath.split(path.sep); const method = resourcePathParts.pop(); if (plugin.httpMethods.indexOf(method) === -1) { return; } // We construct the path to the resource const resourcePath = resourcePathParts.join('/'); endpointPromises.push(loadEndpoint(endpointSpecsPath, resourcePath, method)); }); return Promise.all(endpointPromises); }) .then(endpoints => { return plugin.myrmex.fire('afterEndpointsLoad', endpoints); }) .spread(loadedEndpoints => { endpoints = loadedEndpoints; return Promise.resolve(endpoints); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.endpointsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
javascript
{ "resource": "" }
q8440
loadModels
train
function loadModels() { const modelSpecsPath = path.join(process.cwd(), plugin.config.modelsPath); return plugin.myrmex.fire('beforeModelsLoad') .spread(() => { return Promise.promisify(fs.readdir)(modelSpecsPath); }) .then(fileNames => { // Load all the model specifications return Promise.map(fileNames, fileName => { const modelSpecPath = path.join(modelSpecsPath, fileName); const modelName = path.parse(fileName).name; return loadModel(modelSpecPath, modelName); }); }) .then(models => { return plugin.myrmex.fire('afterModelsLoad', models); }) .spread(models => { return Promise.resolve(models); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.modelsPath)) { return Promise.resolve([]); } Promise.reject(e); }); }
javascript
{ "resource": "" }
q8441
loadModel
train
function loadModel(modelSpecPath, name) { return plugin.myrmex.fire('beforeModelLoad', modelSpecPath, name) .spread(() => { // Because we use require() to get the spec, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const modelSpec = _.cloneDeep(require(modelSpecPath)); // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./model const Model = require('./model'); return Promise.resolve(new Model(name, modelSpec)); }) .then(model => { // This event allows to inject code to alter the model specification return plugin.myrmex.fire('afterModelLoad', model); }) .spread((model) => { return Promise.resolve(model); }); }
javascript
{ "resource": "" }
q8442
loadIntegrations
train
function loadIntegrations(region, context, endpoints) { // The `deployIntegrations` hook takes four arguments // The region of the deployment // The "context" of the deployment // The list of endpoints that must be deployed // An array that will receive integration results const integrationDataInjectors = []; return plugin.myrmex.fire('loadIntegrations', region, context, endpoints, integrationDataInjectors) .spread((region, context, endpoints, integrationDataInjectors) => { // At this point, integration plugins returned their integrationDataInjectors return plugin.myrmex.fire('beforeAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }) .spread((endpoints, integrationDataInjectors) => { return Promise.map(integrationDataInjectors, (integrationDataInjector) => { return Promise.map(endpoints, (endpoint) => { return integrationDataInjector.applyToEndpoint(endpoint); }); }) .then(() => { return plugin.myrmex.fire('afterAddIntegrationDataToEndpoints', endpoints, integrationDataInjectors); }); }) .spread((endpoints, integrationDataInjectors) => { return Promise.resolve(endpoints); }); }
javascript
{ "resource": "" }
q8443
findApi
train
function findApi(identifier) { return loadApis() .then(apis => { const api = _.find(apis, (api) => { return api.getIdentifier() === identifier; }); if (!api) { return Promise.reject(new Error('Could not find the API "' + identifier + '" in the current project')); } return api; }); }
javascript
{ "resource": "" }
q8444
findEndpoint
train
function findEndpoint(resourcePath, method) { return loadEndpoints() .then(endpoints => { const endpoint = _.find(endpoints, endpoint => { return endpoint.getResourcePath() === resourcePath && endpoint.getMethod() === method; }); if (!endpoint) { return Promise.reject(new Error('Could not find the endpoint "' + method + ' ' + resourcePath + '" in the current project')); } return endpoint; }); }
javascript
{ "resource": "" }
q8445
findModel
train
function findModel(name) { return loadModels() .then(models => { const model = _.find(models, model => { return model.getName('spec') === name; }); if (!model) { return Promise.reject(new Error('Could not find the model "' + name + '" in the current project')); } return model; }); }
javascript
{ "resource": "" }
q8446
mergeSpecsFiles
train
function mergeSpecsFiles(beginPath, subPath) { // Initialise specification const spec = {}; // List all directories where we have to look for specifications const subDirs = subPath.split(path.sep); // Initialize the directory path for the do/while statement let searchSpecDir = beginPath; do { let subSpec = {}; const subDir = subDirs.shift(); searchSpecDir = path.join(searchSpecDir, subDir); try { // Try to load the definition and silently ignore the error if it does not exist // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice subSpec = _.cloneDeep(require(searchSpecDir + path.sep + 'spec')); } catch (e) { // Silently ignore the error when calling require() on an unexisting spec.json file if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Merge the spec eventually found _.merge(spec, subSpec); } while (subDirs.length); // return the result of the merges return spec; }
javascript
{ "resource": "" }
q8447
getSelectValue
train
function getSelectValue (elem) { var value, option, i var options = elem.options var index = elem.selectedIndex var one = elem.type === 'select-one' var values = one ? null : [] var max = one ? index + 1 : options.length if (index < 0) { i = max } else { i = one ? index : 0 } // Loop through all the selected options for (; i < max; i++) { option = options[i] // Support: IE <=9 only // IE8-9 doesn't update selected after form reset if ((option.selected || i === index) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && (!option.parentNode.disabled || option.parentNode.tagName.toLowerCase() === 'optgroup')) { // Get the specific value for the option value = option.value // We don't need an array for one selects if (one) { return value } // Multi-Selects return an array values.push(value) } } return values }
javascript
{ "resource": "" }
q8448
updateBinary
train
function updateBinary (os = platform, arch = process.arch) { return new Promise((resolve, reject) => { if (platform === 'freebsd') return resolve(` There are no static ffmpeg builds for FreeBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg install ffmpeg" or via ports. `) if (platform === 'openbsd') return resolve(` There are no static ffmpeg builds for OpenBSD currently available. The module will try to use the system-wide installation. Install it by running "pkg_add ffmpeg" or via ports. `) const dir = `bin/${os}/${arch}` const bin = `${dir}/ffmpeg${os === 'win32' ? '.exe' : ''}` const dest = path.join(__dirname, bin) const fname = `${os}-${arch}.tar.bz2` const tmp = path.join(__dirname, 'bin', fname) try { fs.mkdirSync(path.join(__dirname, 'bin')) } catch(e) {} let bar // Cleanup directory fs.emptyDirSync('bin') // Get the latest version const req = request.get(`https://github.com/FocaBot/ffmpeg-downloader/raw/master/bin/${fname}`) req.on('error', e => reject(e)) // Handle errors .on('data', c => { bar = bar || new ProgressBar(`${fname} [:bar] :percent (ETA: :etas)`, { complete: '=', incomplete: ' ', width: 25, total: parseInt(req.response.headers['content-length']) }) bar.tick(c.length) }) .on('end', () => setTimeout(() => { bar.tick(bar.total - bar.curr) console.log('Decompressing...') decompress(tmp, path.join(__dirname, 'bin')).then(f => { fs.unlinkSync(tmp) // Try to get the version number // Skip this if not the same arch/os as what launched it if (os === platform && arch === process.arch) { execFile(dest, ['-version'], (error, stdout, stderr) => { if (error || stderr.length) return reject(error || stderr) resolve(stdout) }) } else { resolve('Platform and arch are different than this system, cannot display ffmpeg version') } }) }, 1000)) .pipe(fs.createWriteStream(tmp, { mode: 0o755 })) }) }
javascript
{ "resource": "" }
q8449
sortArrayByIndex
train
function sortArrayByIndex(array) { let ii = 0; let length = array.length; let output = []; for (; ii < length; ++ii) { output[array[ii].index] = array[ii]; delete array[ii].index; }; return (output); }
javascript
{ "resource": "" }
q8450
Endpoint
train
function Endpoint(spec, resourcePath, method) { this.method = method; this.resourcePath = resourcePath || '/'; this.spec = spec; }
javascript
{ "resource": "" }
q8451
monkeyPatchPipe
train
function monkeyPatchPipe(stream) { while (!stream.hasOwnProperty('pipe')) { stream = Object.getPrototypeOf(stream) if (!stream) return null } let existingPipe = stream.pipe newPipe['$$monkey-patch'] = true return stream.pipe = newPipe /** Create new pipe copy of existing pipe */ function newPipe() { let result = existingPipe.apply(this, arguments) result.setMaxListeners(0) if (!result.pipe['$$monkey-patch']) { monkeyPatchPipe(result) } return result.on('error', function(err) { gutil.log(gutil.colors.yellow(err)) gutil.beep() this.emit('end') }) } }
javascript
{ "resource": "" }
q8452
train
function(db, id) { this._db = db; this._id = id; this._index = new Map(); this._size = 0; this._changed = false; }
javascript
{ "resource": "" }
q8453
configureBundleStats
train
function configureBundleStats(config) { // Interactive tree map of the bundle. if (interactiveBundleStats) config.plugins.push(new BundleAnalyzerPlugin) // JSON file containing the bundle stats. if (bundleStats) { config.plugins.push(new StatsWriterPlugin({ filename: 'bundle-stats.json', // Include everything. fields: null, })) } }
javascript
{ "resource": "" }
q8454
configureJsMinification
train
function configureJsMinification(config) { if (!(minify || minifyJs)) return config.optimization.minimize = true config.optimization.minimizer = [new UglifyJsPlugin({ sourceMap: !disableSourceMaps, uglifyOptions: { output: { comments: false, }, }, })] }
javascript
{ "resource": "" }
q8455
parseArffFile
train
function parseArffFile(arffObj, cb) { var arffFile = ''; arffFile += '@relation '; arffFile += arffObj.name; arffFile += '\n\n'; async.waterfall([ function (callback) { var i = 0; async.eachSeries(arffObj.data, function (obj, dataCb) { async.eachSeries(_.keys(obj), function (key, mapCb) { if (arffObj.types[key].type.indexOf('nominal') > -1 && !_.isString(arffObj.data[i][key])) { arffObj.data[i][key] = arffObj.types[key].oneof[arffObj.data[i][key]]; } mapCb(); }, function (err) { i++; dataCb(err); }); }, function (err) { callback(err); }); }, function (callback) { async.eachSeries(arffObj.attributes, function (obj, attrCb) { arffFile += '@attribute '; arffFile += obj; arffFile += ' '; if (arffObj.types[obj].type.indexOf('nominal') > -1) { arffFile += '{' + arffObj.types[obj].oneof + '}'; } else { arffFile += arffObj.types[obj].type; } arffFile += '\n'; attrCb(); }, function (err) { callback(err); }); }, function (callback) { arffFile += '\n'; arffFile += '@data'; arffFile += '\n'; async.eachSeries(arffObj.data, function (obj, dataCb) { arffFile += _.values(obj); arffFile += '\n'; dataCb(); }, function (err) { callback(err); }); } ], function (err, result) { var fileId = '/tmp/node-weka-' + _.random(0, 10000000) + '.arff'; // console.log(arffFile); fs.writeFile(fileId, arffFile, function (err) { cb(err, fileId); }); }); }
javascript
{ "resource": "" }
q8456
train
function(N) { cosMap = cosMap || {}; cosMap[N] = new Array(N*N); var PI_N = Math.PI / N; for (var k = 0; k < N; k++) { for (var n = 0; n < N; n++) { cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k); } } }
javascript
{ "resource": "" }
q8457
SVGObj
train
function SVGObj(file, svg, config) { this.file = file; this.id = path.basename(this.file, '.svg'); // this.newSVG = ; // this.newSVG = new dom().parseFromString('<book><title>Harry Potter</title></book>'); // this.newSVG = new dom().parseFromString(svg); // this.svg = libxmljs.parseXml(svg); this.svg = new XMLObject(svg); // console.log(this.svg); // console.log('-----------------------------------------'); // console.log('-----------------------------------------'); // console.log(this.newSVG); // // this.obj = new SVGToObject(svg); // res = this.obj.findAllNodes({name:'path'}); // res = this.obj.findNode({attributes:'width'}); // res = this.obj.findNode('@id'); // this.obj.log(); // var hans = obj.queryNode({name: 'path'}); // var hans = obj.queryNodeAll({name: 'path'}); // _.each(hans, function(node){ // console.log(obj.attribute(node, 'attributes')); // }) // console.log('######################################################'); // console.log('######################################################'); // console.log(); // console.log('hier', obj.queryNode('path')); // // // var select = xpath.useNamespaces({"svg": "http://www.w3.org/2000/svg"}); // var nodes = xpath.select("//title/text()", this.newSVG).toString(); // console.log('-----------------------------------------'); // console.log(select("//svg:title/text()", this.newSVG)[0].nodeValue); // console.log(select("//svg:@", this.newSVG)); // console.log(xpath.select("//svg", this.newSVG)); this._config = _.extend({ maxwidth : 1000, maxheight : 1000, padding : 0 }, config); this._config.maxwidth = Math.abs(parseInt(this._config.maxwidth || 0, 10)); this._config.maxheight = Math.abs(parseInt(this._config.maxheight || 0, 10)); this._config.padding = Math.abs(parseInt(this._config.padding, 10)); var width = this.svg.root().attr('width'), height = this.svg.root().attr('height'); this.width = width ? parseFloat(width, 10) : false; this.height = height ? parseFloat(height, 10) : false; // console.log('this.width',this.width); // console.log('this.height',this.height); // console.log('mywidth',parseFloat(this.obj.root().attr('width'),10)); // console.log('myheight',parseFloat(this.obj.root().attr('height'),10)); }
javascript
{ "resource": "" }
q8458
dateLastPaymentShouldHaveBeenMade
train
function dateLastPaymentShouldHaveBeenMade(loan, cb) { var d = Q.defer(); var result; if (!loan || _.isEmpty(loan.amortizationTable)) { d.reject(new Error('required dateLastPaymentShouldHaveBeenMade not provided')); } else { var determinationDate = loan.determinationDate ? moment(loan.determinationDate) : moment(); var daysUntilLate = loan.daysUntilLate ? Number(loan.daysUntilLate) : 0; determinationDate.add('days', daysUntilLate); loan.amortizationTable.forEach(function (payment) { var paymentDate = moment(payment.date); if (paymentDate.isBefore(determinationDate)) result = paymentDate.toISOString(); }); loan.dateLastPaymentShouldHaveBeenMade = result; d.resolve(loan) } if (cb) return cb(loan); return d.promise; }
javascript
{ "resource": "" }
q8459
addLateFees
train
function addLateFees(loan, cb) { var d = Q.defer(); if (!loan || !loan.closingDate || !loan.loanAmount || !loan.interestRate || !loan.paymentAmount) { d.reject(new Error('required parameters for addLateFees not provided')); } else { var lateFee = calcLateFee(loan); var determinationDate = moment(); var txDate, pmtDate, graceDate, pmtTransactions, elapsedMonths, i; var lateFeeTxs = loan.transactions.filter(function (tx) { return tx.type === 'Late Fee'; }); //remove all existing late fees lateFeeTxs.forEach(function (tx) { loan.transactions.id(tx._id).remove(); }); pmtTransactions = loan.transactions.filter(function (tx) { return tx.type !== 'Late Fee'; }); //calculate the number of months that have lapsed starting with the first payment date //until the determination date elapsedMonths = determinationDate.diff(moment(loan.firstPaymentDate), 'months') + 1; for (i = 0; i < elapsedMonths; i++) { pmtDate = moment(loan.firstPaymentDate).add('months', i); graceDate = moment(loan.firstPaymentDate).add('months', i).add('days', loan.daysUntilLate); if (!paymentMadeOnTime(pmtTransactions, pmtDate, graceDate, loan.paymentAmount) && pmtDate.isBefore(determinationDate) && !lateFeeAppliedForDate(loan, graceDate)) { txDate = graceDate.toISOString(); console.log('loan balance in late fees: ', getLoanBalance(loan, txDate)); loan.transactions.push({ txDate: txDate, type: "Late Fee", amount: -1 * lateFee, comments: "Late fee imposed for failure to pay on time or to pay proper amount", loanBalance: getLoanBalance(loan, txDate) }); } } } console.log('addLateFees'); d.resolve(loan); if (cb) return cb(loan); return d.promise; }
javascript
{ "resource": "" }
q8460
SpotifySearch
train
function SpotifySearch (title) { /** * @public {Array} tracks. */ this.tracks = [] // Query spotify, parse xml response, display in terminal, // prompt user for track number, play track. this._query(title) .then(this._parseJSON.bind(this)) .then(this._printData.bind(this)) .then(this._promptUser.bind(this)) .then(this._playTrack.bind(this)) .fail(this._onError.bind(this)) }
javascript
{ "resource": "" }
q8461
train
function (modelName) { if (["make", "list"].indexOf(modelName) === -1) { throw new Error( "checkOwnerApp middleware can only be configured with 'make' or 'list'. You passed in: '" + modelName + "'" ); } return function (req, res, next) { // Don't enforce write permissions if not enabled. if (!ENFORCE_WRITE_PERMISSIONS) { return next(); } var model = req[modelName], user = req.credentials.user; // check if the authenticated application has admin permissions, or if it owns the make if (req.credentials.admin !== true && user !== model.ownerApp) { return hawkModule.respond(403, res, req.credentials, req.artifacts, { status: "failure", reason: "unauthorized" }, "application/json"); } next(); }; }
javascript
{ "resource": "" }
q8462
getPrototype
train
function getPrototype(value) { let prototype; if (!_.isUndefined(value) && !_.isNull(value)) { if (!_.isObject(value)) { prototype = value.constructor.prototype; } else if (_.isFunction(value)) { prototype = value.prototype; } else { prototype = Object.getPrototypeOf(value); } } return prototype; }
javascript
{ "resource": "" }
q8463
generateKey
train
function generateKey(length) { const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const possibleLength = possible.length - 1; let text = ''; _.times(getNumber(length, 16), () => { text += possible.charAt(_.random(possibleLength)); }); return text; }
javascript
{ "resource": "" }
q8464
executeCommand
train
function executeCommand(parameters) { // If a name has been provided, we create the project directory const modelFilePath = path.join(process.cwd(), plugin.config.modelsPath); return mkdirpAsync(modelFilePath) .then(() => { const model = { type: 'object', properties: {} }; return fs.writeFileAsync(modelFilePath + path.sep + parameters.name + '.json', JSON.stringify(model, null, 2)); }) .then(() => { let msg = '\n A new model has been created!\n\n'; msg += ' Its Swagger specification is available in ' + icli.format.info(modelFilePath + path.sep + parameters.name + '.json') + '\n'; icli.print(msg); }); }
javascript
{ "resource": "" }
q8465
loadPolicies
train
function loadPolicies() { const policyConfigsPath = path.join(process.cwd(), plugin.config.policiesPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforePoliciesLoad') .then(() => { // Retrieve configuration path of all API specifications return fs.readdirAsync(policyConfigsPath); }) .then(policyConfigFiles => { // Load all the policy configurations const policyPromises = []; _.forEach(policyConfigFiles, (filename) => { const policyConfigPath = path.join(policyConfigsPath, filename); const policyName = path.parse(filename).name; policyPromises.push(loadPolicy(policyConfigPath, policyName)); }); return Promise.all(policyPromises); }) .then(policies => { // This event allows to inject code to add or delete or alter policy configurations return plugin.myrmex.fire('afterPoliciesLoad', policies); }) .spread(policies => { return Promise.resolve(policies); }) .catch(e => { if (e.code === 'ENOENT' && path.basename(e.path) === 'policies') { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
{ "resource": "" }
q8466
loadPolicy
train
function loadPolicy(documentPath, name) { return plugin.myrmex.fire('beforePolicyLoad', documentPath, name) .spread((documentPath, name) => { // Because we use require() to get the document, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice const document = _.cloneDeep(require(documentPath)); const Policy = require('./policy'); const policy = new Policy(document, name); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterPolicyLoad', policy); }) .spread((policy) => { return Promise.resolve(policy); }); }
javascript
{ "resource": "" }
q8467
findPolicies
train
function findPolicies(identifiers) { return loadPolicies() .then((policies) => { return _.filter(policies, (policy) => { return identifiers.indexOf(policy.name) !== -1; }); }); }
javascript
{ "resource": "" }
q8468
registerCommands
train
function registerCommands(icli) { return Promise.all([ require('./cli/create-policy')(icli), require('./cli/create-role')(icli), require('./cli/deploy-policies')(icli), require('./cli/deploy-roles')(icli) ]) .then(() => { return Promise.resolve([]); }); }
javascript
{ "resource": "" }
q8469
hasInOfType
train
function hasInOfType(value, path, validator) { return _.hasIn(value, path) ? validator(_.get(value, path)) : false; }
javascript
{ "resource": "" }
q8470
rot13
train
function rot13(x) { return Array.prototype.map.call(x, (ch) => { var code = ch.charCodeAt(0); if (code >= 0x41 && code <= 0x5a) code = (((code - 0x41) + 13) % 26) + 0x41; else if (code >= 0x61 && code <= 0x7a) code = (((code - 0x61) + 13) % 26) + 0x61; return String.fromCharCode(code); }).join(''); }
javascript
{ "resource": "" }
q8471
train
function(options) { options = options || {}; this.datasources = []; this.styles = []; this.projection = DEFAULT_PROJECTION; this.assetsPath = "."; if (options.projection){ this.projection = projector.util.cleanProjString(options.projection); console.log(this.projection); } this.boundsBuffer = ("boundsBuffer" in options) ? options.boundsBuffer : BUFFER_RATIO; this._renderer = cartoRenderer; }
javascript
{ "resource": "" }
q8472
train
function() { var projection = this.projection; this.datasources.forEach(function(datasource) { datasource.load && datasource.load(function(error) { datasource.project && datasource.project(projection); }); }); }
javascript
{ "resource": "" }
q8473
differenceKeys
train
function differenceKeys(first, second) { return filterKeys(first, function(val, key) { return val !== second[key]; }); }
javascript
{ "resource": "" }
q8474
slugify
train
function slugify(string) { return _.deburr(string).trim().toLowerCase().replace(/ /g, '-').replace(/([^a-zA-Z0-9\._-]+)/, ''); }
javascript
{ "resource": "" }
q8475
objectWith
train
function objectWith() { const args = _.reverse(arguments); const [value, path] = _.take(args, 2); const object = _.nth(args, 2) || {}; return _.set(object, path, value); }
javascript
{ "resource": "" }
q8476
executeCommand
train
function executeCommand(parameters) { // If a name has been provided, we create the project directory const specFilePath = path.join(process.cwd(), plugin.config.apisPath, parameters.apiIdentifier); return mkdirpAsync(specFilePath) .then(() => { const spec = { swagger: '2.0', info: { title: parameters.title, description: parameters.desc }, schemes: ['https'], host: 'API_ID.execute-api.REGION.amazonaws.com', consume: parameters.consume, produce: parameters.produce, paths: {}, definitions: {} }; return fs.writeFileAsync(specFilePath + path.sep + 'spec.json', JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The API "' + icli.format.info(parameters.apiIdentifier) + '" has been created\n\n' + ' Its Swagger specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-api ' + parameters.apiIdentifier) + '\n'; icli.print(msg); }); }
javascript
{ "resource": "" }
q8477
generateCode
train
function generateCode(filepath) { var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'amd'; // support 4 types of output as follows: // amd/commonjs/global/umd var choice = { amd: { prefix: 'define([\'module\', \'exports\'], function (module, exports) {', suffix: '});' }, commonjs: { prefix: '', suffix: '' }, global: { prefix: '(function (module, exports) {', suffix: '})(this, this.exports = this.exports || {});' }, umd: { prefix: '\n (function (global, factory) {\n typeof exports === \'object\' && typeof module !== \'undefined\' ? factory(module, exports) :\n typeof define === \'function\' && define.amd ? define([\'module\', \'exports\'], factory) :\n (factory(global, global.exports = global.exports || {}));\n }(this, (function (module, exports) {\n ', suffix: '})));' } }; var _ref = choice[mode] || choice.amd, prefix = _ref.prefix, suffix = _ref.suffix; //const content = readFileSync(filepath, 'utf8'); //const result = parseComponent(content); var result = getBlocks(filepath); var templateCode = result.template.code; var styleCode = result.styles.map(function (style) { return (0, _style2.default)(style.code); }).join('\n'); var scriptCode = result.script.code; var code = '\n ' + prefix + '\n /* append style */\n ' + styleCode + '\n\n /* get render function */\n var _module1 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _template2.default)(templateCode) + '\n })(_module1, _module1.exports);\n\n /* get script output data */\n var _module2 = {\n exports: {}\n };\n (function (module, exports) {\n ' + (0, _script2.default)(scriptCode) + '\n })(_module2, _module2.exports);\n\n var obj = _module2.exports.default || _module2.exports;\n obj.render = _module1.exports.render;\n obj.staticRenderFns = _module1.exports.staticRenderFns;\n\n module.exports = obj;\n ' + suffix + '\n '; return (0, _jsBeautify.js_beautify)(code); }
javascript
{ "resource": "" }
q8478
compile
train
function compile(_ref2) { var resource = _ref2.resource, dest = _ref2.dest, mode = _ref2.mode; dest = dest || 'dest'; resource = resource || '*.vue'; mode = ['amd', 'commonjs', 'umd', 'global'].indexOf(mode) > -1 ? mode : 'amd'; if ((0, _fs.existsSync)(dest)) { if (!(0, _fs.statSync)(dest).isDirectory()) { throw new Error('the destination path is already exist and it is not a directory'); } } else { (0, _fs.mkdirSync)(dest); } var files = _glob2.default.sync(resource); files.forEach(function (file) { var name = (0, _path.parse)(file).name; try { var code = generateCode(file, mode); var outputPath = (0, _path.format)({ dir: dest, name: name, ext: '.js' }); (0, _fs.writeFileSync)(outputPath, code); } catch (e) { throw e; } }); }
javascript
{ "resource": "" }
q8479
train
function(callback) { fs.exists(file, function(exists) { if(!exists) { rawData = file; if(typeof rawData === "string") rawData = new Buffer(file); return callback(); } fs.readFile(file, function(err, data) { if(err) return callback(err); rawData = data; return callback(); }); }); }
javascript
{ "resource": "" }
q8480
train
function(callback) { spidex.put(self.baseUri + "/" + uploadFilename, { data: rawData, header: header, charset: "utf8" }, function(html, status, respHeader) { if(200 !== status && 201 !== status) { return callback(new Error(html.replace("</h1>", "</h1> ").stripTags())); } var result = {}; if(respHeader["x-upyun-width"] !== undefined) result.width = parseInt(respHeader["x-upyun-width"]); if(respHeader["x-upyun-height"] !== undefined) result.height = parseInt(respHeader["x-upyun-height"]); if(respHeader["x-upyun-frames"] !== undefined) result.frames = parseInt(respHeader["x-upyun-frames"]); if(respHeader["x-upyun-file-type"] !== undefined) result.type = respHeader["x-upyun-file-type"]; callback(undefined, result); }).on("error", callback); }
javascript
{ "resource": "" }
q8481
executeCommand
train
function executeCommand(parameters) { if (!parameters.role && parameters.roleManually) { parameters.role = parameters.roleManually; } if (parameters.resourcePath.charAt(0) !== '/') { parameters.resourcePath = '/' + parameters.resourcePath; } // We calculate the path where we will save the specification and create the directory // Destructuring parameters only available in node 6 :( // specFilePath = path.join(process.cwd(), 'endpoints', ...answers.resourcePath.split('/')); const pathParts = parameters.resourcePath.split('/'); pathParts.push(parameters.httpMethod); pathParts.unshift(path.join(process.cwd(), plugin.config.endpointsPath)); const specFilePath = path.join.apply(null, pathParts); return mkdirpAsync(specFilePath) .then(() => { // We create the endpoint Swagger/OpenAPI specification const spec = { 'x-myrmex': { 'apis': parameters.apis }, summary: parameters.summary, consume: parameters.consume, produce: parameters.produce, responses: { '200': {} }, 'x-amazon-apigateway-auth': { type: parameters.auth }, 'x-amazon-apigateway-integration': { credentials: parameters.role, responses: { default: { statusCode: 200 } } } }; switch (parameters.integration) { case 'lambda-proxy': spec['x-amazon-apigateway-integration'].type = 'aws_proxy'; spec['x-amazon-apigateway-integration'].contentHandling = 'CONVERT_TO_TEXT'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; spec['x-amazon-apigateway-integration'].httpMethod = 'POST'; break; case 'mock': spec['x-amazon-apigateway-integration'].requestTemplates = { 'application/json': '{"statusCode": 200}' }; spec['x-amazon-apigateway-integration'].type = 'mock'; spec['x-amazon-apigateway-integration'].passthroughBehavior = 'when_no_match'; break; } config.specModifiers.forEach(fn => { fn(spec, parameters); }); // We save the specification in a json file return fs.writeFileAsync(path.join(specFilePath, 'spec.json'), JSON.stringify(spec, null, 2)); }) .then(() => { const msg = '\n The endpoint ' + icli.format.info(parameters.httpMethod + ' ' + parameters.resourcePath) + ' has been created\n\n' + ' Its OpenAPI specification is available in ' + icli.format.info(specFilePath + path.sep + 'spec.json') + '\n' + ' You can inspect it using the command ' + icli.format.cmd('myrmex inspect-endpoint ' + parameters.resourcePath + ' ' + parameters.httpMethod) + '\n'; icli.print(msg); }); }
javascript
{ "resource": "" }
q8482
executeCommand
train
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.policiesPath); return mkdirpAsync(configFilePath) .then(() => { // We create the configuration file of the Lambda const document = { Version: '2012-10-17', Statement: [{ Effect: 'Deny', Action: ['*'], Resource: ['*'] }] }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(document, null, 2)); }) .then(() => { const msg = '\n The IAM policy ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n\n'; icli.print(msg); }); }
javascript
{ "resource": "" }
q8483
transformValueMap
train
function transformValueMap(collection, path, transformer) { _.each(collection, (element) => { let val = _.get(element, path); if (!_.isUndefined(val)) { _.set(element, path, transformer(val)); } }); return collection; }
javascript
{ "resource": "" }
q8484
executeCommand
train
function executeCommand(parameters) { if (parameters.colors === undefined) { parameters.colors = plugin.myrmex.getConfig('colors'); } return plugin.findEndpoint(parameters.resourcePath, parameters.httpMethod) .then(endpoint => { const jsonSpec = endpoint.generateSpec(parameters.specVersion); let spec = JSON.stringify(jsonSpec, null, 2); if (parameters.colors) { spec = icli.highlight(spec, { json: true }); } icli.print(spec); return Promise.resolve(jsonSpec); }); }
javascript
{ "resource": "" }
q8485
executeCommand
train
function executeCommand(parameters) { let msg = '\n ' + icli.format.ko('Unknown command \n\n'); msg += ' Enter ' + icli.format.cmd('myrmex -h') + ' to see available commands\n'; msg += ' You have to be in the root folder of your Myrmex project to see commands implemented by Myrmex plugins\n'; console.log(msg); process.exit(1); }
javascript
{ "resource": "" }
q8486
getDocument
train
function getDocument(node) { if (isDocument(node)) { return node; } else if (isDocument(node.ownerDocument)) { return node.ownerDocument; } else if (isDocument(node.document)) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); // Range support } else if (node.commonAncestorContainer) { return getDocument(node.commonAncestorContainer); } else if (node.startContainer) { return getDocument(node.startContainer); // Selection support } else if (node.anchorNode) { return getDocument(node.anchorNode); } }
javascript
{ "resource": "" }
q8487
d2h
train
function d2h(d, digits) { d = d.toString(16); while (d.length < digits) { d = '0' + d; } return d; }
javascript
{ "resource": "" }
q8488
train
function() { _.each(this._models, function(model) { var cid = model.get('cid'); model.fetch({ success: function(model, response, options) { if (_.isFunction(model.parseJSON)) model.parseJSON(response); }.bind(model) }); }.bind(this)); }
javascript
{ "resource": "" }
q8489
train
function(method, args){ _.each(this._elements, function(elem){ if (_.isFunction(elem[method])){ elem[method].apply(elem, args || []); } }); }
javascript
{ "resource": "" }
q8490
executeCommand
train
function executeCommand(parameters) { const configFilePath = path.join(process.cwd(), plugin.config.rolesPath); return mkdirpAsync(configFilePath) .then(() => { if (parameters.model !== 'none') { // Case a preset config has been choosen const src = path.join(__dirname, 'templates', 'roles', parameters.model + '.json'); const dest = path.join(configFilePath, parameters.identifier + '.json'); return ncpAsync(src, dest); } else { // Case no preset config has been choosen const config = { 'managed-policies': parameters.policies, 'inline-policies': [], 'trust-relationship': { Version: '2012-10-17', Statement: [{ Effect: 'Allow', Principal: { AWS: '*'}, Action: 'sts:AssumeRole' }] } }; // We save the specification in a json file return fs.writeFileAsync(configFilePath + path.sep + parameters.identifier + '.json', JSON.stringify(config, null, 2)); } }) .then(() => { const msg = '\n The IAM role ' + icli.format.info(parameters.identifier) + ' has been created in ' + icli.format.info(configFilePath + path.sep + parameters.identifier + '.json') + '\n'; icli.print(msg); }); }
javascript
{ "resource": "" }
q8491
getFunction
train
function getFunction(value, replacement) { return baseGetType(_.isFunction, _.noop, value, replacement); }
javascript
{ "resource": "" }
q8492
browser
train
function browser (winOptions) { winOptions = assign({ graceful: true }, winOptions) // Handle `browser-window` being passed as `parent`. if (winOptions.parent && winOptions.parent._native) { winOptions.parent = winOptions.parent._native } if (winOptions.graceful) winOptions.show = false // Create `BrowserWindow` backend. const window = new BrowserWindow(winOptions) if (winOptions.graceful) window.on('ready-to-show', function () { window.show() }) // Method for loading urls or data. function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) } // Send IPC messages function send (...args) { return window.webContents.send(...args) } // Create a child window function subwindow (options) { return browser(assign({ parent: window }, options)) } // Return methods return {load, send, subwindow, native: window} }
javascript
{ "resource": "" }
q8493
load
train
function load (source, options, callback = noop) { if (typeof options === 'function') callback = options, options = {} options = assign({type: null, encoding: 'base64'}, options) // Callback handler var contents = window.webContents eventcb(contents, 'did-finish-load', 'did-fail-load', callback) // Load source as data: if (options.type) { const data = Buffer.from(source).toString(options.encoding) return window.loadURL(`data:${options.type};${options.encoding},${data}`, options) } // Load source as URL: const protocol = url.parse(source).protocol if (!protocol) source = 'file://' + source return window.loadURL(source, options) }
javascript
{ "resource": "" }
q8494
loadLambdas
train
function loadLambdas() { const lambdasPath = path.join(process.cwd(), plugin.config.lambdasPath); // This event allows to inject code before loading all APIs return plugin.myrmex.fire('beforeLambdasLoad') .then(() => { // Retrieve configuration path of all Lambdas return Promise.promisify(fs.readdir)(lambdasPath); }) .then((subdirs) => { // Load all Lambdas configurations const lambdaPromises = []; _.forEach(subdirs, (subdir) => { const lambdaPath = path.join(lambdasPath, subdir); // subdir is the identifier of the Lambda, so we pass it as the second argument lambdaPromises.push(loadLambda(lambdaPath, subdir)); }); return Promise.all(lambdaPromises); }) .then((lambdas) => { // This event allows to inject code to add or delete or alter lambda configurations return plugin.myrmex.fire('afterLambdasLoad', lambdas); }) .spread((lambdas) => { return Promise.resolve(lambdas); }) .catch(e => { // In case the project does not have any Lambda yet, an exception will be thrown // We silently ignore it if (e.code === 'ENOENT' && path.basename(e.path) === 'lambdas') { return Promise.resolve([]); } return Promise.reject(e); }); }
javascript
{ "resource": "" }
q8495
loadLambda
train
function loadLambda(lambdaPath, identifier) { return plugin.myrmex.fire('beforeLambdaLoad', lambdaPath, identifier) .spread((lambdaPath, identifier) => { // Because we use require() to get the config, it could either be a JSON file // or the content exported by a node module // But because require() caches the content it loads, we clone the result to avoid bugs // if the function is called twice. const lambdaConfig = _.cloneDeep(require(path.join(lambdaPath, 'config'))); // If the identifier is not specified, it will be the name of the directory that contains the config lambdaConfig.identifier = lambdaConfig.identifier || identifier; // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./lambda const Lambda = require('./lambda'); const lambda = new Lambda(lambdaConfig, lambdaPath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterLambdaLoad', lambda); }) .spread((lambda) => { return Promise.resolve(lambda); }); }
javascript
{ "resource": "" }
q8496
loadNodeModule
train
function loadNodeModule(nodeModulePath, name) { return plugin.myrmex.fire('beforeNodeModuleLoad', nodeModulePath, name) .spread((nodeModulePath, name) => { let packageJson = {}; try { packageJson = _.cloneDeep(require(path.join(nodeModulePath, 'package.json'))); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } // Lasy loading because the plugin has to be registered in a Myrmex instance before requiring ./node-module const NodeModule = require('./node-module'); const nodePackage = new NodeModule(packageJson, name, nodeModulePath); // This event allows to inject code to alter the Lambda configuration return plugin.myrmex.fire('afterNodeModuleLoad', nodePackage); }) .spread(nodePackage => { return Promise.resolve(nodePackage); }); }
javascript
{ "resource": "" }
q8497
findLambda
train
function findLambda(identifier) { return loadLambdas() .then(lambdas => { const lambda = _.find(lambdas, (lambda) => { return lambda.getIdentifier() === identifier; }); if (!lambda) { throw new Error('The Lambda "' + identifier + '" does not exists in this Myrmex project'); } return lambda; }); }
javascript
{ "resource": "" }
q8498
findNodeModule
train
function findNodeModule(name) { return loadModules() .then(nodeModules => { const nodeModule = _.find(nodeModules, (nodeModule) => { return nodeModule.getName() === name; }); if (!nodeModule) { throw new Error('The node module "' + name + '" does not exists in this Myrmex project'); } return nodeModule; }); }
javascript
{ "resource": "" }
q8499
registerCommandsHook
train
function registerCommandsHook(icli) { return Promise.all([ require('./cli/create-lambda')(icli), require('./cli/create-node-module')(icli), require('./cli/deploy-lambdas')(icli), require('./cli/install-lambdas-locally')(icli), require('./cli/test-lambda-locally')(icli), require('./cli/test-lambda')(icli) ]); }
javascript
{ "resource": "" }