def authorize_token(user):
    config = read_config()
    if config.get('GitHub', 'token'):
        print("The token already exists.")
        sys.exit()

    password = getpass('Password for {0}: '.format(user))

    note = 'OCA (odoo community association) Maintainers Tools'
    note_url = 'https://github.com/OCA/maintainers-tools'
    scopes = ['repo', 'read:org', 'write:org', 'admin:org']

    try:
        auth = github3.authorize(user, password, scopes, note, note_url)
    except github3.GitHubError as err:
        if err.code == 422:
            for error in err.errors:
                if error['code'] == 'already_exists':
                    msg = ("The 'OCA (odoo community association) Maintainers "
                           "Tools' token already exists. You will find it at "
                           "https://github.com/settings/applications and can "
                           "revoke it or set the token manually in the "
                           "configuration file.")
                    sys.exit(msg)
        raise

    config.set("GitHub", "token", auth.token)
    write_config(config)
    print("Token stored in configuration file")
Example #2
0
File: hutils.py Project: czwl/hgit
def clone_hgit_repo(remote_url):
    cwd = Path.cwd()
    print("Setting up {}", remote_url)
    write_config(remote_url)
    hgroot_path = cwd.joinpath(default_hgroot_name)
    subprocess.run(["git", "clone", "--single-branch", remote_url, ".hgroot"])
    os.chdir(hgroot_path)
Example #3
0
    async def remove_all(self, ctx, pattern=""):
        """Remove all server being checked that matches pattern"""
        cfg = self.bot.my_config
        guild_cfg = cfg['guilds'][str(ctx.guild.id)]

        server_cfgs = guild_cfg.setdefault('servers', [])
        if not server_cfgs:
            await cxt.send("No servers are currently being checked for")
            return

        indices_to_remove = []
        for index, server_cfg in enumerate(server_cfgs):
            if pattern in server_cfg['name']:
                indices_to_remove.append(index)

        if not indices_to_remove:
            await ctx.send("No server being checked for matched the pattern")
            return

        if len(indices_to_remove) == len(server_cfgs):
            server_cfgs.clear()
            msg = "Removed all servers currently being checked for"

        else:
            for index in reversed(indices_to_remove):
                del server_cfgs[index]

            msg = f"Removed {len(indices_to_remove)} servers being checked for"

        await send_and_warn(ctx, msg)
        write_config(cfg)
Example #4
0
    async def check_games(self):
        cfg = self.bot.my_config
        url = 'https://multiplayer.factorio.com/get-games'
        params = {
            'username': cfg['factorio-username'],
            'token': cfg['factorio-token'],
        }

        async with self.checker_session.get(url, params=params) as resp:
            games = await resp.json()
            if type(games) is not list:
                logger.error("Unexpected response from get-games endpoint: "
                             f"{games}")
                return

            self.last_check = int(time())
            self.games_cache = games
            logger.info(f"Got response with {len(games)} entries")
            for guild_id, guild_cfg in cfg['guilds'].items():
                guild = self.bot.get_guild(int(guild_id))
                if guild is not None:
                    await check_guild(guild, guild_cfg, games)

        self.update_players(games)
        write_config(self.bot.my_config)
Example #5
0
def nuke(sure=False, env=True):
    """
	Start from scratch. Erases the environment and  resets the config. You must set the species after this.
	"""
    if sure or all(
            re.match('^(y|Y)', (input if sys.version_info > (
                3, 0) else raw_input)('[QUESTION] %s (y/N)? ' % msg)) != None
            for msg in ['okay to nuke everything', 'confirm']):
        #---reset procedure starts here
        write_config({
            'commands':
            ['mill/setup.py', 'mill/shipping.py', 'mill/factory.py'],
            'commands_aliases': [('set', 'set_config')]
        })
        #---we do not touch the connections, obviously, since you might nuke and reconnect
        #---deleting sensitive stuff here
        for fn in [i for i in ['data'] if os.path.isdir(i)]:
            shutil.rmtree(fn)
        for dn in (['env']
                   if env else []) + ['logs', 'calc', 'data', 'pack', 'site']:
            if os.path.isdir(dn): shutil.rmtree(dn)
        #---nuking the interface development codes requires you to remove migrations. if you do not do this
        #---...then any development modifications to the model requires more attention from the user,
        #---...specifically to fill in columns on preexisting rows. this is obviously a great feature
        #---...for a mature database, but nuking typically removes the db hence the name
        for fn in glob.glob(
                os.path.join('interface', 'simulator', 'migrations', '*')):
            os.remove(fn)
