Search is not available for this dataset
text
stringlengths
75
104k
def remove_comments(xml): """ Remove comments, as they can break the xml parser. See html5lib issue #122 ( http://code.google.com/p/html5lib/issues/detail?id=122 ). >>> remove_comments('<!-- -->') '' >>> remove_comments('<!--\\n-->') '' >>> remove_comments('<p>stuff<!-- \\n -->stuff</p...
def remove_newlines(xml): r"""Remove newlines in the xml. If the newline separates words in text, then replace with a space instead. >>> remove_newlines('<p>para one</p>\n<p>para two</p>') '<p>para one</p><p>para two</p>' >>> remove_newlines('<p>line one\nline two</p>') '<p>line one line two</...
def remove_insignificant_text_nodes(dom): """ For html elements that should not have text nodes inside them, remove all whitespace. For elements that may have text, collapse multiple spaces to a single space. """ nodes_to_remove = [] for node in walk_dom(dom): if is_text(node): ...
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
def get_location(dom, location): """ Get the node at the specified location in the dom. Location is a sequence of child indices, starting at the children of the root element. If there is no node at this location, raise a ValueError. """ node = dom.documentElement for i in location: n...
def check_text_similarity(a_dom, b_dom, cutoff): """Check whether two dom trees have similar text or not.""" a_words = list(tree_words(a_dom)) b_words = list(tree_words(b_dom)) sm = WordMatcher(a=a_words, b=b_words) if sm.text_ratio() >= cutoff: return True return False
def tree_words(node): """Return all the significant text below the given node as a list of words. >>> list(tree_words(parse_minidom('<h1>one</h1> two <div>three<em>four</em></div>'))) ['one', 'two', 'three', 'four'] """ for word in split_text(tree_text(node)): word = word.strip() if ...
def tree_text(node): """ >>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>')) 'one two three four' """ text = [] for descendant in walk_dom(node): if is_text(descendant): text.append(descendant.nodeValue) return ' '.join(text)
def insert_or_append(parent, node, next_sibling): """ Insert the node before next_sibling. If next_sibling is None, append the node last instead. """ # simple insert if next_sibling: parent.insertBefore(node, next_sibling) else: parent.appendChild(node)
def wrap(node, tag): """Wrap the given tag around a node.""" wrap_node = node.ownerDocument.createElement(tag) parent = node.parentNode if parent: parent.replaceChild(wrap_node, node) wrap_node.appendChild(node) return wrap_node
def wrap_inner(node, tag): """Wrap the given tag around the contents of a node.""" children = list(node.childNodes) wrap_node = node.ownerDocument.createElement(tag) for c in children: wrap_node.appendChild(c) node.appendChild(wrap_node)
def unwrap(node): """Remove a node, replacing it with its children.""" for child in list(node.childNodes): node.parentNode.insertBefore(child, node) remove_node(node)
def full_split(text, regex): """ Split the text by the regex, keeping all parts. The parts should re-join back into the original text. >>> list(full_split('word', re.compile('&.*?'))) ['word'] """ while text: m = regex.search(text) if not m: yield text ...
def multi_split(text, regexes): """ Split the text by the given regexes, in priority order. Make sure that the regex is parenthesized so that matches are returned in re.split(). Splitting on a single regex works like normal split. >>> '|'.join(multi_split('one two three', [r'\w+'])) 'one| ...
def text_ratio(self): """Return a measure of the sequences' word similarity (float in [0,1]). Each word has weight equal to its length for this measure >>> m = WordMatcher(a=['abcdef', '12'], b=['abcdef', '34']) # 3/4 of the text is the same >>> '%.3f' % m.ratio() # normal ratio fails ...
def match_length(self): """ Find the total length of all words that match between the two sequences.""" length = 0 for match in self.get_matching_blocks(): a, b, size = match length += self._text_length(self.a[a:a+size]) return length
def run_edit_script(self): """ Run an xml edit script, and return the new html produced. """ for action, location, properties in self.edit_script: if action == 'delete': node = get_location(self.dom, location) self.action_delete(node) ...
def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for node in reversed(del_nodes): # diff algorithm deletes nodes in reverse order, so un-reverse the # order for this iteratio...
def remove_nesting(dom, tag_name): """ Unwrap items in the node list that have ancestors with the same tag. """ for node in dom.getElementsByTagName(tag_name): for ancestor in ancestors(node): if ancestor is node: continue if ancestor is dom.documentElemen...
def sort_nodes(dom, cmp_func): """ Sort the nodes of the dom in-place, based on a comparison function. """ dom.normalize() for node in list(walk_dom(dom, elements_only=True)): prev_sib = node.previousSibling while prev_sib and cmp_func(prev_sib, node) == 1: node.parentNod...
def merge_adjacent(dom, tag_name): """ Merge all adjacent tags with the specified tag name. Return the number of merges performed. """ for node in dom.getElementsByTagName(tag_name): prev_sib = node.previousSibling if prev_sib and prev_sib.nodeName == node.tagName: for ch...
def distribute(node): """ Wrap a copy of the given element around the contents of each of its children, removing the node in the process. """ children = list(c for c in node.childNodes if is_element(c)) unwrap(node) tag_name = node.tagName for c in children: wrap_inner(c, tag_nam...
def save(self, *args, **kwargs): """ Save object to the database. Removes all other entries if there are any. """ self.__class__.objects.exclude(id=self.id).delete() super(SingletonModel, self).save(*args, **kwargs)
def get_magicc_region_to_openscm_region_mapping(inverse=False): """Get the mappings from MAGICC to OpenSCM regions. This is not a pure inverse of the other way around. For example, we never provide "GLOBAL" as a MAGICC return value because it's unnecesarily confusing when we also have "World". Fortunat...
def convert_magicc_to_openscm_regions(regions, inverse=False): """ Convert MAGICC regions to OpenSCM regions Parameters ---------- regions : list_like, str Regions to convert inverse : bool If True, convert the other way i.e. convert OpenSCM regions to MAGICC7 regions ...
def get_magicc7_to_openscm_variable_mapping(inverse=False): """Get the mappings from MAGICC7 to OpenSCM variables. Parameters ---------- inverse : bool If True, return the inverse mappings i.e. OpenSCM to MAGICC7 mappings Returns ------- dict Dictionary of mappings """ ...
def convert_magicc7_to_openscm_variables(variables, inverse=False): """ Convert MAGICC7 variables to OpenSCM variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert OpenSCM variables to MAGICC7 ...
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
def convert_magicc6_to_magicc7_variables(variables, inverse=False): """ Convert MAGICC6 variables to MAGICC7 variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert MAGICC7 variables to MAGICC6 ...
def get_pint_to_fortran_safe_units_mapping(inverse=False): """Get the mappings from Pint to Fortran safe units. Fortran can't handle special characters like "^" or "/" in names, but we need these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt CO2 / yr" but we don't want thes...
def convert_pint_to_fortran_safe_units(units, inverse=False): """ Convert Pint units to Fortran safe units Parameters ---------- units : list_like, str Units to convert inverse : bool If True, convert the other way i.e. convert Fortran safe units to Pint units Returns ...
def run_evaluate(self) -> None: """ Overrides the base evaluation to set the value to the evaluation result of the value expression in the schema """ result = None self.eval_error = False if self._needs_evaluation: result = self._schema.value.evaluate(...
def set(self, key: Any, value: Any) -> None: """ Sets the value of a key to a supplied value """ if key is not None: self[key] = value
def increment(self, key: Any, by: int = 1) -> None: """ Increments the value set against a key. If the key is not present, 0 is assumed as the initial state """ if key is not None: self[key] = self.get(key, 0) + by
def insert(self, index: int, obj: Any) -> None: """ Inserts an item to the list as long as it is not None """ if obj is not None: super().insert(index, obj)
def get_dattype_regionmode(regions, scen7=False): """ Get the THISFILE_DATTYPE and THISFILE_REGIONMODE flags for a given region set. In all MAGICC input files, there are two flags: THISFILE_DATTYPE and THISFILE_REGIONMODE. These tell MAGICC how to read in a given input file. This function maps the ...
def get_region_order(regions, scen7=False): """ Get the region order expected by MAGICC. Parameters ---------- regions : list_like The regions to get THISFILE_DATTYPE and THISFILE_REGIONMODE flags for. scen7 : bool, optional Whether the file we are getting the flags for is a SC...
def get_special_scen_code(regions, emissions): """ Get special code for MAGICC6 SCEN files. At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions data is being provided for. The second digit, the 'sce...
def determine_tool(filepath, tool_to_get): """ Determine the tool to use for reading/writing. The function uses an internally defined set of mappings between filepaths, regular expresions and readers/writers to work out which tool to use for a given task, given the filepath. It is intended for...
def pull_cfg_from_parameters_out(parameters_out, namelist_to_read="nml_allcfgs"): """Pull out a single config set from a parameters_out namelist. This function returns a single file with the config that needs to be passed to MAGICC in order to do the same run as is represented by the values in ``parame...
def pull_cfg_from_parameters_out_file( parameters_out_file, namelist_to_read="nml_allcfgs" ): """Pull out a single config set from a MAGICC ``PARAMETERS.OUT`` file. This function reads in the ``PARAMETERS.OUT`` file and returns a single file with the config that needs to be passed to MAGICC in order to...
def get_generic_rcp_name(inname): """Convert an RCP name into the generic Pymagicc RCP name The conversion is case insensitive. Parameters ---------- inname : str The name for which to get the generic Pymagicc RCP name Returns ------- str The generic Pymagicc RCP name ...
def join_timeseries(base, overwrite, join_linear=None): """Join two sets of timeseries Parameters ---------- base : :obj:`MAGICCData`, :obj:`pd.DataFrame`, filepath Base timeseries to use. If a filepath, the data will first be loaded from disk. overwrite : :obj:`MAGICCData`, :obj:`pd.DataF...
def read_scen_file( filepath, columns={ "model": ["unspecified"], "scenario": ["unspecified"], "climate_model": ["unspecified"], }, **kwargs ): """ Read a MAGICC .SCEN file. Parameters ---------- filepath : str Filepath of the .SCEN file to read ...
def _get_openscm_var_from_filepath(filepath): """ Determine the OpenSCM variable from a filepath. Uses MAGICC's internal, implicit, filenaming conventions. Parameters ---------- filepath : str Filepath from which to determine the OpenSCM variable. Returns ------- str ...
def _find_nml(self): """ Find the start and end of the embedded namelist. Returns ------- (int, int) start and end index for the namelist """ nml_start = None nml_end = None for i in range(len(self.lines)): if self.lines[i]...
def process_data(self, stream, metadata): """ Extract the tabulated data from the input file. Parameters ---------- stream : Streamlike object A Streamlike object (nominally StringIO) containing the table to be extracted metadata : dict ...
def _convert_data_block_and_headers_to_df(self, stream): """ stream : Streamlike object A Streamlike object (nominally StringIO) containing the data to be extracted ch : dict Column headers to use for the output pd.DataFrame Returns ------- ...
def _get_variable_from_filepath(self): """ Determine the file variable from the filepath. Returns ------- str Best guess of variable name from the filepath """ try: return self.regexp_capture_variable.search(self.filepath).group(1) ...
def process_header(self, header): """ Parse the header for additional metadata. Parameters ---------- header : str All the lines in the header. Returns ------- dict The metadata in the header. """ metadata = {} ...
def _read_data_header_line(self, stream, expected_header): """Read a data header line, ensuring that it starts with the expected header Parameters ---------- stream : :obj:`StreamIO` Stream object containing the text to read expected_header : str, list of strs ...
def read_chunk(self, t): """ Read out the next chunk of memory Values in fortran binary streams begin and end with the number of bytes :param t: Data type (same format as used by struct). :return: Numpy array if the variable is an array, otherwise a scalar. """ s...
def process_data(self, stream, metadata): """ Extract the tabulated data from the input file # Arguments stream (Streamlike object): A Streamlike object (nominally StringIO) containing the table to be extracted metadata (dict): metadata read in from the header and th...
def process_header(self, data): """ Reads the first part of the file to get some essential metadata # Returns return (dict): the metadata in the header """ metadata = { "datacolumns": data.read_chunk("I"), "firstyear": data.read_chunk("I"), ...
def write(self, magicc_input, filepath): """ Write a MAGICC input file from df and metadata Parameters ---------- magicc_input : :obj:`pymagicc.io.MAGICCData` MAGICCData object which holds the data to write filepath : str Filepath of the file to ...
def append(self, other, inplace=False, **kwargs): """ Append any input which can be converted to MAGICCData to self. Parameters ---------- other : MAGICCData, pd.DataFrame, pd.Series, str Source of data to append. inplace : bool If True, append `...
def write(self, filepath, magicc_version): """ Write an input file to disk. Parameters ---------- filepath : str Filepath of the file to write. magicc_version : int The MAGICC version for which we want to write files. MAGICC7 and MAGICC6 ...
def validate_python_identifier_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[InvalidIdentifierError]: """ Validates a set of attributes as identifiers in a spec """ errors: List[InvalidIdentifierError] = [] checks: List[Tuple...
def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[RequiredAttributeError]: """ Validates to ensure that a set of attributes are present in spec """ return [ RequiredAttributeError(fully_qualified_name, spec, attri...
def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[EmptyAttributeError]: """ Validates to ensure that a set of attributes do not contain empty values """ return [ EmptyAttributeError(fully_qualified_name, spec, attribute...
def validate_number_attribute( fully_qualified_name: str, spec: Dict[str, Any], attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optional[Union[int, float]] = None) -> Optional[InvalidNumberError]: ...
def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str, candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueError]: """ Validates to ensure that the value of an attribute lies within an allowed set of candidates """ if attribute not ...
def parse(key_string: str) -> 'Key': """ Parses a flat key string and returns a key """ parts = key_string.split(Key.PARTITION) key_type = KeyType.DIMENSION if parts[3]: key_type = KeyType.TIMESTAMP return Key(key_type, parts[0], parts[1], parts[2].split(Key.DIMENSION...
def parse_sort_key(identity: str, sort_key_string: str) -> 'Key': """ Parses a flat key string and returns a key """ parts = sort_key_string.split(Key.PARTITION) key_type = KeyType.DIMENSION if parts[2]: key_type = KeyType.TIMESTAMP return Key(key_type, identity, part...
def starts_with(self, other: 'Key') -> bool: """ Checks if this key starts with the other key provided. Returns False if key_type, identity or group are different. For `KeyType.TIMESTAMP` returns True. For `KeyType.DIMENSION` does prefix match between the two dimensions property....
def _evaluate_dimension_fields(self) -> bool: """ Evaluates the dimension fields. Returns False if any of the fields could not be evaluated. """ for _, item in self._dimension_fields.items(): item.run_evaluate() if item.eval_error: return False ...
def _compare_dimensions_to_fields(self) -> bool: """ Compares the dimension field values to the value in regular fields.""" for name, item in self._dimension_fields.items(): if item.value != self._nested_items[name].value: return False return True
def _key(self): """ Generates the Key object based on dimension fields. """ return Key(self._schema.key_type, self._identity, self._name, [str(item.value) for item in self._dimension_fields.values()])
def run(scenario, magicc_version=6, **kwargs): """ Run a MAGICC scenario and return output data and (optionally) config parameters. As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its parameters into ``out/PARAMETERS.OUT`` and they will then be read into ``output.metadata...
def run_evaluate(self, block: TimeAggregate) -> bool: """ Evaluates the anchor condition against the specified block. :param block: Block to run the anchor condition against. :return: True, if the anchor condition is met, otherwise, False. """ if self._anchor.evaluate_anc...
def extend_schema_spec(self) -> None: """ Injects the block start and end times """ super().extend_schema_spec() if self.ATTRIBUTE_FIELDS in self._spec: # Add new fields to the schema spec. Since `_identity` is added by the super, new elements are added after predefined_...
def _build_time_fields_spec(name_in_context: str) -> List[Dict[str, Any]]: """ Constructs the spec for predefined fields that are to be included in the master spec prior to schema load :param name_in_context: Name of the current object in the context :return: """ return [...
def apply_string_substitutions( inputs, substitutions, inverse=False, case_insensitive=False, unused_substitutions="ignore", ): """Apply a number of substitutions to a string(s). The substitutions are applied effectively all at once. This means that conflicting substitutions don't inter...
def get_range(self, base_key: Key, start_time: datetime, end_time: datetime = None, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. :param base_k...
def _get_range_timestamp_key(self, start: Key, end: Key, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. This is used when the key being used is a TIMESTAMP key. """ r...
def _get_range_dimension_key(self, base_key: Key, start_time: datetime, end_time: datetime, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the...
def _restrict_items_to_count(items: List[Tuple[Key, Any]], count: int) -> List[Tuple[Key, Any]]: """ Restricts items to count number if len(items) is larger than abs(count). This function assumes that items is sorted by time. :param items: The items to restrict. :param count: Th...
def build_expression(self, attribute: str) -> Optional[Expression]: """ Builds an expression object. Adds an error if expression creation has errors. """ expression_string = self._spec.get(attribute, None) if expression_string: try: return Expression(str(expression_...
def add_errors(self, *errors: Union[BaseSchemaError, List[BaseSchemaError]]) -> None: """ Adds errors to the error repository in schema loader """ self.schema_loader.add_errors(*errors)
def validate_required_attributes(self, *attributes: str) -> None: """ Validates that the schema contains a series of required attributes """ self.add_errors( validate_required_attributes(self.fully_qualified_name, self._spec, *attributes))
def validate_number_attribute(self, attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optional[Union[int, float]] =...
def validate_enum_attribute(self, attribute: str, candidates: Set[Union[str, int, float]]) -> None: """ Validates that the attribute value is among the candidates """ self.add_errors( validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, ca...
def validate_schema_spec(self) -> None: """ Contains the validation routines that are to be executed as part of initialization by subclasses. When this method is being extended, the first line should always be: ```super().validate_schema_spec()``` """ self.add_errors( validate_empty_...
def _needs_evaluation(self) -> bool: """ Returns True when: 1. Where clause is not specified 2. Where WHERE clause is specified and it evaluates to True Returns false if a where clause is specified and it evaluates to False """ return self._schema.when is ...
def run_evaluate(self, *args, **kwargs) -> None: """ Evaluates the current item :returns An evaluation result object containing the result, or reasons why evaluation failed """ if self._needs_evaluation: for _, item in self._nested_items.items(): ...
def _snapshot(self) -> Dict[str, Any]: """ Implements snapshot for collections by recursively invoking snapshot of all child items """ try: return {name: item._snapshot for name, item in self._nested_items.items()} except Exception as e: raise SnapshotErro...
def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> 'BaseItemCollection': """ Restores the state of a collection from a snapshot """ try: for name, snap in snapshot.items(): if isinstance(name, Key): self._nested_items[name.grou...
def _prepare_window(self, start_time: datetime) -> None: """ Prepares window if any is specified. :param start_time: The anchor block start_time from where the window should be generated. """ # evaluate window first which sets the correct window in the store store...
def _get_end_time(self, start_time: datetime) -> datetime: """ Generates the end time to be used for the store range query. :param start_time: Start time to use as an offset to calculate the end time based on the window type in the schema. :return: """ if Type.is_...
def _load_blocks(self, blocks: List[Tuple[Key, Any]]) -> List[TimeAggregate]: """ Converts [(Key, block)] to [BlockAggregate] :param blocks: List of (Key, block) blocks. :return: List of BlockAggregate """ return [ TypeLoader.load_item(self._schema.source.type...
def execute_per_identity_records( self, identity: str, records: List[TimeAndRecord], old_state: Optional[Dict[Key, Any]] = None) -> Tuple[str, Tuple[Dict, List]]: """ Executes the streaming and window BTS on the given records. An option old state can provi...
def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor ) -> Generator[Tuple[str, TimeAndRecord], None, None]: """ Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity ...
def to_string(self, hdr, other): """String representation with additional information""" result = "%s[%s,%s" % ( hdr, self.get_type(self.type), self.get_clazz(self.clazz)) if self.unique: result += "-unique," else: result += "," result += s...
def answered_by(self, rec): """Returns true if the question is answered by the record""" return self.clazz == rec.clazz and \ (self.type == rec.type or self.type == _TYPE_ANY) and \ self.name == rec.name
def reset_ttl(self, other): """Sets this record's TTL and created time to that of another record.""" self.created = other.created self.ttl = other.ttl
def to_string(self, other): """String representation with addtional information""" arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_millis()), other) return DNSEntry.to_string(self, "record", arg)
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.address, len(self.address))
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.cpu, len(self.cpu)) out.write_string(self.os, len(self.os))
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.text, len(self.text))
def set_property(self, key, value): """ Update only one property in the dict """ self.properties[key] = value self.sync_properties()