def version(self, extended=False): """ What version is cobbler? If extended == False, returns a float for backwards compatibility If extended == True, returns a dict: gitstamp -- the last git commit hash gitdate -- the last git commit date on the builder machine builddate -- the time of the build version -- something like "1.3.2" version_tuple -- something like [ 1, 3, 2 ] """ config = ConfigParser() config.read("/etc/cobbler/version") data = {} data["gitdate"] = config.get("cobbler","gitdate") data["gitstamp"] = config.get("cobbler","gitstamp") data["builddate"] = config.get("cobbler","builddate") data["version"] = config.get("cobbler","version") # dont actually read the version_tuple from the version file data["version_tuple"] = [] for num in data["version"].split("."): data["version_tuple"].append(int(num)) if not extended: # for backwards compatibility and use with koan's comparisons elems = data["version_tuple"] return int(elems[0]) + 0.1*int(elems[1]) + 0.001*int(elems[2]) else: return data
def getBoards(): res = [] config = ConfigParser.RawConfigParser() config.read("BOARDS") for i in config.sections(): res.append([i, config.get(i, "size")]) return res
def init(): """Prepares deterministicpwgen for generating passwords.""" if not config.config_file_exists(): config.create_config_file() ap = ArgumentParser(description="Generate passwords with a seed.") ap.add_argument("--charset", "-c", default=config.read("charset"), help="Define a custom charset for the generator.") ap.add_argument("--hide-seed", "-s", action="store_true", default=bool(config.read("hide-seed")), help="Hide the seed when it's being typed.") ap.add_argument("--length", "-l", default=config.read("length"), type=int, help="The length of the generated password.") ap.add_argument("--keyfile", "-k", default=config.read("keyfile"), help="Use a keyfile?") ap.add_argument("--password", "-p", default=config.read("password"), help="Use a password?") args = ap.parse_args() print "\n", # Perform various setup tasks. setup_charset(args.charset) global hide_seed; hide_seed = args.hide_seed global length; length = args.length get_keyfile(args.keyfile) get_password(args.password)
def Admin(self, handler, query): #Read config file new each time in case there was any outside edits config = ConfigParser.ConfigParser() config.read(config_file_path) shares_data = [] for section in config.sections(): if not(section.startswith('_tivo_') or section.startswith('Server')): if not(config.has_option(section,'type')): shares_data.append((section, dict(config.items(section, raw=True)))) elif config.get(section,'type').lower() != 'admin': shares_data.append((section, dict(config.items(section, raw=True)))) subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'settings.tmpl')) t.container = cname t.server_data = dict(config.items('Server', raw=True)) t.server_known = buildhelp.getknown('server') t.shares_data = shares_data t.shares_known = buildhelp.getknown('shares') t.tivos_data = [ (section, dict(config.items(section, raw=True))) for section in config.sections() \ if section.startswith('_tivo_')] t.tivos_known = buildhelp.getknown('tivos') t.help_list = buildhelp.gethelp() handler.wfile.write(t)
def __init__(self, model_path, port_id, host=config.scoring_engine_host): """Set up the server location, port and model file""" self.hdfs_path = model_path self.name = host.split('.')[0] self.host = host #set port config = SafeConfigParser() filepath = os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), "port.ini")) config.read(filepath) self.port = config.get('port', port_id) self.scoring_process = None
def test_modify(self): c = config.read(StringIO.StringIO(self.sample_text())) s = c.get_section('section') s.set('foo', 'other') s.set('tst', 'blah') self.assertEqual(s['foo'], 'other') self.assertEqual(s['tst'], 'blah') stringio = StringIO.StringIO() c.write(stringio) c = config.read(StringIO.StringIO(stringio.getvalue())) s = c.get_section('section') self.assertEqual(s['foo'], 'other') self.assertEqual(s['baz'], 'quux') self.assertEqual(s['tst'], 'blah')
def test_make_section(self): c = config.read(StringIO.StringIO(self.sample_text())) s = c.make_section('section') self.assertEqual([(k,v) for k,v in s.iterentries()], []) s.set('foo', 'written') s2 = c.make_section('new') s2.set('bar', 'baz') stringio = StringIO.StringIO() c.write(stringio) c = config.read(StringIO.StringIO(stringio.getvalue())) s = c.get_section('section') self.assertItemsEqual([(k,v) for k,v in s.iterentries()], [('foo', 'written')]) s2 = c.get_section('new') self.assertItemsEqual([(k,v) for k,v in s2.iterentries()], [('bar', 'baz')])
def init_tweetbot(): global twitter if(not os.path.isfile(tweet_file)): logging.info('To enable Tweeting, add config file & restart.' + tweet_file) return try: config = RawConfigParser() config.read(tweet_file) twitter = Twython(config.get('TweetAuth','twitter_token'), config.get('TweetAuth','twitter_secret'), config.get('TweetAuth','oauth_token'), config.get('TweetAuth','oauth_token_secret')) except NoSectionError, NoOptionError: logging.error('Twitter Initialisation failed')
def __init__(self): self.config = config.read('config.json') if not 'twitch_id' in self.config: raise config.ConfigurationError( 'Setting twitch_id incorrectly configured in config.json') self.wx = wx.App() self.plugins = plugins.PluginManager() self.plugins.load('plugins/') twitch_id = self.config['twitch_id'] login = self.config['services']['chat']['login'] bot_id = login['id'] bot_oauth = login['oauth'] chat.connect(bot_id, bot_oauth, twitch_id) reactor.interleave(wx.CallAfter) pub.subscribe(self.quit, 'command.quit') self.icon = gui.Icon(self.plugins.plugins()) self.menu = gui.Menu(self.plugins.plugins()) self.wx.MainLoop()
def run(): iptables.init_fq_chains() shutdown_hook.add(iptables.flush_fq_chain) iptables.insert_rules(DNS_RULES) shutdown_hook.add(functools.partial(iptables.delete_rules, DNS_RULES)) iptables.insert_rules(SOCKS_RULES) shutdown_hook.add(functools.partial(iptables.delete_rules, SOCKS_RULES)) wifi.setup_lo_alias() try: comp_scrambler.start() shutdown_hook.add(comp_scrambler.stop) except: LOGGER.exception('failed to start comp_scrambler') comp_scrambler.stop() try: comp_shortcut.start() shutdown_hook.add(comp_shortcut.stop) except: LOGGER.exception('failed to start comp_shortcut') comp_shortcut.stop() args = [ '--log-level', 'INFO', '--log-file', '/data/data/fq.router2/log/fqsocks.log', '--ifconfig-command', '/data/data/fq.router2/busybox', '--ip-command', '/data/data/fq.router2/busybox', '--outbound-ip', '10.1.2.3', '--tcp-gateway-listen', '10.1.2.3:12345', '--dns-server-listen', '10.1.2.3:12345'] args = config.configure_fqsocks(args) if config.read().get('tcp_scrambler_enabled', True): args += ['--tcp-scrambler'] fqsocks.fqsocks.main(args)
def __init__(self): cmdln.Cmdln.__init__(self) if not os.path.exists(app.CONFIG_FILEPATH): self.config_dict = config.default() else: self.config_dict = config.read(app.CONFIG_FILEPATH)
def main(): """ --------------------------------------- WanderBits: A text-based adventure game --------------------------------------- """ description = "WanderBits: a text-based adventure game!" parser = argparse.ArgumentParser(description=description) parser.add_argument("--restore", default=None, help="previously-saved game file.") parser.add_argument("--config", default="game.yml", help="game configuration file.") parser.add_argument("--verbose", default=False, action="store_true", help="display information while running.") # Parse command line arguments. args = parser.parse_args() # Load data from config files. try: game_info = config.read(args.config) except IOError as e: print(e.message) return # Start the game. try: E = executive.Executive(game_info, verbose=args.verbose) E.start() except errors.GameError as e: print(e.message)
def test_remove_section(self): c = config.read(StringIO.StringIO(self.sample_text())) s = c.make_section('other') s.set('x', 'y') c.remove_section('other') self.assertEqual([name for name, section in c.itersections()], ['section']) s = c.get_section('section') self.assertItemsEqual([(k,v) for k,v in s.iterentries()], [('foo', 'bar'), ('baz', 'quux')])
def set_from_config(kwargs): if kwargs["config"] is None: config_path = config.path() else: config_path = kwargs["config"] kwargs["config_path"] = config_path kwargs["config"] = config.read(kwargs["config_path"]) keys = {"paths": [("prefs", "prefs_root", True), ("run_info", "run_info", True)], "web-platform-tests": [("remote_url", "remote_url", False), ("branch", "branch", False), ("sync_path", "sync_path", True)], "SSL": [("openssl_binary", "openssl_binary", True), ("certutil_binary", "certutil_binary", True), ("ca_cert_path", "ca_cert_path", True), ("host_cert_path", "host_cert_path", True), ("host_key_path", "host_key_path", True)]} for section, values in keys.iteritems(): for config_value, kw_value, is_path in values: if kw_value in kwargs and kwargs[kw_value] is None: if not is_path: new_value = kwargs["config"].get(section, config.ConfigDict({})).get(config_value) else: new_value = kwargs["config"].get(section, config.ConfigDict({})).get_path(config_value) kwargs[kw_value] = new_value kwargs["test_paths"] = get_test_paths(kwargs["config"]) if kwargs["tests_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["tests_path"] = kwargs["tests_root"] if kwargs["metadata_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["metadata_path"] = kwargs["metadata_root"] if kwargs.get("manifest_path"): if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["manifest_path"] = kwargs["manifest_path"] kwargs["suite_name"] = kwargs["config"].get("web-platform-tests", {}).get("name", "web-platform-tests") check_paths(kwargs)
def init(self): self.say(["notice", "-== "], ["error", "Welcome to Aires!"], ["notice", " ==-"]) # TODO: load core config files # Load bot config files. self.say(["error", "== "], ["notice", "Reading chatterbot settings"], ["error", " =="]) for cfg in config.list("bots"): self.say(["error", ":: "], "Read: %s" % cfg) bot = re.sub(r"\.json$", "", cfg) self._bots[bot] = config.read("bots/" + cfg) # Initialize the brains. self.say(["error", "== "], ["notice", "Initializing chatterbot brains"], ["error", " =="]) for bot in sorted(self._bots): brain = self._bots[bot]["brain"]["name"] args = self._bots[bot]["brain"]["args"] self.say(["error", ":: "], 'Loading brain "%s" for bot "%s"' % (brain, bot)) # Dynamically import and load the brain. cls = self._dyn_import("aires.brains." + brain, brain) self._brains[bot] = cls(self, args) # Initialize the listeners. self.say(["error", "== "], ["notice", "Initializing chatterbot listeners (mirrors)"], ["error", " =="]) for bot in sorted(self._bots): for listener, largs in self._bots[bot]["listeners"].iteritems(): # Skip inactive listeners. if largs["active"] != True: continue # Import the listener module. cls = self._dyn_import("aires.listeners." + listener, listener) # Initialize all the mirrors. for mirror in largs["mirrors"]: username = mirror["username"] uid = self.format_name(listener, username) self.say("\tCreating mirror: " + uid) # Map the agent name to the bot. self._agents[uid] = bot # Initialize the listener for this mirror. self._mirrors[uid] = cls(self, uid, bot, mirror) self._mirrors[uid].handlers() # Does this mirror use Twisted? if self._mirrors[uid].is_twisted(): self._twisted = True
def SaveNPL(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) if 'tivo_mak' in query: config.set(query['Container'][0], 'tivo_mak', query['tivo_mak'][0]) if 'togo_path' in query: config.set(query['Container'][0], 'togo_path', query['togo_path'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'redirect.tmpl')) t.container = cname t.time = '2' t.url = '/TiVoConnect?last_page=NPL&Command=Reset&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'pyTivo will now do a <b>Soft Reset</b> to allow these changes to take effect.'+\ '<br> The <a href="/TiVoConnect?last_page=NPL&Command=Reset&Container='+ cname +'"> Reset</a> will occur in 2 seconds.' handler.wfile.write(t)
def set_from_config(kwargs): if kwargs["config"] is None: config_path = config.path() else: config_path = kwargs["config"] kwargs["config_path"] = config_path kwargs["config"] = config.read(kwargs["config_path"]) kwargs["test_paths"] = OrderedDict() keys = { "paths": [("serve", "serve_root", True), ("prefs", "prefs_root", True), ("run_info", "run_info", True)], "web-platform-tests": [ ("remote_url", "remote_url", False), ("branch", "branch", False), ("sync_path", "sync_path", True), ], } for section, values in keys.iteritems(): for config_value, kw_value, is_path in values: if kw_value in kwargs and kwargs[kw_value] is None: if not is_path: new_value = kwargs["config"].get(section, {}).get(config_value) else: new_value = kwargs["config"].get(section, {}).get_path(config_value) kwargs[kw_value] = new_value # Set up test_paths for section in kwargs["config"].iterkeys(): if section.startswith("manifest:"): manifest_opts = kwargs["config"].get(section) url_base = manifest_opts.get("url_base", "/") kwargs["test_paths"][url_base] = { "tests_path": manifest_opts.get_path("tests"), "metadata_path": manifest_opts.get_path("metadata"), } if kwargs["tests_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["tests_path"] = kwargs["tests_root"] if kwargs["metadata_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["metadata_path"] = kwargs["metadata_root"]
def main(): options = config.read() logger.info("Running with options %s", options) env = gym.make(options.environment_name) env.reset() # TODO: dimensions shouldn't be hard coded, they can come from the env agent = ContinuousAgent(options, 24, 4) agent.initialize() if options.test_network: logger.action_space("Action space: %s", env.action_space) logger.action_space("Observation space: %s", env.observation_space) action = agent.act(TEST_SPACE_ARRAY) print(action) else: run_training(agent, env, options)
def test_makers(self): c = config.File() s1 = c.make_section('sec1') s1.set('0', '0') s1.set('1', '1') s2 = c.make_section('sec2') s2.set('a', 'a') s2.set('b', 'b') self.assertItemsEqual([(k,v) for k,v in s1.iterentries()], [('0', '0'), ('1', '1')]) self.assertItemsEqual([(k,v) for k,v in s2.iterentries()], [('a', 'a'), ('b', 'b')]) stringio = StringIO.StringIO() c.write(stringio) c = config.read(StringIO.StringIO(stringio.getvalue())) s1 = c.get_section('sec1') s2 = c.get_section('sec2') self.assertItemsEqual([(k,v) for k,v in s1.iterentries()], [('0', '0'), ('1', '1')]) self.assertItemsEqual([(k,v) for k,v in s2.iterentries()], [('a', 'a'), ('b', 'b')])
def pop(path): M = poplib.POP3(pop3_server) M.user(user_name) M.pass_(password) # 设置为1,可查看向pop3服务器提交了什么命令 #M.set_debuglevel(1) # 获取欢迎消息 serverWelcome = M.getwelcome() print serverWelcome # 获取一些统计信息 emailMsgNum, emailSize = M.stat() #print 'email number is %d and size is %d'%(emailMsgNum, emailSize) # 遍历邮件,并打印出每封邮件的标题 for i in range(emailMsgNum): m = M.retr(i+1) buf = cStringIO.StringIO() for piece in m[1]: print >>buf,piece buf.seek(0) for piece in m[1]: #print piece if piece.startswith('From'): addrfrom = str(piece) try: addrfrom.index(config.read('pop', 'addr')) start_addr = addrfrom.index('<') end_addr = addrfrom.index('>') flag = 1 #print addrfrom[start_addr + 1 : end_addr] except ValueError: flag = 0 #print '\t' + piece continue break #if piece.startswith('Subject'): #print '\t' + piece #if piece.startswith('Date'): #print '\t' + piece if (flag == 1): mail_message = email.message_from_file(buf) parseEmail(mail_message,path) M.quit()
def getOptions(_input): _commandlineOptions = [] _configOptions = [] try: if len(_input) > 0: _commandlineOptions,_remainder = getopt.getopt(_input, "f:i:o:vl:c:h,r:,t:,x:,y:",\ ['filter=',\ 'input=',\ 'output=',\ 'verbose',\ 'language=',\ 'config=',\ 'help',\ "chart=",\ "charttype=",\ "chartwidth=",\ "chartheight=",\ "curesecReport=",\ "projectName=",\ "clientName=",\ "clientAddress=",\ "author=",\ "authorAddress=",\ "dateStart=",\ "dateEnd="]) validate_input(_commandlineOptions) # get arguments from config file and revalidate # commandline settings are NOT overwritten _configOptions = config.read(inputOptions['config_file']) _configOptions.extend(_commandlineOptions) validate_input(_configOptions) return inputOptions except Exception as e: print(e) usage.showUsage() return False
def set_from_config(kwargs): if kwargs["config"] is None: kwargs["config"] = config.path() kwargs["config"] = config.read(kwargs["config"]) keys = {"paths": [("tests", "tests_root", True), ("metadata", "metadata_root", True)], "web-platform-tests": [("remote_url", "remote_url", False), ("branch", "branch", False), ("sync_path", "sync_path", True)]} for section, values in keys.iteritems(): for config_value, kw_value, is_path in values: if kw_value in kwargs and kwargs[kw_value] is None: if not is_path: new_value = kwargs["config"].get(section, {}).get(config_value, None) else: new_value = kwargs["config"].get(section, {}).get_path(config_value) kwargs[kw_value] = new_value
def set_from_config(kwargs): if kwargs["config"] is None: config_path = config.path() else: config_path = kwargs["config"] kwargs["config_path"] = config_path kwargs["config"] = config.read(kwargs["config_path"]) keys = {"paths": [("serve", "serve_root", True), ("prefs", "prefs_root", True), ("run_info", "run_info", True)], "web-platform-tests": [("remote_url", "remote_url", False), ("branch", "branch", False), ("sync_path", "sync_path", True)]} for section, values in keys.iteritems(): for config_value, kw_value, is_path in values: if kw_value in kwargs and kwargs[kw_value] is None: if not is_path: new_value = kwargs["config"].get(section, {}).get(config_value) else: new_value = kwargs["config"].get(section, {}).get_path(config_value) kwargs[kw_value] = new_value kwargs["test_paths"] = get_test_paths(kwargs["config"]) if kwargs["tests_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["tests_path"] = kwargs["tests_root"] if kwargs["metadata_root"]: if "/" not in kwargs["test_paths"]: kwargs["test_paths"]["/"] = {} kwargs["test_paths"]["/"]["metadata_path"] = kwargs["metadata_root"]
import config from flask import Flask, jsonify, redirect, render_template, request, url_for from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy from pathlib import Path conf = config.read(Path.home() / '.kyak') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = conf.database app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ma = Marshmallow(app) class Account(db.Model): __tablename__ = 'accounts' id = db.Column(db.String(), primary_key=True) name = db.Column(db.String(), nullable=False) type = db.Column(db.String(), nullable=False) email = db.Column(db.String(), nullable=True) address = db.Column(db.String(), nullable=True) class AccountSchema(ma.ModelSchema): class Meta: model = Account @app.route('/')
def __init__(self): self.socket_file = config.read('socket-file', '/tmp/.vmailmgrd') self.socket = None
def test_read(self): c = config.read(StringIO.StringIO(self.sample_text())) s = c.get_section('section') self.assertEqual(s['foo'], 'bar') self.assertEqual(s['baz'], 'quux') self.assertFalse('none' in s)
import configparser import inspect import model, data, dataset, config, test def maskBig(x, target, threshold): y = x * (target - 0.5) x[y > threshold] = 0.0 return x if __name__ == '__main__': #parser.add_argument('-save', type=str, default = './checkpoint/test/', help='place to save') _path = '' #'/content/drive/My Drive/Colab Notebooks/myblast/' config = configparser.ConfigParser() config.read(_path + 'mixed_23341.ini') #gpu_tracker.track() encoder = model.get_encoder(config, "M").cuda() discriminator = model.get_discriminator(config).cuda() generator = model.get_generator(config).cuda() encoder = encoder.cpu() encoder = encoder.cuda() #classifier = model.get_classifier(config).cuda() #gpu_tracker.track() #optimC = optim.Adam(classifier.parameters(), lr=config.getfloat('training', 'lr')) optimE = optim.Adam(encoder.parameters(), lr=config.getfloat('training', 'lr') * 0.01) optimG = optim.Adam(generator.parameters(), lr=config.getfloat('training', 'lr')) optimD = optim.Adam(discriminator.parameters(), lr=config.getfloat('training', 'lr'))
i+=1 if res and 'name' in res: print("total_num:%s" % i,id) print(updata(res,'ah')) else: print(res) if __name__=="__main__": #dbinfo ={'host':'192.168.10.126','port':3306,'dbname':'gov_corp', # 'user':'******','passwd':'wbsp','charset':'utf8'} #check_exist_corp('js') config.read('./conf/worker.conf') mysqlwrap.setup_db('default',config.CONFIG['mysqld']) THREAD_COUNT = 10 import sys sys.path.append(sys.path[0]+'/modules') import anhui #rediswrap.setup_redis('default','192.168.10.126',6380) wk = Thread(target=doworke) wk.start() while True: time.sleep(3)
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options chrome_options = Options() driver = webdriver.Chrome( executable_path= 'C:\\Users\\jakel\\OneDrive\\Desktop\\Lamers-McKean\\Selenium\\chromedriver', chrome_options=chrome_options) config = ConfigParser() config.read('config.ini') def LoginMethod(driver, config): driver.get(config['config']['WEBSITE_URL']) user_name = driver.find_element_by_name('username') password = driver.find_element_by_name('password') user_name.send_keys(config['config']['username']) password.send_keys(config['config']['password']) driver.find_element_by_xpath( '/html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[1]/form[1]/footer[1]/div[1]/button[1]' ).click()
def load_config(self): self.cfg, self.launcher, self.drawer = config.read(self.cfg_file) ## If intellihide and wnck loaded if self.cfg['auto_hide'] == 2 and not self.wnck: # no wnck module ? fallback to autohide core.logINFO('intellihide : no wnck module found .. fallback to autohide', 'bar') self.cfg['auto_hide'] = 1 self.wnck = None self.zoom_size = self.cfg['icon_size'] * self.cfg['zoom_factor'] * 1.0 # timer for leave_bar callback self.timer_auto_hide = None # timer for smooth_hidding self.timer_smooth_hide = None # use for animate hiding self.moving = False self.count = 0 self.countdown = 0 self.timer_anim = None # middle click - Toggle always visible self.always_visible = False # launcher ( for mouseover/click ) self.focus = None self.widget_pressed = False self.anim = 1 self.fade = True self.anim_cpt = 0 self.anim_flag = True # flag for plugin self.opened_popup = None self.lock_auto_hide = False ## convert color hex->rgb self.cfg['bg_color_rgb'] = core.hex2rgb(self.cfg['background_color']) self.cfg['border_color_rgb'] = core.hex2rgb(self.cfg['border_color']) self.cfg['bg_color_sub_rgb'] = core.hex2rgb(self.cfg['bg_color_sub']) self.cfg['border_color_sub_rgb'] = core.hex2rgb(self.cfg['border_color_sub']) self.cfg['bg_gradient_color_rgb'] = core.hex2rgb(self.cfg['background_gradient_color']) self.pixbuf_glow = gtk.gdk.pixbuf_new_from_file('images/pixmaps/button.png') self.pixbuf_pressed = gtk.gdk.pixbuf_new_from_file('images/pixmaps/launcher.png') ## Create main bar self.create_bar() self.set_below_or_above() ## tooltip if self.tooltip: self.tooltip.destroy() self.tooltip = None if self.cfg['tooltips']: self.tooltip = ui.TooltipWindow(self) # create a new plugin manager self.plg_mgr = PluginManager(self) # and start to pack plugin .. for ind in self.cfg['ind_launcher']: self.plg_mgr.append(ind, self.launcher[ind]) self.plg_mgr.run() # start bar callback self.init_bar_callback() ## FIXME! ## gtk.Window doesn't stick after reload config ?! self.win.realize() self.win.stick() self.reposition() self.win.show_all() # init all plugins self.plg_mgr.on_init() ## FIXME!! # sometimes reposition doesn't work :/ .. quick hack gobject.timeout_add(500, self.reposition) if DEBUG and not 1: for index in self.plg_mgr.index: print ('------------------------------------') for val in self.plg_mgr.plugins[index].settings: print ('%s = %s' % (val, self.plg_mgr.plugins[index].settings[val])) print ('widget :', self.plg_mgr.plugins[index]) print ('index :', self.plg_mgr.plugins[index].index) print ('------------------------------------\n')
parser = optparse.OptionParser() parser.add_option("-c", "--config", dest="configfile", default="$VODKA_HOME/etc/$VODKA_CONFIGFILE", help="path to a vodka config file with couchbase bucket information. Defaults to $VODKA_HOME/etc/$VODKA_CONFIGFILE") parser.add_option("-u", "--user-id", dest="user_id", help="permissions will get updated for the specified user (id)") parser.add_option("-m", "--modules", dest="modules", help="permission will get updated for these modules - separated by ,") parser.add_option("-l", "--level", dest="level", default="0", help="permissions will be updated to this level (r = read, w = write, p = deny / purge entry from database. You may chain these flags together, eg. rw or rwx") parser.add_option("--purge", dest="purge", action="store_true", help="Remove all permission entries for the specified user") parser.add_option("--check", dest="check_perms", action="store_true", help="List the user's permissions for the specified modules") parser.add_option("-f", "--force", dest="force", action="store_true", help="Action will be forced regardless of any concerns") parser.add_option("-p", "--pretend", dest="pretend", action="store_true") (options, args) = parser.parse_args() configfile = os.path.expandvars(options.configfile) config = ConfigParser.RawConfigParser() config.read(configfile) print "Read config from file: %s" % configfile man = module_manager.ModuleManager() couch_engine = dict(config.items("server")).get("couch_engine", "couchdb") couch_config = config.items(couch_engine) man.set_database( twentyc.database.ClientFromConfig( couch_engine, couch_config, "modules" ) ) if config.has_option("xbahn", "username") and config.has_option("xbahn", "password"): xbahn_user = config.get("xbahn", "username") xbahn_pass = config.get("xbahn", "password")
import config import os app = config.connex_app app.add_api('swagger.yml') basedir = os.path.abspath(os.path.dirname(__file__)) @app.route('/') def home(): return render_template('index.html') @app.route('/edit') def edit(): return render_template('edit.html') @app.route('/conf.pp') def var(): return send_file(os.path.join(basedir, 'templates/conf.pp')) if __name__ == '__main__': config = configparser.ConfigParser() config.read(os.path.join(basedir, 'config.ini')) app.run(ssl_context=(os.path.join(basedir, 'ssl/cert.pem'), os.path.join(basedir, 'ssl/key.pem')), host=str(config['DEFAULT']['Bind']), port=str(config['DEFAULT']['Port']))
import json import time import config obj = config.read() config = obj['config'] pattern = '%Y %m %d' def find_month(): tmonth = time.strftime('%m').lstrip('0') if int(time.strftime('%d')) < 10: tmonth = tmonth - 1 return obj['miles_map'][time.strftime("%Y")][tmonth] try: f = open('miles.json', 'r+') except Exception, e: f = open('miles.json', 'a+') try: text = f.read() data = json.loads(text) except Exception, e: data = [{"last_mile": 0, "datetime": time.strftime(pattern)}]
import config import utils __author__ = "Sreejith Sreekumar" __email__ = "*****@*****.**" __version__ = "0.0.1" cfg = config.read() filter_string = cfg.get("archive", "filters") utils.get_urls_from_filters(filter_string)
import requests import json import config import pandas as pd import create_db import configparser config = configparser.ConfigParser() config.read('config_test.ini') def ticket_updation(df): for i in range(len(df)): # config.logger.info('Fetching ticket') inc_id = df.iloc[i]['Incident ID'] data = { "input_data": json.dumps({ "request": { "status": { "name": "Resolved" }, 'status_change_comments': "Issue has been successfully resolved" } }) } URL = URL = config["DEFAULT"]["api link"] + str(inc_id) header = {"Authtoken": config["DEFAULT"]["token"]} r1 = requests.put(url=URL, verify=False, headers=header, data=data) # config.logger.info('Ticket status changed') return r1.json()
def __init__(self, *args): QTGUI.QMainWindow.__init__(*(self, ) + args) self.config = config.read() self.resize(1000, 600) self.setWindowTitle(NAME) self.debug_dialog = None self.debug_lines = [] self.about_dialog = None self.connection_dialog = None # network self.network = Network() self.network.statusChanged.connect(self._network_status_changed) self.network.messageFromWeechat.connect(self._network_weechat_msg) # list of buffers self.list_buffers = BufferListWidget() self.list_buffers.currentRowChanged.connect(self._buffer_switch) # default buffer self.buffers = [Buffer()] self.stacked_buffers = QTGUI.QStackedWidget() self.stacked_buffers.addWidget(self.buffers[0].widget) # splitter with buffers + chat/input splitter = QTGUI.QSplitter() splitter.addWidget(self.list_buffers) splitter.addWidget(self.stacked_buffers) self.setCentralWidget(splitter) if self.config.getboolean('look', 'statusbar'): self.statusBar().visible = True # actions for menu and toolbar actions_def = { 'connect': [ 'network-connect.png', 'Connect to WeeChat', 'Ctrl+O', self.open_connection_dialog ], 'disconnect': [ 'network-disconnect.png', 'Disconnect from WeeChat', 'Ctrl+D', self.network.disconnect_weechat ], 'debug': [ 'edit-find.png', 'Debug console window', 'Ctrl+B', self.open_debug_dialog ], 'preferences': [ 'preferences-other.png', 'Preferences', 'Ctrl+P', self.open_preferences_dialog ], 'about': ['help-about.png', 'About', 'Ctrl+H', self.open_about_dialog], 'save connection': [ 'document-save.png', 'Save connection configuration', 'Ctrl+S', self.save_connection ], 'quit': ['application-exit.png', 'Quit application', 'Ctrl+Q', self.close], } self.actions = {} for name, action in list(actions_def.items()): self.actions[name] = QTGUI.QAction( QTGUI.QIcon( resource_filename(__name__, 'data/icons/%s' % action[0])), name.capitalize(), self) self.actions[name].setStatusTip(action[1]) self.actions[name].setShortcut(action[2]) self.actions[name].triggered.connect(action[3]) # menu self.menu = self.menuBar() menu_file = self.menu.addMenu('&File') menu_file.addActions([ self.actions['connect'], self.actions['disconnect'], self.actions['preferences'], self.actions['save connection'], self.actions['quit'] ]) menu_window = self.menu.addMenu('&Window') menu_window.addAction(self.actions['debug']) menu_help = self.menu.addMenu('&Help') menu_help.addAction(self.actions['about']) self.network_status = QTGUI.QLabel() self.network_status.setFixedHeight(20) self.network_status.setFixedWidth(200) self.network_status.setContentsMargins(0, 0, 10, 0) self.network_status.setAlignment(QTCORE.Qt.AlignRight) if hasattr(self.menu, 'setCornerWidget'): self.menu.setCornerWidget(self.network_status, QTCORE.Qt.TopRightCorner) self.network_status_set(self.network.status_disconnected) # toolbar toolbar = self.addToolBar('toolBar') toolbar.setToolButtonStyle(QTCORE.Qt.ToolButtonTextUnderIcon) toolbar.addActions([ self.actions['connect'], self.actions['disconnect'], self.actions['debug'], self.actions['preferences'], self.actions['about'], self.actions['quit'] ]) self.buffers[0].widget.input.setFocus() # open debug dialog if self.config.getboolean('look', 'debug'): self.open_debug_dialog() # auto-connect to relay if self.config.getboolean('relay', 'autoconnect'): self.network.connect_weechat( self.config.get('relay', 'server'), self.config.get('relay', 'port'), self.config.getboolean('relay', 'ssl'), self.config.get('relay', 'password'), self.config.get('relay', 'lines')) self.show()
#------------------------------------------------------------------------------- # #------------------------------------------------------------------------------- if __name__ == '__main__': wxflore_bin_path = os.path.join(os.path.split(os.path.abspath(__file__))[0],"..","wxflore-x.x") sys.path.append(wxflore_bin_path) import mkthumb options = OPTIONS() parse_argv(options) if os.getenv("HOME") == None: options.home = os.getenv("HOMEPATH")#.decode(sys.stdout.encoding) else: options.home = os.getenv("HOME")#.decode(sys.stdout.encoding) options.wxflore = os.path.join(options.home,".wxflore") if options.local: options.img = os.getcwd() else: import config config.read(options) mkthumb.mkthumb(options) if options.duplicates: mkthumb.check_all_duplicate(options)
import subprocess import os import shutil import time import threading import logging import config print("Welcome to automated server backup script!\n-- Written by James 'Joey' Ellerbee") config.read() process = None processOpen = False ignoreTimedBackup = False beginThread = True #begin functions def beginServer(mcdir): '''function contains logic to start server and to continue communicating with it.''' os.chdir(mcdir) #java is in system path so using 'java' works when invoking the server.jar return subprocess.Popen(['java', '-Xmx4G', '-Xms4G', '-jar', 'server.jar', 'nogui'], stdin = subprocess.PIPE) def commandServer(process, cmd): '''this function writes the command to the input stream the accepting input on''' process.stdin.write(bytes(cmd,'utf-8')) def debugCurrentDir(): '''this function prints the current directory, used for debugging purposes''' cwd = os.getcwd() print("current directory: ", cwd)
def vacuum(self): for x, in self._query_all("SELECT DISTINCT list.listid FROM list LEFT JOIN map ON (map.listid = list.listid) WHERE map.listid IS NULL", ()): self.conn.execute("DELETE FROM list WHERE listid = ?", (x,)) for x, in self._query_all("SELECT DISTINCT key.keyid FROM key LEFT JOIN map ON (key.keyid = map.keyid) WHERE map.keyid IS NULL", ()): self.conn.execute("DELETE FROM key WHERE key.keyid = ?", (x,)) for x, in self._query_all("SELECT DISTINCT obj.objid FROM obj LEFT JOIN map ON (obj.objid = map.objid) WHERE map.objid IS NULL", ()): self.conn.execute("DELETE FROM obj WHERE obj.objid = ?", (x,)) self.conn.execute("VACUUM") def open(config): return DB(config) if __name__ == '__main__': import config db = DB(config.read()) obj = db['myasset'] obj[u'name'] = ValueSet(u'monkeyman', t=time()) print "Yeah, I got", str(obj), obj._dirty db.update(obj) print "Yeah, I got", str(obj), obj._dirty obj = db['myasset'] print "Yeah, I got", str(obj), obj._dirty for obj in db.query({'name': 'monkeyman'}): print obj for k,c in db.list_keys():
def test_itersections(self): c = config.read(StringIO.StringIO(self.sample_text())) self.assertEqual([name for name, section in c.itersections()], ['section'])
def __init__(self, *args): QtGui.QMainWindow.__init__(*(self,) + args) app = QtGui.QApplication.instance() self.config = config.read() app.config = self.config self.resize(1000, 600) self.setWindowTitle(NAME) self.debug_dialog = None self.debug_lines = [] self.about_dialog = None self.connection_dialog = None self.preferences_dialog = None # network self.network = Network() self.network.statusChanged.connect(self._network_status_changed) self.network.messageFromWeechat.connect(self._network_weechat_msg) self._last_msgid = None # list of buffers self.switch_buffers = BufferSwitchWidget() self.switch_buffers.currentItemChanged.connect(self._buffer_switch) self._hotlist = [] # default buffer self.buffers = [Buffer()] self.stacked_buffers = QtGui.QStackedWidget() self.stacked_buffers.addWidget(self.buffers[0].widget) # splitter with buffers + chat/input self.splitter = QtGui.QSplitter() self.splitter.addWidget(self.switch_buffers) self.splitter.addWidget(self.stacked_buffers) self.setCentralWidget(self.splitter) # notification manager: self.notifier = NotificationManager(self) # actions for menu and toolbar actions_def = { 'connect': [ 'network-connect', 'Connect to WeeChat', 'Ctrl+O', self.open_connection_dialog], 'disconnect': [ 'network-disconnect', 'Disconnect from WeeChat', 'Ctrl+D', self.network.disconnect_weechat], 'debug': [ 'edit-find', 'Debug console window', 'Ctrl+Shift+B', self.open_debug_dialog], 'view source': [ None, 'View buffer chat source', 'Ctrl+Shift+U', self.open_chat_source], '_reconnect': [ None, 'Test Reconnect', None, self.network._reconnect_weechat], 'preferences': [ 'preferences-other', 'Preferences', 'Ctrl+P', self.open_preferences_dialog], 'about': [ 'help-about', 'About', 'Ctrl+H', self.open_about_dialog], 'save connection': [ 'document-save', 'Save connection configuration', 'Ctrl+S', self.save_connection], 'quit': [ 'application-exit', 'Quit application', 'Ctrl+Q', self.close], } # toggleable actions self.toggles_def = { 'show menubar': [ False, 'Show Menubar', 'Ctrl+M', lambda: self.config_toggle('look', 'menubar'), 'look.menubar'], 'show toolbar': [ False, 'Show Toolbar', False, lambda: self.config_toggle('look', 'toolbar'), 'look.toolbar'], 'show status bar': [ False, 'Show Status Bar', False, lambda: self.config_toggle('look', 'statusbar'), 'look.statusbar'], 'show title': [ False, 'Show Topic', False, lambda: self.config_toggle('look', 'title'), 'look.title'], 'show nick list': [ False, 'Show Nick List', 'Ctrl+F7', lambda: self.config_toggle('look', 'nicklist'), 'look.nicklist'], 'fullscreen': [ False, 'Fullscreen', 'F11', self.toggle_fullscreen], } self.actions = utils.build_actions(actions_def, self) self.actions.update(utils.build_actions(self.toggles_def, self)) # menu self.menu = self.menuBar() menu_file = self.menu.addMenu('&File') menu_file.addActions([self.actions['connect'], self.actions['disconnect'], self.actions['preferences'], self.actions['save connection'], self.actions['quit']]) menu_view = self.menu.addMenu('&View') menu_view.addActions([self.actions['show menubar'], self.actions['show toolbar'], self.actions['show status bar'], utils.separator(self), self.actions['show title'], self.actions['show nick list'], utils.separator(self), self.actions['fullscreen']]) menu_window = self.menu.addMenu('&Window') menu_window.addAction(self.actions['debug']) menu_window.addAction(self.actions['view source']) menu_window.addAction(self.actions['_reconnect']) menu_help = self.menu.addMenu('&Help') menu_help.addAction(self.actions['about']) # network status indicator self.network_status = QtGui.QPushButton() self.network_status.setContentsMargins(0, 0, 10, 0) self.network_status.setFlat(True) self.network_status.setFocusPolicy(QtCore.Qt.NoFocus) self.network_status.setStyleSheet("""text-align:right;padding:0; background-color: transparent;min-width:216px;min-height:20px""") if hasattr(self.menu, 'setCornerWidget'): self.menu.setCornerWidget(self.network_status, QtCore.Qt.TopRightCorner) # toolbar toolbar = self.addToolBar('toolBar') toolbar.setMovable(False) toolbar.addActions([self.actions['connect'], self.actions['disconnect'], self.actions['debug'], self.actions['preferences'], self.actions['about'], self.actions['quit']]) self.toolbar = toolbar # Override context menu for both -- default is a simple menubar toggle. self.menu.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.toolbar.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.menu.customContextMenuRequested.connect(self._menu_context) self.toolbar.customContextMenuRequested.connect(self._toolbar_context) self.buffers[0].widget.input.setFocus() # requested buffers for focus: self.requested_buffer_names = set() # open debug dialog if self.config.getboolean('look', 'debug'): self.open_debug_dialog() self.apply_preferences() self.network_status_set(self.network.status_disconnected) # auto-connect to relay if self.config.getboolean('relay', 'autoconnect'): self.network.connect_weechat(self.config.get('relay', 'server'), self.config.get('relay', 'port'), self.config.getboolean('relay', 'ssl'), self.config.get('relay', 'password'), self.config.get('relay', 'lines'), self.config.get('relay', 'ping')) self.show()
from PyQt5.QtWidgets import QWidget from PyQt5.QtGui import QPainter, QColor from PyQt5.QtCore import QRect, Qt import config config0 = config.read(0) config1 = config.read(1) config2 = config.read(2) with open("default.json") as choice: choiceIndex = int(choice.read()) print(str(choiceIndex)) lineBarColor = QColor(53, 53, 53) class TerminalBar(QWidget): def __init__(self, parent=None, index=choiceIndex): super().__init__(parent) self.editor = parent self.editor.blockCountChanged.connect(self.update_width) self.editor.updateRequest.connect(self.update_on_scroll) self.update_width('1') self.index = index def update_on_scroll(self, rect, scroll): if self.isVisible(): if scroll: self.scroll(0, scroll) else: self.update()
from flask import g import pymongo import config import configparser #app init app = Flask(__name__) #get session config app.config.from_pyfile('config.py') Session(app) #blueprint register app.register_blueprint(todo, url_prefix='/todo') #get db parameter config = configparser.ConfigParser() config.read('parameter.ini') server = config.get('DB', 'host') port = config.getint('DB', 'port') @app.before_request def before_request(): #open db connection & set into g if 'db' not in g: client = pymongo.MongoClient(host=server, port=port) g.db = client @app.teardown_request def teardown_request(exception): #close db connection & remove from g
import configparser import requests from bs4 import BeautifulSoup from collections import defaultdict from collections import deque import re import logging import config logging.basicConfig(format=config.CONFIG.FORMAT_STRING) log = logging.getLogger(__name__) log.setLevel(config.CONFIG.LOGLEVEL) config = configparser.ConfigParser() # Reading the configuration config.read('dinakaran.ini') print(config.sections()) URL = config['URL']['Address'] DELAY = config['URL']['Delay'] ROOT_PAGE = config['URL']['Page'] OUTPUT_FILENAME = config['URL']['OutputFileName'] LINKS_FILENAME = config['URL']['LinksFileName'] print(URL, DELAY) link_dict = defaultdict(list) link_visited = [] paragraphs = [] prev_len = len(link_dict) web_link = deque() active_link = URL MAX_COUNT = 1000000000000
#!/usr/bin/python #-*- coding:utf-8 -*- # down.py import sys,os import time import pop3 import config import subprocess flag = 0 Download_path = config.read('global','down') BT_path = os.path.join(Download_path,'BT') TXT_path = os.path.join(BT_path,'log.txt') li = [] len_mx = 5 #遍历 def dir_fun(path,txt): for root,dirs,files in os.walk(path): for fn in files: #print(root,fn) if (fn != 'log.txt'): _verifyContent(txt,fn) #查询 def search(path=None,txt=None): if not path or not txt: print('path or searchString is empty') return fobj = open(txt,'w') fobj.close() while True:
# -*- coding: UTF-8 -*- import pygame import datetime import numpy import config as cnf config = cnf.read() class Player(object): def __init__(self, map): self.count_moves = 0 self.time = list() self.finish_time = list() self.time_in_seconds = int self.map = map self.x = map.player_x self.y = map.player_y self.speed = config['player_speed'] self.rect = pygame.rect.Rect(6, 58, 38, 38) self.goal_reached = False def move_up(self): self.y -= self.speed for line in self.map.lines_x: if line[1] <= self.y + self.speed: if self.y <= line[1] and self.x <= line[0][ 1] and self.x + 38 > line[0][0]: self.y = line[1] + 2 self.check_goal()
def UpdateSettings(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) for key in query: if key.startswith('Server.'): section, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(section, option) else: config.set(section, option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.set('Server', new_setting, new_value) sections = query['Section_Map'][0].split(']') sections.pop() #last item is junk for section in sections: ID, name = section.split('|') if query[ID][0] == "Delete_Me": config.remove_section(name) continue if query[ID][0] != name: config.remove_section(name) config.add_section(query[ID][0]) for key in query: if key.startswith(ID + '.'): junk, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(query[ID][0], option) else: config.set(query[ID][0], option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.set(query[ID][0], new_setting, new_value) if query['new_Section'][0] != " ": config.add_section(query['new_Section'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'redirect.tmpl')) t.container = cname t.time = '10' t.url = '/TiVoConnect?Command=Admin&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'However you will need to do a <b>Soft Reset</b> before these changes will take effect.'+\ '<br> The <a href="/TiVoConnect?Command=Admin&Container='+ cname +'"> Admin</a> page will reload in 10 seconds.' handler.wfile.write(t)
import time import json import numpy as np import requests import sys import tools import loggers import config import ccxt import buffer from docopt import docopt args = docopt(__doc__) if (args['--config']): config.read(args['--config'][0]) else: config.read('./config.ini') # 動作モードの設定 demoflag = args['demo'] timeflag = args['time'] if demoflag: print('Demo mode') elif timeflag: print('Time mode') else: print('Trade mode') # ロガーのセットアップ l = loggers.aggregator(loggers.console_logger()) if config.SLACK_FLAG == 1: l.append(loggers.slack_logger(config.SLACK_URL))
import os from setuptools import setup import config b = os.path.dirname(__file__) setup(name='vsx2_rotate', version='1.0.0', author='Vladyslav Samotoy', author_email="*****@*****.**", maintainer_email="vsx2.com", url="https://github.com/mcwladkoe/vsx2_rotate", license="GNU GPL-3.0", long_description=config.read(os.path.join(b, 'README.md')), packages=['vsx2_rotate'], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU GPL-3.0 License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ])
import data_processing from constants import CONFIG_PATH, MODELS_PATH from data_ingestion.transform import Normalize, Tensorize # Tensorboard runs_dir = '/home/jorge/Documents/Blog/img_bin/runs' tb = SummaryWriter(log_dir=os.path.join(runs_dir, 'adam-bs1500')) # Data Ingestion transform = Compose([Normalize(mean=0.733, std=0.129), Tensorize()]) dataset_factory = data_ingestion.DatasetFactory() dataset = dataset_factory.get_dataset(kind='train', transform=transform) dataloader = DataLoader(dataset, batch_size=1000, shuffle=True, num_workers=4) # Load Model model = models.BinNet() #tb.add_graph(model) # Training device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') trainer = data_processing.Trainer(dataloader=dataloader, model=model, device=device, tensorboard=tb) trainer.train() # Save Model config = configparser.ConfigParser() config.read(CONFIG_PATH) write_path = os.path.join(MODELS_PATH, config['MODEL SERIALIZATION']['name']) torch.save(trainer._model.state_dict(), write_path)