Example #6
0
    async def set_unlisted_pings(self, ctx, *pings: Union[Role, Member]):
        """Set the pings to emmit when a server becomes unlisted"""
        cfg = self.bot.my_config
        guild_cfg = cfg['guilds'][str(ctx.guild.id)]

        if pings:
            guild_cfg['role-pings'] = []
            guild_cfg['member-pings'] = []
            for ping in pings:
                if isinstance(ping, Role):
                    guild_cfg['role-pings'].append(ping.id)
                else:
                    guild_cfg['member-pings'].append(ping.id)

            await send_and_warn(ctx, "Updated unlisted pings")

        else:
            if ('role-pings' not in guild_cfg
                    and 'member-pings' not in guild_cfg):
                await send_and_warn(ctx, "No unlisted pings")

            else:
                del guild_cfg['role-pings']
                del guild_cfg['member-pings']
                await send_and_warn(ctx, "Removed unlisted pings")

        write_config(cfg)
Example #7
0
 def validatePage(self):
     self.wizard().finished = True
     if self.field("save_conf").toBool():
         config.write_config(CONF_FILE)
     if self.field("verbose_dev").toBool():
         google2piwik.__VERBOSE__ = 2
     return True
Example #8
0
def event_by_event(fname_partons, fout, etaos=0.0):
    if not os.path.exists(fout):
        os.mkdir(fout)
    cfg.NX = 301
    cfg.NY = 301
    cfg.NZ = 101

    cfg.DT = 0.005
    cfg.DX = 0.1
    cfg.DY = 0.1
    cfg.DZ = 0.15
    cfg.IEOS = 4
    cfg.TFRZ = 0.136

    cfg.ntskip = 60
    cfg.nzskip = 2

    cfg.TAU0 = 0.4
    cfg.ETAOS = etaos
    cfg.fPathOut = fout

    write_config(cfg)

    t0 = time()
    visc = CLVisc(cfg, gpu_id=3)
    visc.create_ini_from_partons(fname_partons, SIGR=0.6, SIGZ=0.6, KFACTOR=1.3)
    visc.evolve(max_loops=4000, save_hypersf=True, save_bulk=True, save_vorticity=True)
    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime = t1-t0))
    def do_set(self, args):
        """
        Set config for cloudmonkey. For example, options can be:
        url, auth, log_file, history_file
        You may also edit your ~/.cloudmonkey_config instead of using set.

        Example:
        set url http://localhost:8080/client/api
        set prompt 🐵 cloudmonkey>
        set log_file /var/log/cloudmonkey.log
        """
        args = args.strip().partition(" ")
        key, value = (args[0].strip(), args[2].strip())
        if not key:
            return
        if not value:
            print "Blank value of %s is not allowed" % key
            return

        self.prompt = self.get_prompt()
        setattr(self, key, value)
        if key in ['host', 'port', 'path', 'protocol']:
            key = 'url'
            self.url = "%s://%s:%s%s" % (self.protocol, self.host,
                                         self.port, self.path)
            print "This option has been deprecated, please set 'url' instead"
            print "This server url will be used:", self.url
        write_config(self.get_attr, self.config_file)
        read_config(self.get_attr, self.set_attr, self.config_file)
        self.init_credential_store()
        if key.strip() == 'profile':
            print "\nLoaded server profile '%s' with options:" % value
            for option in default_profile.keys():
                print "    %s = %s" % (option, self.get_attr(option))
            print
Example #10
0
def decrypt_config(path="./config"):
    """
    Decrypt all json.encrypt files to .json files
    """
    title_screen()
    password = utils.get_master_password()
    
    print "Processing folder `%s`" % path
     
    print(green("Decrypting..."))
    
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".encrypt"):
                encrypt_file_path = os.path.join(root, file)
                with open(encrypt_file_path) as ciphertext:
                    file_path = encrypt_file_path[:-8]
                    try:
                        config_data = config.read_config(file_path)
                        
                        config.write_config(file_path,
                                            config_data)
                        print(green("File `%s` decrypted." % encrypt_file_path))
                        os.remove(encrypt_file_path)
                    except:
                        print(red("Cannot decrypt file... `%s` skipping..." % encrypt_file_path))
