获取响应正文body
@param  {Object} config   静态服务器中间件配置
@param  {Object} stats    文件信息
@param  {String} pathname 文件路径
@return {Stream}          响应正文
974845
function getBody(context, config, stats, pathname) {
  let _stream
  // 判断是否range请求
  const hasRange = context.get('Range')
  if (hasRange) {
    let range = getRange(hasRange, stats.size)
    if (range !== -1 && range !== -2) {
      // 设置响应头
      context.set({
        'Accept-Ranges': range.AcceptRanges,
        'Content-Range': range[0].ContentRange
      })
      // 设置正文长度
      context.length = range[0].ContentLength
      context.status = 206
      _stream = fs.createReadStream(pathname, {
        start: range[0].start,
        end: range[0].end
      })
    } else {
      // 所请求的范围无法满足 (Requested Range not satisfiable)
      context.status = 416
      return
    }
  } else {
    context.length = stats.size
    _stream = fs.createReadStream(pathname)
  }
  return _stream
}
696913
function statFile(file, source) {
  return function(cb) {
    var abs = join(source, file);
    stat(abs, function(err, stats) {
      if (err) return cb(err);

      var manifest = {
        name: file,
        abs: abs,
        mtime: Math.floor(stats.mtime.getTime() / 1000),
        mode: '' + parseInt(stats.mode.toString(8), 10),
        size: '' + stats.size // do we need this?
      };

      if (stats.isDirectory()) return cb();
      if (stats.isSymbolicLink()) return fs.readlink(abs, finish('link'));
      calculateHash(abs, finish('hash'));

      function finish(key) {
        return function(err, val) {
          if (err) return cb(err);
          manifest[key] = val;
          cb(null, manifest);
        };
      }
    });
  };
}
1013939
function (config) {
  this.config  = config;
  this.backend = this.config.backend || 'stdout';
  this.level   = this.config.level || "LOG_INFO";
  if (this.backend == 'stdout') {
    this.util = require('util');
  } else {
    if (this.backend == 'syslog') {
      this.util = require('modern-syslog');
      this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
    } else {
      throw "Logger: Should be 'stdout' or 'syslog'.";
    }
  }
}
552348
function getStreams(config) {
  // Any passed in streams
  const streams = Array.isArray(config.streams)
    ? [...config.streams]
    : [];

  // Nice console output
  if (config.stdout) {
    streams.push({
      name: 'stdout',
      level: config.level,
      stream: new ClientConsoleLogger(),
      type: 'raw',
    });
  }

  // Rollbar Transport
  // Messages at the warn level or higher are transported to Rollbar
  // Detects presence of global Rollbar and passed in token
  if (isGlobalRollbarConfigured()) {
    if (config.rollbarToken) {
      streams.push({
        name: 'rollbar',
        level: 'warn',
        stream: new ClientRollbarLogger({
          token: config.rollbarToken,
          environment: config.environment,
          codeVersion: config.codeVersion,
        }),
        type: 'raw',
      });
    }
  } else {
    /* eslint-disable no-console */
    console.warn('Client rollbar is not correctly configured');
    /* eslint-enable */
  }

  // Transport client logs
  if (config.logentriesToken) {
    streams.push({
      name: 'logentries',
      level: config.level,
      stream: new ClientLogentriesLogger({
        name: config.name,
        token: config.logentriesToken,
      }),
      type: 'raw',
    });
  }

  return streams;
}
73013
function normalizeConfig(config, data) {
  const newConfig = Object.assign({}, data.callback.baseConfig, config)
  const { dest, src, watch } = newConfig
  const errors = []

  if (dest != null && typeof dest !== 'string' && typeof dest !== 'function') {
    errors.push(`- 'dest' must be a string or a function`)
  }

  if (src != null) {
    newConfig.src = toUniqueStrings(newConfig.src)
    if (newConfig.src.length === 0) {
      errors.push(`- 'src' must be a string or an array of strings`)
    }
  }

  if (watch === true) {
    if (Array.isArray(newConfig.src) && newConfig.src.length) {
      newConfig.watch = [].concat(newConfig.src)
    }
  } else if (watch) {
    newConfig.watch = toUniqueStrings(newConfig.watch)
    if (newConfig.watch.length === 0) {
      errors.push(`- 'watch' must be boolean, a string or an array of strings`)
    }
  }

  if (errors.length > 0) {
    const msg = [
      `Invalid config for '${data.name}'`,
      errors.join('\n'),
      JSON.stringify(config, null, 2)
    ].join('\n')
    handleError(new Error(msg), options.strict ? null : data.errors)
    return
  }

  return newConfig
}
718320
function ConfigReader(path) {
  const self = this;
  const fs = require('fs');
  const util = require('util');
  const yaml = require('js-yaml');
  const _ = require('lodash');
  const allowedEnvironmentVars = {
    token: 'CF_API_KEY',
    email: 'CF_API_EMAIL',
    domain: 'CF_API_DOMAIN'
  };

  const homePath = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];


  path = path ? path.replace('~', homePath) : false;
  self.readConfig = readConfig;

  function readConfig(account) {
    let config = {};
    //Load allowed environment variables
    const envConfig = _.fromPairs(
      _.filter(_.map(allowedEnvironmentVars, function (envVar, key) {
          if (process.env[envVar]) {
            return [key, process.env[envVar]];
          } else {
            return false;
          }
        }
      ), function (value) {
        return value !== false;
      })
    );
    if (path && fs.existsSync(path)) {
      try {
        const ymlConfig = yaml.safeLoad(fs.readFileSync(path, 'utf8'));
        if (ymlConfig !== undefined) {
          if (ymlConfig.defaults.account || account) {
            account = (account) ? account : ymlConfig.defaults.account;
            if (ymlConfig.accounts[account] !== undefined) {
              config = ymlConfig.accounts[account];
            } else {
              console.log(util.format('Unable to find account %s', account));
              console.log('Available accounts: ');
              _.each(ymlConfig.accounts, function (acc, name) {
                console.log(util.format(' - %s', name));
              });
              return false;
            }
          } else {
            config = ymlConfig.defaults;
          }
        } else {
          throw new Error(util.format('Unable to parse file: %s', path));
        }
      } catch (error) {
        throw new Error(util.format('Invalid config file: %s message: ', path, error.message));
      }
    }
    return _.extend(config, envConfig);
  }
}
416940
def stat(self, path=None, client_kwargs=None, header=None):
        
        # Should contain at least the strict minimum of os.stat_result
        stat = OrderedDict((
            ("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
            ("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
            ("st_mtime", 0), ("st_ctime", 0)))

        # Populate standard os.stat_result values with object header content
        header = self.head(path, client_kwargs, header)
        for key, method in (
                ('st_size', self._getsize_from_header),
                ('st_ctime', self._getctime_from_header),
                ('st_mtime', self._getmtime_from_header),):
            try:
                stat[key] = int(method(header))
            except UnsupportedOperation:
                continue

        # File mode
        if self.islink(path=path, header=header):
            # Symlink
            stat['st_mode'] = S_IFLNK
        elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
                stat['st_size']):
            # Directory
            stat['st_mode'] = S_IFDIR
        else:
            # File
            stat['st_mode'] = S_IFREG

        # Add storage specific keys
        sub = self._CHAR_FILTER.sub
        for key, value in tuple(header.items()):
            stat['st_' + sub('', key.lower())] = value

        # Convert to "os.stat_result" like object
        stat_result = namedtuple('stat_result', tuple(stat))
        stat_result.__name__ = 'os.stat_result'
        stat_result.__module__ = 'pycosio'
        return stat_result(**stat)
388047
function statAsync(path) {
  return new Promise((resolve, reject) => {
    _fs2.default.stat(path, (error, stats) => error ? reject(error) : resolve(stats));
  });
}
1213532
function formatArrayArgs(config) {
  ["ids", "tags", "add"].forEach(key => {
    if (config[key]) {
      try {
        if(key == "tags"){
          config[key] = config[key].split(",");
        }else {
          config[key] = JSON.parse(`[${config[key]}]`);
        }
      } catch (e) {
        logger.log("error",{message:`输入${key}有误，请确定输入为数字，或以','分割的数字`});
        process.exit(-1); // 直接退出进程
      }
    }
  });
}
27819
function (url) {
			var dir = path.dirname( getCurrent().docConfigDest );
			return path.join(dir,url);
		}
711175
function( fileName ) {
        // console.log('Read configuration from ' + fileName);
        var pathSep = require('path').sep;
        var inFileName = process.cwd() + pathSep + fileName;

        var config = require( inFileName );

        // TODO: validate config

        for ( var procs in config ) {
            if ( config.hasOwnProperty(procs) ) {
                config[procs].forEach(function(proc){
                    if ( proc.hasOwnProperty('fileName') ) {
                        proc.fileName = process.cwd() + pathSep + proc.fileName;
                    }
                });
            }
        }
        return config;
    }
1346194
function getConfig(config, update) {
	let configFilepath
	if (isString(config)) {
		// Load config from a given file
		configFilepath = path.resolve(process.cwd(), config)
		if (!fs.existsSync(configFilepath)) {
			throw new StyleguidistError('Styleguidist config not found: ' + configFilepath + '.')
		}
		config = {}
	} else if (!isPlainObject(config)) {
		// Try to read config options from a file
		configFilepath = findConfigFile()
		config = {}
	}

	if (configFilepath) {
		config = require(configFilepath)
	}

	if (update) {
		config = update(config)
	}

	const configDir = configFilepath ? path.dirname(configFilepath) : process.cwd()

	if (config.serverPort && isString(config.serverPort)) {
		config.serverPort = parseInt(config.serverPort)
	}

	try {
		return sanitizeConfig(config, schema, configDir)
	} catch (exception) {
		/* eslint-disable */
		console.log(exception instanceof StyleguidistError, exception.constructor.name)
		throw exception.message
	}
}
1158210
def write_config(params, config_path=None):
    
    if config_path is None:
        config_path = tempfile.mktemp(prefix="mongo-")

    cfg = params.copy()
    if 'setParameter' in cfg:
        set_parameters = cfg.pop('setParameter')
        try:
            for key, value in set_parameters.items():
                cfg['setParameter = ' + key] = value
        except AttributeError:
            reraise(RequestError,
                    'Not a valid value for setParameter: %r '
                    'Expected "setParameter": {<param name> : value, ...}'
                    % set_parameters)

    # fix boolean value
    for key, value in cfg.items():
        if isinstance(value, bool):
            cfg[key] = json.dumps(value)

    with open(config_path, 'w') as fd:
        data = '\n'.join('%s=%s' % (key, item) for key, item in cfg.items())
        fd.write(data)
    return config_path
299710
def write_stats_to_json(cls, file_name, stats):
    """"""
    params = cls._json_dump_options(stats)
    mode = 'w' if PY3 else 'wb'
    try:
      safe_file_dump(file_name, params, mode=mode)
    except Exception as e: # Broad catch - we don't want to fail in stats related failure.
      print('WARNING: Failed to write stats to {} due to Error: {}'.format(file_name, e),
            file=sys.stderr)
824742
function getTemplates(config) {

  var templates = {};

  Object.keys(templatePaths).forEach(function(key) {
      if (config.templates && (config.templates[key] && config.templates[key] !== true)) {
        templates[key] = config.templates[key];
      } else {
        templates[key] = fs.readFileSync(__dirname + templatePaths[key], "utf-8");
      }
    });

  return templates;
}
251861
function loadConfigFile(configPath) {
	logger.debug('Loading configuration file at:', configPath);

	function loadConfig() {
		return fs.readFileSync(configPath, { encoding: 'utf8' });
	}

	function parseConfig(content, extension) {
		switch (extension) {
		case '.js':
			return require(configPath);

		case '.yaml':
			return jsYaml.safeLoad(content, { filename: configPath });

		case '.json':
			try {
				return JSON.parse(content);
			} catch (error) {
				// Try to provide more specific syntax errors
				lintJson(content);

				// If no syntax errors are found, throw a generic error
				throw new Error('There was a problem loading a configuration file: ' + configPath);
			}

		case '.json5':
			return JSON5.parse(content);

		default:
			throw new Error(`Configuration file is an unsupported type [${supportedTypes.join(', ')}]: ` + configPath);
		}
	}

	var extension = path.extname(configPath);
	var content;

	try {
		content = loadConfig();
	} catch (error) {
		throw new ConfigurationError('Failed to read configuration file', configPath, error);
	}

	try {
		return parseConfig(content, extension);
	} catch (error) {
		throw new ConfigurationError('Failed to parse configuration file', configPath, error);
	}
}
458449
function (config) {

    // check parameters
    if ((typeof config.IN_PORT !== 'number' && 
        typeof config.OUT_PORT !== 'number')) {
    
        LOG.warn('config needs to define parameters: IN_PORT or OUT_PORT');
        return; 
    }
	
	var server_type = config.type || 'MPEG';

    var STREAM_SECRET = config.secret;
		IN_PORT = config.IN_PORT || 8082,
		OUT_PORT = config.OUT_PORT || 8084,
		STREAM_MAGSR_BYTES = 'jsmp'; // Must be 4 bytes
		
	// channel info
	var l_channels = {};
        
    var socketServer = undefined;
    var streamServer = undefined;

    this.start = function () {
    
        // Websocket Server
        socketServer = new (require('ws').Server)({port: OUT_PORT});
		
		// process incoming connection of subscribers
        socketServer.on('connection', function (socket) {

			// generate unique clientID
			var clientID = UTIL.createUUID();
			var clientData = socketServer.clients[socketServer.clients.length - 1];
			
			var channel = undefined;
			LOG.sys( 'New WebSocket Connection (' + socketServer.clients.length + ' total) id: ' + clientID );
					 
			// we start to handle after receiving channel name to subscribe
			// NOTE: the incoming content is not string type
			socket.on('message', function (name) {

                try {
 
                    /*
					var obj = JSON.parse(name.data);
					LOG.warn(obj);
					*/
                    
					// extract info
					if (l_channels.hasOwnProperty(name) === false) {
						var msg = 'no stream registered for channel [' + name + ']';
						LOG.warn(msg);
						socket.send(msg);
						return;
					}
					
					// record channel name
					channel = name;
					
					// get parameters
					var params = l_channels[channel].para;
		        
					// NOTE: we convert string to numbers with | 0			
					var width = (params[0] || 320) | 0;
					var height = (params[1] || 240) | 0;
					
					LOG.warn('params:');
					LOG.warn(params);
					LOG.warn('client to receive channel: ' + channel + ' w: ' + width + ' h: ' + height);
                
					// record this user's reference as part of the channel subscribers
					// NOTE: we record clientData, not socket
					l_channels[channel].users[clientID] = clientData;   
					
					LOG.warn('channel [' + channel + '] has ' + Object.keys(l_channels[channel].users).length + ' users', 'message');
					
					// Send back magic bytes and video size to the newly connected socket
					// struct { char magic[4]; unsigned short width, height;}
					var streamHeader = new Buffer(8);
					streamHeader.write(STREAM_MAGSR_BYTES);
					streamHeader.writeUInt16BE(width, 4);
					streamHeader.writeUInt16BE(height, 6);
					socket.send(streamHeader, {binary:true}); 
                
                }
                catch(e) {
                    LOG.error(e);
                }    
			});
			
			// handles closing in-coming connection
			socket.on('close', function (code, message) {
				LOG.sys( 'Disconnected WebSocket (' + socketServer.clients.length + ' total)' );
				
				// remove user record (i.e., socket) from channel
				if (l_channels.hasOwnProperty(channel)) {		
					delete l_channels[channel].users[clientID];
					LOG.warn('client [' + clientID + '] unsubscribe from channel [' + channel + ']');
				}
			});
        });
    
        socketServer.broadcast = function (channel, data, opts) {
		
			// go over all clients for a given channel
			if (l_channels.hasOwnProperty(channel) === false) {
				LOG.warn('channel [' + channel + '] not registered, cannot broadcast');
				return;
			}
			//LOG.warn('channel [' + channel + '] has ' + Object.keys(l_channels[channel].users).length + ' users', 'broadcast');
			
			var clients = l_channels[channel].users;
			
			for (var id in clients) {
				
				try {
					//this.clients[i].send(data, opts);
					clients[id].send(data, opts);
				}
				catch(e) {
					LOG.warn('client[' + id + '] fails to send to channel [' + channel + ']');
				}
			}
        };
    
        // HTTP Server to accept incoming MPEG Stream
        streamServer = require('http').createServer(function (request, response) {
			var params = request.url.substr(1).split('/');			
			var channel = params[0];
        
			if (channel) {
				LOG.sys(
					'Stream Connected: ' + request.socket.remoteAddress + 
					':' + request.socket.remotePort + ' channel: ' + channel
				);
				
				//' size: ' + width + 'x' + height
				
				
				// remove first element (channel name) and store the rest as parameters
				params.splice(0, 1);
				l_channels[channel] = {
					para: params,		// app-specific parameters in string array format
					users: {}			// user clients conneted awating message updates
				}
				
				request.on('data', function(data) {
					if (socketServer)
						socketServer.broadcast(channel, data, {binary:true});
				});
			}
			else {
				LOG.sys(
					'failed connection: '+ request.socket.remoteAddress + 
					request.socket.remotePort + ' - no channel specified.'
				);
				response.end();
			}
        }).listen(IN_PORT);
    
        LOG.warn('Listening for stream on http://'+ SR.Settings.SERVER_INFO.IP +':'+IN_PORT+'/<channel>/<para1>/<para2>/<para3>/...', 'SR.Stream');
        LOG.warn('Awaiting WebSocket connections on ws://' + SR.Settings.SERVER_INFO.IP + ':'+OUT_PORT+'/', 'SR.Stream');
    }
    
    this.stop = function () {

        if (socketServer) {
            socketServer.close();
        }
        
        if (streamServer) {
            streamServer.close();
        }
    }
    
}