_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q16600
LogInterceptorMixin.add_request_log_fields
train
def add_request_log_fields( self, log_fields: LogFields, call_details: Union[grpc.HandlerCallDetails, grpc.ClientCallDetails] ): """Add log fields related to a request to the provided log fields :param log_fields: log fields instance to which ...
python
{ "resource": "" }
q16601
LogInterceptorMixin.add_response_log_fields
train
def add_response_log_fields(self, log_fields: LogFields, start_time: datetime, err: Exception): """Add log fields related to a response to the provided log fields :param log_fields: log fields instnace to which to add the fields :param start_time: start time of t...
python
{ "resource": "" }
q16602
select_worstcase_snapshots
train
def select_worstcase_snapshots(network): """ Select two worst-case snapshots from time series Two time steps in a time series represent worst-case snapshots. These are 1. Load case: refers to the point in the time series where the (load - generation) achieves its maximum and is greater than 0....
python
{ "resource": "" }
q16603
get_residual_load_from_pypsa_network
train
def get_residual_load_from_pypsa_network(pypsa_network): """ Calculates residual load in MW in MV grid and underlying LV grids. Parameters ---------- pypsa_network : :pypsa:`pypsa.Network<network>` The `PyPSA network <https://www.pypsa.org/doc/components.html#network>`_ container, ...
python
{ "resource": "" }
q16604
assign_load_feedin_case
train
def assign_load_feedin_case(network): """ For each time step evaluate whether it is a feed-in or a load case. Feed-in and load case are identified based on the generation and load time series and defined as follows: 1. Load case: positive (load - generation) at HV/MV substation 2. Feed-in case...
python
{ "resource": "" }
q16605
load_config
train
def load_config(filename, config_dir=None, copy_default_config=True): """ Loads the specified config file. Parameters ----------- filename : :obj:`str` Config file name, e.g. 'config_grid.cfg'. config_dir : :obj:`str`, optional Path to config file. If None uses default edisgo co...
python
{ "resource": "" }
q16606
get_default_config_path
train
def get_default_config_path(): """ Returns the basic edisgo config path. If it does not yet exist it creates it and copies all default config files into it. Returns -------- :obj:`str` Path to default edisgo config directory specified in config file 'config_system.cfg' in sectio...
python
{ "resource": "" }
q16607
make_directory
train
def make_directory(directory): """ Makes directory if it does not exist. Parameters ----------- directory : :obj:`str` Directory path """ if not os.path.isdir(directory): os.mkdir(directory) logger.info('Path {} not found, I will create it.' .for...
python
{ "resource": "" }
q16608
mv_line_load
train
def mv_line_load(network): """ Checks for over-loading issues in MV grid. Parameters ---------- network : :class:`~.grid.network.Network` Returns ------- :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded MV lines, their maximum relative over-loading...
python
{ "resource": "" }
q16609
lv_line_load
train
def lv_line_load(network): """ Checks for over-loading issues in LV grids. Parameters ---------- network : :class:`~.grid.network.Network` Returns ------- :pandas:`pandas.DataFrame<dataframe>` Dataframe containing over-loaded LV lines, their maximum relative over-loadin...
python
{ "resource": "" }
q16610
_line_load
train
def _line_load(network, grid, crit_lines): """ Checks for over-loading issues of lines. Parameters ---------- network : :class:`~.grid.network.Network` grid : :class:`~.grid.grids.LVGrid` or :class:`~.grid.grids.MVGrid` crit_lines : :pandas:`pandas.DataFrame<dataframe>` Dataframe co...
python
{ "resource": "" }
q16611
_station_load
train
def _station_load(network, station, crit_stations): """ Checks for over-loading of stations. Parameters ---------- network : :class:`~.grid.network.Network` station : :class:`~.grid.components.LVStation` or :class:`~.grid.components.MVStation` crit_stations : :pandas:`pandas.DataFrame<dataf...
python
{ "resource": "" }
q16612
mv_voltage_deviation
train
def mv_voltage_deviation(network, voltage_levels='mv_lv'): """ Checks for voltage stability issues in MV grid. Parameters ---------- network : :class:`~.grid.network.Network` voltage_levels : :obj:`str` Specifies which allowed voltage deviations to use. Possible options are: ...
python
{ "resource": "" }
q16613
check_ten_percent_voltage_deviation
train
def check_ten_percent_voltage_deviation(network): """ Checks if 10% criteria is exceeded. Parameters ---------- network : :class:`~.grid.network.Network` """ v_mag_pu_pfa = network.results.v_res() if (v_mag_pu_pfa > 1.1).any().any() or (v_mag_pu_pfa < 0.9).any().any(): message...
python
{ "resource": "" }
q16614
calc_geo_lines_in_buffer
train
def calc_geo_lines_in_buffer(network, node, grid, radius, radius_inc): """Determines lines in nodes' associated graph that are at least partly within buffer of radius from node. If there are no lines, the buffer is successively extended by radius_inc until lines are found. Parameters ---------- ...
python
{ "resource": "" }
q16615
calc_geo_dist_vincenty
train
def calc_geo_dist_vincenty(network, node_source, node_target): """Calculates the geodesic distance between node_source and node_target incorporating the detour factor in config. Parameters ---------- network : :class:`~.grid.network.Network` The eDisGo container object node_source : :cl...
python
{ "resource": "" }
q16616
get_username
train
def get_username(details, backend, response, *args, **kwargs): """Sets the `username` argument. If the user exists already, use the existing username. Otherwise generate username from the `new_uuid` using the `helusers.utils.uuid_to_username` function. """ user = details.get('user') if not...
python
{ "resource": "" }
q16617
SocialAccountAdapter.pre_social_login
train
def pre_social_login(self, request, sociallogin): """Update user based on token information.""" user = sociallogin.user # If the user hasn't been saved yet, it will be updated # later on in the sign-up flow. if not user.pk: return data = sociallogin.account....
python
{ "resource": "" }
q16618
AbstractUser.sync_groups_from_ad
train
def sync_groups_from_ad(self): """Determine which Django groups to add or remove based on AD groups.""" ad_list = ADGroupMapping.objects.values_list('ad_group', 'group') mappings = {ad_group: group for ad_group, group in ad_list} user_ad_groups = set(self.ad_groups.filter(groups__isnul...
python
{ "resource": "" }
q16619
patch_jwt_settings
train
def patch_jwt_settings(): """Patch rest_framework_jwt authentication settings from allauth""" defaults = api_settings.defaults defaults['JWT_PAYLOAD_GET_USER_ID_HANDLER'] = ( __name__ + '.get_user_id_from_payload_handler') if 'allauth.socialaccount' not in settings.INSTALLED_APPS: retur...
python
{ "resource": "" }
q16620
uuid_to_username
train
def uuid_to_username(uuid): """ Convert UUID to username. >>> uuid_to_username('00fbac99-0bab-5e66-8e84-2e567ea4d1f6') 'u-ad52zgilvnpgnduefzlh5jgr6y' >>> uuid_to_username(UUID('00fbac99-0bab-5e66-8e84-2e567ea4d1f6')) 'u-ad52zgilvnpgnduefzlh5jgr6y' """ uuid_data = getattr(uuid, 'bytes',...
python
{ "resource": "" }
q16621
username_to_uuid
train
def username_to_uuid(username): """ Convert username to UUID. >>> username_to_uuid('u-ad52zgilvnpgnduefzlh5jgr6y') UUID('00fbac99-0bab-5e66-8e84-2e567ea4d1f6') """ if not username.startswith('u-') or len(username) != 28: raise ValueError('Not an UUID based username: %r' % (username,)) ...
python
{ "resource": "" }
q16622
oidc_to_user_data
train
def oidc_to_user_data(payload): """ Map OIDC claims to Django user fields. """ payload = payload.copy() field_map = { 'given_name': 'first_name', 'family_name': 'last_name', 'email': 'email', } ret = {} for token_attr, user_attr in field_map.items(): if t...
python
{ "resource": "" }
q16623
UserAuthorization.has_api_scopes
train
def has_api_scopes(self, *api_scopes): """ Test if all given API scopes are authorized. :type api_scopes: list[str] :param api_scopes: The API scopes to test :rtype: bool|None :return: True or False, if the API Token has the API scopes field set, oth...
python
{ "resource": "" }
q16624
UserAuthorization.has_api_scope_with_prefix
train
def has_api_scope_with_prefix(self, prefix): """ Test if there is an API scope with the given prefix. :rtype: bool|None """ if self._authorized_api_scopes is None: return None return any( x == prefix or x.startswith(prefix + '.') for x...
python
{ "resource": "" }
q16625
Client.register_site
train
def register_site(self): """Function to register the site and generate a unique ID for the site Returns: **string:** The ID of the site (also called client id) if the registration is successful Raises: **OxdServerError:** If the site registration fails. """ ...
python
{ "resource": "" }
q16626
Client.get_authorization_url
train
def get_authorization_url(self, acr_values=None, prompt=None, scope=None, custom_params=None): """Function to get the authorization url that can be opened in the browser for the user to provide authorization and authentication Parameters: * **acr_values...
python
{ "resource": "" }
q16627
Client.get_tokens_by_code
train
def get_tokens_by_code(self, code, state): """Function to get access code for getting the user details from the OP. It is called after the user authorizes by visiting the auth URL. Parameters: * **code (string):** code, parse from the callback URL querystring * **state (...
python
{ "resource": "" }
q16628
Client.get_access_token_by_refresh_token
train
def get_access_token_by_refresh_token(self, refresh_token, scope=None): """Function that is used to get a new access token using refresh token Parameters: * **refresh_token (str):** refresh_token from get_tokens_by_code command * **scope (list, optional):** a list of scopes. If ...
python
{ "resource": "" }
q16629
Client.get_user_info
train
def get_user_info(self, access_token): """Function to get the information about the user using the access code obtained from the OP Note: Refer to the /.well-known/openid-configuration URL of your OP for the complete list of the claims for different scopes. Para...
python
{ "resource": "" }
q16630
Client.get_logout_uri
train
def get_logout_uri(self, id_token_hint=None, post_logout_redirect_uri=None, state=None, session_state=None): """Function to logout the user. Parameters: * **id_token_hint (string, optional):** oxd server will use last used ID Token, if not provided * **pos...
python
{ "resource": "" }
q16631
Client.update_site
train
def update_site(self, client_secret_expires_at=None): """Function to update the site's information with OpenID Provider. This should be called after changing the values in the cfg file. Parameters: * **client_secret_expires_at (long, OPTIONAL):** milliseconds since 1970, can be used...
python
{ "resource": "" }
q16632
Client.uma_rs_protect
train
def uma_rs_protect(self, resources, overwrite=None): """Function to be used in a UMA Resource Server to protect resources. Parameters: * **resources (list):** list of resource to protect. See example at `here <https://gluu.org/docs/oxd/3.1.2/api/#uma-rs-protect-resources>`_ * **...
python
{ "resource": "" }
q16633
Client.uma_rs_check_access
train
def uma_rs_check_access(self, rpt, path, http_method): """Function to be used in a UMA Resource Server to check access. Parameters: * **rpt (string):** RPT or blank value if absent (not send by RP) * **path (string):** Path of resource (e.g. for http://rs.com/phones, /phones sho...
python
{ "resource": "" }
q16634
Client.uma_rp_get_rpt
train
def uma_rp_get_rpt(self, ticket, claim_token=None, claim_token_format=None, pct=None, rpt=None, scope=None, state=None): """Function to be used by a UMA Requesting Party to get RPT token. Parameters: * **ticket (str, REQUIRED):** ticket * **claim_token (st...
python
{ "resource": "" }
q16635
Client.uma_rp_get_claims_gathering_url
train
def uma_rp_get_claims_gathering_url(self, ticket): """UMA RP function to get the claims gathering URL. Parameters: * **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt Returns: **string** sp...
python
{ "resource": "" }
q16636
Client.setup_client
train
def setup_client(self): """The command registers the client for communication protection. This will be used to obtain an access token via the Get Client Token command. The access token will be passed as a protection_access_token parameter to other commands. Note: If ...
python
{ "resource": "" }
q16637
Client.get_client_token
train
def get_client_token(self, client_id=None, client_secret=None, op_host=None, op_discovery_path=None, scope=None, auto_update=True): """Function to get the client token which can be used for protection in all future communication. The access token receive...
python
{ "resource": "" }
q16638
Client.remove_site
train
def remove_site(self): """Cleans up the data for the site. Returns: oxd_id if the process was completed without error Raises: OxdServerError if there was an issue with the operation """ params = dict(oxd_id=self.oxd_id) logger.debug("Sending com...
python
{ "resource": "" }
q16639
Client.introspect_rpt
train
def introspect_rpt(self, rpt): """Gives information about an RPT. Parameters: * **rpt (str, required):** rpt from uma_rp_get_rpt function Returns: **dict:** The information about the RPT. Example response :: { "active": ...
python
{ "resource": "" }
q16640
DjangoCmsMixin.get_placeholder_field_names
train
def get_placeholder_field_names(self): """ Returns a list with the names of all PlaceholderFields. """ return [field.name for field in self._meta.fields if field.get_internal_type() == 'PlaceholderField']
python
{ "resource": "" }
q16641
logout_callback
train
def logout_callback(): """Route called by the OpenID provider when user logs out. Clear the cookies here. """ resp = make_response('Logging Out') resp.set_cookie('sub', 'null', expires=0) resp.set_cookie('session_id', 'null', expires=0) return resp
python
{ "resource": "" }
q16642
SocketMessenger.__connect
train
def __connect(self): """A helper function to make connection.""" try: logger.debug("Socket connecting to %s:%s", self.host, self.port) self.sock.connect((self.host, self.port)) except socket.error as e: logger.exception("socket error %s", e) logger...
python
{ "resource": "" }
q16643
SocketMessenger.send
train
def send(self, command): """send function sends the command to the oxd server and recieves the response. Parameters: * **command (dict):** Dict representation of the JSON command string Returns: **response (dict):** The JSON response from the oxd Server as a dic...
python
{ "resource": "" }
q16644
SocketMessenger.request
train
def request(self, command, **kwargs): """Function that builds the request and returns the response from oxd-server Parameters: * **command (str):** The command that has to be sent to the oxd-server * ** **kwargs:** The parameters that should accompany the request ...
python
{ "resource": "" }
q16645
HttpMessenger.request
train
def request(self, command, **kwargs): """Function that builds the request and returns the response Parameters: * **command (str):** The command that has to be sent to the oxd-server * ** **kwargs:** The parameters that should accompany the request Returns: *...
python
{ "resource": "" }
q16646
ChebiEntity.get_mol_filename
train
def get_mol_filename(self): '''Returns mol filename''' mol_filename = parsers.get_mol_filename(self.__chebi_id) if mol_filename is None: mol_filename = parsers.get_mol_filename(self.get_parent_id()) if mol_filename is None: for parent_or_child_id in self.__get_a...
python
{ "resource": "" }
q16647
ChebiEntity.__get_all_ids
train
def __get_all_ids(self): '''Returns all ids''' if self.__all_ids is None: parent_id = parsers.get_parent_id(self.__chebi_id) self.__all_ids = parsers.get_all_ids(self.__chebi_id if math.isnan(parent_id) ...
python
{ "resource": "" }
q16648
Resource.set_scope
train
def set_scope(self, http_method, scope): """Set a scope condition for the resource for a http_method Parameters: * **http_method (str):** HTTP method like GET, POST, PUT, DELETE * **scope (str, list):** the scope of access control as str if single, or as a list of strings if mul...
python
{ "resource": "" }
q16649
ResourceSet.add
train
def add(self, path): """Adds a new resource with the given path to the resource set. Parameters: * **path (str, unicode):** path of the resource to be protected Raises: TypeError when the path is not a string or a unicode string """ if not isinstance(pat...
python
{ "resource": "" }
q16650
search
train
def search(term, exact=False, rows=1e6): '''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['ob...
python
{ "resource": "" }
q16651
Configurer.get
train
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 require...
python
{ "resource": "" }
q16652
Configurer.set
train
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...
python
{ "resource": "" }
q16653
get_all_formulae
train
def get_all_formulae(chebi_ids): '''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]
python
{ "resource": "" }
q16654
get_all_comments
train
def get_all_comments(chebi_ids): '''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]
python
{ "resource": "" }
q16655
get_all_compound_origins
train
def get_all_compound_origins(chebi_ids): '''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]
python
{ "resource": "" }
q16656
get_all_modified_on
train
def get_all_modified_on(chebi_ids): '''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 els...
python
{ "resource": "" }
q16657
get_all_database_accessions
train
def get_all_database_accessions(chebi_ids): '''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]
python
{ "resource": "" }
q16658
get_all_names
train
def get_all_names(chebi_ids): '''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]
python
{ "resource": "" }
q16659
get_all_outgoings
train
def get_all_outgoings(chebi_ids): '''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]
python
{ "resource": "" }
q16660
get_all_incomings
train
def get_all_incomings(chebi_ids): '''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]
python
{ "resource": "" }
q16661
get_mol_filename
train
def get_mol_filename(chebi_id): '''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.writ...
python
{ "resource": "" }
q16662
get_file
train
def get_file(filename): '''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.u...
python
{ "resource": "" }
q16663
__is_current
train
def __is_current(filepath): '''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()
python
{ "resource": "" }
q16664
__get_last_update_time
train
def __get_last_update_time(): '''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, n...
python
{ "resource": "" }
q16665
__get_first_tuesday
train
def __get_first_tuesday(this_date): '''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_...
python
{ "resource": "" }
q16666
get_frontend_data_dict_for_cms_page
train
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. """ placeholders = list(cms_page.placeholders.all()) placeholder_frontend_data_dict = get_frontend_data_dict_for_placeholders( ...
python
{ "resource": "" }
q16667
get_frontend_data_dict_for_placeholders
train
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. """ data_dict = {} for placeholder in placeho...
python
{ "resource": "" }
q16668
Writer.write_waypoint
train
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( ...
python
{ "resource": "" }
q16669
Model.set_model_pathnames
train
def set_model_pathnames(self): """Define the paths associated with this model.""" 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(se...
python
{ "resource": "" }
q16670
Model.archive
train
def archive(self): """Store model output to laboratory archive.""" # 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.pa...
python
{ "resource": "" }
q16671
parse
train
def parse(): """Parse the command line inputs and execute the subcommand.""" # Build the list of subcommand modules modnames = [mod for (_, mod, _) in pkgutil.iter_modules(payu.subcommands.__path__, prefix=payu.subcommands.__name__ + '.') ...
python
{ "resource": "" }
q16672
get_model_type
train
def get_model_type(model_type, config): """Determine and validate the active model type.""" # 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: mod...
python
{ "resource": "" }
q16673
set_env_vars
train
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.""" payu_env_vars = {} # Setup Python dynamic library link lib_paths = sysconfig.get_config_vars('LIBDIR') payu_env_vars...
python
{ "resource": "" }
q16674
submit_job
train
def submit_job(pbs_script, pbs_config, pbs_vars=None): """Submit a userscript the scheduler.""" # 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 = pb...
python
{ "resource": "" }
q16675
Namcouple.substitute_timestep
train
def substitute_timestep(self, regex, timestep): """ Substitute a new timestep value using regex. """ # Make one change at a time, each change affects subsequent matches. timestep_changed = False while True: matches = re.finditer(regex, self.str, re.MULTILINE ...
python
{ "resource": "" }
q16676
int_to_date
train
def int_to_date(date): """ Convert an int of form yyyymmdd to a python date object. """ year = date // 10**4 month = date % 10**4 // 10**2 day = date % 10**2 return datetime.date(year, month, day)
python
{ "resource": "" }
q16677
runtime_from_date
train
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. """ end_date = start_date + relativedelta(years=years, months=months, ...
python
{ "resource": "" }
q16678
date_plus_seconds
train
def date_plus_seconds(init_date, seconds, caltype): """ Get a new_date = date + seconds. Ignores Feb 29 for no-leap days. """ end_date = init_date + datetime.timedelta(seconds=seconds) if caltype == NOLEAP: end_date += get_leapdays(init_date, end_date) if end_date.month == 2 a...
python
{ "resource": "" }
q16679
get_leapdays
train
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. """ curr_date = init_date leap_days = 0 while curr_date != final_date: if curr_date.month == 2 and curr_d...
python
{ "resource": "" }
q16680
calculate_leapdays
train
def calculate_leapdays(init_date, final_date): """Currently unsupported, it only works for differences in years.""" 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 - (ini...
python
{ "resource": "" }
q16681
Laboratory.get_default_lab_path
train
def get_default_lab_path(self, config): """Generate a default laboratory path based on user environment.""" # Default path settings # Append project name if present (NCI-specific) default_project = os.environ.get('PROJECT', '') default_short_path = os.path.join('/short', default...
python
{ "resource": "" }
q16682
Laboratory.initialize
train
def initialize(self): """Create the laboratory directories.""" mkdir_p(self.archive_path) mkdir_p(self.bin_path) mkdir_p(self.codebase_path) mkdir_p(self.input_basepath)
python
{ "resource": "" }
q16683
get_job_id
train
def get_job_id(short=True): """ Return PBS job id """ jobid = os.environ.get('PBS_JOBID', '') if short: # Strip off '.rman2' jobid = jobid.split('.')[0] return(jobid)
python
{ "resource": "" }
q16684
get_job_info
train
def get_job_info(): """ Get information about the job from the PBS server """ 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['Jo...
python
{ "resource": "" }
q16685
Experiment.postprocess
train
def postprocess(self): """Submit a postprocessing script after collation""" 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, '...
python
{ "resource": "" }
q16686
date_to_um_date
train
def date_to_um_date(date): """ Convert a date object to 'year, month, day, hour, minute, second.' """ assert date.hour == 0 and date.minute == 0 and date.second == 0 return [date.year, date.month, date.day, 0, 0, 0]
python
{ "resource": "" }
q16687
um_date_to_date
train
def um_date_to_date(d): """ Convert a string with format 'year, month, day, hour, minute, second' to a datetime date. """ return datetime.datetime(year=d[0], month=d[1], day=d[2], hour=d[3], minute=d[4], second=d[5])
python
{ "resource": "" }
q16688
setup
train
def setup(basepath=DEFAULT_BASEPATH): """Set the environment modules used by the Environment Module system.""" 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(modulesh...
python
{ "resource": "" }
q16689
module
train
def module(command, *args): """Run the modulecmd tool and use its Python-formatted output to set the environment variables.""" if 'MODULESHOME' not in os.environ: print('payu: warning: No Environment Modules found; skipping {0} call.' ''.format(command)) return modulecmd ...
python
{ "resource": "" }
q16690
Mom6.init_config
train
def init_config(self): """Patch input.nml as a new or restart run.""" 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'...
python
{ "resource": "" }
q16691
mkdir_p
train
def mkdir_p(path): """Create a new directory; ignore if it already exists.""" try: os.makedirs(path) except EnvironmentError as exc: if exc.errno != errno.EEXIST: raise
python
{ "resource": "" }
q16692
read_config
train
def read_config(config_fname=None): """Parse input configuration file and return a config dict.""" 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 ex...
python
{ "resource": "" }
q16693
make_symlink
train
def make_symlink(src_path, lnk_path): """Safely create a symbolic link to an input field.""" # 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 s...
python
{ "resource": "" }
q16694
splitpath
train
def splitpath(path): """Recursively split a filepath into all directories and files.""" head, tail = os.path.split(path) if tail == '': return head, elif head == '': return tail, else: return splitpath(head) + (tail,)
python
{ "resource": "" }
q16695
patch_lustre_path
train
def patch_lustre_path(f_path): """Patch any 60-character pathnames, to avoid a current Lustre bug.""" 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
python
{ "resource": "" }
q16696
PayuManifest.check_fast
train
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. """ hashvals = {} fast_check = self.check_file( filepaths=self.data.keys...
python
{ "resource": "" }
q16697
PayuManifest.add_filepath
train
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 "...
python
{ "resource": "" }
q16698
PayuManifest.add_fast
train
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. """ if has...
python
{ "resource": "" }
q16699
PayuManifest.copy_file
train
def copy_file(self, filepath): """ Returns flag which says to copy rather than link a file. """ copy_file = False try: copy_file = self.data[filepath]['copy'] except KeyError: return False return copy_file
python
{ "resource": "" }