Example #11
0
def write_res(cur_config, char_list, img_list):
    """

    this function writes the final result todisk
    there are three types of  result
    the first  is the npz file for all char image data stack together as whole in one npz file named after npz_save_file
    the second is the txt file saving the configuration information  for this generation named after txt_save_file
    the last is a directory which named 'char' containing all npz files , one per char, for corresponding image data

    Args
                cur_config(dict) : a dictionary to hold current configuration for char image generation
                char_list(list) : a list with all char names in it
                img_ list(list): a list of images generated by pygame , list shape is N x H x W x C
                                            N: number of  images, also is the length of char_list
                                            H: height of the char image
                                            W: width  of the char image
                                            C: channel  of the char image, with order [r, g, b]

    """
    #======================================
    #           rename the space char ' '  with 'space'
    #======================================
    # char_list[0] = 'space'
    #======================================
    #       stack the image array
    #======================================
    print 'stacking'
    img_arr = np.stack(img_list, axis=0)
    del img_list
    print img_arr.shape
    assert len(char_list) == img_arr.shape[0]

    #======================================
    #       output directory
    #======================================
    results_dir = common_cfg['results_dir']
    results_dir = os.path.join(results_dir, cur_config['cur_generation_name'])
    if os.path.exists(results_dir):
        shutil.rmtree(results_dir)
    os.mkdir(results_dir)
    npz_save_file = os.path.join(results_dir,
                                 cur_config['cur_generation_name']) + '.npz'
    txt_save_file = os.path.join(results_dir,
                                 cur_config['cur_generation_name']) + '.txt'
    print 'save npz'
    np.savez_compressed(npz_save_file, img_arr)
    del img_arr
    print 'save config'
    write_config(cur_config, txt_save_file)

    #======================================
    #                          save char index and name
    #======================================
    print 'save char index name file'
    char_index_name_file = os.path.join(results_dir,
                                        common_cfg['char_index_name'])
    char_fw = codecs.open(char_index_name_file, 'w', 'utf-8')
    for idx, char_name in enumerate(char_list):
        char_fw.write(str(idx) + '_' + char_name + '\n')
    char_fw.close()
Example #12
0
    def test_write_config(self):
        settings = {
            "host":
            "localhost",
            "probes": [{
                "pin": 4,
                "sensor": 22,
                "outdoor": "False"
            }, {
                "pin": 21,
                "sensor": 11,
                "outdoor": "True"
            }],
            "dataStore":
            0,
            "delay":
            300,
            "hiveId":
            1,
            "filename":
            "hivedata.csv"
        }
        write_config(settings, 'tempfile.json')

        # tests load_config method as well
        file_settings = load_config('tempfile.json')
        self.assertEqual(settings, file_settings)
Example #13
0
def authenticate(self):
    '''
    Authenticate with the remarkable cloud and write the 
    token key in a configuration file inside the working directory
    '''

    auth_code = 'ukcqshzd'  #one-time authentication code

    payload = {
        "code": auth_code,
        "deviceDesc": "desktop-macos",
        "deviceID": str(uuid4())
    }
    '''
    - code is the authentication code generated at https://my.remarkable.com/connect/remarkable
    - deviceDesc is a brief desription of the device
    -  deviceID is a Universally unique identifier(https://en.wikipedia.org/wiki/Universally_unique_identifier)
    '''
    r = requests.post(api_base, data=json.dumps(payload))

    # print(r.status_code, r.text, r.headers)

    if r.status_code == 200:
        self.token = r.text
    else:
        r.raise_for_status()

    # Write the token key to the configuration file

    configuration = {'token': self.token}

    from config import write_config

    write_config(configuration)
Example #14
0
def getRoots():

    config = get_config('indexPaths')

    if config != None and len(config) > 0:
        return config

    if 'linux' in plt:
        indexPaths = [
            'Desktop', 'Documents', 'Downloads', 'Music', 'Picture', 'Public',
            'Templates', 'Videos'
        ]
        indexPaths = list(
            map(lambda x: os.path.join(os.environ["HOME"], x), indexPaths))
        write_config('indexPaths', indexPaths)
        return indexPaths

    home = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]
    roots = subprocess.check_output(['fsutil', 'fsinfo', 'drives'])
    roots = str(roots)
    roots = roots.split()
    roots = roots[1:-1]
    rts = []
    for root in roots:
        rts.append(root[:-1])
    if 'linux' in plt:
        rts.remove(home[0] + ":/")
    else:
        rts.remove(home[0] + ":\\")
    rts.append(home)

    write_config('indexPaths', rts)
    return rts
