code
stringlengths
1
18.2k
# replace first TaxRef in cladeidents with cladestring cladeidents[0].change(ident=cladestring, rank=rank) # replace all other TaxRefs with '' for e in cladeidents[1:]: e.change(ident='', rank=rank) # join any remaining strands into tree if len(taxdict.hierarchy[taxdict.taxonomy[-1]]) > 1: # unlist first clade = [e[0] ...
def change(self, ident, rank=None): '''Change ident''' self.ident = ident if rank: self.rank = rank self.level = self._getLevel(rank, self.taxonomy) # count changes made to instance self.counter += 1
def _additional(self, idents, kwargs): '''Add additional data slots from **kwargs''' if kwargs: for name, value in list(kwargs.items()): if not isinstance(value, list): raise ValueError('Additional arguments must be lists of \ same length as idents') for i in range(len(value)): self[idents[i]][name] = value[i]
def _slice(self, level): '''Return list of tuples of ident and lineage ident for given level (numbered rank)''' if level >= len(self.taxonomy): raise IndexError('Level greater than size of taxonomy') res = [] for ident in sorted(list(self.keys())): res.append((self[ident]['taxref'], self[ident]['lineage'][level])) retu...
def _group(self, taxslice): '''Return list of lists of idents grouped by shared rank''' res = [] while taxslice: taxref, lident = taxslice.pop() if lident == '': res.append(([taxref], lident)) else: # identify idents in the same group and pop from taxslice i = 0 group = [] while i < len(taxslice): if taxslice[i][1] == ...
def _hierarchy(self): '''Generate dictionary of referenced idents grouped by shared rank''' self.hierarchy = {} for rank in self.taxonomy: # extract lineage idents for this rank taxslice = self._slice(level=self.taxonomy.index(rank)) # group idents by shared group at this rank self.hierarchy[rank] = self._group(taxslic...
def _contextualise(self): '''Determine contextual idents (cidents)''' # loop through hierarchy identifying unique lineages # TODO: gain other contextual information, not just ident deja_vues = [] for rank in reversed(self.taxonomy): # return named clades -- '' are ignored clades = [e for e in self.hierarchy[rank] if e[...
def load_module(self, module): """ Load a module string like django.contrib.markup.templatetags.markup into the registry Iterates through the module looking for callables w/ attributes matching Native Tags """ if isinstance(module, basestring) and module.find('.') > -1: a = module.split('.') module = ('.%s' % a[-1], '....
def register(self, bucket, name_or_func, func=None): """ Add a function to the registry by name """ assert bucket in self, 'Bucket %s is unknown' % bucket if func is None and hasattr(name_or_func, '__name__'): name = name_or_func.__name__ func = name_or_func elif func: name = name_or_func if name in self[bucket]: raise...
def unregister(self, bucket, name): """ Remove the function from the registry by name """ assert bucket in self, 'Bucket %s is unknown' % bucket if not name in self[bucket]: raise NotRegistered('The function %s is not registered' % name) del self[bucket][name]
def get_doc(self, tag_name): "Get documentation for the first tag matching the given name" for tag,func in self.tags: if tag.startswith(tag_name) and func.__doc__: return func.__doc__
def get_bucket(self, name): "Find out which bucket a given tag name is in" for bucket in self: for k,v in self[bucket].items(): if k == name: return bucket
def get(self, name): "Get the first tag function matching the given name" for bucket in self: for k,v in self[bucket].items(): if k == name: return v
def tags(self): "Iterate over all tags yielding (name, function)" for bucket in self: for k,v in self[bucket].items(): yield k,v
def open_listing_page(trailing_part_of_url): """ Opens a BBC radio tracklisting page based on trailing part of url. Returns a lxml ElementTree derived from that page. trailing_part_of_url: a string, like the pid or e.g. pid/segments.inc """ base_url = 'http://www.bbc.co.uk/programmes/' print("Opening web page: " + base...
def get_programme_title(pid): """Take BBC programme ID as string; returns programme title as string.""" print("Extracting title and station...") main_page_etree = open_listing_page(pid) try: title, = main_page_etree.xpath('//title/text()') except ValueError: title = '' return title.strip()
def get_broadcast_date(pid): """Take BBC pid (string); extract and return broadcast date as string.""" print("Extracting first broadcast date...") broadcast_etree = open_listing_page(pid + '/broadcasts.inc') original_broadcast_date, = broadcast_etree.xpath( '(//div[@class="grid__inner"]//div' '[@class="broadcast-event_...
def extract_listing(pid): """Extract listing; return list of tuples (artist(s), title, label).""" print("Extracting tracklisting...") listing_etree = open_listing_page(pid + '/segments.inc') track_divs = listing_etree.xpath('//div[@class="segment__track"]') listing = [] for track_div in track_divs: try: artist_names = ...
def generate_output(listing, title, date): """ Returns a string containing a full tracklisting. listing: list of (artist(s), track, record label) tuples title: programme title date: programme date """ listing_string = '{0}\n{1}\n\n'.format(title, date) for entry in listing: listing_string += '\n'.join(entry) + '\n***\n...
def get_output_filename(args): """Returns a filename as string without an extension.""" # If filename and path provided, use these for output text file. if args.directory is not None and args.fileprefix is not None: path = args.directory filename = args.fileprefix output = os.path.join(path, filename) # Otherwise, set ...
def write_listing_to_textfile(textfile, tracklisting): """Write tracklisting to a text file.""" with codecs.open(textfile, 'wb', 'utf-8') as text: text.write(tracklisting)
def save_tag_to_audio_file(audio_file, tracklisting): """ Saves tag to audio file. """ print("Trying to tag {}".format(audio_file)) f = mediafile.MediaFile(audio_file) if not f.lyrics: print("No tracklisting present. Creating lyrics tag.") f.lyrics = 'Tracklisting' + '\n' + tracklisting elif tracklisting not in f.lyric...
def tag_audio_file(audio_file, tracklisting): """ Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails. """ try: save_tag_to_audio_file(audio_file, tracklisting) # TODO: is IOError required now or would the mediafile exception cover it? e...
def output_to_file(filename, tracklisting, action): """ Produce requested output; either output text file, tag audio file or do both. filename: a string of path + filename without file extension tracklisting: a string containing a tracklisting action: 'tag', 'text' or 'both', from command line arguments """ if action i...
def write_text(filename, tracklisting): """Handle writing tracklisting to text.""" print("Saving text file.") try: write_listing_to_textfile(filename + '.txt', tracklisting) except IOError: # if all else fails, just print listing print("Cannot write text file to path: {}".format(filename)) print("Printing tracklisting ...
def tag_audio(filename, tracklisting): """Return True if audio tagged successfully; handle tagging audio.""" # TODO: maybe actually glob for files, then try tagging if present? if not(tag_audio_file(filename + '.m4a', tracklisting) or tag_audio_file(filename + '.mp3', tracklisting)): print("Cannot find or access any re...
def main(): """Get a tracklisting, write to audio file or text.""" args = parse_arguments() pid = args.pid title = get_programme_title(pid) broadcast_date = get_broadcast_date(pid) listing = extract_listing(pid) filename = get_output_filename(args) tracklisting = generate_output(listing, title, broadcast_date) output_t...
def replace_vcf_info(keyword, annotation, variant_line=None, variant_dict=None): """Replace the information of a info field of a vcf variant line or a variant dict. Arguments: variant_line (str): A vcf formatted variant line variant_dict (dict): A variant dictionary keyword (str): The info field key annotation (str): I...
';'.join(new_info_list) splitted_variant[7] = new_info_string fixed_variant = '\t'.join(splitted_variant) elif variant_dict: logger.debug("Adding information to a variant dict") old_info = variant_dict['INFO'] if old_info == '.': variant_dict['INFO'] = new_info else: for info in old_info.split(';'): splitted_info_entry...
def remove_vcf_info(keyword, variant_line=None, variant_dict=None): """Remove the information of a info field of a vcf variant line or a variant dict. Arguments: variant_line (str): A vcf formatted variant line variant_dict (dict): A variant dictionary keyword (str): The info field key Returns: variant_line (str): A an...
= variant_dict['INFO'] if old_info == '.': variant_dict['INFO'] = old_info else: new_info_string = get_new_info_string(old_info, keyword) variant_dict['INFO'] = new_info_string fixed_variant = variant_dict return fixed_variant
def add_vcf_info(keyword, variant_line=None, variant_dict=None, annotation=None): """ Add information to the info field of a vcf variant line. Arguments: variant_line (str): A vcf formatted variant line keyword (str): The info field key annotation (str): If the annotation is a key, value pair this is the string that re...
if old_info == '.': variant_dict['INFO'] = new_info else: variant_dict['INFO'] = "{0};{1}".format(old_info, new_info) fixed_variant = variant_dict return fixed_variant
def sync_auth_groups(): """ Syncs auth groups according to settings.AUTH_GROUPS :return: """ from django.conf import settings from django.contrib.auth.models import Group, Permission from django.db.models import Q for data in settings.AUTH_GROUPS: g1 = Group.objects.get_or_create(name=data['name'])[0] g1.permissions.cl...
def createsuperusers(): """ Creates all superusers defined in settings.INITIAL_SUPERUSERS. These superusers do not have any circles. They are plain superusers. However you may want to signup yourself and make this new user a super user then. """ from django.contrib.auth import models as auth_models from django.conf imp...
default is_staff root.is_staff = True root.is_superuser = True root.save() send_mail( subject='Your superuser account', recipient_list=[entry['email']], from_email=settings.DEFAULT_FROM_EMAIL, message='username: {username}\npassword: {pw}\nsite: {site}'.format( username=root.username, pw=password, site=site.domain ), )...
def _log(message): """ Logs a message. :param str message: The log message. :rtype: None """ # @todo Replace with log package. print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ' ' + str(message), flush=True)
def _handle_exception(self, row, exception): """ Logs an exception occurred during transformation of a row. :param list|dict|() row: The source row. :param Exception exception: The exception. """ self._log('Error during processing of line {0:d}.'.format(self._source_reader.row_number)) self._log(row) self._log(str(exce...
def _find_all_step_methods(self): """ Finds all _step<n> methods where n is an integer in this class. """ steps = ([method for method in dir(self) if callable(getattr(self, method)) and re.match(r'_step\d+\d+.*', method)]) steps = sorted(steps) for step in steps: self._steps.append(getattr(self, step))
def _transform_rows(self): """ Transforms all source rows. """ self._find_all_step_methods() for row in self._source_reader.next(): self._transform_row_wrapper(row)
def _transform_row_wrapper(self, row): """ Transforms a single source row. :param dict[str|str] row: The source row. """ self._count_total += 1 try: # Transform the naturals keys in line to technical keys. in_row = copy.copy(row) out_row = {} park_info, ignore_info = self._transform_row(in_row, out_row) except Exceptio...
def _transform_row(self, in_row, out_row): """ Transforms an input row to an output row (i.e. (partial) dimensional data). :param dict[str,str] in_row: The input row. :param dict[str,T] out_row: The output row. :rtype: (str,str) """ tmp_row = {} for step in self._steps: park_info, ignore_info = step(in_row, tmp_row, ou...
def _step00(self, in_row, tmp_row, out_row): """ Prunes whitespace for all fields in the input row. :param dict in_row: The input row. :param dict tmp_row: Not used. :param dict out_row: Not used. """ for key, value in in_row.items(): in_row[key] = WhitespaceCleaner.clean(value) return None, None
def _step99(self, in_row, tmp_row, out_row): """ Validates all mandatory fields are in the output row and are filled. :param dict in_row: The input row. :param dict tmp_row: Not used. :param dict out_row: The output row. """ park_info = '' for field in self._mandatory_fields: if field not in out_row or not out_row[fiel...
def _log_statistics(self): """ Log statistics about the number of rows and number of rows per second. """ rows_per_second_trans = self._count_total / (self._time1 - self._time0) rows_per_second_load = self._count_transform / (self._time2 - self._time1) rows_per_second_overall = self._count_total / (self._time3 - self._...
def transform_source_rows(self): """ Transforms the rows for the source system into (partial) dimensional data. """ # Start timer for overall progress. self._time0 = time.perf_counter() self.pre_transform_source_rows() # Transform all source rows. with self._source_reader: with self._transformed_writer: with self._park...
def list_tags(self): """ Get the tags of current object :return: the tags :rtype: list """ from highton.models.tag import Tag return fields.ListField( name=self.ENDPOINT, init_class=Tag ).decode( self.element_from_string( self._get_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Tag.ENDPOINT, ).text ) )
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") and (not whitelist or k in whitelist) }
def _get_user_agent(platform=None): """ Convenience function that looks up a user agent string, random if N/A """ if isinstance(platform, ustr): platform = platform.upper() return {"chrome": AGENT_CHROME, "edge": AGENT_EDGE, "ios": AGENT_IOS}.get( platform, random.choice(AGENT_ALL) )
def _request_json( url, parameters=None, body=None, headers=None, cache=True, agent=None, reattempt=5, ): """ Queries a url for json data Note: Requests are cached using requests_cached for a week, this is done transparently by using the package's monkey patching """ assert url content = None status = 500 log.info("url...
False) except RequestException as e: log.debug(e, exc_info=True) return _request_json( url, parameters, body, headers, cache, agent, reattempt - 1 ) except Exception as e: log.error(e, exc_info=True) if reattempt > 0: SESSION.cache.clear() return _request_json( url, parameters, body, headers, False, agent, 0 ) else: lo...
def tmdb_find( api_key, external_source, external_id, language="en-US", cache=True ): """ Search for The Movie Database objects using another DB's foreign key Note: language codes aren't checked on this end or by TMDb, so if you enter an invalid language code your search itself will succeed, but certain fields like syn...
API key") elif status != 200 or not any(content.keys()): raise MapiNetworkException("TMDb down or unavailable?") elif status == 404 or not any(content.get(k, {}) for k in keys): raise MapiNotFoundException return content
def tmdb_movies(api_key, id_tmdb, language="en-US", cache=True): """ Lookup a movie item using The Movie Database Online docs: developers.themoviedb.org/3/movies """ try: url = "https://api.themoviedb.org/3/movie/%d" % int(id_tmdb) except ValueError: raise MapiProviderException("id_tmdb must be numeric") parameters = {...
def tmdb_search_movies( api_key, title, year=None, adult=False, region=None, page=1, cache=True ): """ Search for movies using The Movie Database Online docs: developers.themoviedb.org/3/search/search-movies """ url = "https://api.themoviedb.org/3/search/movie" try: if year: year = int(year) except ValueError: raise Ma...
def tvdb_login(api_key): """ Logs into TVDb using the provided api key Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister Online docs: api.thetvdb.com/swagger#!/Authentication/post_login= """ url = "https://api.thetvdb.com/login" body = {"apikey": api_key} status, content = _request_json(url, bo...
def tvdb_refresh_token(token): """ Refreshes JWT token Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token= """ url = "https://api.thetvdb.com/refresh_token" headers = {"Authorization": "Bearer %s" % token} status, content = _request_json(url, headers=headers, cache=False) if status == 401: raise Ma...
def tvdb_series_id(token, id_tvdb, lang="en", cache=True): """ Returns a series records that contains all information known about a particular series id Online docs: api.thetvdb.com/swagger#!/Series/get_series_id= """ if lang not in TVDB_LANGUAGE_CODES: raise MapiProviderException( "'lang' must be one of %s" % ",".join...
def tvdb_search_series( token, series=None, id_imdb=None, id_zap2it=None, lang="en", cache=True ): """ Allows the user to search for a series based on the following parameters Online docs: https://api.thetvdb.com/swagger#!/Search/get_search_series Note: results a maximum of 100 entries per page, no option for paginatio...
def t_ID(self, t): r'~?[a-zA-Z_][a-zA-Z0-9_]*' if t.value[0] == '~': t.type = 'TYVAR' t.value = t.value[1:] elif t.value in self.reserved_words: t.type = self.reserved_words[t.value] else: t.type = 'ID' return t
def parse_meta_data(self, line): """Parse a vcf metadataline""" line = line.rstrip() logger.debug("Parsing metadata line:{0}".format(line)) line_info = line[2:].split('=') match = False if line_info[0] == 'fileformat': logger.debug("Parsing fileformat") try: self.fileformat = line_info[1] logger.debug("Found fileformat...
'').split(':')[-1].split('|')] self.info_dict[match.group('id')] = line elif line_info[0] == 'FILTER': match = self.filter_pattern.match(line) if not match: raise SyntaxError("One of the FILTER lines is malformed: {0}".format(line)) matches = [match.group('id'), match.group('desc')] self.filter_lines.append(dict( list(...
self.meta_pattern.match(line) if not match: raise SyntaxError("One of the meta data lines is malformed: {0}".format(line)) self.other_lines.append({match.group('key'): match.group('val')}) self.other_dict[match.group('key')] = line
def remove_header(self, name): """Remove a field from the header""" if name in self.info_dict: self.info_dict.pop(name) logger.info("Removed '{0}' from INFO".format(name)) if name in self.filter_dict: self.filter_dict.pop(name) logger.info("Removed '{0}' from FILTER".format(name)) if name in self.format_dict: self.form...
def add_fileformat(self, fileformat): """ Add fileformat line to the header. Arguments: fileformat (str): The id of the info line """ self.fileformat = fileformat logger.info("Adding fileformat to vcf: {0}".format(fileformat)) return
def add_meta_line(self, key, value): """ Adds an arbitrary metadata line to the header. This must be a key value pair Arguments: key (str): The key of the metadata line value (str): The value of the metadata line """ meta_line = '##{0}={1}'.format( key, value ) logger.info("Adding meta line to vcf: {0}".format(meta_lin...
def add_filter(self, filter_id, description): """ Add a filter line to the header. Arguments: filter_id (str): The id of the filter line description (str): A description of the info line """ filter_line = '##FILTER=<ID={0},Description="{1}">'.format( filter_id, description ) logger.info("Adding filter line to vcf: {0}"...
def add_format(self, format_id, number, entry_type, description): """ Add a format line to the header. Arguments: format_id (str): The id of the format line number (str): Integer or any of [A,R,G,.] entry_type (str): Any of [Integer,Float,Flag,Character,String] description (str): A description of the info line """ form...
def add_alt(self, alt_id, description): """ Add a alternative allele format field line to the header. Arguments: alt_id (str): The id of the alternative line description (str): A description of the info line """ alt_line = '##ALT=<ID={0},Description="{1}">'.format( alt_id, description ) logger.info("Adding alternative ...
def add_contig(self, contig_id, length): """ Add a contig line to the header. Arguments: contig_id (str): The id of the alternative line length (str): A description of the info line """ contig_line = '##contig=<ID={0},length={1}>'.format( contig_id, length ) logger.info("Adding contig line to vcf: {0}".format(contig_li...
def get_vcf_handle(fsock=None, infile=None): """Open the vcf file and return a handle""" vcf = None if (fsock or infile): if fsock: # if not infile and hasattr(fsock, 'name'): logger.info("Reading vcf form stdin") if sys.version_info < (3, 0): logger.info("Using codecs to read stdin") sys.stdin = getreader('utf-8')(fso...
def delete_tag(self, tag_id): """ Deletes a Tag to current object :param tag_id: the id of the tag which should be deleted :type tag_id: int :rtype: None """ from highton.models.tag import Tag self._delete_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Tag.ENDPOINT + '/' + str(tag_id), )
def expand(conf, output_requirements_filename, input_requirements_filename): """Expand given requirements file by extending it using pip freeze args: input_requirements_filename: the requirements filename to expand output_requirements_filename: the output filename for the expanded requirements file """ exit_if_file_not...
def verify(conf, input_requirements_filename): """Verifying that given requirements file is not missing any pins args: input_requirements_filename: requriements file to verify """ exit_if_file_not_exists(input_requirements_filename, conf) cireqs.check_if_requirements_are_up_to_date( requirements_filename=input_requirem...
def list_tasks(self): """ Get the tasks of current object :return: the tasks :rtype: list """ from highton.models.task import Task return fields.ListField( name=self.ENDPOINT, init_class=Task ).decode( self.element_from_string( self._get_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Task.ENDPOINT, ).text...
def get(self, *args, **kwargs): """ This view is used for changing the language (i18n). :return: """ from django.conf import settings new_lang = self.request.GET.get('lang') response = HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) translation.activate(new_lang) if new_lang and check_for_language(new_lang)...
def people(self): """ Retrieve all people of the company :return: list of people objects :rtype: list """ return fields.ListField(name=HightonConstants.PEOPLE, init_class=Person).decode( self.element_from_string( self._get_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/people', ).text ) )
def nx_to_ontology(graph, source_node, output_path, base_iri): """Graph nodes are ID's, and have a 'label' in the node data with the right label :param graph: :param source_node: :param str output_path: :param base_iri: """ ontology = owlready.Ontology(base_iri) parent_lookup = { source_node: types.new_class(source_nod...
def filter_none(list_of_points): """ :param list_of_points: :return: list_of_points with None's removed """ remove_elementnone = filter(lambda p: p is not None, list_of_points) remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone) return list(remove_sublistnone)
async def check_in(self): """ Checks this participant in |methcoro| Warning: |unstable| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/{}/check_in'.format(self._tournament_id, self._id)) self._refresh_from_json(res)
async def undo_check_in(self): """ Undo the check in for this participant |methcoro| Warning: |unstable| Raises: APIException """ res = await self.connection('POST', 'tournaments/{}/participants/{}/undo_check_in'.format(self._tournament_id, self._id)) self._refresh_from_json(res)
async def get_matches(self, state: MatchState = MatchState.all_): """ Return the matches of the given state |methcoro| Args: state: see :class:`MatchState` Raises: APIException """ matches = await self.connection('GET', 'tournaments/{}/matches'.format(self._tournament_id), state=state.value, participant_id=self._id) # ...
async def get_next_match(self): """ Return the first open match found, or if none, the first pending match found |methcoro| Raises: APIException """ if self._final_rank is not None: return None matches = await self.get_matches(MatchState.open_) if len(matches) == 0: matches = await self.get_matches(MatchState.pending) ...
async def get_next_opponent(self): """ Get the opponent of the potential next match. See :func:`get_next_match` |methcoro| Raises: APIException """ next_match = await self.get_next_match() if next_match is not None: opponent_id = next_match.player1_id if next_match.player2_id == self._id else next_match.player2_id retu...
def _get_pseudo_key(self, row): """ Returns the pseudo key in a row. :param dict row: The row. :rtype: tuple """ ret = list() for key in self._pseudo_key: ret.append(row[key]) return tuple(ret)
def _date2int(date): """ Returns an integer representation of a date. :param str|datetime.date date: The date. :rtype: int """ if isinstance(date, str): if date.endswith(' 00:00:00') or date.endswith('T00:00:00'): # Ignore time suffix. date = date[0:-9] tmp = datetime.datetime.strptime(date, '%Y-%m-%d') return tmp.toor...
def _rows_date2int(self, rows): """ Replaces start and end dates in a row set with their integer representation :param list[dict[str,T]] rows: The list of rows. """ for row in rows: # Determine the type of dates based on the first start date. if not self._date_type: self._date_type = self._get_date_type(row[self._key_s...
def _rows_int2date(self, rows): """ Replaces start and end dates in the row set with their integer representation :param list[dict[str,T]] rows: The list of rows. """ for row in rows: if self._date_type == 'str': row[self._key_start_date] = datetime.date.fromordinal(row[self._key_start_date]).isoformat() row[self._key_...
def _rows_sort(self, rows): """ Returns a list of rows sorted by start and end date. :param list[dict[str,T]] rows: The list of rows. :rtype: list[dict[str,T]] """ return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))
def _get_date_type(date): """ Returns the type of a date. :param str|datetime.date date: The date. :rtype: str """ if isinstance(date, str): return 'str' if isinstance(date, datetime.date): return 'date' if isinstance(date, int): return 'int' raise ValueError('Unexpected type {0!s}'.format(date.__class__))
def _equal(self, row1, row2): """ Returns True if two rows are identical excluding start and end date. Returns False otherwise. :param dict[str,T] row1: The first row. :param dict[str,T] row2: The second row. :rtype: bool """ for key in row1.keys(): if key not in [self._key_start_date, self._key_end_date]: if row1[key]...
def _merge_adjacent_rows(self, rows): """ Resolves adjacent and overlapping rows. Overlapping rows are resolved as follows: * The interval with the most recent begin date prevails for the overlapping period. * If the begin dates are the same the interval with the most recent end date prevails. * If the begin and end da...
interval). Hence, the join is empty. return [] elif relation == Allen.X_BEFORE_Y: # Two rows with distinct intervals. # prev_row: |----| # row: |-----| ret.append(prev_row) prev_row = row elif relation == Allen.X_MEETS_Y: # The two rows are adjacent. # prev_row: |-------| # row: |-------| if self._equal(prev_row, row):...
one row. prev_row[self._key_end_date] = row[self._key_end_date] else: # Rows are overlapping but not identical. prev_row[self._key_end_date] = row[self._key_start_date] - 1 ret.append(prev_row) prev_row = row elif relation == Allen.X_STARTS_Y: # prev_row start row. Should not occur with proper reference data. # prev_ro...
= row elif relation == Allen.X_FINISHES_Y_INVERSE: # row finishes prev_row. Should not occur with proper reference data. # prev_row: |----------------| # row: |------| if not self._equal(prev_row, row): prev_row[self._key_end_date] = row[self._key_start_date] - 1 ret.append(prev_row) prev_row = row # Note: if the two r...
def enumerate(self, name, start=1): """ Enumerates all rows such that the pseudo key and the ordinal number are a unique key. :param str name: The key holding the ordinal number. :param int start: The start of the ordinal numbers. Foreach pseudo key the first row has this ordinal number. """ for pseudo_key, rows in sel...
def get_rows(self, sort=False): """ Returns the rows of this Type2Helper. :param bool sort: If True the rows are sorted by the pseudo key. """ ret = [] for _, rows in sorted(self._rows.items()) if sort else self._rows.items(): self._rows_int2date(rows) ret.extend(rows) return ret
def prepare_data(self, rows): """ Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key. :param list[dict] rows: The rows """ self._rows = dict() for row in copy.copy(rows) if ...
def _get_type_description(annotation): ''' Given an annotation, return the (type, description) for the parameter. If you provide an annotation that is somehow both a string and a callable, the behavior is undefined. ''' if annotation is _empty: return None, None elif callable(annotation): return annotation, None elif i...
def _add_arguments(param, parser, used_char_args, add_nos): ''' Add the argument(s) to an ArgumentParser (using add_argument) for a given parameter. used_char_args is the set of -short options currently already in use, and is updated (if necessary) by this function. If add_nos is True, this will also add an inverse swi...