code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Searches ChEBI via ols.''' url = 'https://www.ebi.ac.uk/ols/api/search?ontology=chebi' + \ '&exact=' + str(exact) + '&q=' + term + \ '&rows=' + str(int(rows)) response = requests.get(url) data = response.json() return [ChebiEntity(doc['obo_id']) for doc in data['response']['docs...
def search(term, exact=False, rows=1e6)
Searches ChEBI via ols.
3.653198
3.015822
1.211344
try: return self.parser.get(section, key) except (NoOptionError, NoSectionError) as e: logger.warning("%s", e) return None
def get(self, section, key)
get function reads the config value for the requested section and key and returns it Parameters: * **section (string):** the section to look for the config value either - oxd, client * **key (string):** the key for the config value required Returns: **value ...
2.759536
4.248405
0.649546
if not self.parser.has_section(section): logger.warning("Invalid config section: %s", section) return False self.parser.set(section, key, value) with open(self.config_file, 'wb') as cfile: self.parser.write(cfile) return True
def set(self, section, key, value)
set function sets a particular value for the specified key in the specified section and writes it to the config file. Parameters: * **section (string):** the section under which the config should be saved. Only accepted values are - oxd, client * **key (string):** the key/name ...
2.532696
3.093745
0.818651
'''Returns all formulae''' all_formulae = [get_formulae(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_formulae for x in sublist]
def get_all_formulae(chebi_ids)
Returns all formulae
2.301386
2.539103
0.906378
'''Returns mass''' if len(__MASSES) == 0: __parse_chemical_data() return __MASSES[chebi_id] if chebi_id in __MASSES else float('NaN')
def get_mass(chebi_id)
Returns mass
4.018003
4.341086
0.925575
'''Returns charge''' if len(__CHARGES) == 0: __parse_chemical_data() return __CHARGES[chebi_id] if chebi_id in __CHARGES else float('NaN')
def get_charge(chebi_id)
Returns charge
4.56146
5.072176
0.89931
'''Gets and parses file''' filename = get_file('chemical_data.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') if tokens[3] == 'FORMULA': # Many seemingly contra...
def __parse_chemical_data()
Gets and parses file
3.52196
3.454762
1.019451
'''Returns all comments''' all_comments = [get_comments(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_comments for x in sublist]
def get_all_comments(chebi_ids)
Returns all comments
2.636415
2.905982
0.907237
'''Gets and parses file''' filename = get_file('comments.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') chebi_id = int(tokens[1]) if chebi_id not in __COMMENTS: ...
def __parse_comments()
Gets and parses file
3.786868
3.626494
1.044223
'''Returns all compound origins''' all_compound_origins = [get_compound_origins(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_compound_origins for x in sublist]
def get_all_compound_origins(chebi_ids)
Returns all compound origins
2.422929
2.541777
0.953242
'''Gets and parses file''' filename = get_file('compound_origins.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') if len(tokens) > 10: chebi_id = int(tokens[1]) ...
def __parse_compound_origins()
Gets and parses file
2.580425
2.470756
1.044387
'''Returns parent id''' if len(__PARENT_IDS) == 0: __parse_compounds() return __PARENT_IDS[chebi_id] if chebi_id in __PARENT_IDS else float('NaN')
def get_parent_id(chebi_id)
Returns parent id
4.78679
4.853532
0.986249
'''Returns all modified on''' all_modified_ons = [get_modified_on(chebi_id) for chebi_id in chebi_ids] all_modified_ons = [modified_on for modified_on in all_modified_ons if modified_on is not None] return None if len(all_modified_ons) == 0 else sorted(all_modified_ons)[-1]
def get_all_modified_on(chebi_ids)
Returns all modified on
2.163296
2.196897
0.984705
'''Returns created by''' if len(__STARS) == 0: __parse_compounds() return __STARS[chebi_id] if chebi_id in __STARS else float('NaN')
def get_star(chebi_id)
Returns created by
6.773267
5.679543
1.192572
'''Gets and parses file''' filename = get_file('compounds.tsv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') chebi_id = int(tokens[0]) __STATUSES[chebi_id] = tokens...
def __parse_compounds()
Gets and parses file
2.377506
2.329214
1.020734
'''COMMENT''' if parent_id in __ALL_IDS: __ALL_IDS[parent_id].append(child_id) else: __ALL_IDS[parent_id] = [child_id]
def __put_all_ids(parent_id, child_id)
COMMENT
2.981661
2.604397
1.144857
'''Returns all database accessions''' all_database_accessions = [get_database_accessions(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_database_accessions for x in sublist]
def get_all_database_accessions(chebi_ids)
Returns all database accessions
2.57025
2.710038
0.948418
'''Gets and parses file''' filename = get_file('database_accession.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') chebi_id = int(tokens[1]) if chebi_id not in __DA...
def __parse_database_accessions()
Gets and parses file
3.51464
3.42305
1.026757
'''Gets and parses file''' filename = get_file('chebiId_inchi.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') __INCHIS[int(tokens[0])] = tokens[1]
def __parse_inchi()
Gets and parses file
5.227216
4.751341
1.100156
'''Returns all names''' all_names = [get_names(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_names for x in sublist]
def get_all_names(chebi_ids)
Returns all names
2.660594
2.906978
0.915244
'''Gets and parses file''' filename = get_file('names.tsv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') chebi_id = int(tokens[1]) if chebi_id not in __ALL_NAMES: ...
def __parse_names()
Gets and parses file
3.977268
3.853838
1.032028
'''Returns references''' references = [] chebi_ids = [str(chebi_id) for chebi_id in chebi_ids] filename = get_file('reference.tsv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') ...
def get_references(chebi_ids)
Returns references
2.84806
2.86988
0.992397
'''Returns all outgoings''' all_outgoings = [get_outgoings(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_outgoings for x in sublist]
def get_all_outgoings(chebi_ids)
Returns all outgoings
2.358227
2.540676
0.928189
'''Returns all incomings''' all_incomings = [get_incomings(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_incomings for x in sublist]
def get_all_incomings(chebi_ids)
Returns all incomings
2.369883
2.496808
0.949165
'''Gets and parses file''' relation_filename = get_file('relation.tsv') vertice_filename = get_file('vertice.tsv') relation_textfile = open(relation_filename, 'r') vertice_textfile = open(vertice_filename, 'r') # Parse vertice: vertices = {} next(vertice_textfile) for line in vert...
def __parse_relation()
Gets and parses file
2.192417
2.153135
1.018244
'''Returns mol''' chebi_id_regexp = '^\\d+\\,' + str(chebi_id) + '\\,.*' mol_file_end_regexp = '\",mol,\\dD' this_structure = [] filename = get_file('structures.csv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: in_chebi_id = False next(textfile) for...
def get_mol(chebi_id)
Returns mol
4.253942
4.282882
0.993243
'''Returns mol file''' mol = get_mol(chebi_id) if mol is None: return None file_descriptor, mol_filename = tempfile.mkstemp(str(chebi_id) + '_', '.mol') mol_file = open(mol_filename, 'w') mol_file.write(mol.get_structure()) mol_f...
def get_mol_filename(chebi_id)
Returns mol file
3.126164
3.096102
1.00971
'''COMMENT''' filename = get_file('structures.csv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split(',') if len(tokens) == 5: if tokens[3] == 'InChIKey': ...
def __parse_structures()
COMMENT
3.051815
2.953263
1.03337
'''COMMENT''' if len(__DEFAULT_STRUCTURE_IDS) == 0: filename = get_file('default_structures.tsv') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens = line.strip().split('\t') __DEFAULT...
def __get_default_structure_ids()
COMMENT
3.442257
3.12806
1.100445
'''Downloads filename from ChEBI FTP site''' destination = __DOWNLOAD_PARAMS['path'] filepath = os.path.join(destination, filename) if not __is_current(filepath): if not os.path.exists(destination): os.makedirs(destination) url = 'ftp://ftp.ebi.ac.uk/pub/databases/chebi/' ...
def get_file(filename)
Downloads filename from ChEBI FTP site
2.548866
2.397093
1.063315
'''Checks whether file is current''' if not __DOWNLOAD_PARAMS['auto_update']: return True if not os.path.isfile(filepath): return False return datetime.datetime.utcfromtimestamp(os.path.getmtime(filepath)) \ > __get_last_update_time()
def __is_current(filepath)
Checks whether file is current
4.495999
4.791716
0.938286
'''Returns last FTP site update time''' now = datetime.datetime.utcnow() # Get the first Tuesday of the month first_tuesday = __get_first_tuesday(now) if first_tuesday < now: return first_tuesday else: first_of_month = datetime.datetime(now.year, now.month, 1) last_mont...
def __get_last_update_time()
Returns last FTP site update time
3.328157
2.799711
1.18875
'''Get the first Tuesday of the month''' month_range = calendar.monthrange(this_date.year, this_date.month) first_of_month = datetime.datetime(this_date.year, this_date.month, 1) first_tuesday_day = (calendar.TUESDAY - month_range[0]) % 7 first_tuesday = first_of_month + datetime.timedelta(days=firs...
def __get_first_tuesday(this_date)
Get the first Tuesday of the month
2.180048
2.243077
0.971901
if validate: if not patterns.MANUFACTURER_CODE.match(manufacturer): raise ValueError('Invalid manufacturer code') if not patterns.LOGGER_ID.match(logger_id): raise ValueError('Invalid logger id') record = '%s%s' % (manufacturer, logger_i...
def write_logger_id(self, manufacturer, logger_id, extension=None, validate=True)
Write the manufacturer and logger id header line:: writer.write_logger_id('XXX', 'ABC', extension='FLIGHT:1') # -> AXXXABCFLIGHT:1 Some older loggers have decimal logger ids which can be written like this:: writer.write_logger_id('FIL', '13961', validate=False) ...
2.952797
3.200201
0.922691
if accuracy is None: accuracy = 500 accuracy = int(accuracy) if not 0 < accuracy < 1000: raise ValueError('Invalid fix accuracy') self.write_fr_header('FXA', '%03d' % accuracy)
def write_fix_accuracy(self, accuracy=None)
Write the GPS fix accuracy header:: writer.write_fix_accuracy() # -> HFFXA500 writer.write_fix_accuracy(25) # -> HFFXA025 :param accuracy: the estimated GPS fix accuracy in meters (optional)
5.521961
4.854019
1.137606
if code is None: code = 100 if gps_datum is None: gps_datum = 'WGS-1984' self.write_fr_header( 'DTM', '%03d' % code, subtype_long='GPSDATUM', value_long=gps_datum, )
def write_gps_datum(self, code=None, gps_datum=None)
Write the mandatory GPS datum header:: writer.write_gps_datum() # -> HFDTM100GPSDATUM:WGS-1984 writer.write_gps_datum(33, 'Guam-1963') # -> HFDTM033GPSDATUM:Guam-1963 Note that the default GPS datum is WGS-1984 and you should use that unless you have ve...
5.120681
4.430873
1.155682
for header in self.REQUIRED_HEADERS: if header not in headers: raise ValueError('%s header missing' % header) self.write_logger_id( headers['manufacturer_code'], headers['logger_id'], extension=headers.get('logger_id_extension') ...
def write_headers(self, headers)
Write all the necessary headers in the correct order:: writer.write_headers({ 'manufacturer_code': 'XCS', 'logger_id': 'TBX', 'date': datetime.date(1987, 2, 24), 'fix_accuracy': 50, 'pilot': 'Tobias Bieniek', 'c...
2.443269
1.746801
1.398711
if declaration_datetime is None: declaration_datetime = datetime.datetime.utcnow() if isinstance(declaration_datetime, datetime.datetime): declaration_datetime = ( self.format_date(declaration_datetime) + self.format_time(declaration_dat...
def write_task_metadata( self, declaration_datetime=None, flight_date=None, task_number=None, turnpoints=None, text=None)
Write the task declaration metadata record:: writer.write_task_metadata( datetime.datetime(2014, 4, 13, 12, 53, 02), task_number=42, turnpoints=3, ) # -> C140413125302000000004203 There are sensible defaults in place for all p...
2.028598
1.936089
1.047782
latitude = self.format_latitude(latitude) longitude = self.format_longitude(longitude) record = latitude + longitude if None not in [distance_min, distance_max, bearing1, bearing2]: record += '%04d' % int(distance_min) record += '%03d' % int((distance_...
def write_task_point(self, latitude=None, longitude=None, text='', distance_min=None, distance_max=None, bearing1=None, bearing2=None)
Write a task declaration point:: writer.write_task_point( latitude=(51 + 7.345 / 60.), longitude=(6 + 24.765 / 60.), text='Meiersberg', ) # -> C5107345N00624765EMeiersberg If no ``latitude`` or ``longitude`` is passed, the fie...
1.704927
1.773651
0.961253
for args in points: if len(args) not in [3, 7]: raise ValueError('Invalid number of task point tuple items') self.write_task_point(*args)
def write_task_points(self, points)
Write multiple task declaration points with one call:: writer.write_task_points([ (None, None, 'TAKEOFF'), (51.40375, 6.41275, 'START'), (50.38210, 8.82105, 'TURN 1'), (50.59045, 7.03555, 'TURN 2', 0, 32.5, 0, 180), (51.40375, ...
6.421734
6.778564
0.947359
for start in range(0, len(security), bytes_per_line): self.write_record('G', security[start:start + bytes_per_line])
def write_security(self, security, bytes_per_line=75)
Write the security signature:: writer.write_security('ABCDEF') # -> GABCDEF If a signature of more than 75 bytes is used the G record will be broken into multiple lines according to the IGC file specification. This rule can be configured with the ``bytes_per_line`` para...
4.153735
3.47815
1.194237
if time is None: time = datetime.datetime.utcnow() record = self.format_time(time) record += self.format_latitude(latitude) record += self.format_longitude(longitude) record += 'A' if valid else 'V' record += '%05d' % (pressure_alt or 0) rec...
def write_fix(self, time=None, latitude=None, longitude=None, valid=False, pressure_alt=None, gps_alt=None, extensions=None)
Write a fix record:: writer.write_fix( datetime.time(12, 34, 56), latitude=51.40375, longitude=6.41275, valid=True, pressure_alt=1234, gps_alt=1432, ) # -> B1234565124225N00624765EA012340...
2.313271
2.284847
1.01244
num_args = len(args) if not (1 <= num_args <= 3): raise ValueError('Invalid number of parameters received') if num_args == 3: time, code, text = args elif num_args == 1: code = args[0] time = text = None elif isinstance(a...
def write_event(self, *args)
Write an event record:: writer.write_event(datetime.time(12, 34, 56), 'PEV') # -> B123456PEV writer.write_event(datetime.time(12, 34, 56), 'PEV', 'Some Text') # -> B123456PEVSome Text writer.write_event('PEV') # uses utcnow() # -> B121503PEV ...
3.111805
2.678299
1.161859
num_args = len(args) if num_args not in (1, 2): raise ValueError('Invalid number of parameters received') if num_args == 1: satellites = args[0] time = None else: time, satellites = args if time is None: time...
def write_satellites(self, *args)
Write a satellite constellation record:: writer.write_satellites(datetime.time(12, 34, 56), [1, 2, 5, 22]) # -> F12345601020522 :param time: UTC time of the satellite constellation record (default: :meth:`~datetime.datetime.utcnow`) :param satellites: a list of sate...
2.620544
2.349189
1.11551
num_args = len(args) if num_args not in (1, 2): raise ValueError('Invalid number of parameters received') if num_args == 1: extensions = args[0] time = None else: time, extensions = args if time is None: time...
def write_k_record(self, *args)
Write a K record:: writer.write_k_record_extensions([ ('FXA', 3), ('SIU', 2), ('ENL', 3), ]) writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2]) # -> J030810FXA1112SIU1315ENL # -> K02030402313002 :param time: UTC time of t...
2.766431
2.435484
1.135885
if not patterns.THREE_LETTER_CODE.match(code): raise ValueError('Invalid source') self.write_record('L', code + text)
def write_comment(self, code, text)
Write a comment record:: writer.write_comment('PLT', 'Arrived at the first turnpoint') # -> LPLTArrived at the first turnpoint :param code: a three-letter-code describing the source of the comment (e.g. ``PLT`` for pilot) :param text: the text that should be added t...
13.794737
9.255806
1.490387
placeholders = list(cms_page.placeholders.all()) placeholder_frontend_data_dict = get_frontend_data_dict_for_placeholders( placeholders=placeholders, request=request, editable=editable ) global_placeholder_data_dict = get_global_placeholder_data(placeholder_frontend_data_dic...
def get_frontend_data_dict_for_cms_page(cms_page, cms_page_title, request, editable=False)
Returns the data dictionary of a CMS page that is used by the frontend.
2.335683
2.331236
1.001907
data_dict = {} for placeholder in placeholders: if placeholder: plugins = [] # We don't use the helper method `placeholder.get_plugins()` because of the wrong order by path. placeholder_plugins = placeholder.cmsplugin_set.filter(language=request.LANGUAGE_CODE).o...
def get_frontend_data_dict_for_placeholders(placeholders, request, editable=False)
Takes a list of placeholder instances and returns the data that is used by the frontend to render all contents. The returned dict is grouped by placeholder slots.
4.083675
4.118442
0.991558
json_data = {} instance, plugin = plugin.get_plugin_instance() if not instance: return json_data renderer = renderer_pool.renderer_for_plugin(plugin) if renderer: json_data = renderer.render(request=request, plugin=plugin, instance=instance, editable=editable) if hasattr(...
def get_frontend_data_dict_for_plugin(request, plugin, editable)
Returns a serializable data dict of a CMS plugin and all its children. It expects a `render_json_plugin()` method from each plugin. Make sure you implement it for your custom plugins and monkey patch all third-party plugins.
2.976731
2.754621
1.080632
# Split static placeholders from partials that have a custom callback. static_placeholder_names = [] custom_callback_partials = [] for partial in partials: if partial in settings.DJANGOCMS_SPA_PARTIAL_CALLBACKS.keys(): custom_callback_partials.append(partial) else: ...
def get_frontend_data_dict_for_partials(partials, request, editable=False, renderer=None)
We call global page elements that are used to render a template `partial`. The contents of a partial do not change from one page to another. In a django CMS project partials are implemented as static placeholders. But there are usually other parts (e.g. menu) that work pretty much the same way. Because we don't...
2.684713
2.600736
1.03229
post_processer = settings.DJANGOCMS_SPA_PLACEHOLDER_DATA_POST_PROCESSOR if not post_processer: return {} func = get_function_by_path(post_processer) return func(placeholder_frontend_data_dict=placeholder_frontend_data_dict)
def get_global_placeholder_data(placeholder_frontend_data_dict)
In some rare cases you need to post process the placeholder data and add additional, global data to the route object. Define your post-processor in the DJANGOCMS_SPA_VUE_JS_PLACEHOLDER_DATA_POST_PROCESSOR setting variable (e.g. `my_app.my_module.my_function` and return the data you need.
4.310298
2.669518
1.614635
if not description: description = '' latitude = self.format_latitude(latitude) longitude = self.format_longitude(longitude) self.write_config( 'ADDWP', '%s,%s,%s' % (latitude, longitude, description[0:50]) )
def write_waypoint(self, latitude=None, longitude=None, description=None)
Adds a waypoint to the current task declaration. The first and the last waypoint added will be treated as takeoff and landing location, respectively. :: writer.write_waypoint( latitude=(51 + 7.345 / 60.), longitude=(6 + 24.765 / 60.), ...
3.911789
3.703044
1.056371
for args in points: if len(args) != 3: raise ValueError('Invalid number of task point tuple items') self.write_waypoint(*args)
def write_waypoints(self, points)
Write multiple task declaration points with one call:: writer.write_waypoints([ (None, None, 'TAKEOFF'), (51.40375, 6.41275, 'START'), (50.38210, 8.82105, 'TURN 1'), (50.59045, 7.03555, 'TURN 2'), (51.40375, 6.41275, 'FINISH'),...
9.175541
8.432825
1.088074
self.control_path = self.expt.control_path self.input_basepath = self.expt.lab.input_basepath self.work_path = self.expt.work_path self.codebase_path = self.expt.lab.codebase_path if len(self.expt.models) > 1: self.control_path = os.path.join(self.control_p...
def set_model_pathnames(self)
Define the paths associated with this model.
2.946825
2.883849
1.021838
# Traverse the model directory deleting symlinks, zero length files # and empty directories for path, dirs, files in os.walk(self.work_path, topdown=False): for f_name in files: f_path = os.path.join(path, f_name) if os.path.islink(f_path) or...
def archive(self)
Store model output to laboratory archive.
2.761104
2.604948
1.059946
# Build the list of subcommand modules modnames = [mod for (_, mod, _) in pkgutil.iter_modules(payu.subcommands.__path__, prefix=payu.subcommands.__name__ + '.') if mod.endswith('_cmd')] subcmds = [importlib.import_module(mod) fo...
def parse()
Parse the command line inputs and execute the subcommand.
2.512746
2.422172
1.037394
# If no model type is given, then check the config file if not model_type: model_type = config.get('model') # If there is still no model type, try the parent directory if not model_type: model_type = os.path.basename(os.path.abspath(os.pardir)) print('payu: warning: Assumi...
def get_model_type(model_type, config)
Determine and validate the active model type.
3.19294
3.244404
0.984138
payu_env_vars = {} # Setup Python dynamic library link lib_paths = sysconfig.get_config_vars('LIBDIR') payu_env_vars['LD_LIBRARY_PATH'] = ':'.join(lib_paths) if 'PYTHONPATH' in os.environ: payu_env_vars['PYTHONPATH'] = os.environ['PYTHONPATH'] # Set (or import) the path to the PAY...
def set_env_vars(init_run=None, n_runs=None, lab_path=None, dir_path=None, reproduce=None)
Construct the environment variables used by payu for resubmissions.
2.22781
2.151594
1.035423
# Initialisation if pbs_vars is None: pbs_vars = {} pbs_flags = [] pbs_queue = pbs_config.get('queue', 'normal') pbs_flags.append('-q {queue}'.format(queue=pbs_queue)) pbs_project = pbs_config.get('project', os.environ['PROJECT']) pbs_flags.append('-P {project}'.format(proje...
def submit_job(pbs_script, pbs_config, pbs_vars=None)
Submit a userscript the scheduler.
2.96799
2.975129
0.997601
# Make one change at a time, each change affects subsequent matches. timestep_changed = False while True: matches = re.finditer(regex, self.str, re.MULTILINE | re.DOTALL) none_updated = True for m in matches: if m.group(1) == timestep...
def substitute_timestep(self, regex, timestep)
Substitute a new timestep value using regex.
3.523786
3.34627
1.053049
year = date // 10**4 month = date % 10**4 // 10**2 day = date % 10**2 return datetime.date(year, month, day)
def int_to_date(date)
Convert an int of form yyyymmdd to a python date object.
2.357388
1.920087
1.227751
end_date = start_date + relativedelta(years=years, months=months, days=days) runtime = end_date - start_date if caltype == NOLEAP: runtime -= get_leapdays(start_date, end_date) return int(runtime.total_seconds() + seconds)
def runtime_from_date(start_date, years, months, days, seconds, caltype)
Get the number of seconds from start date to start date + date_delta. Ignores Feb 29 for caltype == NOLEAP.
3.38999
3.292768
1.029526
end_date = init_date + datetime.timedelta(seconds=seconds) if caltype == NOLEAP: end_date += get_leapdays(init_date, end_date) if end_date.month == 2 and end_date.day == 29: end_date += datetime.timedelta(days=1) return end_date
def date_plus_seconds(init_date, seconds, caltype)
Get a new_date = date + seconds. Ignores Feb 29 for no-leap days.
2.574601
2.616816
0.983868
curr_date = init_date leap_days = 0 while curr_date != final_date: if curr_date.month == 2 and curr_date.day == 29: leap_days += 1 curr_date += datetime.timedelta(days=1) return datetime.timedelta(days=leap_days)
def get_leapdays(init_date, final_date)
Find the number of leap days between arbitrary dates. Returns a timedelta object. FIXME: calculate this instead of iterating.
1.929558
1.739699
1.109134
leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4 leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100 leap_days += (final_date.year - 1) // 400 - (init_date.year - 1) // 400 # TODO: Internal date correction (e.g. init_date is 1-March or later) return date...
def calculate_leapdays(init_date, final_date)
Currently unsupported, it only works for differences in years.
2.514468
2.380913
1.056094
# Default path settings # Append project name if present (NCI-specific) default_project = os.environ.get('PROJECT', '') default_short_path = os.path.join('/short', default_project) default_user = pwd.getpwuid(os.getuid()).pw_name short_path = config.get('shortp...
def get_default_lab_path(self, config)
Generate a default laboratory path based on user environment.
3.577262
3.490297
1.024916
mkdir_p(self.archive_path) mkdir_p(self.bin_path) mkdir_p(self.codebase_path) mkdir_p(self.input_basepath)
def initialize(self)
Create the laboratory directories.
4.962448
3.801501
1.305392
jobid = os.environ.get('PBS_JOBID', '') if short: # Strip off '.rman2' jobid = jobid.split('.')[0] return(jobid)
def get_job_id(short=True)
Return PBS job id
5.160103
4.362428
1.182851
jobid = get_job_id() if jobid == '': return None info = get_qstat_info('-ft {0}'.format(jobid), 'Job Id:') # Select the dict for this job (there should only be one entry in any case) info = info['Job Id: {}'.format(jobid)] # Add the jobid to the dict and then return info['J...
def get_job_info()
Get information about the job from the PBS server
6.894554
6.513298
1.058535
assert self.postscript envmod.setup() envmod.module('load', 'pbs') cmd = 'qsub {script}'.format(script=self.postscript) cmd = shlex.split(cmd) rc = sp.call(cmd) assert rc == 0, 'Postprocessing script submission failed.'
def postprocess(self)
Submit a postprocessing script after collation
8.434851
6.431413
1.311508
assert(date.month <= 12) decade = date.year // 10 # UM can only handle 36 decades then goes back to the beginning. decade = decade % 36 year = date.year % 10 month = date.month day = date.day um_d = string.digits + string.ascii_letters[:26] um_dump_date = ( '{decade}...
def date_to_um_dump_date(date)
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.
3.213266
2.926744
1.097898
assert date.hour == 0 and date.minute == 0 and date.second == 0 return [date.year, date.month, date.day, 0, 0, 0]
def date_to_um_date(date)
Convert a date object to 'year, month, day, hour, minute, second.'
2.723794
2.332197
1.167909
return datetime.datetime(year=d[0], month=d[1], day=d[2], hour=d[3], minute=d[4], second=d[5])
def um_date_to_date(d)
Convert a string with format 'year, month, day, hour, minute, second' to a datetime date.
2.295211
2.039204
1.125543
module_version = os.environ.get('MODULE_VERSION', DEFAULT_VERSION) moduleshome = os.path.join(basepath, module_version) # Abort if MODULESHOME does not exist if not os.path.isdir(moduleshome): print('payu: warning: MODULESHOME does not exist; disabling ' 'environment modules...
def setup(basepath=DEFAULT_BASEPATH)
Set the environment modules used by the Environment Module system.
5.912081
5.758064
1.026748
if 'MODULESHOME' not in os.environ: print('payu: warning: No Environment Modules found; skipping {0} call.' ''.format(command)) return modulecmd = ('{0}/bin/modulecmd'.format(os.environ['MODULESHOME'])) cmd = '{0} python {1} {2}'.format(modulecmd, command, ' '.join(args...
def module(command, *args)
Run the modulecmd tool and use its Python-formatted output to set the environment variables.
5.677893
5.003112
1.134872
input_fpath = os.path.join(self.work_path, 'input.nml') input_nml = f90nml.read(input_fpath) if self.expt.counter == 0 or self.expt.repeat_run: input_type = 'n' else: input_type = 'r' input_nml['MOM_input_nml']['input_filename'] = input_type ...
def init_config(self)
Patch input.nml as a new or restart run.
4.278423
3.607924
1.18584
try: os.makedirs(path) except EnvironmentError as exc: if exc.errno != errno.EEXIST: raise
def mkdir_p(path)
Create a new directory; ignore if it already exists.
3.038451
2.961169
1.026099
if not config_fname: config_fname = DEFAULT_CONFIG_FNAME try: with open(config_fname, 'r') as config_file: config = yaml.load(config_file) except IOError as exc: if exc.errno == errno.ENOENT: print('payu: warning: Configuration file {0} not found!' ...
def read_config(config_fname=None)
Parse input configuration file and return a config dict.
3.462003
3.409415
1.015424
# Check for Lustre 60-character symbolic link path bug if CHECK_LUSTRE_PATH_LEN: src_path = patch_lustre_path(src_path) lnk_path = patch_lustre_path(lnk_path) # os.symlink will happily make a symlink to a non-existent # file, but we don't want that behaviour # XXX: Do we want ...
def make_symlink(src_path, lnk_path)
Safely create a symbolic link to an input field.
3.310174
3.342851
0.990225
head, tail = os.path.split(path) if tail == '': return head, elif head == '': return tail, else: return splitpath(head) + (tail,)
def splitpath(path)
Recursively split a filepath into all directories and files.
2.751589
2.599524
1.058497
if CHECK_LUSTRE_PATH_LEN and len(f_path) == 60: if os.path.isabs(f_path): f_path = '/.' + f_path else: f_path = './' + f_path return f_path
def patch_lustre_path(f_path)
Patch any 60-character pathnames, to avoid a current Lustre bug.
3.468307
2.771615
1.251367
hashvals = {} fast_check = self.check_file( filepaths=self.data.keys(), hashvals=hashvals, hashfn=fast_hashes, shortcircuit=True, **args ) if not fast_check: # Save all the fast hashes for failed files th...
def check_fast(self, reproduce=False, **args)
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.
4.540131
4.332084
1.048025
# Ignore directories if os.path.isdir(fullpath): return False # Ignore anything matching the ignore patterns for pattern in self.ignore: if fnmatch.fnmatch(os.path.basename(fullpath), pattern): return False if filepath not in se...
def add_filepath(self, filepath, fullpath, copy=False)
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
2.509221
2.563476
0.978836
if hashfn is None: hashfn = fast_hashes self.add(filepath, hashfn, force, shortcircuit=True)
def add_fast(self, filepath, hashfn=None, force=False)
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.
5.474544
3.689701
1.483736
copy_file = False try: copy_file = self.data[filepath]['copy'] except KeyError: return False return copy_file
def copy_file(self, filepath)
Returns flag which says to copy rather than link a file.
4.826125
3.495077
1.380835
# Check file exists. It may have been deleted but still in manifest if not os.path.exists(self.fullpath(filepath)): print('File not found: {filepath}'.format( filepath=self.fullpath(filepath))) if self.contains(filepath): print('removing...
def make_link(self, filepath)
Payu integration function for creating symlinks in work directories which point back to the original file.
3.949842
3.891165
1.01508
filepath = os.path.normpath(filepath) if self.manifests[manifest].add_filepath(filepath, fullpath, copy): # Only link if filepath was added self.manifests[manifest].make_link(filepath)
def add_filepath(self, manifest, filepath, fullpath, copy=False)
Wrapper to the add_filepath function in PayuManifest. Prevents outside code from directly calling anything in PayuManifest.
4.56756
4.441004
1.028497
cmd = ['git', 'rev-parse', 'HEAD'] try: with open(os.devnull, 'w') as devnull: revision_hash = subprocess.check_output( cmd, cwd=dir, stderr=devnull ) if sys.version_info.major > 2: revision_hash = revisio...
def commit_hash(dir='.')
Return commit hash for HEAD of checked out branch of the specified directory.
2.362961
2.186433
1.080738
config_path = os.path.join(self.expt.control_path, DEFAULT_CONFIG_FNAME) self.manifest = [] if os.path.isfile(config_path): self.manifest.append(config_path) for model in self.expt.models: config_files = model.config_...
def create_manifest(self)
Construct the list of files to be tracked by the runlog.
4.080473
3.555129
1.147771
expt_name = self.config.get('name', self.expt.name) default_ssh_key = 'id_rsa_payu_' + expt_name ssh_key = self.config.get('sshid', default_ssh_key) ssh_key_path = os.path.join(os.path.expanduser('~'), '.ssh', 'payu', ssh_key) if not...
def push(self)
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:...
3.726795
2.986148
1.248028
if re.match(r'^[1-9][0-9]*$', expiration): return expiration + ".0a1" if re.match(r'^[1-9][0-9]*\.0$', expiration): return expiration + "a1" return expiration
def add_expiration_postfix(expiration)
Formats the expiration version and adds a version postfix if needed. :param expiration: the expiration version string. :return: the modified expiration string.
3.198048
3.17634
1.006834
try: with open(filename, 'r') as f: return yaml.safe_load(f) except IOError as e: raise ParserError('Error opening ' + filename + ': ' + e.message) except ValueError as e: raise ParserError('Error parsing processes in {}: {}' .format(filenam...
def load_yaml_file(filename)
Load a YAML file from disk, throw a ParserError on failure.
3.021659
2.66521
1.133741
if string in self.table: return self.table[string] else: result = self.current_index self.table[string] = result self.current_index += self.c_strlen(string) return result
def stringIndex(self, string)
Returns the index in the table of the provided string. Adds the string to the table if it's not there. :param string: the input string.
3.562003
3.793287
0.939028
entries = self.table.items() entries.sort(key=lambda x: x[1]) # Avoid null-in-string warnings with GCC and potentially # overlong string constants; write everything out the long way. def explodeToCharArray(string): def toCChar(s): if s == "'"...
def writeDefinition(self, f, name)
Writes the string table to a file as a C const char array. This writes out the string table as one single C char array for memory size reasons, separating the individual strings with '\0' characters. This way we can index directly into the string array and avoid the additional storage c...
5.133181
4.908601
1.045752
content_type = ContentType.objects.get_for_model(obj.__class__) comment_list = LogEntry.objects.filter( content_type=content_type, object_id=obj.pk, action_flag=COMMENT ) return { 'obj': obj, 'comment_list': comment_list, 'is_admin': context['is_admin...
def comments(context, obj)
Render comments for obj.
2.167509
2.16326
1.001964
try: ua = Account.objects.get( username=username, date_deleted__isnull=True) except Account.DoesNotExist: return 'Account not found' result = ua.get_disk_quota() if result is None: return False return result * 1048576
def get_disk_quota(username, machine_name=None)
Returns disk quota for username in KB
4.578815
4.472534
1.023763
filename = graphs.get_project_trend_graph_filename(project, start, end) csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv') png_filename = os.path.join(GRAPH_ROOT, filename + '.png') _check_directory_exists(csv_filename) _check_directory_exists(png_filename) if not settings.GRAPH_D...
def _gen_project_trend_graph(project, start, end, force_overwrite=False)
Generates a bar graph for a project Keyword arguments: project -- Project start -- start date end -- end date
1.952854
2.002125
0.975391
filename = graphs.get_institute_graph_filename(start, end) csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv') png_filename = os.path.join(GRAPH_ROOT, filename + '.png') _check_directory_exists(csv_filename) _check_directory_exists(png_filename) if not settings.GRAPH_DEBUG or force...
def _gen_institute_graph(start, end, force_overwrite=False)
Pie chart comparing institutes usage.
2.628359
2.562345
1.025763
filename = graphs.get_machine_graph_filename(start, end) csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv') png_filename = os.path.join(GRAPH_ROOT, filename + '.png') _check_directory_exists(csv_filename) _check_directory_exists(png_filename) if not settings.GRAPH_DEBUG or force_o...
def _gen_machine_graph(start, end, force_overwrite=False)
Pie chart comparing machines usage.
2.321159
2.208687
1.050922
filename = graphs.get_trend_graph_filename(start, end) csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv') png_filename = os.path.join(GRAPH_ROOT, filename + '.png') _check_directory_exists(csv_filename) _check_directory_exists(png_filename) if not settings.GRAPH_DEBUG or force_ove...
def _gen_trend_graph(start, end, force_overwrite=False)
Total trend graph for machine category.
2.019798
2.004606
1.007579