Example #15
0
    def authenticate(self, auth_code):
        '''
        Authenticate with the remarkable cloud and write the 
        token key in a configuration file inside the working directory
        '''
        # TODO this code changes each time
        # THis code has been moved to authentication.py (?)
        # Do something like this: if first use, ask for it in the terminal
        auth_code = 'mmrkbahp'  #one-time verification code

        payload = {
            "code": auth_code,
            "deviceDesc": "desktop-macos",
            "deviceID": str(uuid4())
        }
        '''
        - "code" is the authentication code generated at https://my.remarkable.com/connect/remarkable
        - "deviceDesc" is a brief desription of the device
        -  "deviceID" is a Universally unique identifier(https://en.wikipedia.org/wiki/Universally_unique_identifier)
        '''
        r = requests.post(AUTH_API, data=json.dumps(payload))

        # print(r.status_code, r.text, r.headers)

        if r.status_code == 200:
            self.token = r.text
        else:
            r.raise_for_status()

        # Write the token key to the configuration file
        configuration = {'token': self.token}
        write_config(configuration)  #writes configuration json
Example #16
0
 def browse_directory(self):
     dir = os.path.normpath(filedialog.askdirectory())
     if dir is not '':
         self.root_path = dir
         config.write_config('config.ini', 'Paths',
                             'root_path', self.root_path)
         self.entry_path.delete(0, END)
         self.entry_path.insert(0, self.root_path)
Example #17
0
File: gui.py Project: rcuhljr/PADKP
 def confirm_quit(self):
     confirm = messagebox.askyesno('', 'Really quit?')
     if confirm:
         config.write_config(self.config)
         if self.thread is not None:
             self.thread.stop()
         self.master.destroy()
         sys.exit()
Example #18
0
def main():
    filename = os.getenv("CONFIG_FILE", 'config.json')
    data = load_config(filename)
    if print_help():
        if check_for_probes(data):
            write_config(get_settings(data), filename)
        else:
            print("No probes found. Run 'find_probes.py' to find them.")
Example #19
0
def glueball(Tmax = 0.6, outdir = '../results/event0', eos_type='pure_gauge'):
    print('start ...')
    t0 = time()
    if not os.path.exists(outdir):
        os.mkdir(outdir)

    cfg.eos_type = eos_type 
    eos = Eos(cfg.eos_type)
    # update the configuration
    #cfg.Edmax = eos.f_ed(Tmax)
    #cfg.Edmax = 166.0
    cfg.Edmax = 55.0

    cfg.fPathOut = outdir

    cfg.NX = 501
    cfg.NY = 501
    cfg.NZ = 1
    cfg.DT = 0.01
    cfg.DX = 0.08
    cfg.DY = 0.08

    #cfg.NumOfNucleons = 208
    #cfg.Ra = 6.62
    #cfg.Eta = 0.546
    #cfg.Si0 = 6.4

    cfg.NumOfNucleons = 197
    cfg.Ra = 6.4
    cfg.Eta = 0.546
    cfg.Si0 = 4.0

    cfg.TAU0 = 0.4
    cfg.ImpactParameter = 7.74

    #cfg.ImpactParameter = 0.0
    cfg.ETAOS = 0.0

    cfg.save_to_hdf5 = False

    if eos_type == 'pure_gauge':
        cfg.TFRZ = 0.2

    #cfg.Edmax = 600.0
    #cfg.Hwn = 1.0
    cfg.Hwn = 0.95
    write_config(cfg)

    ideal = CLIdeal(cfg, gpu_id=2)
    from glauber import Glauber
    Glauber(cfg, ideal.ctx, ideal.queue, ideal.compile_options, ideal.d_ev[1])

    ideal.evolve(max_loops=3000, save_hypersf=False, to_maxloop=True)
    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime = t1-t0 ))

    from subprocess import call
    call(['python', './spec.py', cfg.fPathOut])
