import WordpressConnector from '../../lib/connector'; import sinon from 'sinon'; import config from 'config'; import {expect} from 'chai'; import Nightmare from 'nightmare'; import url from 'url'; import os from 'os'; let osType = os.type(); describe('authorization steps', function () { let connector; let clientId = config.get('clientId'); let clientSecret = config.get('clientSecret'); let nightmare; before(function () { if (osType !== 'Linux') { nightmare = Nightmare({ show: true }); } connector = new WordpressConnector({clientId, clientSecret}); }); after(function () { if (osType !== 'Linux') { return nightmare.end(); } }) describe('on first bounce', () => { let bounce; before(function () {
const platform = os.platform(); if ([ "android", "darwin", "freebsd", "linux", "openbsd", "sunos", "win32", "aix", ].indexOf(platform) !== -1) { let file; if (platform === "aix") { // AIX `netstat` output is compatible with Solaris file = `${os.type() === "OS400" ? "ibmi" : "sunos"}.js`; } else { file = `${platform}.js`; } const m = require(`./${file}`); module.exports.v4 = () => m.v4(); module.exports.v6 = () => m.v6(); module.exports.v4.sync = () => m.v4.sync(); module.exports.v6.sync = () => m.v6.sync(); } else { const unsupported = () => { throw new Error(`Unsupported Platform: ${platform}`); }; module.exports.v4 = unsupported; module.exports.v6 = unsupported; module.exports.v4.sync = unsupported; module.exports.v6.sync = unsupported;
getType:function(callback) { return callback(null, OS.type()); },
exports = module.exports = function(user, system, Data) { // Load modules. var decisions = require('decisions') , pkginfo = require('pkginfo') , os = require('os') , path = require('path-os') , fs = require('fs') , properties = require('properties') , existsSync = fs.existsSync || path.existsSync; // <=0.6 var approot = path.dirname(pkginfo.find(require.main)); var ostype = os.type().toLowerCase(); //var settings = decisions.createSettings(); var settings = new decisions.Settings(); var file = decisions.resolve(path.join(approot, 'etc', 'settings'), Data.getExtensions()); var conf = new decisions.File(file); conf.read(); settings.use(conf); settings.use(user); settings.use(system); return settings; // FIXME: Remove below here... var dirname = path.resolve(approot, 'etc') , exts = [ '.toml', '.yaml', '.json' ] , ext, i, len, file, data; // Load default settings. // // The default settings are defined in a file relative to the application's // main script, at etc/settings.toml. Note that this file is considered // internal application configuration, and as such does not vary between // deployment environments. As such, it is suitable for maintaining under // source control. // // Separate files, located outside of source control, will be loaded in order // to override defaults, allowing settings to be modified according to // deployment specific requirements. for (i = 0, len = exts.length; i < len; ++i) { ext = exts[i]; file = path.join(dirname, 'settings' + ext); if (existsSync(file)) { settings.load(file); break; } } var pkg = pkginfo.read(require.main).package; var vend = pkg.author && pkg.author.organization ? path.join(pkg.author.organization, pkg.name) : pkg.name; // Load host-specific settings. // // Host-specific settings are loaded from system-wide configuration files. // // It is recommended to use host-specific settings in deployment environments, // overriding any defaults that are not suitable to the requirements. // // The location of host-specific settings vary depending on the OS, and can be // found at the following locations: // // Linux: /etc/<package>.toml // Mac OS X: /Library/Preferences/<package>.toml if (ostype.indexOf('darwin') === 0) { dirname = '/Library/Preferences' } else { // UNIX dirname = '/etc'; } for (i = 0, len = exts.length; i < len; ++i) { ext = exts[i]; file = path.join(dirname, vend + ext); if (existsSync(file)) { settings.load(file); break; } } // Load user-specific settings. // // User-specific settings are loaded from directories owned by the user. This // allows users to override system-wide settings according to user specific // requirements. // // It is recommended to use user-specific settings in development, allowing // each developer to tune their environment without risk of conflicts with // settings used by other developers. // // The location of user-specific settings vary depending on the OS, and can be // found at the following locations: // // Linux: /home/<username>/.config/<package>.toml // Mac OS X: /Users/<username>/Library/Preferences/<package>.toml for (i = 0, len = exts.length; i < len; ++i) { ext = exts[i]; file = path.configdir(vend + ext); if (existsSync(file)) { settings.load(file); break; } } // Load environment variables. // // Environment variables will be loaded into settings according to a mapping // file that specified the name of the environment variable, and the // corresponding key that will be set in in settings. // // The mapping file is considered internal application configuration and is // located at etc/env.properties. file = path.resolve(approot, 'etc/env.properties'); if (existsSync(file)) { data = fs.readFileSync(file, 'utf8'); var map, k, v; map = properties.parse(data); Object.keys(map).forEach(function(ev) { k = map[ev]; v = process.env[ev]; if (v) { settings.set(k, v); } }); } // TODO: Implement command-line argument mapping return settings; };
var os = require('os'); var message = 'Here is some info about your system'; var sysArray = new Array( 'Type: ' + os.type(), 'Node Version: ' + process.version, 'Platform: ' + os.platform(), 'Hostname: ' + os.hostname(), 'Total Memory: ' + os.totalmem(), 'Free Memory: ' + os.freemem(), 'Uptime: ' + os.uptime() ); console.log(message); var arrayLen = sysArray.length; for (i = 0; i < arrayLen; i++) { console.log(sysArray[i]); }
* }); */ // Allowed parameters var legalOptionNames = ['ha', 'haInterval', 'replicaSet', 'rs_name', 'secondaryAcceptableLatencyMS' , 'connectWithNoPrimary', 'poolSize', 'ssl', 'checkServerIdentity', 'sslValidate' , 'sslCA', 'sslCert', 'sslCRL', 'sslKey', 'sslPass', 'socketOptions', 'bufferMaxEntries' , 'store', 'auto_reconnect', 'autoReconnect', 'emitError' , 'keepAlive', 'noDelay', 'connectTimeoutMS', 'socketTimeoutMS', 'strategy', 'debug' , 'loggerLevel', 'logger', 'reconnectTries', 'appname', 'domainsEnabled' , 'servername', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'maxStalenessSeconds']; // Get package.json variable var driverVersion = require('../package.json').version; var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); var type = os.type(); var name = process.platform; var architecture = process.arch; var release = os.release(); /** * Creates a new ReplSet instance * @class * @deprecated * @param {Server[]} servers A seedlist of servers participating in the replicaset. * @param {object} [options=null] Optional settings. * @param {booelan} [options.ha=true] Turn on high availability monitoring. * @param {number} [options.haInterval=10000] Time between each replicaset status check. * @param {string} [options.replicaSet] The name of the replicaset to connect to. * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available
( function( module ) { var os = require('os'); var path = require('path'); var spawn = require('child_process').spawn; var dirname = __dirname; var vendor = path.resolve(dirname, '../vendor'); var osname = os.type(); var win32 = os.type() == 'Windows_NT'; var cmd = 'cmd.exe'; var gnome_terminal = undefined; var xterm = undefined; function search_bin(name, locations) { var process = require('process'); var path = require('path'); var fs = require('fs'); var os = require('os'); var win32 = os.type() == 'Windows_NT'; if (process.env.PATH) { var PATH = process.env.PATH; if (win32) { PATH = PATH.split(';'); } else { PATH = PATH.split(':'); } for (var i = 0; i < PATH.length; i++) { var filepath = path.join(PATH[i], name); try { fs.accessSync(filepath, fs.F_OK); return win32? filepath.split('/').join('\\') : filepath; } catch (e) { } } } if (locations) { for (var i = 0; i < locations.length; i++) { var filepath = path.join(locations[i], name); try { fs.accessSync(filepath, fs.F_OK); return win32? filepath.split('/').join('\\') : filepath; } catch (e) { } } } return undefined; } if (win32) { var loc = ['C:/Windows/System32', 'C:/Windows/SysWOW64']; loc.push('C:/WinNT/System32'); loc.push('C:/WinNT/SysWOW64'); cmd = search_bin('cmd.exe', loc); cmd = cmd.split('/').join('\\'); } else if (osname == 'Linux') { gnome_terminal = search_bin('gnome-terminal', ['/bin', '/usr/bin']); xterm = search_bin('xterm', ['/bin', '/usr/bin']); } module.exports.open_windows = function(command, argv, options) { var argument = ['/C', 'start', cmd, '/C']; argument.push(path.join(vendor, "launch.cmd")); argument.push(command); argument = argument.concat(argv); options.detached = true; options.stdout = 'ignore'; options.stderr = 'ignore'; options.shell = false; command = cmd; if (false) { command = 'cmd.exe'; argument = ['/C', 'start', cmd, '/C', 'echo', 'f**k']; } var proc = spawn(command, argument, options); } module.exports.open_linux_gnome = function(command, argv, options) { } module.exports.open_linux_xterm = function(command, argv, options) { } module.exports.open_darwin_terminal = function(command, argv, options) { } module.exports.open_terminal = function(command, argv, options) { options.detached = true; options.stdout = 'ignore'; options.stderr = 'ignore'; options.shell = false; if (osname == 'Windows_NT') { this.open_windows(command, argv, options); } else if (osname == 'Linux') { var terminal = 'xterm'; } } module.exports.test = function(a, b) { return a + b; } } ) (module);
function getOSType() { return os.type(); }
//initalize the http server function (callback) { //create server var app = express.createServer(); //load modules that needs a initalized db readOnlyManager = require("./db/ReadOnlyManager"); exporthtml = require("./utils/ExportHtml"); exportHandler = require('./handler/ExportHandler'); importHandler = require('./handler/ImportHandler'); apiHandler = require('./handler/APIHandler'); padManager = require('./db/PadManager'); securityManager = require('./db/SecurityManager'); socketIORouter = require("./handler/SocketIORouter"); //install logging var httpLogger = log4js.getLogger("http"); app.configure(function() { // If the log level specified in the config file is WARN or ERROR the application server never starts listening to requests as reported in issue #158. // Not installing the log4js connect logger when the log level has a higher severity than INFO since it would not log at that level anyway. if (!(settings.loglevel === "WARN" || settings.loglevel == "ERROR")) app.use(log4js.connectLogger(httpLogger, { level: log4js.levels.INFO, format: ':status, :method :url'})); app.use(express.cookieParser()); }); //serve static files app.get('/static/*', function(req, res) { res.header("Server", serverName); var filePath = path.normalize(__dirname + "/.." + req.url.replace(/\.\./g, '').split("?")[0]); res.sendfile(filePath, { maxAge: exports.maxAge }); }); //serve minified files app.get('/minified/:id', function(req, res, next) { res.header("Server", serverName); var id = req.params.id; if(id == "pad.js" || id == "timeslider.js") { minify.minifyJS(req,res,id); } else { next(); } }); //checks for padAccess function hasPadAccess(req, res, callback) { securityManager.checkAccess(req.params.pad, req.cookies.sessionid, req.cookies.token, req.cookies.password, function(err, accessObj) { if(err) throw err; //there is access, continue if(accessObj.accessStatus == "grant") { callback(); } //no access else { res.send("403 - Can't touch this", 403); } }); } //serve read only pad app.get('/ro/:id', function(req, res) { res.header("Server", serverName); var html; var padId; var pad; async.series([ //translate the read only pad to a padId function(callback) { readOnlyManager.getPadId(req.params.id, function(err, _padId) { padId = _padId; //we need that to tell hasPadAcess about the pad req.params.pad = padId; callback(err); }); }, //render the html document function(callback) { //return if the there is no padId if(padId == null) { callback("notfound"); return; } hasPadAccess(req, res, function() { //render the html document exporthtml.getPadHTMLDocument(padId, null, false, function(err, _html) { html = _html; callback(err); }); }); } ], function(err) { //throw any unexpected error if(err && err != "notfound") throw err; if(err == "notfound") res.send('404 - Not Found', 404); else res.send(html); }); }); //serve pad.html under /p app.get('/p/:pad', function(req, res, next) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(req.params.pad) || /\/$/.test(req.url)) { res.send('Such a padname is forbidden', 404); return; } res.header("Server", serverName); var filePath = path.normalize(__dirname + "/../static/pad.html"); res.sendfile(filePath, { maxAge: exports.maxAge }); }); //serve timeslider.html under /p/$padname/timeslider app.get('/p/:pad/timeslider', function(req, res, next) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(req.params.pad) || /\/$/.test(req.url)) { res.send('Such a padname is forbidden', 404); return; } res.header("Server", serverName); var filePath = path.normalize(__dirname + "/../static/timeslider.html"); res.sendfile(filePath, { maxAge: exports.maxAge }); }); //serve timeslider.html under /p/$padname/timeslider app.get('/p/:pad/export/:type', function(req, res, next) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(req.params.pad) || /\/$/.test(req.url)) { res.send('Such a padname is forbidden', 404); return; } var types = ["pdf", "doc", "txt", "html", "odt"]; //send a 404 if we don't support this filetype if(types.indexOf(req.params.type) == -1) { next(); return; } //if abiword is disabled, and this is a format we only support with abiword, output a message if(settings.abiword == null && req.params.type != "html" && req.params.type != "txt" ) { res.send("Abiword is not enabled at this Etherpad Lite instance. Set the path to Abiword in settings.json to enable this feature"); return; } res.header("Access-Control-Allow-Origin", "*"); res.header("Server", serverName); hasPadAccess(req, res, function() { exportHandler.doExport(req, res, req.params.pad, req.params.type); }); }); //handle import requests app.post('/p/:pad/import', function(req, res, next) { //ensure the padname is valid and the url doesn't end with a / if(!padManager.isValidPadId(req.params.pad) || /\/$/.test(req.url)) { res.send('Such a padname is forbidden', 404); return; } //if abiword is disabled, skip handling this request if(settings.abiword == null) { next(); return; } res.header("Server", serverName); hasPadAccess(req, res, function() { importHandler.doImport(req, res, req.params.pad); }); }); var apiLogger = log4js.getLogger("API"); //This is a api call, collect all post informations and pass it to the apiHandler app.get('/api/1/:func', function(req, res) { res.header("Server", serverName); res.header("Content-Type", "application/json; charset=utf-8"); apiLogger.info("REQUEST, " + req.params.func + ", " + JSON.stringify(req.query)); //wrap the send function so we can log the response res._send = res.send; res.send = function(response) { response = JSON.stringify(response); apiLogger.info("RESPONSE, " + req.params.func + ", " + response); //is this a jsonp call, if yes, add the function call if(req.query.jsonp) response = req.query.jsonp + "(" + response + ")"; res._send(response); } //call the api handler apiHandler.handle(req.params.func, req.query, req, res); }); //The Etherpad client side sends information about how a disconnect happen app.post('/ep/pad/connection-diagnostic-info', function(req, res) { new formidable.IncomingForm().parse(req, function(err, fields, files) { console.log("DIAGNOSTIC-INFO: " + fields.diagnosticInfo); res.end("OK"); }); }); //The Etherpad client side sends information about client side javscript errors app.post('/jserror', function(req, res) { new formidable.IncomingForm().parse(req, function(err, fields, files) { console.error("CLIENT SIDE JAVASCRIPT ERROR: " + fields.errorInfo); res.end("OK"); }); }); //serve index.html under / app.get('/', function(req, res) { res.header("Server", serverName); var filePath = path.normalize(__dirname + "/../static/index.html"); res.sendfile(filePath, { maxAge: exports.maxAge }); }); //serve robots.txt app.get('/robots.txt', function(req, res) { res.header("Server", serverName); var filePath = path.normalize(__dirname + "/../static/robots.txt"); res.sendfile(filePath, { maxAge: exports.maxAge }); }); //serve favicon.ico app.get('/favicon.ico', function(req, res) { res.header("Server", serverName); var filePath = path.normalize(__dirname + "/../static/custom/favicon.ico"); res.sendfile(filePath, { maxAge: exports.maxAge }, function(err) { //there is no custom favicon, send the default favicon if(err) { filePath = path.normalize(__dirname + "/../static/favicon.ico"); res.sendfile(filePath, { maxAge: exports.maxAge }); } }); }); //let the server listen app.listen(settings.port, settings.ip); console.log("Server is listening at " + settings.ip + ":" + settings.port); var onShutdown = false; var gracefulShutdown = function(err) { if(err && err.stack) { console.error(err.stack); } else if(err) { console.error(err); } //ensure there is only one graceful shutdown running if(onShutdown) return; onShutdown = true; console.log("graceful shutdown..."); //stop the http server app.close(); //do the db shutdown db.db.doShutdown(function() { console.log("db sucessfully closed."); process.exit(0); }); setTimeout(function(){ process.exit(1); }, 3000); } //connect graceful shutdown with sigint and uncaughtexception if(os.type().indexOf("Windows") == -1) { //sigint is so far not working on windows //https://github.com/joyent/node/issues/1553 process.on('SIGINT', gracefulShutdown); } process.on('uncaughtException', gracefulShutdown); //init socket.io and redirect all requests to the MessageHandler var io = socketio.listen(app); //this is only a workaround to ensure it works with all browers behind a proxy //we should remove this when the new socket.io version is more stable io.set('transports', ['xhr-polling']); var socketIOLogger = log4js.getLogger("socket.io"); io.set('logger', { debug: function (str) { socketIOLogger.debug(str); }, info: function (str) { socketIOLogger.info(str); }, warn: function (str) { socketIOLogger.warn(str); }, error: function (str) { socketIOLogger.error(str); }, }); //minify socket.io javascript if(settings.minify) io.enable('browser client minification'); var padMessageHandler = require("./handler/PadMessageHandler"); var timesliderMessageHandler = require("./handler/TimesliderMessageHandler"); //Initalize the Socket.IO Router socketIORouter.setSocketIO(io); socketIORouter.addComponent("pad", padMessageHandler); socketIORouter.addComponent("timeslider", timesliderMessageHandler); callback(null); }
var chai = require('chai') , expect = chai.expect , Support = require(__dirname + '/support') , DataTypes = require(__dirname + "/../lib/data-types") , dialect = Support.getTestDialect() , _ = require('lodash') , exec = require('child_process').exec , version = (require(__dirname + '/../package.json')).version , path = require('path') , os = require('os') chai.config.includeStack = true if (os.type().toLowerCase().indexOf('windows') === -1) { describe(Support.getTestDialectTeaser("Executable"), function() { describe('call without arguments', function() { it("prints usage instructions", function(done) { exec('bin/sequelize', function(err, stdout, stderr) { expect(stdout).to.include("No action specified. Try \"sequelize --help\" for usage information.") done() }) }) }) ;(function(flags) { flags.forEach(function(flag) { describe(flag, function() { it("prints the help", function(done) { exec("bin/sequelize " + flag, function(err, stdout, stderr) { expect(stdout).to.include("Usage: sequelize [options]") done()
var defaultUserAgent = function() { return 'QiniuNodejs/' + pkg.version + ' (' + os.type() + '; ' + os.platform() + '; ' + os.arch() + '; )'; };
var child_process = require('child_process') var fs = require('fs') var path = require('path') var os = require('os') var is_windows = ! (os.type().indexOf('Windows') < 0) var jscomp = path.join(__dirname,'..','jscomp') var working_dir = process.cwd() console.log("Working dir", working_dir) var working_config = {cwd: jscomp, stdio:[0,1,2]} process.env.BS_RELEASE_BUILD=true child_process.execSync('make -j4 -B -C bin all', working_config) var result = child_process.execSync('make -B -j1 --dry-run libs',{cwd:jscomp,encoding:'utf8'}) var jobs = result.split('\n').reduce(function(acc,line){ if(line.indexOf('Entering') !== -1){ var line_segs = line.split(' ') var new_path = path.parse(line_segs[line_segs.length - 1].slice(1,-1)) acc.push({base : new_path.base, jobs : []}) return acc } else if(line.indexOf('bsc.exe') !== -1){ var current_job = acc [acc.length - 1] var new_line = line if(current_job.base==='stdlib'){
const jsonist = require('jsonist') const {ipcRenderer} = require('electron') const fs = require('fs') const request = require('request') const progress = require('request-progress') const {app} = require('electron').remote const ps = require('ps-node') const exec = require('child_process').exec const config = require('../config') const pathf = require('path') const os = require('os') let agent = `RealLifeRPG Launcher/${app.getVersion()} (${os.type()} ${os.release()}; ${os.platform()}; ${os.arch()}) - ` if (typeof process.env.PORTABLE_EXECUTABLE_DIR !== 'undefined') { agent = agent.concat('Portable') } else if (typeof process.windowsStore !== 'undefined') { agent = agent.concat('Windows UWP') } else { agent = agent.concat('Desktop') } ipcRenderer.on('to-web', (event, args) => { switch (args.type) { case 'get-url' : getUrl(args) break case 'start-file-download' : downloadFILE(args.file) break case 'ping-server-via-rdp' :
fTime.getHours().toString(), fTime.getMinutes().toString(), fTime.getSeconds().toString() ] /* var time1 = Date.parse(new Date()), time2 = (new Date()).valueOf(), time3 = new Date().getTime(); */ for (var i = 0; i < formatArr.length; i++) { formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]); } return formatStr; } console.info( //service info "\nSalam Mulazimiti Qozghaldi : " + hostname + "/" + '\n - Start time : ' + formatDate() //author info + '\n ' + '\n - author : Salam Sanji' + '\n email : Salam.14@163.com' + '\n ' ); console.log( //yerliktiki uchurlar '::::::::::Info::::::::::' + '\n - Address : ' + __dirname + addYour + ' \n - temp dir : ' + os.tmpdir() + ' \n - endianness : ' + os.endianness() + ' \n - host name : ' + os.hostname() + ' \n - type : ' + os.type() + ' \n - platform : ' + os.platform() + ' \n - arch : ' + os.arch() + ' \n - release : ' + os.release() + ' \n - system uptime : ' + os.uptime() + " (s)" + '\n' ); /*for u end*/
function errorHandler (er) { log.disableProgress() // console.error('errorHandler', er) if (!npm.config || !npm.config.loaded) { // logging won't work unless we pretend that it's ready er = er || new Error('Exit prior to config file resolving.') console.error(er.stack || er.message) } if (cbCalled) { er = er || new Error('Callback called more than once.') } cbCalled = true if (!er) return exit(0) if (typeof er === 'string') { log.error('', er) return exit(1, true) } else if (!(er instanceof Error)) { log.error('weird error', er) return exit(1, true) } var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/) if (m && !er.code) { er.code = m } ;[ 'type', 'fstream_path', 'fstream_unc_path', 'fstream_type', 'fstream_class', 'fstream_finish_call', 'fstream_linkpath', 'stack', 'fstream_stack', 'statusCode', 'pkgid' ].forEach(function (k) { var v = er[k] if (!v) return if (k === 'fstream_stack') v = v.join('\n') log.verbose(k, v) }) log.verbose('cwd', process.cwd()) var os = require('os') // log.error('System', os.type() + ' ' + os.release()) // log.error('command', process.argv.map(JSON.stringify).join(' ')) // log.error('node -v', process.version) // log.error('npm -v', npm.version) log.error('', os.type() + ' ' + os.release()) log.error('argv', process.argv.map(JSON.stringify).join(' ')) log.error('node', process.version) log.error('npm ', 'v' + npm.version) ;[ 'file', 'path', 'code', 'errno', 'syscall' ].forEach(function (k) { var v = er[k] if (v) log.error(k, v) }) // just a line break if (log.levels[log.level] <= log.levels.error) console.error('') var msg = errorMessage(er) msg.summary.concat(msg.detail).forEach(function (errline) { log.error.apply(log, errline) }) exit(typeof er.errno === 'number' ? er.errno : 1) }
, exists = fs.existsSync || path.existsSync , os = require('os') , quote = JSON.stringify , cmd; function which(name) { var paths = process.env.PATH.split(':'); var loc; for (var i = 0, len = paths.length; i < len; ++i) { loc = path.join(paths[i], name); if (exists(loc)) return loc; } } switch(os.type()) { case 'Darwin': if (which('terminal-notifier')) { cmd = { type: "Darwin-NotificationCenter" , pkg: "terminal-notifier" , msg: '-message' , title: '-title' , subtitle: '-subtitle' , priority: { cmd: '-execute' , range: [] } }; } else { cmd = {
// Used to detect for Cygwin var os = require("os"); // Required for Windows/Cygwin support var root = [__dirname, "/../vendor/libgit2/build/shared"].join(""), path = process.env.PATH; if (~os.type().indexOf("CYGWIN") && !~path.indexOf(root)) { process.env.PATH = root + ":" + path; } // Import libraries exports.blob = require("./blob.js").blob; exports.repo = require("./repo.js").repo; exports.sig = require("./sig.js").sig; exports.oid = require("./oid.js").oid; exports.object = require("./object.js").object; exports.ref = require("./ref.js").ref; exports.revwalk = require("./revwalk.js").revwalk; exports.commit = require("./commit.js").commit; exports.tree = require("./tree.js").tree; exports.entry = require("./tree_entry.js").entry; // Assign raw api to module try { exports.raw = require('../build/Debug/nodegit'); } catch (error) { exports.raw = require('../build/Release/nodegit'); } // Initialize objects that need to access their raw counterparts
// ---------------------------------------------------------------------------------- // Description: System Information - library // for Node.js // Copyright: (c) 2014 - 2017 // Author: Sebastian Hildebrandt // ---------------------------------------------------------------------------------- // License: MIT // ================================================================================== // 13. Docker // ---------------------------------------------------------------------------------- const os = require('os'); const util = require('./util'); const DockerSocket = require('./dockerSocket'); let _platform = os.type(); const _windows = (_platform === 'Windows_NT'); const NOT_SUPPORTED = 'not supported'; let _docker_container_stats = {}; let _docker_socket; // -------------------------- // get containers (parameter all: get also inactive/exited containers) function dockerContainers(all, callback) { function inContainers(containers, id) { let filtered = containers.filter(obj => {
var http = require('http'); var fs = require('fs'); var os = require('os'); var exec = require('child_process').exec; var targetDir = __dirname + '/tools/'; try { fs.statSync(targetDir); } catch (e) { fs.mkdirSync(targetDir); } var platform = null; if (os.type() == 'Darwin') { platform = 'macosx'; } else if (os.type() == 'Linux') { platform = 'linux'; } else { throw new Error('Unknown OS!'); } function attemptDownload(attemptsLeft) { var url = "http://dl-ssl.google.com/android/repository/platform-tools_r16-" + platform + ".zip"; var tempFile = "/tmp/platform-tools-" + (new Date().getTime()) + ".zip"; var file = fs.createWriteStream(tempFile); var request = http.get(url, function(response) { response.pipe(file); response.on('end', function () { exec("unzip -j -o " + tempFile + " platform-tools/aapt -d tools/", function (err) { if (err) {
var os = require("os"); console.log("--- OS DETAILS ---"); console.log("OS HOSTNAME :",os.hostname()); console.log("OS TYPE :",os.type()); console.log("OS PLATFORM :",os.platform()); console.log("OS ARCHITECTURE :",os.arch()); console.log("OS RELEASE :",os.release()); console.log("CONSOLE PROFILE : ",process.env.KONSOLE_PROFILE_NAME); console.log("DESKTOP SESSION :",process.env.DESKTOP_SESSION); console.log("USERNAME :"******"LANGUAGE : ",process.env.LANGUAGE); console.log("--- NETWORK ---"); console.log("NETWORK :",os.networkInterfaces()); console.log("--- CPU DETAILS ---"); console.log("CPU :",os.cpus()[0].model); console.log("CPU CORES :",os.cpus().length); console.log("--- MEMORY --"); console.log("UPTIME :",os.uptime()); console.log("FREE MEMORY : ",os.freemem()); console.log( os.endianness()); console.log("---PROCESS DETAILS---"); console.log("COMMAND : ",process.title); console.log("NODE VERSION : ",process.version); console.log("NODE ARGUMENTS : ",process.argv);
if (version[1] <= 8 && version[2] <= 5) badVersion = true; } return badVersion && os.arch() === 'x64' && os.type() === 'SunOS'; } /** * Settings actually get scraped below. */ // in 64-bit SmartOS zones, node <= 0.8.5 pukes on os.cpus() if (!badOS()) addSetting('Processors', os.cpus().length); addSetting('OS', os.type()); addSetting('OS version', os.release()); addSetting('Node.js version', process.version); addSetting('Architecture', process.arch); remapConfigSettings(); findPackages(); module.exports = { setFramework : function setFramework(framework) { addSetting('Framework', framework); }, setDispatcher : function setDispatcher(dispatcher) { addSetting('Dispatcher', dispatcher); }, clearFramework : function clearFramework() { clearSetting('Framework'); }, clearDispatcher : function clearDispatcher() { clearSetting('Dispatcher'); }, toJSON : function toJSON() { return settings; }, get : getSetting };
var collect = function() { for (var key in values) { var obj = values[key]; if(obj.op === 'hist') { emit(obj.scope, obj.name, obj._bins, obj.unit, obj.op); } else if(obj.op === 'sum') { emit(obj.scope, obj.name, obj._sum, obj.unit, obj.op); } else if(obj.op === 'avg') { var avg = Math.round(obj._sum / obj._count); emit(obj.scope, obj.name, avg, obj.unit, obj.op); } } values = {}; var osScope = os.hostname(); var processScope = osScope + ' - Process[' + process.pid + ']'; try { emit(osScope, 'Load average', os.loadavg()[0]); } catch(err) { nt.error(err); } try { emit(osScope, 'Free memory', os.freemem() / 1000000, 'MB'); } catch(err) { nt.error(err); } try { var mem = process.memoryUsage(); emit(processScope, 'Node RSS', mem.rss / 1000000, 'MB'); emit(processScope, 'V8 heap used', mem.heapUsed / 1000000, 'MB'); emit(processScope, 'V8 heap total', mem.heapTotal / 1000000, 'MB'); } catch(err) { nt.error(err); } var cpuTime = nt.cputime(); if(cpuTime !== undefined && nt.lastCpuTime !== undefined) { emit(processScope, 'CPU time', (cpuTime - nt.lastCpuTime) / 1000, 'ms'); nt.lastCpuTime = cpuTime; } var info = {}; try { info['Hostname'] = os.hostname() } catch(err) { nt.error(err) } try { info['OS type'] = os.type() } catch(err) { nt.error(err) } try { info['Platform'] = os.platform() } catch(err) { nt.error(err) } try { info['Total memory (MB)'] = os.totalmem() / 1000000 } catch(err) { nt.error(err) } try { var cpus = os.cpus(); info['CPU'] = {architecture: os.arch(), model: cpus[0].model, speed: cpus[0].speed, cores: cpus.length} } catch(err) { nt.error(err) } try { info['Interfaces'] = os.networkInterfaces() } catch(err) { nt.error(err) } try { info['OS Uptime (Hours)'] = Math.floor(os.uptime() / 3600) } catch(err) { nt.error(err) } try { info['Node arguments'] = process.argv } catch(err) { nt.error(err) } try { info['Node versions'] = process.versions } catch(err) { nt.error(err) } try { info['Node PID'] = process.pid; } catch(err) { nt.error(err) } try { info['Node uptime (Hours)'] = Math.floor(process.uptime() / 3600); } catch(err) { nt.error(err) } try { nt.emit('info', info); } catch(err) { nt.error(err); } };
var os = require("os"); // CPU 的字节序 console.log('endianness : ' + os.endianness()); // 操作系统名 console.log('type : ' + os.type()); // 操作系统名 console.log('platform : ' + os.platform()); // 系统内存总量 console.log('total memory : ' + os.totalmem() + " bytes."); // 操作系统空闲内存量 console.log('free memory : ' + os.freemem() + " bytes.");
function uploadFileArray(req, res, callback) { var files = []; if (req.files && !req.files.attachfile.length) { req.files.attachfile = [req.files.attachfile]; } var path; var os = require("os"); var osType = (os.type().split('_')[0]); req.files.attachfile.forEach(function (item) { var localPath; switch (osType) { case "Windows": { localPath = __dirname + "\\uploads\\" + req.headers.id; } break; case "Linux": { localPath = __dirname + "\/uploads\/" + req.headers.id; } } fs.readdir(localPath, function (err, files) { if (!err) { var k = ''; var maxK = 0; var checkIs = false; var attachfileName = item.name.slice(0, item.name.lastIndexOf('.')); files.forEach(function (fileName) { if (fileName == item.name) { k = 1; checkIs = true; } else { if ((fileName.indexOf(attachfileName) === 0) && (fileName.lastIndexOf(attachfileName) === 0) && (fileName.lastIndexOf(').') !== -1) && (fileName.lastIndexOf('(') !== -1) && (fileName.lastIndexOf('(') < fileName.lastIndexOf(').')) && (attachfileName.length == fileName.lastIndexOf('('))) { var intVal = fileName.slice(fileName.lastIndexOf('(') + 1, fileName.lastIndexOf(').')); k = parseInt(intVal) + 1; } } if (maxK < k) { maxK = k; } }); if (!(maxK == 0) && checkIs) { item.name = attachfileName + '(' + maxK + ')' + item.name.slice(item.name.lastIndexOf('.')); } } }); fs.readFile(item.path, function (err, data) { var shortPas; switch (osType) { case "Windows": { path = __dirname + "\\uploads\\" + req.headers.id + "\\" + item.name; shortPas = "******" + req.headers.id + "\\" + item.name; } break; case "Linux": { path = __dirname + "\/uploads\/" + req.headers.id + "\/" + item.name; shortPas = "******" + req.headers.id + "\/" + item.name; } } fs.writeFile(path, data, function (err) { if (!err) { var file = {}; file._id = mongoose.Types.ObjectId(); file.name = item.name; file.shortPas = encodeURIComponent(shortPas); if (item.size>=1024) { file.size = (Math.round(item.size / 1024 / 1024 * 1000) / 1000)+' Mb'; } else{ file.size = (Math.round(item.size / 1024 * 1000)/1000)+' Kb'; } file.uploadDate = new Date(); file.uploaderName = req.session.uName; files.push(file); if (files.length == req.files.attachfile.length) { if (callback) { callback(files); } } } else { console.log(err); res.send(500); } }); }); }); }
_getStatsAndParts(tp, function(err, stats, dirAbsPaths){ if (err) return cb(err); var ext, mymime; if (/\.tar\.gz$/.test(tp.absPath)) { ext = '.tar.gz'; mymime = 'application/x-gtar'; } else { ext = path.extname(tp.absPath); //if directory -> '' mymime = mime.lookup(ext); //if '' -> 'application/octet-stream' } var prefix = (opts.namespace)? (opts.namespace + '/') : ''; var mypath = path.relative(this.root, tp.absPath) , myid = prefix + (path.basename(tp.absPath, ext).trim().replace(/ /g, '-').toLowerCase() || 'p') ; var hasPart; if (stats.isDirectory()) { hasPart = dirAbsPaths.map(function(x){ return { '@type': 'MediaObject', 'filePath': path.relative(this.root, x.absPath), 'contentSize': x.stats.size, 'dateModified': x.stats.mtime }; }, this); } //try to patch MIME if (stats.isFile() && mymime == 'application/octet-stream') { if (~['readme', 'license'].indexOf(path.basename(tp.absPath).trim().toLowerCase())) { mymime = 'text/plain'; } } var uid = myid, i = 1; while (uid in reservedIds) { uid = myid + '-' + i++; } reservedIds[uid] = true; var r = { '@id': uid, '@type': tp.type || Dcat.type(mymime) || 'CreativeWork' }; if (this.packager.isClassOrSubClassOf(r['@type'], 'SoftwareApplication')) { //special case if (stats.isDirectory()) { return cb(new Error('directories are not supported for SoftwareApplication or subclasses of SoftwareApplication')); } r.fileFormat = mymime; r.filePath = mypath; r.fileSize = stats.size; r.dateModified = stats.mtime.toISOString(); r.operatingSystem = os.type() + ' ' + os.release(); r.processorRequirements = os.arch(); } else { var encoding = { dateModified: stats.mtime.toISOString() }; if (stats.isDirectory()) { encoding.encodingFormat = 'application/x-gtar'; //.tar.gz according to http://en.wikipedia.org/wiki/List_of_archive_formats encoding.hasPart = hasPart; } else { encoding.encodingFormat = mymime; encoding.filePath = mypath; encoding.contentSize = stats.size; } if (this.packager.isClassOrSubClassOf(r['@type'], 'Dataset')) { //TODO about r.distribution = _.extend({'@type': 'DataDownload'}, encoding); } else if (this.packager.isClassOrSubClassOf(r['@type'], 'Code')) { //try to guess programming language if (stats.isDirectory()) { var langs = []; for (var i=0; i<hasPart.length; i++) { var p = hasPart[i].filePath; var m; if (/\.tar\.gz$/.test(p)) { m = 'application/x-gtar'; } else { m = mime.lookup(p); } var m2 = m.split('/')[1]; if (Dcat.type(m) === 'Code') { langs.push(m2.split('-')[1] || m2); } } if (langs.length){ langs = _.uniq(langs).map(function(lang){return {name: lang};}); r.programmingLanguage = (langs.length === 1) ? langs[0]: langs; } } else { var m2 = mymime.split('/')[1]; if (Dcat.type(mymime) === 'Code') { r.programmingLanguage = { name: m2.split('-')[1] || m2 }; } } r.encoding = _.extend({'@type': 'MediaObject'}, encoding); } else { r.encoding = _.extend({'@type': 'MediaObject'}, encoding); } } cb(null, r); }.bind(this));
function errorHandler (er) { var printStack = false // console.error("errorHandler", er) if (!npm.config.loaded) { // logging won't work unless we pretend that it's ready er = er || new Error("Exit prior to config file resolving.") console.error(er.stack || er.message) } if (cbCalled) { er = er || new Error("Callback called more than once.") } cbCalled = true if (!er) return exit(0) if (typeof er === "string") { log.error("", er) return exit(1, true) } else if (!(er instanceof Error)) { log.error("weird error", er) return exit(1, true) } var m = er.code || er.message.match(/^(?:Error: )?(E[A-Z]+)/) if (m && !er.code) er.code = m switch (er.code) { case "ECONNREFUSED": log.error("", er) log.error("", ["\nIf you are behind a proxy, please make sure that the" ,"'proxy' config is set properly. See: 'npm help config'" ].join("\n")) printStack = true break case "EACCES": case "EPERM": log.error("", er) log.error("", ["\nPlease try running this command again as root/Administrator." ].join("\n")) printStack = true break case "ELIFECYCLE": er.code = "ELIFECYCLE" log.error("", er.message) log.error("", ["","Failed at the "+er.pkgid+" "+er.stage+" script." ,"This is most likely a problem with the "+er.pkgname+" package," ,"not with npm itself." ,"Tell the author that this fails on your system:" ," "+er.script ,"You can get their info via:" ," npm owner ls "+er.pkgname ,"There is likely additional logging output above." ].join("\n")) break case "ENOGIT": er.code = "ENOGIT" log.error("", er.message) log.error("", ["","Failed using git." ,"This is most likely not a problem with npm itself." ,"Please check if you have git installed and in your PATH." ].join("\n")) break case "EJSONPARSE": er.code = "EJSONPARSE" log.error("", er.message) log.error("", "File: "+er.file) log.error("", ["Failed to parse package.json data." ,"package.json must be actual JSON, not just JavaScript." ,"","This is not a bug in npm." ,"Tell the package author to fix their package.json file." ].join("\n"), "JSON.parse") break case "E404": er.code = "E404" if (er.pkgid && er.pkgid !== "-") { var msg = ["'"+er.pkgid+"' is not in the npm registry." ,"You should bug the author to publish it"] if (er.pkgid.match(/^node[\.\-]|[\.\-]js$/)) { var s = er.pkgid.replace(/^node[\.\-]|[\.\-]js$/g, "") if (s !== er.pkgid) { s = s.replace(/[^a-z0-9]/g, ' ') msg.push("\nMaybe try 'npm search " + s + "'") } } msg.push("\nNote that you can also install from a" ,"tarball, folder, or http url, or git url.") log.error("404", msg.join("\n")) } break case "EPUBLISHCONFLICT": er.code = "EPUBLISHCONFLICT" log.error("publish fail", ["Cannot publish over existing version." ,"Update the 'version' field in package.json and try again." ,"" ,"If the previous version was published in error, see:" ," npm help unpublish" ,"" ,"To automatically increment version numbers, see:" ," npm help version" ].join("\n")) break case "EISGIT": er.code = "EISGIT" log.error("git", [er.message ," "+er.path ,"Refusing to remove it. Update manually," ,"or move it out of the way first." ].join("\n")) break case "ECYCLE": er.code = "ECYCLE" log.error("cycle", [er.message ,"While installing: "+er.pkgid ,"Found a pathological dependency case that npm cannot solve." ,"Please report this to the package author." ].join("\n")) break case "EBADPLATFORM": er.code = "EBADPLATFORM" log.error("notsup", [er.message ,"Not compatible with your operating system or architecture: "+er.pkgid ,"Valid OS: "+er.os.join(",") ,"Valid Arch: "+er.cpu.join(",") ,"Actual OS: "+process.platform ,"Actual Arch: "+process.arch ].join("\n")) break case "EEXIST": log.error([er.message ,"File exists: "+er.path ,"Move it away, and try again."].join("\n")) break case "ENEEDAUTH": log.error("need auth", [er.message ,"You need to authorize this machine using `npm adduser`" ].join("\n")) break case "EPEERINVALID": var peerErrors = Object.keys(er.peersDepending).map(function (peer) { return "Peer " + peer + " wants " + er.packageName + "@" + er.peersDepending[peer] }) log.error("peerinvalid", [er.message].concat(peerErrors).join("\n")) break case "ECONNRESET": case "ENOTFOUND": case "ETIMEDOUT": log.error("network", [er.message ,"This is most likely not a problem with npm itself" ,"and is related to network connectivity." ,"In most cases you are behind a proxy or have bad network settings." ,"\nIf you are behind a proxy, please make sure that the" ,"'proxy' config is set properly. See: 'npm help config'" ].join("\n")) break case "ENOTSUP": if (er.required) { log.error("notsup", [er.message ,"Not compatible with your version of node/npm: "+er.pkgid ,"Required: "+JSON.stringify(er.required) ,"Actual: " +JSON.stringify({npm:npm.version ,node:npm.config.get("node-version")}) ].join("\n")) break } // else passthrough default: log.error("", er.stack || er.message || er) log.error("", ["If you need help, you may report this log at:" ," <http://github.com/isaacs/npm/issues>" ,"or email it to:" ," <*****@*****.**>" ].join("\n")) printStack = false break } var os = require("os") // just a line break console.error("") log.error("System", os.type() + " " + os.release()) log.error("command", process.argv .map(JSON.stringify).join(" ")) log.error("cwd", process.cwd()) log.error("node -v", process.version) log.error("npm -v", npm.version) ; [ "file" , "path" , "type" , "syscall" , "fstream_path" , "fstream_unc_path" , "fstream_type" , "fstream_class" , "fstream_finish_call" , "fstream_linkpath" , "code" , "errno" , "stack" , "fstream_stack" ].forEach(function (k) { var v = er[k] if (k === "stack") { if (!printStack) return if (!v) v = er.message } if (!v) return if (k === "fstream_stack") v = v.join("\n") log.error(k, v) }) exit(typeof er.errno === "number" ? er.errno : 1) }
FileManager.setupBinaries = function (alternateCDN) { return FileManager.compileBinaries_(os.type(), alternateCDN); };
.parse(process.argv); console.log('=====Environment====='.yellow); _.each(env, function(v, k){ console.log(k.yellow, ':', v); }); console.log('---------------------'.yellow); //from calling cli.js console.log(checkPrereq().msg); console.log('---------------------'.yellow); //system status check console.log('cpu(s):', String(os.cpus().length).yellow, '@', os.cpus()[0].model); var freemem = os.freemem()/1024/1024/1024, totalmem = os.totalmem()/1024/1024/1024; console.log('memory:', (_.str.numberFormat(freemem, 2)).yellow + 'GB', '/', (_.str.numberFormat(totalmem, 2).yellow + 'GB'), freemem < 0.25?'Warning: Free memory too low...'.red:''); console.log('operating system:', os.type().yellow); console.log('---------------------'.yellow); //stagejs project detection if(!env['stagejs-version']) console.log('[', 'No project found at the current directory...'.grey, ']'); else console.log('[', 'Project detected!'.green, ']'); //console.log('====================='.yellow);
var os = require('os'); var message = 'Here is some info about your system.'; var sysarray = new Array('Type: ' + os.type(), 'Node Version: '+ process.version, 'Platform: ' + os.platform(), 'Hostname: ' + os.hostname(), 'Total Memory: ' + os.totalmem(), 'Free Memory: ' + os.freemem(), 'Uptime: ' + os.uptime() ); console.log(message); for (var i = 0; i < sysarray.length; i++) { console.log(sysarray[i]); }
module.exports = (function() { var path = require('path'); var ReadLine = require('readline'); var spawn = require('child_process').spawn; var events = require('events'); var os = require('os'); var request = require('request'); var _url; var _hash; var _local; var _backend; var _running = false; var _osName = os.type(); return { startNew: function() { var eventEmitter = new events.EventEmitter(); if (_osName.startsWith('Windows')) { process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk'); process.chdir(__dirname + '/../dist'); _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command.bat'), ['--open-browser', 'false']); } else if (_osName.startsWith('Darwin')) { process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk/Contents/Home'); _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']); } else if (_osName.startsWith('Linux')) { process.env['JAVA_HOME'] = path.resolve(__dirname + '/../jdk'); _backend = spawn(path.resolve(__dirname + '/../dist/beaker.command'), ['--open-browser', 'false']); } var rl = ReadLine.createInterface({ input: _backend.stdout }); rl.on('line', function(line) { console.log(line); // Pipe backend's stdout to electron's stdout if (line.startsWith('Beaker hash')) { _hash = line.split(' ')[2]; } else if (line.startsWith('Beaker listening on')) { _url = line.split(' ')[3]; _local = true; _running = true; eventEmitter.emit('ready', { url: _url, hash: _hash, local: _local }); } }); return eventEmitter; }, kill: function() { var eventEmitter = new events.EventEmitter(); if (_local) { request(this.getUrl() + this.getHash() + '/beaker/rest/util/exit', function (error, response, body) { _running = false; eventEmitter.emit('killed'); }); } _backend = {}; return eventEmitter; }, getInfo: function() { return { url: _url, hash: _hash, local: _local, running: _running }; }, getUrl: function() { return _url; }, setUrl: function(url) { _url = url; }, getHash: function() { return _hash; }, setHash: function(hash) { _hash = hash; }, getLocal: function() { return _local; }, setLocal: function(local) { _local = local; }, isRunning: function() { return _running; } } })();