signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def find_task(self, name): | try:<EOL><INDENT>return self.tasks[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>similarities = []<EOL>for task_name, task in self.tasks.items():<EOL><INDENT>ratio = SequenceMatcher(None, name, task_name).ratio()<EOL>if ratio >= <NUM_LIT>:<EOL><INDENT>similarities.append(task)<EOL><DEDENT><DEDENT>if len(similarities) == <NUM_LIT:1>:<EOL><INDENT>return similarities[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise NoSuchTaskError(similarities)<EOL><DEDENT> | Find a task by name.
If a task with the exact name cannot be found, then tasks with similar
names are searched for.
Returns
-------
Task
If the task is found.
Raises
------
NoSuchTaskError
If the task cannot be found. | f11997:c9:m1 |
def run(self): | for name in self.task_queue:<EOL><INDENT>yield from self.run_task(name)<EOL><DEDENT> | Run any queued tasks. | f11998:c1:m1 |
def help(self): | yield events.help(self.project)<EOL> | Run a help event. | f11998:c1:m2 |
def queue_task(self, name): | self.task_queue.append(name)<EOL> | Queue a task for execution. | f11998:c1:m3 |
def find_task(self, name): | return self.project.find_task(name)<EOL> | Find a task by name. | f11998:c1:m4 |
def resolve_variables(self, task): | variables = {**task.variables, **self.project.variables}<EOL>values = {}<EOL>for variable in variables.values():<EOL><INDENT>value = self.variables.get(variable.name) or variable.default<EOL>if value is None:<EOL><INDENT>raise LookupError(variable)<EOL><DEDENT>values[variable.name] = value<EOL><DEDENT>return values<EOL> | Resolve task variables based on input variables and the default
values.
Raises
------
LookupError
If a variable is missing. | f11998:c1:m5 |
def run_task(self, name): | if name in self.tasks_run:<EOL><INDENT>yield events.skipping_task(name)<EOL><DEDENT>else:<EOL><INDENT>yield events.finding_task(name)<EOL>try:<EOL><INDENT>task = self.find_task(name)<EOL><DEDENT>except NoSuchTaskError as e:<EOL><INDENT>yield events.task_not_found(name, e.similarities)<EOL>raise StopTask<EOL><DEDENT>yield events.starting_task(task)<EOL>for name in task.dependencies:<EOL><INDENT>yield from self.run_task(name)<EOL><DEDENT>self.tasks_run.append(name)<EOL>yield events.running_task(task)<EOL>yield from self.run_task_steps(task)<EOL>yield events.finished_task(task)<EOL><DEDENT> | Run a task. | f11998:c1:m7 |
def load(filename: str, format: str = None): | path = Path(filename).resolve()<EOL>with path.open() as file:<EOL><INDENT>data = file.read()<EOL><DEDENT>if format is None:<EOL><INDENT>loader, error_class = _load_autodetect, InvalidMofileFormat<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>loader, error_class = formats[format]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise InvalidMofileFormat(f'<STR_LIT>')<EOL><DEDENT><DEDENT>try:<EOL><INDENT>config = loader(data)<EOL><DEDENT>except error_class as e:<EOL><INDENT>raise InvalidMofileFormat(f'<STR_LIT>')<EOL><DEDENT>return Project(config, path.parent)<EOL> | Load a task file and get a ``Project`` back. | f11999:m1 |
def runcmd(model_type, config_path, lab_path): | lab = Laboratory(model_type, config_path, lab_path)<EOL>expt = Experiment(lab)<EOL>if expt.runlog.enabled:<EOL><INDENT>expt.runlog.github_setup()<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT> | Execute the command. | f12003:m0 |
def setup(basepath=DEFAULT_BASEPATH): | module_version = os.environ.get('<STR_LIT>', DEFAULT_VERSION)<EOL>moduleshome = os.path.join(basepath, module_version)<EOL>if not os.path.isdir(moduleshome):<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>os.environ['<STR_LIT>'] = '<STR_LIT>'<EOL>return<EOL><DEDENT>os.environ['<STR_LIT>'] = module_version<EOL>os.environ['<STR_LIT>'] = module_version<EOL>os.environ['<STR_LIT>'] = moduleshome<EOL>if '<STR_LIT>' not in os.environ:<EOL><INDENT>module_initpath = os.path.join(moduleshome, '<STR_LIT>', '<STR_LIT>')<EOL>with open(module_initpath) as initpaths:<EOL><INDENT>modpaths = [<EOL>line.partition('<STR_LIT:#>')[<NUM_LIT:0>].strip()<EOL>for line in initpaths.readlines() if not line.startswith('<STR_LIT:#>')<EOL>]<EOL><DEDENT>os.environ['<STR_LIT>'] = '<STR_LIT::>'.join(modpaths)<EOL><DEDENT>os.environ['<STR_LIT>'] = os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>bash_func_module = os.environ['<STR_LIT>']<EOL>os.environ['<STR_LIT>'] = bash_func_module.replace('<STR_LIT:\n>', '<STR_LIT:;>')<EOL><DEDENT> | Set the environment modules used by the Environment Module system. | f12015:m0 |
def module(command, *args): | if '<STR_LIT>' not in os.environ:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(command))<EOL>return<EOL><DEDENT>modulecmd = ('<STR_LIT>'.format(os.environ['<STR_LIT>']))<EOL>cmd = '<STR_LIT>'.format(modulecmd, command, '<STR_LIT:U+0020>'.join(args))<EOL>envs, _ = subprocess.Popen(shlex.split(cmd),<EOL>stdout=subprocess.PIPE).communicate()<EOL>exec(envs)<EOL> | Run the modulecmd tool and use its Python-formatted output to set the
environment variables. | f12015:m1 |
def parse(): | <EOL>modnames = [mod for (_, mod, _)<EOL>in pkgutil.iter_modules(payu.subcommands.__path__,<EOL>prefix=payu.subcommands.__name__ + '<STR_LIT:.>')<EOL>if mod.endswith('<STR_LIT>')]<EOL>subcmds = [importlib.import_module(mod) for mod in modnames]<EOL>parser = argparse.ArgumentParser()<EOL>parser.add_argument('<STR_LIT>', action='<STR_LIT:version>',<EOL>version='<STR_LIT>'.format(payu.__version__))<EOL>subparsers = parser.add_subparsers()<EOL>for cmd in subcmds:<EOL><INDENT>cmd_parser = subparsers.add_parser(cmd.title, **cmd.parameters)<EOL>cmd_parser.set_defaults(run_cmd=cmd.runcmd)<EOL>for arg in cmd.arguments:<EOL><INDENT>cmd_parser.add_argument(*arg['<STR_LIT>'], **arg['<STR_LIT>'])<EOL><DEDENT><DEDENT>if len(sys.argv) == <NUM_LIT:1>:<EOL><INDENT>parser.print_help()<EOL><DEDENT>else:<EOL><INDENT>args = vars(parser.parse_args())<EOL>run_cmd = args.pop('<STR_LIT>')<EOL>run_cmd(**args)<EOL><DEDENT> | Parse the command line inputs and execute the subcommand. | f12016:m0 |
def get_model_type(model_type, config): | <EOL>if not model_type:<EOL><INDENT>model_type = config.get('<STR_LIT>')<EOL><DEDENT>if not model_type:<EOL><INDENT>model_type = os.path.basename(os.path.abspath(os.pardir))<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(model_type))<EOL><DEDENT>if model_type not in supported_models:<EOL><INDENT>print('<STR_LIT>'.format(model_type))<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT> | Determine and validate the active model type. | f12016:m1 |
def set_env_vars(init_run=None, n_runs=None, lab_path=None, dir_path=None,<EOL>reproduce=None): | payu_env_vars = {}<EOL>lib_paths = sysconfig.get_config_vars('<STR_LIT>')<EOL>payu_env_vars['<STR_LIT>'] = '<STR_LIT::>'.join(lib_paths)<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>payu_env_vars['<STR_LIT>'] = os.environ['<STR_LIT>']<EOL><DEDENT>payu_binpath = os.environ.get('<STR_LIT>')<EOL>if not payu_binpath or not os.path.isdir(payu_binpath):<EOL><INDENT>payu_binpath = os.path.dirname(sys.argv[<NUM_LIT:0>])<EOL><DEDENT>payu_env_vars['<STR_LIT>'] = payu_binpath<EOL>if init_run:<EOL><INDENT>init_run = int(init_run)<EOL>assert init_run >= <NUM_LIT:0><EOL>payu_env_vars['<STR_LIT>'] = init_run<EOL><DEDENT>if n_runs:<EOL><INDENT>n_runs = int(n_runs)<EOL>assert n_runs > <NUM_LIT:0><EOL>payu_env_vars['<STR_LIT>'] = n_runs<EOL><DEDENT>if lab_path:<EOL><INDENT>payu_env_vars['<STR_LIT>'] = os.path.normpath(lab_path)<EOL><DEDENT>if dir_path:<EOL><INDENT>payu_env_vars['<STR_LIT>'] = os.path.normpath(dir_path)<EOL><DEDENT>if reproduce:<EOL><INDENT>payu_env_vars['<STR_LIT>'] = reproduce<EOL><DEDENT>return payu_env_vars<EOL> | Construct the environment variables used by payu for resubmissions. | f12016:m2 |
def submit_job(pbs_script, pbs_config, pbs_vars=None): | <EOL>if pbs_vars is None:<EOL><INDENT>pbs_vars = {}<EOL><DEDENT>pbs_flags = []<EOL>pbs_queue = pbs_config.get('<STR_LIT>', '<STR_LIT>')<EOL>pbs_flags.append('<STR_LIT>'.format(queue=pbs_queue))<EOL>pbs_project = pbs_config.get('<STR_LIT>', os.environ['<STR_LIT>'])<EOL>pbs_flags.append('<STR_LIT>'.format(project=pbs_project))<EOL>pbs_resources = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>for res_key in pbs_resources:<EOL><INDENT>res_flags = []<EOL>res_val = pbs_config.get(res_key)<EOL>if res_val:<EOL><INDENT>res_flags.append('<STR_LIT>'.format(key=res_key, val=res_val))<EOL><DEDENT>if res_flags:<EOL><INDENT>pbs_flags.append('<STR_LIT>'.format(res='<STR_LIT:U+002C>'.join(res_flags)))<EOL><DEDENT><DEDENT>pbs_jobname = pbs_config.get('<STR_LIT>', os.path.basename(os.getcwd()))<EOL>if pbs_jobname:<EOL><INDENT>pbs_flags.append('<STR_LIT>'.format(name=pbs_jobname[:<NUM_LIT:15>]))<EOL><DEDENT>pbs_priority = pbs_config.get('<STR_LIT>')<EOL>if pbs_priority:<EOL><INDENT>pbs_flags.append('<STR_LIT>'.format(priority=pbs_priority))<EOL><DEDENT>pbs_flags.append('<STR_LIT>')<EOL>pbs_join = pbs_config.get('<STR_LIT>', '<STR_LIT:n>')<EOL>if pbs_join not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:n>'):<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>pbs_flags.append('<STR_LIT>'.format(join=pbs_join))<EOL><DEDENT>pbs_vstring = '<STR_LIT:U+002C>'.join('<STR_LIT>'.format(k, v)<EOL>for k, v in pbs_vars.items())<EOL>pbs_flags.append('<STR_LIT>' + pbs_vstring)<EOL>pbs_flags_extend = pbs_config.get('<STR_LIT>')<EOL>if pbs_flags_extend:<EOL><INDENT>pbs_flags.append(pbs_flags_extend)<EOL><DEDENT>if not os.path.isabs(pbs_script):<EOL><INDENT>payu_bin = pbs_vars.get('<STR_LIT>', os.path.dirname(sys.argv[<NUM_LIT:0>]))<EOL>pbs_script = os.path.join(payu_bin, pbs_script)<EOL>assert os.path.isfile(pbs_script)<EOL><DEDENT>envmod.setup()<EOL>envmod.module('<STR_LIT>', '<STR_LIT>')<EOL>cmd = '<STR_LIT>'.format(<EOL>flags='<STR_LIT:U+0020>'.join(pbs_flags),<EOL>python=sys.executable,<EOL>script=pbs_script<EOL>)<EOL>print(cmd)<EOL>subprocess.check_call(shlex.split(cmd))<EOL> | Submit a userscript the scheduler. | f12016:m3 |
def __init__(self, expt, model_name, model_config): | <EOL>self.expt = expt<EOL>self.name = model_name<EOL>self.config = model_config<EOL>self.top_level_model = False<EOL>self.model_type = None<EOL>self.default_exec = None<EOL>self.input_basepath = None<EOL>self.modules = []<EOL>self.config_files = []<EOL>self.optional_config_files = []<EOL>self.work_input_path = None<EOL>self.work_restart_path = None<EOL>self.work_init_path = None<EOL>self.exec_prefix = None<EOL>self.exec_path = None<EOL>self.exec_name = None<EOL>self.codebase_path = None<EOL>self.work_path_local = None<EOL>self.work_input_path_local = None<EOL>self.work_restart_path_local = None<EOL>self.work_init_path_local = None<EOL>self.exec_path_local = None<EOL>self.build_exec_path = None<EOL>self.build_path = None<EOL>self.copy_restarts = False<EOL>self.copy_inputs = False<EOL>self.repo_url = None<EOL>self.repo_tag = None<EOL>self.build_command = None<EOL> | Create the model interface. | f12019:c0:m0 |
def set_model_pathnames(self): | self.control_path = self.expt.control_path<EOL>self.input_basepath = self.expt.lab.input_basepath<EOL>self.work_path = self.expt.work_path<EOL>self.codebase_path = self.expt.lab.codebase_path<EOL>if len(self.expt.models) > <NUM_LIT:1>:<EOL><INDENT>self.control_path = os.path.join(self.control_path, self.name)<EOL>self.work_path = os.path.join(self.work_path, self.name)<EOL>self.codebase_path = os.path.join(self.codebase_path, self.name)<EOL><DEDENT>self.work_input_path = self.work_path<EOL>self.work_restart_path = self.work_path<EOL>self.work_output_path = self.work_path<EOL>self.work_init_path = self.work_path<EOL>self.exec_prefix = self.config.get('<STR_LIT>', '<STR_LIT>')<EOL>self.exec_name = self.config.get('<STR_LIT>', self.default_exec)<EOL>if self.exec_name:<EOL><INDENT>self.exec_path = os.path.join(self.expt.lab.bin_path,<EOL>self.exec_name)<EOL><DEDENT>else:<EOL><INDENT>self.exec_path = None<EOL><DEDENT>if self.exec_path:<EOL><INDENT>self.exec_name = os.path.basename(self.exec_path)<EOL><DEDENT> | Define the paths associated with this model. | f12019:c0:m1 |
def set_timestep(self, timestep): | raise NotImplementedError<EOL> | Set the model timestep. | f12019:c0:m7 |
def archive(self): | <EOL>for path, dirs, files in os.walk(self.work_path, topdown=False):<EOL><INDENT>for f_name in files:<EOL><INDENT>f_path = os.path.join(path, f_name)<EOL>if os.path.islink(f_path) or os.path.getsize(f_path) == <NUM_LIT:0>:<EOL><INDENT>os.remove(f_path)<EOL><DEDENT><DEDENT>if len(os.listdir(path)) == <NUM_LIT:0>:<EOL><INDENT>os.rmdir(path)<EOL><DEDENT><DEDENT> | Store model output to laboratory archive. | f12019:c0:m8 |
def collate(self): | raise NotImplementedError<EOL> | Collate any tiled output into a single file. | f12019:c0:m9 |
def init_config(self): | input_fpath = os.path.join(self.work_path, '<STR_LIT>')<EOL>input_nml = f90nml.read(input_fpath)<EOL>if self.expt.counter == <NUM_LIT:0> or self.expt.repeat_run:<EOL><INDENT>input_type = '<STR_LIT:n>'<EOL><DEDENT>else:<EOL><INDENT>input_type = '<STR_LIT:r>'<EOL><DEDENT>input_nml['<STR_LIT>']['<STR_LIT>'] = input_type<EOL>f90nml.write(input_nml, input_fpath, force=True)<EOL> | Patch input.nml as a new or restart run. | f12020:c0:m2 |
def init_config(self): | input_fpath = os.path.join(self.work_path, '<STR_LIT>')<EOL>input_nml = f90nml.read(input_fpath)<EOL>input_type = '<STR_LIT:n>' if self.expt.counter == <NUM_LIT:0> else '<STR_LIT:r>'<EOL>input_nml['<STR_LIT>']['<STR_LIT>'] = input_type<EOL>f90nml.write(input_nml, input_fpath, force=True)<EOL> | Patch input.nml as a new or restart run. | f12023:c0:m2 |
def date_to_um_dump_date(date): | assert(date.month <= <NUM_LIT:12>)<EOL>decade = date.year // <NUM_LIT:10><EOL>decade = decade % <NUM_LIT><EOL>year = date.year % <NUM_LIT:10><EOL>month = date.month<EOL>day = date.day<EOL>um_d = string.digits + string.ascii_letters[:<NUM_LIT>]<EOL>um_dump_date = (<EOL>'<STR_LIT>'.format(<EOL>decade=um_d[decade],<EOL>year=um_d[year],<EOL>month=um_d[month],<EOL>day=um_d[day]<EOL>)<EOL>)<EOL>return um_dump_date<EOL> | Convert a time date object to a um dump format date which is
<decade><year><month><day>0
To accommodate two digit months and days the UM uses letters. e.g. 1st oct
is writing 01a10. | f12025:m0 |
def date_to_um_date(date): | assert date.hour == <NUM_LIT:0> and date.minute == <NUM_LIT:0> and date.second == <NUM_LIT:0><EOL>return [date.year, date.month, date.day, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]<EOL> | Convert a date object to 'year, month, day, hour, minute, second.' | f12025:m1 |
def um_date_to_date(d): | return datetime.datetime(year=d[<NUM_LIT:0>], month=d[<NUM_LIT:1>], day=d[<NUM_LIT:2>],<EOL>hour=d[<NUM_LIT:3>], minute=d[<NUM_LIT:4>], second=d[<NUM_LIT:5>])<EOL> | Convert a string with format 'year, month, day, hour, minute, second'
to a datetime date. | f12025:m2 |
def um_time_to_time(d): | assert d[<NUM_LIT:0>] == <NUM_LIT:0> and d[<NUM_LIT:1>] == <NUM_LIT:0> and d[<NUM_LIT:3>] == <NUM_LIT:0> and d[<NUM_LIT:4>] == <NUM_LIT:0> and d[<NUM_LIT:5>] == <NUM_LIT:0><EOL>return d[<NUM_LIT:2>]*<NUM_LIT><EOL> | Convert a list with format [year, month, day, hour, minute, second]
to a number of seconds.
Only days are supported. | f12025:m3 |
def time_to_um_time(seconds): | assert(seconds % <NUM_LIT> == <NUM_LIT:0>)<EOL>return [<NUM_LIT:0>, <NUM_LIT:0>, seconds // <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]<EOL> | Convert a number of seconds to a list with format [year, month, day, hour,
minute, second]
Only days are supported. | f12025:m4 |
def check_output(*popenargs, **kwargs): | process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)<EOL>output, unused_err = process.communicate()<EOL>retcode = process.poll()<EOL>if retcode:<EOL><INDENT>cmd = kwargs.get("<STR_LIT:args>")<EOL>if cmd is None:<EOL><INDENT>cmd = popenargs[<NUM_LIT:0>]<EOL><DEDENT>error = subprocess.CalledProcessError(retcode, cmd)<EOL>error.output = output<EOL>raise error<EOL><DEDENT>return output<EOL> | r"""Run command with arguments and return its output as a byte string.
Backported from Python 2.7 as it's implemented as pure python on stdlib.
>>> check_output(['/usr/bin/python', '--version'])
Python 2.6.2 | f12035:m0 |
def mkdir_p(path): | try:<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>except EnvironmentError as exc:<EOL><INDENT>if exc.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT> | Create a new directory; ignore if it already exists. | f12036:m0 |
def read_config(config_fname=None): | if not config_fname:<EOL><INDENT>config_fname = DEFAULT_CONFIG_FNAME<EOL><DEDENT>try:<EOL><INDENT>with open(config_fname, '<STR_LIT:r>') as config_file:<EOL><INDENT>config = yaml.load(config_file)<EOL><DEDENT><DEDENT>except IOError as exc:<EOL><INDENT>if exc.errno == errno.ENOENT:<EOL><INDENT>print('<STR_LIT>'<EOL>.format(config_fname))<EOL>config = {}<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>collate_config = config.pop('<STR_LIT>', {})<EOL>if type(collate_config) is bool:<EOL><INDENT>collate_config = {'<STR_LIT>': collate_config}<EOL><DEDENT>collatestr = '<STR_LIT>'<EOL>foundkeys = []<EOL>for key in list(config.keys()):<EOL><INDENT>if key.startswith(collatestr):<EOL><INDENT>foundkeys.append(key)<EOL>collate_config[key[len(collatestr):]] = config.pop(key)<EOL><DEDENT><DEDENT>if foundkeys:<EOL><INDENT>print("<STR_LIT>".format(<EOL>"<STR_LIT:U+002CU+0020>".join(foundkeys)))<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>config['<STR_LIT>'] = collate_config<EOL>return config<EOL> | Parse input configuration file and return a config dict. | f12036:m1 |
def make_symlink(src_path, lnk_path): | <EOL>if CHECK_LUSTRE_PATH_LEN:<EOL><INDENT>src_path = patch_lustre_path(src_path)<EOL>lnk_path = patch_lustre_path(lnk_path)<EOL><DEDENT>if not os.path.exists(src_path):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>os.symlink(src_path, lnk_path)<EOL><DEDENT>except EnvironmentError as exc:<EOL><INDENT>if exc.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT>elif not os.path.islink(lnk_path):<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>".format(p=src_path, f=lnk_path))<EOL><DEDENT>else:<EOL><INDENT>if os.path.realpath(lnk_path) != src_path:<EOL><INDENT>os.remove(lnk_path)<EOL>os.symlink(src_path, lnk_path)<EOL><DEDENT><DEDENT><DEDENT> | Safely create a symbolic link to an input field. | f12036:m2 |
def splitpath(path): | head, tail = os.path.split(path)<EOL>if tail == '<STR_LIT>':<EOL><INDENT>return head,<EOL><DEDENT>elif head == '<STR_LIT>':<EOL><INDENT>return tail,<EOL><DEDENT>else:<EOL><INDENT>return splitpath(head) + (tail,)<EOL><DEDENT> | Recursively split a filepath into all directories and files. | f12036:m3 |
def patch_lustre_path(f_path): | if CHECK_LUSTRE_PATH_LEN and len(f_path) == <NUM_LIT>:<EOL><INDENT>if os.path.isabs(f_path):<EOL><INDENT>f_path = '<STR_LIT>' + f_path<EOL><DEDENT>else:<EOL><INDENT>f_path = '<STR_LIT>' + f_path<EOL><DEDENT><DEDENT>return f_path<EOL> | Patch any 60-character pathnames, to avoid a current Lustre bug. | f12036:m4 |
def int_to_date(date): | year = date // <NUM_LIT:10>**<NUM_LIT:4><EOL>month = date % <NUM_LIT:10>**<NUM_LIT:4> // <NUM_LIT:10>**<NUM_LIT:2><EOL>day = date % <NUM_LIT:10>**<NUM_LIT:2><EOL>return datetime.date(year, month, day)<EOL> | Convert an int of form yyyymmdd to a python date object. | f12037:m0 |
def runtime_from_date(start_date, years, months, days, seconds, caltype): | end_date = start_date + relativedelta(years=years, months=months,<EOL>days=days)<EOL>runtime = end_date - start_date<EOL>if caltype == NOLEAP:<EOL><INDENT>runtime -= get_leapdays(start_date, end_date)<EOL><DEDENT>return int(runtime.total_seconds() + seconds)<EOL> | Get the number of seconds from start date to start date + date_delta.
Ignores Feb 29 for caltype == NOLEAP. | f12037:m2 |
def date_plus_seconds(init_date, seconds, caltype): | end_date = init_date + datetime.timedelta(seconds=seconds)<EOL>if caltype == NOLEAP:<EOL><INDENT>end_date += get_leapdays(init_date, end_date)<EOL>if end_date.month == <NUM_LIT:2> and end_date.day == <NUM_LIT>:<EOL><INDENT>end_date += datetime.timedelta(days=<NUM_LIT:1>)<EOL><DEDENT><DEDENT>return end_date<EOL> | Get a new_date = date + seconds.
Ignores Feb 29 for no-leap days. | f12037:m3 |
def get_leapdays(init_date, final_date): | curr_date = init_date<EOL>leap_days = <NUM_LIT:0><EOL>while curr_date != final_date:<EOL><INDENT>if curr_date.month == <NUM_LIT:2> and curr_date.day == <NUM_LIT>:<EOL><INDENT>leap_days += <NUM_LIT:1><EOL><DEDENT>curr_date += datetime.timedelta(days=<NUM_LIT:1>)<EOL><DEDENT>return datetime.timedelta(days=leap_days)<EOL> | Find the number of leap days between arbitrary dates. Returns a
timedelta object.
FIXME: calculate this instead of iterating. | f12037:m4 |
def calculate_leapdays(init_date, final_date): | leap_days = (final_date.year - <NUM_LIT:1>) // <NUM_LIT:4> - (init_date.year - <NUM_LIT:1>) // <NUM_LIT:4><EOL>leap_days -= (final_date.year - <NUM_LIT:1>) // <NUM_LIT:100> - (init_date.year - <NUM_LIT:1>) // <NUM_LIT:100><EOL>leap_days += (final_date.year - <NUM_LIT:1>) // <NUM_LIT> - (init_date.year - <NUM_LIT:1>) // <NUM_LIT><EOL>return datetime.timedelta(days=leap_days)<EOL> | Currently unsupported, it only works for differences in years. | f12037:m5 |
def get_job_id(short=True): | jobid = os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>if short:<EOL><INDENT>jobid = jobid.split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL><DEDENT>return(jobid)<EOL> | Return PBS job id | f12044:m0 |
def get_job_info(): | jobid = get_job_id()<EOL>if jobid == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>info = get_qstat_info('<STR_LIT>'.format(jobid), '<STR_LIT>')<EOL>info = info['<STR_LIT>'.format(jobid)]<EOL>info['<STR_LIT>'] = jobid<EOL>return info<EOL> | Get information about the job from the PBS server | f12044:m1 |
def postprocess(self): | assert self.postscript<EOL>envmod.setup()<EOL>envmod.module('<STR_LIT>', '<STR_LIT>')<EOL>cmd = '<STR_LIT>'.format(script=self.postscript)<EOL>cmd = shlex.split(cmd)<EOL>rc = sp.call(cmd)<EOL>assert rc == <NUM_LIT:0>, '<STR_LIT>'<EOL> | Submit a postprocessing script after collation | f12045:c0:m13 |
def commit_hash(dir='<STR_LIT:.>'): | cmd = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>try:<EOL><INDENT>with open(os.devnull, '<STR_LIT:w>') as devnull:<EOL><INDENT>revision_hash = subprocess.check_output(<EOL>cmd,<EOL>cwd=dir,<EOL>stderr=devnull<EOL>)<EOL><DEDENT>if sys.version_info.major > <NUM_LIT:2>:<EOL><INDENT>revision_hash = revision_hash.decode('<STR_LIT:ascii>')<EOL><DEDENT>return revision_hash.strip()<EOL><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>return None<EOL><DEDENT> | Return commit hash for HEAD of checked out branch of the
specified directory. | f12046:m0 |
def create_manifest(self): | config_path = os.path.join(self.expt.control_path,<EOL>DEFAULT_CONFIG_FNAME)<EOL>self.manifest = []<EOL>if os.path.isfile(config_path):<EOL><INDENT>self.manifest.append(config_path)<EOL><DEDENT>for model in self.expt.models:<EOL><INDENT>config_files = model.config_files + model.optional_config_files<EOL>self.manifest.extend(os.path.join(model.control_path, f)<EOL>for f in config_files)<EOL><DEDENT>for mf in self.expt.manifest:<EOL><INDENT>self.manifest.append(mf.path)<EOL><DEDENT> | Construct the list of files to be tracked by the runlog. | f12046:c0:m1 |
def push(self): | expt_name = self.config.get('<STR_LIT:name>', self.expt.name)<EOL>default_ssh_key = '<STR_LIT>' + expt_name<EOL>ssh_key = self.config.get('<STR_LIT>', default_ssh_key)<EOL>ssh_key_path = os.path.join(os.path.expanduser('<STR_LIT>'), '<STR_LIT>', '<STR_LIT>',<EOL>ssh_key)<EOL>if not os.path.isfile(ssh_key_path):<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(key=ssh_key_path))<EOL>print('<STR_LIT>')<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>cmd = ('<STR_LIT>'<EOL>'<STR_LIT>'.format(key=ssh_key_path))<EOL>subprocess.check_call(shlex.split(cmd), cwd=self.expt.control_path)<EOL> | Push the changes to the remote repository.
Usage: payu push
This command pushes local runlog changes to the remote runlog
repository, currently named `payu`, using the SSH key associated with
this experiment.
For an experiment `test`, it is equivalent to the following command::
ssh-agent bash -c "
ssh-add $HOME/.ssh/payu/id_rsa_payu_test
git push --all payu
" | f12046:c0:m3 |
def github_setup(self): | github_auth = self.authenticate()<EOL>github_username = github_auth[<NUM_LIT:0>]<EOL>expt_name = self.config.get('<STR_LIT:name>', self.expt.name)<EOL>expt_description = self.expt.config.get('<STR_LIT:description>')<EOL>if not expt_description:<EOL><INDENT>expt_description = input('<STR_LIT>')<EOL>assert isinstance(expt_description, str)<EOL><DEDENT>expt_private = self.config.get('<STR_LIT>', False)<EOL>github_api_url = '<STR_LIT>'<EOL>org_name = self.config.get('<STR_LIT>')<EOL>if org_name:<EOL><INDENT>repo_target = org_name<EOL>org_query_url = os.path.join(github_api_url, '<STR_LIT>', org_name)<EOL>org_req = requests.get(org_query_url)<EOL>if org_req.status_code == <NUM_LIT>:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(org=org_name))<EOL>print('<STR_LIT>')<EOL><DEDENT>elif org_req.status_code == <NUM_LIT:200>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>repo_query_url = os.path.join(github_api_url, '<STR_LIT>', org_name,<EOL>'<STR_LIT>')<EOL>repo_api_url = os.path.join(github_api_url, '<STR_LIT>', org_name,<EOL>expt_name)<EOL><DEDENT>else:<EOL><INDENT>repo_target = github_username<EOL>repo_query_url = os.path.join(github_api_url, '<STR_LIT:user>', '<STR_LIT>')<EOL>repo_api_url = os.path.join(github_api_url, '<STR_LIT>',<EOL>github_username, expt_name)<EOL><DEDENT>user_repos = []<EOL>page = <NUM_LIT:1><EOL>while True:<EOL><INDENT>repo_params = {'<STR_LIT>': page, '<STR_LIT>': <NUM_LIT:100>}<EOL>repo_query = requests.get(repo_query_url, auth=github_auth,<EOL>params=repo_params)<EOL>assert repo_query.status_code == <NUM_LIT:200><EOL>if repo_query.json():<EOL><INDENT>user_repos.extend(list(r['<STR_LIT:name>'] for r in repo_query.json()))<EOL>page += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if expt_name not in user_repos:<EOL><INDENT>repo_config = {<EOL>'<STR_LIT:name>': expt_name,<EOL>'<STR_LIT:description>': expt_description,<EOL>'<STR_LIT>': expt_private,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': False<EOL>}<EOL>repo_gen = requests.post(repo_query_url, json.dumps(repo_config),<EOL>auth=github_auth)<EOL>assert repo_gen.status_code == <NUM_LIT><EOL><DEDENT>git_remote_out = subprocess.check_output(shlex.split('<STR_LIT>'),<EOL>cwd=self.expt.control_path)<EOL>git_remotes = dict([(r.split()[<NUM_LIT:0>], r.split()[<NUM_LIT:1>])<EOL>for r in git_remote_out.split('<STR_LIT:\n>') if r])<EOL>remote_name = self.config.get('<STR_LIT>', '<STR_LIT>')<EOL>remote_url = os.path.join('<STR_LIT>', repo_target,<EOL>self.expt.name + '<STR_LIT>')<EOL>if remote_name not in git_remotes:<EOL><INDENT>cmd = ('<STR_LIT>'<EOL>'<STR_LIT>'.format(name=remote_name, url=remote_url))<EOL>subprocess.check_call(shlex.split(cmd), cwd=self.expt.control_path)<EOL><DEDENT>elif git_remotes[remote_name] != remote_url:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(name=remote_name))<EOL>sys.exit(-<NUM_LIT:1>)<EOL><DEDENT>default_ssh_key = '<STR_LIT>' + expt_name<EOL>ssh_key = self.config.get('<STR_LIT>', default_ssh_key)<EOL>ssh_dir = os.path.join(os.path.expanduser('<STR_LIT>'), '<STR_LIT>', '<STR_LIT>')<EOL>mkdir_p(ssh_dir)<EOL>ssh_keypath = os.path.join(ssh_dir, ssh_key)<EOL>if not os.path.isfile(ssh_keypath):<EOL><INDENT>cmd = '<STR_LIT>'.format(key=ssh_key)<EOL>subprocess.check_call(shlex.split(cmd), cwd=ssh_dir)<EOL><DEDENT>with open(ssh_keypath + '<STR_LIT>') as keyfile:<EOL><INDENT>pubkey = '<STR_LIT:U+0020>'.join(keyfile.read().split()[:-<NUM_LIT:1>])<EOL><DEDENT>repo_keys_url = os.path.join(repo_api_url, '<STR_LIT>')<EOL>keys_req = requests.get(repo_keys_url, auth=github_auth)<EOL>assert keys_req.status_code == <NUM_LIT:200><EOL>if not any(k['<STR_LIT:key>'] == pubkey for k in keys_req.json()):<EOL><INDENT>add_key_param = {'<STR_LIT:title>': '<STR_LIT>', '<STR_LIT:key>': pubkey}<EOL>add_key_req = requests.post(repo_keys_url, auth=github_auth,<EOL>json=add_key_param)<EOL>assert add_key_req.status_code == <NUM_LIT><EOL><DEDENT> | Set up authentication keys and API tokens. | f12046:c0:m4 |
def substitute_timestep(self, regex, timestep): | <EOL>timestep_changed = False<EOL>while True:<EOL><INDENT>matches = re.finditer(regex, self.str, re.MULTILINE | re.DOTALL)<EOL>none_updated = True<EOL>for m in matches:<EOL><INDENT>if m.group(<NUM_LIT:1>) == timestep:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>self.str = (self.str[:m.start(<NUM_LIT:1>)] + timestep +<EOL>self.str[m.end(<NUM_LIT:1>):])<EOL>none_updated = False<EOL>timestep_changed = True<EOL>break<EOL><DEDENT><DEDENT>if none_updated:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not timestep_changed:<EOL><INDENT>sys.stderr.write('<STR_LIT>'.format(regex))<EOL><DEDENT> | Substitute a new timestep value using regex. | f12047:c0:m2 |
def check_fast(self, reproduce=False, **args): | hashvals = {}<EOL>fast_check = self.check_file(<EOL>filepaths=self.data.keys(),<EOL>hashvals=hashvals,<EOL>hashfn=fast_hashes,<EOL>shortcircuit=True,<EOL>**args<EOL>)<EOL>if not fast_check:<EOL><INDENT>for filepath in hashvals:<EOL><INDENT>for hash, val in hashvals[filepath].items():<EOL><INDENT>self.data[filepath]['<STR_LIT>'][hash] = val<EOL><DEDENT><DEDENT>if reproduce:<EOL><INDENT>for filepath in hashvals:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(filepath, hashvals[filepath]))<EOL>tmphash = {}<EOL>full_check = self.check_file(<EOL>filepaths=filepath,<EOL>hashfn=full_hashes,<EOL>hashvals=tmphash,<EOL>shortcircuit=False,<EOL>**args<EOL>)<EOL>if full_check:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(full_hashes))<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(filepath, self.path))<EOL>self.add_fast(filepath, force=True)<EOL>print('<STR_LIT>')<EOL>self.needsync = True<EOL><DEDENT>else:<EOL><INDENT>sys.stderr.write(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(self.path)<EOL>)<EOL>for path, hashdict in tmphash.items():<EOL><INDENT>print('<STR_LIT>'.format(path))<EOL>for hash, val in hashdict.items():<EOL><INDENT>hash_table = self.data[path]['<STR_LIT>']<EOL>hash_table_val = hash_table.get(hash, None)<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(hash, val, hash_table_val))<EOL><DEDENT><DEDENT>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(hashvals), self.path))<EOL>self.add(<EOL>filepaths=list(hashvals.keys()),<EOL>hashfn=full_hashes,<EOL>force=True,<EOL>fullpaths=[self.fullpath(fpath) for fpath<EOL>in list(hashvals.keys())]<EOL>)<EOL>self.needsync = True<EOL><DEDENT><DEDENT> | Check hash value for all filepaths using a fast hash function and fall
back to slower full hash functions if fast hashes fail to agree. | f12048:c0:m1 |
def add_filepath(self, filepath, fullpath, copy=False): | <EOL>if os.path.isdir(fullpath):<EOL><INDENT>return False<EOL><DEDENT>for pattern in self.ignore:<EOL><INDENT>if fnmatch.fnmatch(os.path.basename(fullpath), pattern):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if filepath not in self.data:<EOL><INDENT>self.data[filepath] = {}<EOL><DEDENT>self.data[filepath]['<STR_LIT>'] = fullpath<EOL>if '<STR_LIT>' not in self.data[filepath]:<EOL><INDENT>self.data[filepath]['<STR_LIT>'] = {hash: None for hash in all_hashes}<EOL><DEDENT>if copy:<EOL><INDENT>self.data[filepath]['<STR_LIT>'] = copy<EOL><DEDENT>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>if filepath in self.existing_filepaths:<EOL><INDENT>self.existing_filepaths.remove(filepath)<EOL><DEDENT><DEDENT>return True<EOL> | Bespoke function to add filepath & fullpath to manifest
object without hashing. Can defer hashing until all files are
added. Hashing all at once is much faster as overhead for
threading is spread over all files | f12048:c0:m2 |
def add_fast(self, filepath, hashfn=None, force=False): | if hashfn is None:<EOL><INDENT>hashfn = fast_hashes<EOL><DEDENT>self.add(filepath, hashfn, force, shortcircuit=True)<EOL> | Bespoke function to add filepaths but set shortcircuit to True, which
means only the first calculable hash will be stored. In this way only
one "fast" hashing function need be called for each filepath. | f12048:c0:m3 |
def copy_file(self, filepath): | copy_file = False<EOL>try:<EOL><INDENT>copy_file = self.data[filepath]['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>return copy_file<EOL> | Returns flag which says to copy rather than link a file. | f12048:c0:m4 |
def make_link(self, filepath): | <EOL>if not os.path.exists(self.fullpath(filepath)):<EOL><INDENT>print('<STR_LIT>'.format(<EOL>filepath=self.fullpath(filepath)))<EOL>if self.contains(filepath):<EOL><INDENT>print('<STR_LIT>')<EOL>self.delete(filepath)<EOL>self.needsync = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>destdir = os.path.dirname(filepath)<EOL>if not os.path.exists(destdir):<EOL><INDENT>os.makedirs(destdir)<EOL><DEDENT>if self.copy_file(filepath):<EOL><INDENT>shutil.copy(self.fullpath(filepath), filepath)<EOL>perm = (stat.S_IRUSR | stat.S_IRGRP<EOL>| stat.S_IROTH | stat.S_IWUSR)<EOL>os.chmod(filepath, perm)<EOL><DEDENT>else:<EOL><INDENT>make_symlink(self.fullpath(filepath), filepath)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>action = '<STR_LIT>' if self.copy_file else '<STR_LIT>'<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(action=action,<EOL>orig=self.fullpath(filepath),<EOL>local=filepath))<EOL>raise<EOL><DEDENT><DEDENT> | Payu integration function for creating symlinks in work directories
which point back to the original file. | f12048:c0:m5 |
def make_links(self): | for filepath in list(self):<EOL><INDENT>self.make_link(filepath)<EOL><DEDENT> | Used to make all links at once for reproduce runs or scaninputs=False | f12048:c0:m6 |
def copy(self, path): | shutil.copy(self.path, path)<EOL> | Copy myself to another location | f12048:c0:m7 |
def __iter__(self): | for mf in self.manifests:<EOL><INDENT>yield self.manifests[mf]<EOL><DEDENT> | Iterator method | f12048:c1:m1 |
def __len__(self): | return len(self.manifests)<EOL> | Return the number of manifests in the manifest class. | f12048:c1:m2 |
def add_filepath(self, manifest, filepath, fullpath, copy=False): | filepath = os.path.normpath(filepath)<EOL>if self.manifests[manifest].add_filepath(filepath, fullpath, copy):<EOL><INDENT>self.manifests[manifest].make_link(filepath)<EOL><DEDENT> | Wrapper to the add_filepath function in PayuManifest. Prevents outside
code from directly calling anything in PayuManifest. | f12048:c1:m6 |
def __init__(self, model_type=None, config_path=None, lab_path=None): | config = read_config(config_path)<EOL>perms = config.get('<STR_LIT>', <NUM_LIT>)<EOL>os.umask(perms)<EOL>if not model_type:<EOL><INDENT>model_type = config.get('<STR_LIT>')<EOL><DEDENT>if not model_type:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.model_type = model_type<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>self.basepath = os.environ.get('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.basepath = lab_path<EOL><DEDENT>if not self.basepath:<EOL><INDENT>self.basepath = self.get_default_lab_path(config)<EOL><DEDENT>self.archive_path = os.path.join(self.basepath, '<STR_LIT>')<EOL>self.bin_path = os.path.join(self.basepath, '<STR_LIT>')<EOL>self.codebase_path = os.path.join(self.basepath, '<STR_LIT>')<EOL>self.input_basepath = os.path.join(self.basepath, '<STR_LIT:input>')<EOL>self.work_path = os.path.join(self.basepath, '<STR_LIT>')<EOL> | Create the Payu laboratory interface. | f12049:c0:m0 |
def get_default_lab_path(self, config): | <EOL>default_project = os.environ.get('<STR_LIT>', '<STR_LIT>')<EOL>default_short_path = os.path.join('<STR_LIT>', default_project)<EOL>default_user = pwd.getpwuid(os.getuid()).pw_name<EOL>short_path = config.get('<STR_LIT>', default_short_path)<EOL>lab_name = config.get('<STR_LIT>', self.model_type)<EOL>if os.path.isabs(lab_name):<EOL><INDENT>lab_path = lab_name<EOL><DEDENT>else:<EOL><INDENT>user_name = config.get('<STR_LIT:user>', default_user)<EOL>lab_path = os.path.join(short_path, user_name, lab_name)<EOL><DEDENT>return lab_path<EOL> | Generate a default laboratory path based on user environment. | f12049:c0:m1 |
def initialize(self): | mkdir_p(self.archive_path)<EOL>mkdir_p(self.bin_path)<EOL>mkdir_p(self.codebase_path)<EOL>mkdir_p(self.input_basepath)<EOL> | Create the laboratory directories. | f12049:c0:m2 |
def read_config(config_path): | <EOL>if not os.path.exists(config_path):<EOL><INDENT>print('<STR_LIT>')<EOL>config = {<EOL>'<STR_LIT>': [<EOL>{<EOL>'<STR_LIT:host>': input('<STR_LIT>'.format('<STR_LIT>')),<EOL>'<STR_LIT:username>': input('<STR_LIT>'.format('<STR_LIT>')),<EOL>'<STR_LIT:password>': input('<STR_LIT>'.format('<STR_LIT>')),<EOL>'<STR_LIT:port>': input('<STR_LIT>'.format('<STR_LIT>')),<EOL>}<EOL>]<EOL>}<EOL>if len(config['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:port>']) < <NUM_LIT:1>:<EOL><INDENT>config['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:port>'] = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>config['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:port>'] = int(config['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:port>'])<EOL><DEDENT>JSON(config_path).write(config)<EOL>return config<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>return JSON(config_path).read()<EOL><DEDENT> | Read/create a configuration file and prompt the user for values.
:param config_path: Path to configuration file
:return config: FTP configurations dictionary | f12053:m0 |
def humanize_bytes(bytes, precision=<NUM_LIT:2>): | abbrevs = (<EOL>(<NUM_LIT:1> << <NUM_LIT:50>, '<STR_LIT>'),<EOL>(<NUM_LIT:1> << <NUM_LIT>, '<STR_LIT>'),<EOL>(<NUM_LIT:1> << <NUM_LIT:30>, '<STR_LIT>'),<EOL>(<NUM_LIT:1> << <NUM_LIT:20>, '<STR_LIT>'),<EOL>(<NUM_LIT:1> << <NUM_LIT:10>, '<STR_LIT>'),<EOL>(<NUM_LIT:1>, '<STR_LIT>')<EOL>)<EOL>if bytes == <NUM_LIT:1>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>for factor, suffix in abbrevs:<EOL><INDENT>if bytes >= factor:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return '<STR_LIT>' % (precision, bytes / factor, suffix)<EOL> | Return a humanized string representation of a number of bytes. | f12054:m0 |
def pool_process(func, iterable, cpus=cpu_count(), return_vals=False, cpu_reduction=<NUM_LIT:0>, progress_bar=False): | with Pool(cpus - abs(cpu_reduction)) as pool:<EOL><INDENT>if return_vals:<EOL><INDENT>if progress_bar:<EOL><INDENT>vals = [v for v in tqdm(pool.imap_unordered(func, iterable), total=len(iterable))]<EOL><DEDENT>else:<EOL><INDENT>vals = pool.map(func, iterable)<EOL><DEDENT>pool.close()<EOL>return vals<EOL><DEDENT>else:<EOL><INDENT>pool.map(func, iterable)<EOL>pool.close()<EOL>return True<EOL><DEDENT><DEDENT> | Multiprocessing helper function for performing looped operation using multiple processors.
:param func: Function to call
:param iterable: Iterable object to perform each function on
:param cpus: Number of cpu cores, defaults to system's cpu count
:param return_vals: Bool, returns output values when True
:param cpu_reduction: Number of cpu core's to not use
:param progress_bar: Display text based progress bar
:return: | f12059:m0 |
def __init__(self, func, iterable, cpus=cpu_count(), cpu_reduction=<NUM_LIT:0>): | self._func = func<EOL>self._iterable = iterable<EOL>self.cpu_count = cpus - abs(cpu_reduction)<EOL> | Multiprocessing helper function for performing looped operation using multiple processors.
:param func: Function to call
:param iterable: Iterable object to perform each function on
:param cpus: Number of cpu cores, defaults to system's cpu count
:param cpu_reduction: Number of cpu core's to not use | f12059:c0:m0 |
def map(self): | with Pool(self.cpu_count) as pool:<EOL><INDENT>pool.map(self._func, self._iterable)<EOL>pool.close()<EOL><DEDENT>return True<EOL> | Perform a function on every item in an iterable. | f12059:c0:m1 |
def map_return(self): | with Pool(self.cpu_count) as pool:<EOL><INDENT>vals = pool.map(self._func, self._iterable)<EOL>pool.close()<EOL>return vals<EOL><DEDENT> | Perform a function on every item and return a list of yield values. | f12059:c0:m2 |
def map_tqdm(self): | with Pool(self.cpu_count) as pool:<EOL><INDENT>vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))]<EOL>pool.close()<EOL>return vals<EOL><DEDENT> | Perform a function on every item while displaying a progress bar.
:return: A list of yielded values | f12059:c0:m3 |
def open_window(path): | if '<STR_LIT>' in modules:<EOL><INDENT>try:<EOL><INDENT>call(["<STR_LIT>", "<STR_LIT>", str(Path(str(path)))])<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>Popen(r'<STR_LIT>' + str(Path(str(path))))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT> | Open path in finder or explorer window | f12060:m0 |
def __init__(self): | self.title = '<STR_LIT>'<EOL>self.params = {}<EOL> | GUI window for inputing DirPaths parameters | f12061:c0:m0 |
def _saving(self): | with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(<NUM_LIT>, <NUM_LIT:1>)) as form:<EOL><INDENT>layout = [<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:30>, <NUM_LIT:1>), font=("<STR_LIT>", <NUM_LIT>), text_color='<STR_LIT>')],<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:15>, <NUM_LIT:1>), auto_size_text=False), gui.InputText(desktop()),<EOL>gui.FolderBrowse()],<EOL>[gui.Text('<STR_LIT>')],<EOL>[gui.Checkbox('<STR_LIT>', default=True), gui.Checkbox('<STR_LIT>')],<EOL>[_line()],<EOL>[gui.Submit(), gui.Cancel()]]<EOL>(button, (values)) = form.LayoutAndShow(layout)<EOL><DEDENT>self.params['<STR_LIT>'] = {<EOL>'<STR_LIT>': values[<NUM_LIT:0>],<EOL>'<STR_LIT>': values[<NUM_LIT:1>],<EOL>'<STR_LIT>': values[<NUM_LIT:2>],<EOL>}<EOL>return self.params<EOL> | Parameters for saving results to file | f12061:c0:m3 |
def parsing(self): | with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(<NUM_LIT>, <NUM_LIT:1>)) as form:<EOL><INDENT>layout = [<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:30>, <NUM_LIT:1>), font=("<STR_LIT>", <NUM_LIT>), text_color='<STR_LIT>')],<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:15>, <NUM_LIT:1>), auto_size_text=False), gui.InputText('<STR_LIT>'),<EOL>gui.FolderBrowse()],<EOL>[gui.Text('<STR_LIT>'<EOL>'<STR_LIT>')],<EOL>[gui.Radio('<STR_LIT>', "<STR_LIT>"), gui.Radio('<STR_LIT>', "<STR_LIT>",<EOL>default=True)],<EOL>[_line()],<EOL>[gui.Text('<STR_LIT>')],<EOL>[gui.Radio('<STR_LIT>', "<STR_LIT>", default=True), gui.Radio('<STR_LIT>',<EOL>"<STR_LIT>")],<EOL>[_line()],<EOL>[gui.Text('<STR_LIT>')],<EOL>[gui.InputCombo(list(reversed(range(<NUM_LIT:0>, <NUM_LIT>))), size=(<NUM_LIT:20>, <NUM_LIT:3>))],<EOL>[_line()],<EOL>[gui.Text('<STR_LIT>'<EOL>'<STR_LIT>')],<EOL>[gui.Radio('<STR_LIT>', "<STR_LIT>", default=True), gui.Radio('<STR_LIT>', "<STR_LIT>")],<EOL>[_line()],<EOL>[gui.Checkbox('<STR_LIT>', default=True), gui.Checkbox('<STR_LIT>')],<EOL>[_line()],<EOL>[gui.Checkbox('<STR_LIT>', default=False)],<EOL>[gui.Submit(), gui.Cancel()]]<EOL>(button, (values)) = form.LayoutAndShow(layout)<EOL><DEDENT>self.params['<STR_LIT>'] = {<EOL>'<STR_LIT>': values[<NUM_LIT:0>],<EOL>'<STR_LIT>': values[<NUM_LIT:1>],<EOL>'<STR_LIT>': values[<NUM_LIT:2>],<EOL>'<STR_LIT>': values[<NUM_LIT:3>],<EOL>'<STR_LIT>': values[<NUM_LIT:4>],<EOL>'<STR_LIT>': int(values[<NUM_LIT:5>]),<EOL>'<STR_LIT>': values[<NUM_LIT:6>],<EOL>'<STR_LIT>': values[<NUM_LIT:7>],<EOL>'<STR_LIT>': values[<NUM_LIT:8>],<EOL>'<STR_LIT>': values[<NUM_LIT:9>],<EOL>'<STR_LIT>': values[<NUM_LIT:10>],<EOL>}<EOL>if self.params['<STR_LIT>']['<STR_LIT>']:<EOL><INDENT>self._saving()<EOL><DEDENT>return self.params<EOL> | Parameters for parsing directory trees | f12061:c0:m4 |
def __init__(self): | self.title = '<STR_LIT>'<EOL> | GUI window for saving zip backups | f12061:c1:m0 |
@property<EOL><INDENT>def source(self):<DEDENT> | with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(<NUM_LIT>, <NUM_LIT:1>)) as form:<EOL><INDENT>layout = [<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:30>, <NUM_LIT:1>), font=("<STR_LIT>", <NUM_LIT:30>), text_color='<STR_LIT>')],<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:50>, <NUM_LIT:1>), font=("<STR_LIT>", <NUM_LIT>),<EOL>text_color='<STR_LIT>')],<EOL>[gui.Text('<STR_LIT:->' * <NUM_LIT:200>)],<EOL>[gui.Text('<STR_LIT>', size=(<NUM_LIT:20>, <NUM_LIT:1>), font=("<STR_LIT>", <NUM_LIT>), auto_size_text=False),<EOL>gui.InputText('<STR_LIT>', key='<STR_LIT:source>', font=("<STR_LIT>", <NUM_LIT:20>)),<EOL>gui.FolderBrowse()],<EOL>[gui.Submit(), gui.Cancel()]]<EOL>button, values = form.LayoutAndRead(layout)<EOL>if button == '<STR_LIT>':<EOL><INDENT>return values['<STR_LIT:source>']<EOL><DEDENT>else:<EOL><INDENT>exit()<EOL><DEDENT><DEDENT> | Parameters for saving zip backups | f12061:c1:m1 |
def __init__(self, command, decode_output=True, immediate_execution=True): | <EOL>self.command = command<EOL>self._decode_output = decode_output<EOL>self._output, self._success = None, False<EOL>if immediate_execution:<EOL><INDENT>self.execute()<EOL><DEDENT> | Execute a system command.
When decode_output is True, console output is captured, decoded
and returned in list a list of strings.
:param command: Command to execute
:param decode_output: Optionally capture and decode console output
:param immediate_execution: Execute system command during initialization
:return: List of output strings | f12062:c0:m0 |
@property<EOL><INDENT>def output(self):<DEDENT> | return self._output<EOL> | Return the standard output produced by execution of the system command. | f12062:c0:m5 |
@property<EOL><INDENT>def success(self):<DEDENT> | return self._success<EOL> | Return a boolean stating weather the command has been successfully executed. | f12062:c0:m6 |
def execute(self): | if self._decode_output:<EOL><INDENT>with Popen(self.command, shell=True, stdout=PIPE) as process:<EOL><INDENT>self._output = [i.decode("<STR_LIT:utf-8>").strip() for i in process.stdout]<EOL>self._success = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>os.system(self.command)<EOL>self._success = True<EOL><DEDENT>return self<EOL> | Execute a system command. | f12062:c0:m7 |
def __init__(self, source, destination=None, compress_level=<NUM_LIT:0>, delete_source=False, overwrite=False): | <EOL>self.compress_level = compress_level<EOL>self.delete_source = delete_source<EOL>self.overwrite = overwrite<EOL>self.source, self.zip_filename = self._set_paths(source, destination)<EOL> | Create zip file backup of a directory.
Backup the entire contents of "source" into a zip file.
or
Backup all "source" files to destination zip file.
:param source: Source folder path or iterable of paths
:param destination: Defaults source parent directory
:param compress_level: Compression level | f12063:c0:m0 |
@staticmethod<EOL><INDENT>def _resolve_file_name(source, destination):<DEDENT> | number = <NUM_LIT:1><EOL>if os.path.exists(os.path.join(destination, os.path.basename(source) + '<STR_LIT>')):<EOL><INDENT>while True:<EOL><INDENT>zip_filename = os.path.join(destination, os.path.basename(source) + '<STR_LIT:_>' + str(number) + '<STR_LIT>')<EOL>if not os.path.exists(zip_filename):<EOL><INDENT>break<EOL><DEDENT>number = number + <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>zip_filename = os.path.join(destination, os.path.basename(source) + '<STR_LIT>')<EOL><DEDENT>return zip_filename<EOL> | Create a filename for the destination zip file. | f12063:c0:m3 |
def _backup_compresslevel(self, dirs): | <EOL>with ZipFile(self.zip_filename, '<STR_LIT:w>', compresslevel=self.compress_level) as backup_zip:<EOL><INDENT>for path in tqdm(dirs, desc='<STR_LIT>', total=len(dirs)):<EOL><INDENT>backup_zip.write(path, path[len(self.source):len(path)])<EOL><DEDENT><DEDENT> | Create a backup file with a compresslevel parameter. | f12063:c0:m6 |
def _backup_pb_gui(self, dirs): | import PySimpleGUI as sg<EOL>with ZipFile(self.zip_filename, '<STR_LIT:w>') as backup_zip:<EOL><INDENT>for count, path in enumerate(dirs):<EOL><INDENT>backup_zip.write(path, path[len(self.source):len(path)])<EOL>if not sg.OneLineProgressMeter('<STR_LIT>', count + <NUM_LIT:1>, len(dirs) - <NUM_LIT:1>, '<STR_LIT>'):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT> | Create a zip backup with a GUI progress bar. | f12063:c0:m7 |
def _backup_pb_tqdm(self, dirs): | with ZipFile(self.zip_filename, '<STR_LIT:w>') as backup_zip:<EOL><INDENT>for path in tqdm(dirs, desc='<STR_LIT>', total=len(dirs)):<EOL><INDENT>backup_zip.write(path, path[len(self.source):len(path)])<EOL><DEDENT><DEDENT> | Create a backup with a tqdm progress bar. | f12063:c0:m8 |
def backup(self, paths=None): | if not paths:<EOL><INDENT>paths = self._get_paths()<EOL><DEDENT>try:<EOL><INDENT>self._backup_compresslevel(paths)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>self._backup_pb_gui(paths)<EOL><DEDENT>except ImportError:<EOL><INDENT>self._backup_pb_tqdm(paths)<EOL><DEDENT><DEDENT>if self.delete_source:<EOL><INDENT>shutil.rmtree(self.source)<EOL><DEDENT>return self.zip_filename<EOL> | Backup method driver. | f12063:c0:m9 |
def move_files_to_folders(directory): | <EOL>files, folders, files_to_move = [], [], []<EOL>for path in os.listdir(directory):<EOL><INDENT>if os.path.isdir(path):<EOL><INDENT>folders.append(path)<EOL><DEDENT>elif os.path.isfile(path):<EOL><INDENT>files.append(path)<EOL><DEDENT><DEDENT>for path in folders:<EOL><INDENT>child_files = [f for f in files if f.startswith(path)]<EOL>files_to_move.append((path, child_files))<EOL><DEDENT>for each in files_to_move:<EOL><INDENT>folder, files = each<EOL>for f in files:<EOL><INDENT>shutil.move(f, folder)<EOL><DEDENT><DEDENT> | Loops through a parent directory and nests files within folders that already exists and have matching prefixs
:param directory: Starting directory | f12065:m0 |
def __init__(self, directory, target='<STR_LIT:root>'): | self.directory = directory<EOL>self.target = target<EOL>self.root_paths = [Path(self.directory + os.sep + dirs) for dirs in os.listdir(self.directory)]<EOL>self.flatten()<EOL> | Loops through parent folders in a root directory and moves child files out of sub folders and into parent folder
:param root: Starting directory
:param target: Target destination for files. Default is 'directory' which will move files into corresponding
directory under parent root. If set to 'root' then files will be moved into root folder | f12065:c0:m0 |
@staticmethod<EOL><INDENT>def remove_path_dirname(path):<DEDENT> | dir_to_remove = os.path.dirname(path)<EOL>if not os.listdir(dir_to_remove):<EOL><INDENT>shutil.rmtree(dir_to_remove)<EOL><DEDENT>else:<EOL><INDENT>if len(os.listdir(dir_to_remove)) == <NUM_LIT:1>:<EOL><INDENT>if os.listdir(dir_to_remove)[<NUM_LIT:0>].startswith('<STR_LIT:.>'):<EOL><INDENT>shutil.rmtree(dir_to_remove)<EOL><DEDENT><DEDENT><DEDENT> | Removes file paths directory if the directory is empty
:param path: Filepath | f12065:c0:m1 |
@property<EOL><INDENT>def session(self):<DEDENT> | return self._session<EOL> | Return ftplib.FTP object to give exposure to methods. | f12067:c0:m3 |
@staticmethod<EOL><INDENT>def connect(host, port, username, password):<DEDENT> | <EOL>session = ftplib.FTP()<EOL>session.connect(host, port)<EOL>session.login(username, password)<EOL>return session<EOL> | Connect and login to an FTP server and return ftplib.FTP object. | f12067:c0:m4 |
def disconnect(self): | self.session.quit()<EOL>return True<EOL> | Send a QUIT command to the server and close the connection (polite way). | f12067:c0:m5 |
def close(self): | self.session.close()<EOL>return True<EOL> | Close the connection unilaterally, FTP instance is unusable after call. | f12067:c0:m6 |
def put(self, local, remote): | return self._store_binary(local, remote)<EOL> | Upload a local file to a directory on the remote ftp server. | f12067:c0:m7 |
def get(self, remote, local=None, keep_dir_structure=False): | if local and os.path.isdir(local):<EOL><INDENT>os.chdir(local)<EOL><DEDENT>elif keep_dir_structure:<EOL><INDENT>for directory in remote.split(os.sep)[:-<NUM_LIT:1>]:<EOL><INDENT>if not os.path.isdir(directory):<EOL><INDENT>os.mkdir(directory)<EOL><DEDENT>os.chdir(directory)<EOL><DEDENT><DEDENT>if os.sep in remote:<EOL><INDENT>directory, file_name = remote.rsplit(os.sep, <NUM_LIT:1>)<EOL>self.chdir(directory)<EOL><DEDENT>else:<EOL><INDENT>file_name = remote<EOL><DEDENT>response = self._retrieve_binary(file_name)<EOL>if local and isinstance(local, str):<EOL><INDENT>os.rename(file_name, local)<EOL><DEDENT>return response<EOL> | Download a remote file on the fto sever to a local directory.
:param remote: File path of remote source file
:param local: Directory of local destination directory
:param keep_dir_structure: If True, replicates the remote files folder structure | f12067:c0:m8 |
def chdir(self, directory_path, make=False): | if os.sep in directory_path:<EOL><INDENT>for directory in directory_path.split(os.sep):<EOL><INDENT>if make and not self.directory_exists(directory):<EOL><INDENT>try:<EOL><INDENT>self.session.mkd(directory)<EOL><DEDENT>except ftplib.error_perm:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.session.cwd(directory)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.session.cwd(directory_path)<EOL><DEDENT> | Change directories and optionally make the directory if it doesn't exist. | f12067:c0:m9 |
def listdir(self, directory_path=None, hidden_files=False): | <EOL>if directory_path:<EOL><INDENT>self.chdir(directory_path)<EOL><DEDENT>if not hidden_files:<EOL><INDENT>return [path for path in self.session.nlst() if not path.startswith('<STR_LIT:.>')]<EOL><DEDENT>else:<EOL><INDENT>return self.session.nlst()<EOL><DEDENT> | Return a list of files and directories in a given directory.
:param directory_path: Optional str (defaults to current directory)
:param hidden_files: Include hidden files
:return: Directory listing | f12067:c0:m10 |
def rename(self, from_name, to_name): | return self.session.rename(from_name, to_name)<EOL> | Rename a file from_name on the server to to_name. | f12067:c0:m11 |
def delete(self, file_path): | if os.sep in file_path:<EOL><INDENT>directory, file_name = file_path.rsplit(os.sep, <NUM_LIT:1>)<EOL>self.chdir(directory)<EOL>return self.session.delete(file_name)<EOL><DEDENT>else:<EOL><INDENT>return self.session.delete(file_path)<EOL><DEDENT> | Remove the file named filename from the server. | f12067:c0:m12 |
def directory_exists(self, directory): | file_list = []<EOL>self.session.retrlines('<STR_LIT>', file_list.append)<EOL>return any(f.split()[-<NUM_LIT:1>] == directory and f.upper().startswith('<STR_LIT:D>') for f in file_list)<EOL> | Check if directory exists (in current location) | f12067:c0:m13 |
def set_verbosity(self, level): | self.session.set_debuglevel(level)<EOL> | Set the instance’s debugging level, controls the amount of debugging output printed. | f12067:c0:m14 |
def _retrieve_binary(self, file_name): | with open(file_name, '<STR_LIT:wb>') as f:<EOL><INDENT>return self.session.retrbinary('<STR_LIT>' + file_name, f.write)<EOL><DEDENT> | Retrieve a file in binary transfer mode. | f12067:c0:m15 |
def _store_binary(self, local_path, remote): | <EOL>dst_dir = os.path.dirname(remote)<EOL>dst_file = os.path.basename(remote)<EOL>dst_cmd = '<STR_LIT>'.format(dst_file)<EOL>with open(local_path, '<STR_LIT:rb>') as local_file:<EOL><INDENT>if dst_dir != dst_file:<EOL><INDENT>self.chdir(dst_dir, make=True)<EOL><DEDENT>return self.session.storbinary(dst_cmd, local_file)<EOL><DEDENT> | Store a file in binary via ftp. | f12067:c0:m16 |
def make_octal_permissions_mode(user=(False, False, False), group=(False, False, False), other=(False, False, False)): | <EOL>mode = '<STR_LIT>'<EOL>for name in (user, group, other):<EOL><INDENT>read, write, execute = name<EOL>if execute and not all(i for i in (read, write)):<EOL><INDENT>code = <NUM_LIT:1><EOL><DEDENT>elif write and not all(i for i in (read, execute)):<EOL><INDENT>code = <NUM_LIT:2><EOL><DEDENT>elif all(i for i in (write, execute)) and not read:<EOL><INDENT>code = <NUM_LIT:3><EOL><DEDENT>elif read and not all(i for i in (write, execute)):<EOL><INDENT>code = <NUM_LIT:4><EOL><DEDENT>elif all(i for i in (read, execute)) and not write:<EOL><INDENT>code = <NUM_LIT:5><EOL><DEDENT>elif all(i for i in (read, write)) and not execute:<EOL><INDENT>code = <NUM_LIT:6><EOL><DEDENT>elif all(i for i in (read, write, execute)):<EOL><INDENT>code = <NUM_LIT:7><EOL><DEDENT>else:<EOL><INDENT>code = <NUM_LIT:0><EOL><DEDENT>mode += str(code)<EOL><DEDENT>return int(mode)<EOL> | Create a permissions bit in absolute notation (octal).
The user, group and other parameters are tuples representing Read, Write and Execute values.
All are set disallowed (set to false) by default and can be individually permitted.
:param user: User permissions
:param group: Group permissions
:param other: Other permissions
:return: Permissions bit | f12068:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.