Example #20
0
def ppcollision(eostype='SU3', outdir = '../results/event0'):
    print('start ...')
    t0 = time()
    if not os.path.exists(outdir):
        os.mkdir(outdir)

    if eostype == 'SU3':
        cfg.eos_type = 'pure_gauge'
    elif eostype == 'QCD':
        cfg.eos_type = 'lattice_wb'
    elif eostype == 'EOSI':
        cfg.eos_type == 'ideal_gas'

    eos = Eos(cfg.eos_type)
    # update the configuration
    #cfg.Edmax = eos.f_ed(Tmax)
    cfg.Edmax = 50.0

    cfg.fPathOut = outdir

    cfg.NX = 301
    cfg.NY = 301
    cfg.NZ = 1
    cfg.DT = 0.01
    cfg.DX = 0.08
    cfg.DY = 0.08
    cfg.ntskip = 50
    cfg.NumOfNucleons = 1
    cfg.Ra = 0.8
    cfg.Eta = 0.6
    cfg.Si0 = 6.4
    cfg.TAU0 = 0.6
    cfg.ImpactParameter = 0.0
    cfg.ETAOS = 0.0
    cfg.SQRTS = 2760

    #cfg.Edmax = 600.0
    cfg.Hwn = 1.0
    write_config(cfg)

    xmax = cfg.NX/2*cfg.DX
    ymax = cfg.NY/2*cfg.DY
    x = np.linspace(-xmax, xmax, cfg.NX)
    y = np.linspace(-ymax, ymax, cfg.NY)
    x, y = np.meshgrid(x, y)
    ed = cfg.Edmax * pp_energydensity(x, y, b=cfg.ImpactParameter)
    #plt.imshow(ed)
    #plt.show()

    ideal = CLIdeal(cfg, gpu_id=1)
    edv = np.zeros((ideal.size, 4), ideal.cfg.real)
    print(edv.shape)
    edv[:, 0] = ed.T.flatten()
    ideal.load_ini(edv)

    ideal.evolve(max_loops=1000, save_hypersf=False, to_maxloop=True)
    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime = t1-t0 ))
Example #21
0
def nuke(sure=False):
	"""
	Reset this copy of omnicalc. Be careful!
	"""
	if sure or all(re.match('^(y|Y)',(input if sys.version_info>(3,0) else raw_input)
		('[QUESTION] %s (y/N)? '%msg))!=None for msg in 
		['`nuke` deletes everything. okay?','confirm']):
		#---reset procedure starts here
		write_config(default_config)
Example #22
0
def setup():
	"""
	"""
	if not os.path.isfile('config.py'):	write_config(default_config)
	config = read_config()
	required_settings = ['post_data_spot','post_plot_spot']
	needs_keys = [i for i in required_settings if i not in config]
	if any(needs_keys): 
		print('[NOTE] setting is incomplete until you add: %s. use `make set key="val"`.'%needs_keys)
Example #23
0
 def type_selected(self, *args):
     utils.log('INFO', 'Config updated:')
     j_dict = {}
     for i in range(len(self.type_vars)):
         utils.log(
             'INFO',
             str(self.devices[i]) + ' caps ' + self.type_vars[i].get())
         j_dict[self.devices[i]] = SELECTIONS[self.type_vars[i].get()]
     config.write_config(j_dict)
Example #24
0
    def register_finished(self):
        """
		Update the config.py to make note of the changes to the environment.
		"""
        #---record success and load/unload commands for the environment
        if hasattr(self, 'loader_commands'):
            self.config['activate_env'] = self.loader_commands['env_activate']
        self.config['setup_stamp'] = time.strftime('%Y%m%d%H%M%s')
        write_config(self.config)
Example #25
0
 def update_config(self, filename, host, username=None, password=None):
     new_config = {}
     new_config['filename'] = filename
     new_config['host'] = host
     if username:
         new_config['username'] = username
         if password:
             new_config['password'] = password
     config.write_config(new_config)
