Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def main(confdir: str = "/etc/cslbot") -> None:
config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
with open(path.join(confdir, 'config.cfg')) as f:
config.read_file(f)
session = get_session(config)()
parser = argparse.ArgumentParser()
parser.add_argument('outdir', help='The directory to write logs too.')
cmdargs = parser.parse_args()
if not path.exists(cmdargs.outdir):
makedirs(cmdargs.outdir)
lockfile = open(path.join(cmdargs.outdir, '.lock'), 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
current_id = get_id(cmdargs.outdir)
new_id = session.query(Log.id).order_by(Log.id.desc()).limit(1).scalar()
# Don't die on empty log table.
if new_id is None:
new_id = 0
save_id(cmdargs.outdir, new_id)
def get_ini(path):
fn, path = path.split(':')
section, key = path.split('.')
cfg = ConfigParser(interpolation=ExtendedInterpolation())
cfg.read([fn])
try:
return cfg[section][key]
except KeyError:
raise KeyError('%s not found in %s' % (path, fn))
model['optim'] = getattr(tf.train, config.get('global', 'optim'))(model['lrate']).minimize(model['loss'], global_step = model['step'], name = 'optim')
return model
def feed(features, labelslen, labelsind, labelsval, batch_size, time_size):
feed_dict = {model['cnn_inputs']: [[features[i][:, t] if t < labelslen[i] else np.zeros(features[i][:, labelslen[i] - 1].shape, np.float32) for i in xrange(batch_size)] for t in xrange(time_size)]}
feed_dict.update({model['cnn_in2length']: [features[i].shape[1] for i in xrange(batch_size)], model['ctc_labels_len']: labelslen, model['ctc_labels_ind']: labelsind, model['ctc_labels_val']: labelsval})
return feed_dict
def handler(signum, stack):
print datetime.datetime.now(), 'saving model prematurely'
tf.train.Saver().save(sess, os.path.join(config.get('global', 'path'), 'model'))
sys.exit()
if __name__ == '__main__':
config = configparser.ConfigParser(interpolation = configparser.ExtendedInterpolation())
config.read(sys.argv[1])
print datetime.datetime.now(), 'creating model'
model = cldnn(config)
with tf.Session() as sess:
signal.signal(signal.SIGINT, handler)
if sys.argv[2] == 'init':
sess.run(tf.initialize_all_variables())
elif sys.argv[2] == 'train':
tf.train.Saver().restore(sess, os.path.join(config.get('global', 'path'), 'model'))
print datetime.datetime.now(), 'training model'
loss = speechutil.train(model, sess, config, sys.argv[3], feed)
print datetime.datetime.now(), 'trained model', loss
elif sys.argv[2] == 'test':
tf.train.Saver().restore(sess, os.path.join(config.get('global', 'path'), 'model'))
print datetime.datetime.now(), 'testing model'
% (eloc(self,"__init__"),parms)
self.parms=parms # Configuration object used by tool
self.debug=debug # Whether debug messages are enabled.
# List of configuration files used by the tool
self.files=[]
# Option/Value delimiters: = :
# Comment line prefixes: # ;
# Inline comments: #
self.parser=configparser.ConfigParser(\
delimiters=("=",":"),\
comment_prefixes=("#",";"),\
inline_comment_prefixes=("#"),\
interpolation=configparser.ExtendedInterpolation(),\
defaults=defaults)
# List of available sections, updated after each config file is read
self.sections=[] # See read_cfg() method
self.missing=[] # Requested section but missing
# Current default setting after reading a new config file
self.defaults=self.defaults() # Also, see read_cfg() method
def create_ini_config() -> configparser.ConfigParser:
"""
Standard configuration.
"""
ret = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation()
)
return ret
def main(confdir: str = "/etc/cslbot") -> None:
botconfig = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
with open(join(confdir, 'config.cfg')) as f:
botconfig.read_file(f)
conf_obj = config.Config()
conf_obj.set_main_option('bot_config_path', confdir)
with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
conf_obj.set_main_option('script_location', str(script_location))
command.upgrade(conf_obj, 'head')
# The parser doesn't add a layer of context; run it with a path= keyword to add a layer
parser = automata.dfa_post( service, initial=automata.state( 'select' ),
terminal=True )
# No config, by default (use default values). Allows ${<section>:} interpolation, and
# comments anywhere via the # symbol (this implies no # allowed in any value, due to the lack of
# support for escape symbol).
#
# If config files are desired, somewhere early in program initialization, add:
#
# Object.config_loader.read( ["", ...] )
#
config_loader = configparser.ConfigParser(
comment_prefixes=('#',), inline_comment_prefixes=('#',),
allow_no_value=True, empty_lines_in_values=False,
interpolation=configparser.ExtendedInterpolation() )
@classmethod
def register_service_parser( cls, number, name, short, machine ):
"""Registers a parser with the Object. May be invoked during import; no logging."""
assert number not in cls.service and name not in cls.service, \
"Duplicate service #%d: %r registered for Object %s" % ( number, name, cls.__name__ )
cls.service[number] = name
cls.service[name] = number
cls.transit[number] = chr( number ) if sys.version_info[0] < 3 else number
cls.parser.initial[cls.transit[number]] \
= automata.dfa( name=short, initial=machine, terminal=True )
GA_ALL_NAM = "Get Attributes All"</section>
"""
import os
import sys
import configparser
import logging
import functools
from typing import Any
getenv = os.getenv
LOGGER = logging.getLogger('SRVLOG')
CONFIG = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
def print_config( fp ):
""" print configuration to file
"""
CONFIG.write(fp)
def load_configuration():
""" Read configuration file
Load server configuration from configuration file.
"""
CONFIG.clear()
LOGGER.info('loading configuration')
def main(confdir="/etc/cslbot") -> None:
config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
with open(join(confdir, 'config.cfg')) as f:
config.read_file(f)
passwd = config['auth']['ctrlpass']
port = config['core']['serverport']
msg = '%s\nreload' % passwd
try:
proc = subprocess.run(['nc', 'localhost', port],
input=msg,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
check=True)
output = proc.stdout.splitlines()
for line in output:
print(line)
if output[-1] != "Aye Aye Capt'n":
def main():
parser = make_parser()
args = parser.parse_args()
args.server_socket = expandpath(args.server_socket)
# Set default pid file location
if not args.pid_file:
args.pid_file = "%s.pid" % args.server_socket
else:
args.pid_file = expandpath(args.pid_file)
config = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation())
config.read(args.config)
# Set default log file location
if not args.log_file:
args.log_file = "%s.log" % args.server_socket
else:
args.log_file = expandpath(args.log_file)
# Logging setup
init_logger(args)
logger.info('logging to %r', args.log_file)
if args.auto_close:
logger.debug('will auto close')
else:
logger.debug('will not auto close')