Example #26
0
def main():
    '''set default platform and device in opencl'''
    #os.environ[ 'PYOPENCL_CTX' ] = '0:0'
    #os.environ['PYOPENCL_COMPILER_OUTPUT']='1'
    from config import cfg, write_config
    #import pandas as pd
    print('start ...')
    cfg.eos_type = 'lattice_pce165'
    cfg.NX = 201
    cfg.NY = 201
    cfg.NZ = 105
    cfg.DX = 0.16
    cfg.DY = 0.16
    cfg.DZ = 0.16
    cfg.DT = 0.02
    cfg.ntskip = 16
    cfg.nxskip = 2
    cfg.nyskip = 2
    cfg.nzskip = 2
    cfg.Eta_gw = 0.4
    cfg.ImpactParameter = 2.4
    cfg.ETAOS = 0.0
    cfg.TFRZ = 0.137

    cfg.Edmax = 55
    cfg.TAU0 = 0.4

    cfg.fPathOut = '../results/ideal_vs_bjorn_check/'

    cfg.save_to_hdf5 = True

    cfg.BSZ = 64

    write_config(cfg)

    ideal = CLIdeal(cfg, gpu_id=0)

    from glauber import Glauber
    ini = Glauber(cfg, ideal.ctx, ideal.queue, ideal.compile_options,
                  ideal.d_ev[1])

    t0 = time()
    #ini.save_nbinary(ideal.ctx, ideal.queue, cfg)
    ideal.evolve(max_loops=2000, save_bulk=True)
    t1 = time()
    print('finished. Total time for hydro evolution: {dtime}'.format(dtime=t1 -
                                                                     t0))
    print('Events are written in %s' % cfg.fPathOut)

    from subprocess import call

    # get particle spectra from MC sampling and force decay
    call([
        'python', 'spec.py', '--event_dir', cfg.fPathOut, '--viscous_on',
        "false", "--reso_decay", "false", "--nsampling", "2000", '--mode', 'mc'
    ])
Example #27
0
def show_bot_id():
    try:
        bot_id = get_config()["bot_id"]

    except Exception:
        config = get_config()
        config.update({"bot_id": token_urlsafe(7)})
        write_config(config)
        bot_id = get_config()["bot_id"]

    return bot_id
Example #28
0
 def write_config(self):
     if self.has_acceptable_values:
         config.write_config(
             self.host,
             self.port,
             self.db_name,
             self.user,
             self.password,
             self.surgery)
     else:
         sys.exit("TERMINAL ERROR - Unable to write config file")
Example #29
0
    def on_save(self, widget):
        n_tabs = self.note.get_n_pages()
        for tabno in xrange(n_tabs - 1):
            tab = self.note.get_nth_page(tabno)
            for opt in tab.options:
                if opt.type == config.OptionTypePlain:
                    config.options[tab.tab_name][opt.m_name] = \
                            config.Option(opt.value.get_text(), config.OptionTypePlain)

        config.write_config(config_path)
        pass
Example #30
0
def event_by_event(fout,
                   cent='30_35',
                   idx=0,
                   etaos=0.0,
                   fname_ini='/lustre/nyx/hyihp/lpang/hdf5_data/auau39.h5',
                   gpu_id=3):
    ''' Run event_by_event hydro, with initial condition 
    from smearing on the particle list'''
    if not os.path.exists(fout):
        os.mkdir(fout)
    cfg.NX = 301
    cfg.NY = 301
    cfg.NZ = 5

    cfg.DT = 0.005
    cfg.DX = 0.1
    cfg.DY = 0.1
    cfg.DZ = 0.15
    cfg.IEOS = 1
    cfg.TFRZ = 0.136

    cfg.ntskip = 60
    cfg.nzskip = 1

    cfg.TAU0 = 0.4
    cfg.ETAOS = etaos
    cfg.fPathOut = fout

    t0 = time()
    visc = CLVisc(cfg, gpu_id=gpu_id)

    parton_list, eid, imp_b, nwound, npartons = read_p4x4(cent, idx, fname_ini)

    comments = 'cent=%s, eventid=%s, impact parameter=%s, nw=%s, npartons=%s' % (
        cent, eid, imp_b, nwound, npartons)

    write_config(cfg, comments)

    visc.smear_from_p4x4(parton_list,
                         SIGR=0.6,
                         SIGZ=0.6,
                         KFACTOR=1.3,
                         force_bjorken=True)

    visc.evolve(max_loops=4000,
                save_hypersf=True,
                save_bulk=True,
                save_vorticity=False)

    # test whether queue.finish() fix the opencl memory leak problem
    visc.queue.finish()

    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime=t1 - t0))
Example #31
0
 def _set_specify_alias(self, config, arg):
     # 设置alias
     arg.pop(0)
     alias_name = arg.pop(0)
     # 去除引号
     full_cmd = ' '.join(
         map(lambda x: x.replace("'", '').replace('"', ''), arg))
     old_alias = config.get('alias')
     old_alias[alias_name] = full_cmd
     config.set('alias', old_alias)
     write_config(config)
     return f"[green]alias {alias_name}='[red]{full_cmd}[/red]' updated[/green]"
Example #32
0
def dropbox():
    while True:
        config.set_value("dropbox", "token", input("Enter Dropbox access token: "))
        config.write_config()
        functions.clear()
        try:
            login.dropbox_login()
            config.set_value("ftp", "enabled", "true")
            config.write_config()
            print("Successfully logged in\n")
            break
        except:
            print("Failed to log in\n")
Example #33
0
def clone_calcs(source):
	"""
	Clone a calculations repository.
	"""
	config = read_config()
	if 'calculations_repo' in config and not os.path.isdir('calcs/.git'):
		raise Exception('config has a calculations repo registered but we cannot find calcs/.git')
	elif not 'calculations_repo' in config and os.path.isdir('calcs/.git'):
		raise Exception('found calcs/.git but no calculations_repo in the config')
	elif 'calculations_repo' in config and os.path.isdir('calcs/.git'):
		raise Exception('you already have a calculations repo at calcs')
	#---clone and register
	bash('git clone %s calcs'%source)
	config['calculations_repo'] = source
	write_config(config)
Example #34
0
def one_shot(fout, impact_parameter=7.8):
    if not os.path.exists(fout):
        os.makedirs(fout)
    cfg.NX = 301
    cfg.NY = 301
    cfg.NZ = 121

    cfg.DT = 0.005
    cfg.DX = 0.08
    cfg.DY = 0.08
    cfg.DZ = 0.15
    cfg.IEOS = 1
    cfg.ntskip = 60
    cfg.nxskip = 4
    cfg.nyskip = 4
    cfg.nzskip = 2
    cfg.ImpactParameter = impact_parameter

    cfg.Hwn = 0.95

    cfg.TAU0 = 0.4
    cfg.Edmax = 55.0
    cfg.ETAOS = 0.20
    cfg.fPathOut = fout
    write_config(cfg)

    t0 = time()
    visc = CLVisc(cfg, gpu_id=2)
    ini = Glauber(cfg,
                  visc.ctx,
                  visc.queue,
                  visc.compile_options,
                  visc.ideal.d_ev[1],
                  save_nbc=True)
    #visc.create_ini_from_partons(fname_partons, SIGR=0.6, SIGZ=0.6, KFACTOR=1.2)
    visc.evolve(max_loops=4000, save_hypersf=True, save_bulk=True)
    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime=t1 - t0))

    cwd = os.getcwd()
    os.chdir('../CLSmoothSpec/build')
    os.system('cmake -D VISCOUS_ON=ON ..')
    os.system('make')
    call(['./spec', fout])
    os.chdir(cwd)
    after_reso = '0'
    call(['python', '../spec/main.py', fout, after_reso])
    os.chdir(cwd)
Example #35
0
 def save_or_reset(self, button=None, event=None):
     if button == self.rescan:
         self.settings['user']['profile'] = self.profile.get_text()
         self.settings['projects']['other'] = ', '.join(
             self.projects.get_buffer().get_text(
                 self.projects.get_buffer().get_start_iter(),
                 self.projects.get_buffer().get_end_iter(),
                 False).split('\n'))
         self.settings['projects']['hide_after'] = self.timeout.get_text()
         config.write_config(self.settings)
         win.load_projects()
     else:
         self.profile.set_text(self.settings['user']['profile'])
         self.projects.get_buffer().set_text('\n'.join(
             self.settings['projects']['other'].split(', ')))
         self.timeout.set_text(self.settings['projects']['hide_after'])
Example #36
0
    def do_set(self, args):
        """
        Set config for cloudmonkey. For example, options can be:
        host, port, apikey, secretkey, log_file, history_file
        You may also edit your ~/.cloudmonkey_config instead of using set.

        Example:
        set host 192.168.56.2
        set prompt 🐵 cloudmonkey>
        set log_file /var/log/cloudmonkey.log
        """
        args = args.strip().partition(" ")
        key, value = (args[0], args[2])
        setattr(self, key, value)  # keys and attributes should have same names
        self.prompt = self.prompt.strip() + " "  # prompt fix
        write_config(self.get_attr)
Example #37
0
def decrypt_config():
    """
    Decrypt all json.encrypt files to .json files
    """
    title_screen()
    password = utils.get_master_password()
    
    print(green("Decrypting..."))
    
    for root, dirs, files in os.walk("./config"):
        for file in files:
            if file.endswith(".encrypt"):
                encrypt_file_path = os.path.join(root, file)
                with open(encrypt_file_path) as ciphertext:
                    file_path = encrypt_file_path[:-8]
                    
                    config.write_config(file_path,
                                        config.read_config(file_path))
                    print(green("File `%s` decrypted." % encrypt_file_path))
                    os.remove(encrypt_file_path)
Example #38
0
    def set_bar_color(self, bar_color=None):
        '''
            Set color.
        '''
        if bar_color is None:
            bar_color = tkcc.askcolor(initialcolor=self.bar_color)[1]
        if bar_color is None: return
        self.bar_color = bar_color
        self.bar_color_button.config(background=self.bar_color, activebackground=bar_color)
        self.progress_bar.set_color(bar_color)
        self.myconfig['layout/color'] = bar_color

        # save color to INI file
        temp = config.read_config(self.myconfig_filename)
        temp['eval']['layout']['color'] = bar_color
        config.write_config(temp)

        if not self.mybarplot is None:
            self.mybarplot.bar_color = bar_color
            self.mybarplot.redraw()
Example #39
0
def remove_device(pb, conf, dev_num):
    """
    Removes a device identity
    from the config using
    --remove-device or -r
    """
    dev_lst = pb.get_devices()
    try:
        dev_name, dev_id = dev_lst[dev_num]
    except:
        print('Invalid device')
        return

    if 'devices' in conf:
        try:
            conf['devices'].pop(conf['devices'].index(dev_id))
        except:
            print('That device is not in your config')
            return
        config.write_config(conf)
        print('Removed %s' % dev_name)
    def do_set(self, args):
        """
        Set config for cloudmonkey. For example, options can be:
        url, auth, log_file, history_file
        You may also edit your ~/.cloudmonkey_config instead of using set.

        Example:
        set url http://localhost:8080/client/api
        set prompt 🐵 cloudmonkey>
        set log_file /var/log/cloudmonkey.log
        """
        args = args.strip().partition(" ")
        key, value = (args[0].strip(), args[2].strip())
        if not key:
            return
        allowed_blank_keys = ["username", "password", "apikey", "secretkey", "domain"]
        if key not in allowed_blank_keys and not value:
            print "Blank value of %s is not allowed" % key
            return

        self.prompt = self.get_prompt()
        setattr(self, key, value)
        if key in ["host", "port", "path", "protocol"]:
            key = "url"
            self.url = "%s://%s:%s%s" % (self.protocol, self.host, self.port, self.path)
            print "This option has been deprecated, please set 'url' instead"
            print "This server url will be used:", self.url
        write_config(self.get_attr, self.config_file)
        read_config(self.get_attr, self.set_attr, self.config_file)
        self.init_credential_store()
        if key.strip() == "profile" and self.interpreterMode:
            print "\nLoaded server profile '%s' with options:" % value
            for option in default_profile.keys():
                value = self.get_attr(option)
                if option in ["password", "apikey", "secretkey"] and value:
                    value = value[:2] + "XXX" + value[4:6] + "YYY...(hidden)"
                print "    %s = %s" % (option, value)
            print
Example #41
0
def add_device(pb, conf, dev_num):
    """
    Adds a device identity to config
    using --add-device or -a command
    """
    dev_lst = pb.get_devices()
    try:
        dev_name, dev_id = dev_lst[dev_num]
    except:
        print('Invalid device')
        return

    if 'devices' not in conf:
        conf['devices'] = []

    if not isinstance(conf['devices'], list):
        conf['devices'] = []

    if dev_id in conf['devices']:
        print('%s is already listed' % dev_name)
    else:
        conf['devices'].append(dev_id)
        config.write_config(conf)
        print('Added %s' % dev_name)
Example #42
0
def save_and_quit(window, event):
    config.write_config(window.settings_page.settings)
    Gtk.main_quit()
Example #43
0
 def OnSaveZipOption(self, event):
     config.write_config(self.get_zipoption())