INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
send SIGTERM to the tagger child process
def shutdown(self): ''' send SIGTERM to the tagger child process ''' if self._child: try: self._child.terminate() except OSError, exc: if exc.errno == 3: ## child is already gone, possibly because it ran ...
Returns a Pattern that matches exactly n repetitions of Pattern p.
def mult(p, n): """Returns a Pattern that matches exactly n repetitions of Pattern p. """ np = P() while n >= 1: if n % 2: np = np + p p = p + p n = n // 2 return np
Replace all angle bracket emails with a unique key.
def fix_emails(text): '''Replace all angle bracket emails with a unique key.''' emails = bracket_emails.findall(text) keys = [] for email in emails: _email = email.replace("<","&lt;").replace(">","&gt;") text = text.replace(email, _email) return text
generate strings identified as sentences
def _sentences(self, clean_visible): 'generate strings identified as sentences' previous_end = 0 clean_visible = clean_visible.decode('utf8') for start, end in self.sentence_tokenizer.span_tokenize(clean_visible): # no need to check start, because the first byte of text ...
make a sortedcollection on body. labels
def make_label_index(self, stream_item): 'make a sortedcollection on body.labels' labels = stream_item.body.labels.get(self.annotator_id) if not labels: labels = [] self.label_index = SortedCollection( [l for l in labels if OffsetType.CHARS in l.offsets], ...
assemble Sentence and Token objects
def make_sentences(self, stream_item): 'assemble Sentence and Token objects' self.make_label_index(stream_item) sentences = [] token_num = 0 new_mention_id = 0 for sent_start, sent_end, sent_str in self._sentences( stream_item.body.clean_visible): ...
Convert any HTML XML or numeric entities in the attribute values. For example &amp ; becomes &.
def html_entities_to_unicode(text, space_padding=False, safe_only=False): ''' Convert any HTML, XML, or numeric entities in the attribute values. For example '&amp;' becomes '&'. This is adapted from BeautifulSoup, which should be able to do the same thing when called like this --- but this fails t...
: param text: tag - free UTF - 8 string of free text: returns string: 32 - character md5 hash in hexadecimal
def tps(text, min_token_len=2, quant_rate=0.01): ''' :param text: tag-free UTF-8 string of free text :returns string: 32-character md5 hash in hexadecimal Python implementation of the TextProfileSignature provided in SOLR. Unlike most other locality sensitive hashes, a TPS can be indexed as a ...
make a temp file of cleansed text
def make_cleansed_file(i_chunk, tmp_cleansed_path): '''make a temp file of cleansed text''' tmp_cleansed = open(tmp_cleansed_path, 'wb') for idx, si in enumerate(i_chunk): tmp_cleansed.write('<FILENAME docid="%s">\n' % si.stream_id) tmp_cleansed.write(si.body.cleansed) ## how to deal...
run child process to get OWPL output
def make_ner_file(tagger_id, tmp_cleansed_path, tmp_ner_path, pipeline_root): '''run child process to get OWPL output''' params = dict(INPUT_FILE=tmp_cleansed_path, #RAW_OUTPUT_FILE=tmp_ner_raw_path, OUTPUT_FILE=tmp_ner_path, PIPELINE_ROOT=pipeline_root) ...
Convert a string of text into a lowercase string with no punctuation and only spaces for whitespace.
def cleanse(span): '''Convert a string of text into a lowercase string with no punctuation and only spaces for whitespace. :param span: string ''' try: ## attempt to force it to utf8, which might fail span = span.encode('utf8', 'ignore') except: pass ## lowercase, st...
iterate through the i_chunk and tmp_ner_path to generate a new Chunk with body. ner
def align_chunk_with_ner(tmp_ner_path, i_chunk, tmp_done_path): ''' iterate through the i_chunk and tmp_ner_path to generate a new Chunk with body.ner ''' o_chunk = Chunk() input_iter = i_chunk.__iter__() ner = '' stream_id = None all_ner = xml.dom.minidom.parse(open(tmp_ner_path)) ...
given a config dict with streamcorpus_pipeline as a key find all keys under streamcorpus_pipeline that end with _path and if the value of that key is a relative path convert it to an absolute path using the value provided by root_path
def make_absolute_paths(config): '''given a config dict with streamcorpus_pipeline as a key, find all keys under streamcorpus_pipeline that end with "_path" and if the value of that key is a relative path, convert it to an absolute path using the value provided by root_path ''' if not 'streamcor...
Makes a hash from a dictionary list tuple or set to any level that contains only other hashable types ( including any lists tuples sets and dictionaries ). See second answer ( not the accepted answer ): http:// stackoverflow. com/ questions/ 5884066/ hashing - a - python - dictionary
def make_hash(obj): ''' Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). See second answer (not the accepted answer): http://stackoverflow.com/questions/5884066/hashing-a-python-dictio...
setup the config and load external modules
def instantiate_config(config): '''setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_mod...
This _looks_ like a Chunk only in that it generates StreamItem instances when iterated upon.
def generate_john_smith_chunk(path_to_original): ''' This _looks_ like a Chunk only in that it generates StreamItem instances when iterated upon. ''' ## Every StreamItem has a stream_time property. It usually comes ## from the document creation time. Here, we assume the JS corpus ## was cr...
Takes an HTML - like binary string as input and returns a binary string of the same length with all tags replaced by whitespace. This also detects script and style tags and replaces the text between them with whitespace.
def re_based_make_clean_visible(html): ''' Takes an HTML-like binary string as input and returns a binary string of the same length with all tags replaced by whitespace. This also detects script and style tags, and replaces the text between them with whitespace. Pre-existing whitespace of any k...
Takes an HTML - like Unicode string as input and returns a UTF - 8 encoded string with all tags replaced by whitespace. In particular all Unicode characters inside HTML are replaced with a single whitespace character.
def make_clean_visible(_html, tag_replacement_char=' '): ''' Takes an HTML-like Unicode string as input and returns a UTF-8 encoded string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. This does not detec...
generator that yields clean visible as it transitions through states in the raw html
def non_tag_chars_from_raw(html): '''generator that yields clean visible as it transitions through states in the raw `html` ''' n = 0 while n < len(html): # find start of tag angle = html.find('<', n) if angle == -1: yield html[n:] n = len(html) ...
Takes an HTML - like Unicode ( or UTF - 8 encoded ) string as input and returns a Unicode string with all tags replaced by whitespace. In particular all Unicode characters inside HTML are replaced with a single whitespace character.
def make_clean_visible_from_raw(_html, tag_replacement_char=' '): '''Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. Th...
make a temp file of clean_visible text
def make_clean_visible_file(i_chunk, clean_visible_path): '''make a temp file of clean_visible text''' _clean = open(clean_visible_path, 'wb') _clean.write('<?xml version="1.0" encoding="UTF-8"?>') _clean.write('<root>') for idx, si in enumerate(i_chunk): if si.stream_id is None: ...
Convert a unicode string into a lowercase string with no punctuation and only spaces for whitespace.
def cleanse(span, lower=True): '''Convert a unicode string into a lowercase string with no punctuation and only spaces for whitespace. Replace PennTreebank escaped brackets with ' ': -LRB- -RRB- -RSB- -RSB- -LCB- -RCB- (The acronyms stand for (Left|Right) (Round|Square|Curly) Bracket.) http://www.cis.upenn.edu/~tr...
manual test loop for make_clean_visible_from_raw
def main(): '''manual test loop for make_clean_visible_from_raw ''' import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('path') args = parser.parse_args() html = open(args.path).read() html = html.decode('utf8') cursor = 0 for s in non_tag_...
Try to load a stage into self ignoring errors.
def tryload_stage(self, moduleName, functionName, name=None): '''Try to load a stage into self, ignoring errors. If loading a module fails because of some subordinate load failure, just give a warning and move on. On success the stage is added to the stage dictionary. :param s...
Add external stages from the Python module in path.
def load_external_stages(self, path): '''Add external stages from the Python module in `path`. `path` must be a path to a Python module source that contains a `Stages` dictionary, which is a map from stage name to callable. :param str path: path to the module file ''' m...
Add external stages from the Python module mod.
def load_module_stages(self, mod): '''Add external stages from the Python module `mod`. If `mod` is a string, then it will be interpreted as the name of a module; otherwise it is an actual module object. The module should exist somewhere in :data:`sys.path`. The module must co...
Construct and configure a stage from known stages.
def init_stage(self, name, config): '''Construct and configure a stage from known stages. `name` must be the name of one of the stages in this. `config` is the configuration dictionary of the containing object, and its `name` member will be passed into the stage constructor. ...
iterates through idx_bytes until a byte in stop_bytes or a byte not in run_bytes.
def read_to( idx_bytes, stop_bytes=None, run_bytes=None ): ''' iterates through idx_bytes until a byte in stop_bytes or a byte not in run_bytes. :rtype (int, string): idx of last byte and all of bytes including the terminal byte from stop_bytes or not in run_bytes ''' idx = None vals = ...
called when idx_chars is just past <a inside an HTML anchor tag generates tuple ( end_idx attr_name attr_value )
def iter_attrs( idx_bytes ): ''' called when idx_chars is just past "<a " inside an HTML anchor tag generates tuple(end_idx, attr_name, attr_value) ''' ## read to the end of the "A" tag while 1: idx, attr_name, next_b = read_to(idx_bytes, ['=', '>']) attr_vals = [] ...
Test whether an href string meets criteria specified by configuration parameters require_abs_url which means does it look like it is probably an absolute URL? and domain_substrings. It searches for each of the domain_substrings in the href individually and if any match then returns True.
def href_filter(self, href): ''' Test whether an href string meets criteria specified by configuration parameters 'require_abs_url', which means "does it look like it is probably an absolute URL?" and 'domain_substrings'. It searches for each of the domain_substrings in ...
simple regex - based extractor of anchor tags so we can compute LINE offsets for anchor texts and associate them with their href. Generates tuple ( href_string first_byte byte_length anchor_text )
def line_href_anchors(self): ''' simple, regex-based extractor of anchor tags, so we can compute LINE offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) Also, this mangles the body.clea...
simple regex - based extractor of anchor tags so we can compute BYTE offsets for anchor texts and associate them with their href. Generates tuple ( href_string first_byte byte_length anchor_text )
def byte_href_anchors(self, chars=False): ''' simple, regex-based extractor of anchor tags, so we can compute BYTE offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) ''' input_bu...
byte - based state machine extractor of anchor tags so we can compute byte offsets for anchor texts and associate them with their href. Generates tuple ( href_string first_byte byte_length anchor_text )
def byte_href_anchors_state_machine(self): ''' byte-based state machine extractor of anchor tags, so we can compute byte offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) ''' ta...
Make a list of Labels for author and the filtered hrefs & anchors
def make_labels(self, clean_html, clean_visible=None): ''' Make a list of Labels for 'author' and the filtered hrefs & anchors ''' if self.offset_type == OffsetType.BYTES: parser = self.byte_href_anchors elif self.offset_type == OffsetType.CHARS: ...
yield all file paths under input_dir
def paths(input_dir): 'yield all file paths under input_dir' for root, dirs, fnames in os.walk(input_dir): for i_fname in fnames: i_path = os.path.join(root, i_fname) yield i_path
Creates a column family of the name family and sets any of the names in the bytes_column list to have the BYTES_TYPE.
def _create_column_family(self, family, bytes_columns=[], key_validation_class=TIME_UUID_TYPE): ''' Creates a column family of the name 'family' and sets any of the names in the bytes_column list to have the BYTES_TYPE. key_validation_class defaults to TIM...
Creates a column family of the name family and sets any of the names in the bytes_column list to have the BYTES_TYPE.
def _create_counter_column_family(self, family, counter_columns=[], key_validation_class=UTF8Type): ''' Creates a column family of the name 'family' and sets any of the names in the bytes_column list to have the BYTES_TYPE. key_validation_class defaults to ...
generate the data objects for every task
def tasks(self, key_prefix=''): ''' generate the data objects for every task ''' for row in self._tasks.get_range(): logger.debug(row) if not row[0].startswith(key_prefix): continue data = json.loads(row[1]['task_data']) dat...
get a random key out of the first max_iter rows
def get_random_available(self, max_iter=10000): ''' get a random key out of the first max_iter rows ''' c = 1 keeper = None ## note the ConsistencyLevel here. If we do not do this, and ## get all slick with things like column_count=0 and filter ## empty F...
Iterate over <FILENAME > XML - like tags and tokenize with nltk
def files(text): ''' Iterate over <FILENAME> XML-like tags and tokenize with nltk ''' for f_match in filename_re.finditer(text): yield f_match.group('stream_id'), f_match.group('tagged_doc')
Iterate over <s > XML - like tags and tokenize with nltk
def sentences(self): ''' Iterate over <s> XML-like tags and tokenize with nltk ''' for sentence_id, node in enumerate(self.ner_dom.childNodes): ## increment the char index with any text before the <s> ## tag. Crucial assumption here is that the LingPipe XML ...
Instantiates a Token from self. _input_string [ start: end ]
def _make_token(self, start, end): ''' Instantiates a Token from self._input_string[start:end] ''' ## all thfift strings must be encoded first tok_string = self._input_string[start:end].encode('utf-8') if only_whitespace.match(tok_string): ## drop any tokens w...
Tokenize all the words and preserve NER labels from ENAMEX tags
def tokens(self, sentence_dom): ''' Tokenize all the words and preserve NER labels from ENAMEX tags ''' ## keep track of sentence position, which is reset for each ## sentence, and used above in _make_token self.sent_pos = 0 ## keep track of mention_id, so we...
parse the sentences and tokens out of the XML
def get_sentences(self, ner_dom): '''parse the sentences and tokens out of the XML''' lp_parser = LingPipeParser(self.config) lp_parser.set(ner_dom) sentences = list( lp_parser.sentences() ) return sentences, lp_parser.relations, lp_parser.attributes
generate a list of tuples ( new_base list ( paths to put there ) where the files are found inside of old_base/ treeroot.
def recursive_glob_with_tree(new_base, old_base, treeroot, pattern): '''generate a list of tuples(new_base, list(paths to put there) where the files are found inside of old_base/treeroot. ''' results = [] old_cwd = os.getcwd() os.chdir(old_base) for rel_base, dirs, files in os.walk(treeroot)...
Decorator for methods that need many retries because of intermittent failures such as AWS calls via boto which has a non - back - off retry.
def _retry(func): ''' Decorator for methods that need many retries, because of intermittent failures, such as AWS calls via boto, which has a non-back-off retry. ''' def retry_func(self, *args, **kwargs): tries = 1 while True: # If a handler allows execution to contin...
return True if okay raise Exception if not
def verify_md5(md5_expected, data, other_errors=None): "return True if okay, raise Exception if not" # O_o ? md5_recv = hashlib.md5(data).hexdigest() if md5_expected != md5_recv: if other_errors is not None: logger.critical('\n'.join(other_errors)) raise FailedVerification('orig...
This function is mostly about managing configuration and then finally returns a boto. Bucket object.
def get_bucket(config, bucket_name=None): '''This function is mostly about managing configuration, and then finally returns a boto.Bucket object. AWS credentials come first from config keys aws_access_key_id_path, aws_secret_access_key_path (paths to one line files); secondly from environment varia...
Given the raw data from s3 return a generator for the items contained in that data. A generator is necessary to support chunk files but non - chunk files can be provided by a generator that yields exactly one item.
def _decode(self, data): ''' Given the raw data from s3, return a generator for the items contained in that data. A generator is necessary to support chunk files, but non-chunk files can be provided by a generator that yields exactly one item. Decoding works by case anal...
return Chunk object full of records bucket_name may be None
def get_chunk(self, bucket_name, key_path): '''return Chunk object full of records bucket_name may be None''' bucket = get_bucket(self.config, bucket_name=bucket_name) key = bucket.get_key(key_path) if key is None: raise FailedExtraction('Key "%s" does not exist.' % k...
Convert a text stream ID to a kvlayer key.
def stream_id_to_kvlayer_key(stream_id): '''Convert a text stream ID to a kvlayer key. The return tuple can be used directly as a key in the :data:`STREAM_ITEMS_TABLE` table. :param str stream_id: stream ID to convert :return: :mod:`kvlayer` key tuple :raise exceptions.KeyError: if `stream_id`...
Convert a kvlayer key to a text stream ID.
def kvlayer_key_to_stream_id(k): '''Convert a kvlayer key to a text stream ID. `k` should be of the same form produced by :func:`stream_id_to_kvlayer_key`. :param k: :mod:`kvlayer` key tuple :return: converted stream ID :returntype str: ''' abs_url_hash, epoch_ticks = k return '{0...
Get a kvlayer key from a stream item.
def key_for_stream_item(si): '''Get a kvlayer key from a stream item. The return tuple can be used directly as a key in the :data:`STREAM_ITEMS_TABLE` table. Note that this recalculates the stream ID, and if the internal data on the stream item is inconsistent then this could return a different re...
Serve up some ponies.
def main(argv=sys.argv): args = parse(argv) """Serve up some ponies.""" hostname = args.listen port = args.port print( "Making all your dreams for a pony come true on http://{0}:{1}.\n" "Press Ctrl+C to quit.\n".format(hostname, port)) # Hush, werkzeug. logging.getLogger('we...
Build the parser that will have all available commands and options.
def build_parser(): """Build the parser that will have all available commands and options.""" description = ( 'HTTPony (pronounced aych-tee-tee-pony) is a simple HTTP ' 'server that pretty prints HTTP requests to a terminal. It ' 'is a useful aide for developing clients that send HTTP ' ...
Mutably tag tokens with xpath offsets.
def add_xpaths_to_stream_item(si): '''Mutably tag tokens with xpath offsets. Given some stream item, this will tag all tokens from all taggings in the document that contain character offsets. Note that some tokens may not have computable xpath offsets, so an xpath offset for those tokens will not b...
Convert stream item sentences to character Offset s.
def sentences_to_char_tokens(si_sentences): '''Convert stream item sentences to character ``Offset``s.''' for sentence in si_sentences: for token in sentence.tokens: if OffsetType.CHARS in token.offsets: yield token
Convert character Offset s to character ranges.
def char_tokens_to_char_offsets(si_tokens): '''Convert character ``Offset``s to character ranges.''' for token in si_tokens: offset = token.offsets[OffsetType.CHARS] yield offset.first, offset.first + offset.length
Converts HTML and a sequence of char offsets to xpath offsets.
def char_offsets_to_xpaths(html, char_offsets): '''Converts HTML and a sequence of char offsets to xpath offsets. Returns a generator of :class:`streamcorpus.XpathRange` objects in correspondences with the sequence of ``char_offsets`` given. Namely, each ``XpathRange`` should address precisely the same...
Roundtrip all Xpath offsets in the given stream item.
def stream_item_roundtrip_xpaths(si, quick=False): '''Roundtrip all Xpath offsets in the given stream item. For every token that has both ``CHARS`` and ``XPATH_CHARS`` offsets, slice the ``clean_html`` with the ``XPATH_CHARS`` offset and check that it matches slicing ``clean_visible`` with the ``CH...
Record that tag has been seen at this depth.
def add_element(self, tag): '''Record that `tag` has been seen at this depth. If `tag` is :class:`TextElement`, it records a text node. ''' # Collapse adjacent text nodes if tag is TextElement and self.last_tag is TextElement: return self.last_tag = tag ...
Get an XPath fragment for this location.
def xpath_piece(self): '''Get an XPath fragment for this location. It is of the form ``tag[n]`` where `tag` is the most recent element added and n is its position. ''' if self.last_tag is TextElement: return 'text()[{count}]'.format(count=self.text_index()) ...
Returns the one - based index of the current text node.
def text_index(self): '''Returns the one-based index of the current text node.''' # This is the number of text nodes we've seen so far. # If we are currently in a text node, great; if not then add # one for the text node that's about to begin. i = self.tags.get(TextElement, 0) ...
Returns a tuple of ( xpath character offset ).
def xpath_offset(self): '''Returns a tuple of ``(xpath, character offset)``. The ``xpath`` returned *uniquely* identifies the end of the text node most recently inserted. The character offsets indicates where the text inside the node ends. (When the text node is empty, the offse...
Yields all the elements descendant of elem in document order
def descendants(elem): ''' Yields all the elements descendant of elem in document order ''' for child in elem.xml_children: if isinstance(child, element): yield child yield from descendants(child)
Yields all the elements from the source source - if an element yields all child elements in order ; if any other iterator yields the elements from that iterator
def select_elements(source): ''' Yields all the elements from the source source - if an element, yields all child elements in order; if any other iterator yields the elements from that iterator ''' if isinstance(source, element): source = source.xml_children return filter(lambda x: isins...
Yields all the elements with the given name source - if an element starts with all child elements in order ; can also be any other iterator name - will yield only elements with this name
def select_name(source, name): ''' Yields all the elements with the given name source - if an element, starts with all child elements in order; can also be any other iterator name - will yield only elements with this name ''' return filter(lambda x: x.xml_name == name, select_elements(source))
Yields elements from the source whose name matches the given regular expression pattern source - if an element starts with all child elements in order ; can also be any other iterator pat - re. pattern object
def select_name_pattern(source, pat): ''' Yields elements from the source whose name matches the given regular expression pattern source - if an element, starts with all child elements in order; can also be any other iterator pat - re.pattern object ''' return filter(lambda x: pat.match(x.xml_na...
Yields elements from the source with the given value ( accumulated child text ) source - if an element starts with all child elements in order ; can also be any other iterator val - string value to match
def select_value(source, val): ''' Yields elements from the source with the given value (accumulated child text) source - if an element, starts with all child elements in order; can also be any other iterator val - string value to match ''' if isinstance(source, element): source = source...
Yields elements from the source having the given attrivute optionally with the given attribute value source - if an element starts with all child elements in order ; can also be any other iterator name - attribute name to check val - if None check only for the existence of the attribute otherwise compare the given valu...
def select_attribute(source, name, val=None): ''' Yields elements from the source having the given attrivute, optionally with the given attribute value source - if an element, starts with all child elements in order; can also be any other iterator name - attribute name to check val - if None check o...
Yields elements and text which have the same parent as elem but come afterward in document order
def following_siblings(elem): ''' Yields elements and text which have the same parent as elem, but come afterward in document order ''' it = itertools.dropwhile(lambda x: x != elem, elem.xml_parent.xml_children) next(it) #Skip the element itself return it
Yield descendant nodes matching the given pattern specification pattern - tuple of steps each of which matches an element by name with * acting like a wildcard descending the tree in tuple order sort of like a subset of XPath in Python tuple form state - for internal use only
def select_pattern(node, pattern, state=None): ''' Yield descendant nodes matching the given pattern specification pattern - tuple of steps, each of which matches an element by name, with "*" acting like a wildcard, descending the tree in tuple order sort of like a subset of XPath in Python ...
Add text nodes as possible to all descendants of an element for spacing & indentation to make the MicroXML as printed easier for people to read. Will not modify the value of any text node which is not already entirely whitespace.
def make_pretty(elem, depth=0, indent=' '): ''' Add text nodes as possible to all descendants of an element for spacing & indentation to make the MicroXML as printed easier for people to read. Will not modify the value of any text node which is not already entirely whitespace. Warning: even though...
Call inkscape CLI with arguments and returns its return value.
def call_inkscape(args_strings, inkscape_binpath=None): """Call inkscape CLI with arguments and returns its return value. Parameters ---------- args_string: list of str inkscape_binpath: str Returns ------- return_value Inkscape command CLI call return value. """ log.d...
Call Inkscape to export the input_file to output_file using the specific export argument flag for the output file type.
def inkscape_export(input_file, output_file, export_flag="-A", dpi=90, inkscape_binpath=None): """ Call Inkscape to export the input_file to output_file using the specific export argument flag for the output file type. Parameters ---------- input_file: str Path to the input file outpu...
Transform SVG file to PDF file
def svg2pdf(svg_file_path, pdf_file_path, dpi=150, command_binpath=None, support_unicode=False): """ Transform SVG file to PDF file """ if support_unicode: return rsvg_export(svg_file_path, pdf_file_path, dpi=dpi, rsvg_binpath=command_binpath) return inkscape_export(svg_file_path, pdf_file_pat...
Transform SVG file to PNG file
def svg2png(svg_file_path, png_file_path, dpi=150, inkscape_binpath=None): """ Transform SVG file to PNG file """ return inkscape_export(svg_file_path, png_file_path, export_flag="-e", dpi=dpi, inkscape_binpath=inkscape_binpath)
Return a Jinja2 environment for where file_path is.
def get_environment_for(file_path): """Return a Jinja2 environment for where file_path is. Parameters ---------- file_path: str Returns ------- jinja_env: Jinja2.Environment """ work_dir = os.path.dirname(os.path.abspath(file_path)) if not os.path.exists(work_dir): ra...
Setup self. template
def _setup_template_file(self, template_file_path): """ Setup self.template Parameters ---------- template_file_path: str Document template file path. """ try: template_file = template_file_path template_env = get_environment_for(templ...
Fill the content of the document with the information in doc_contents.
def fill(self, doc_contents): """ Fill the content of the document with the information in doc_contents. Parameters ---------- doc_contents: dict Set of values to set the template document. Returns ------- filled_doc: str The content of t...
Save the content of the. txt file in a text file.
def save_content(self, file_path, encoding='utf-8'): """ Save the content of the .txt file in a text file. Parameters ---------- file_path: str Path to the output file. """ if self.file_content_ is None: msg = 'Template content has not been update...
Factory function to create a specific document of the class given by the command or the extension of template_file_path.
def from_template_file(cls, template_file_path, command=None): """ Factory function to create a specific document of the class given by the `command` or the extension of `template_file_path`. See get_doctype_by_command and get_doctype_by_extension. Parameters ---------- ...
Fill the content of the document with the information in doc_contents. This is different from the TextDocument fill function because this will check for symbools in the values of doc_content and replace them to good XML codes before filling the template.
def fill(self, doc_contents): """ Fill the content of the document with the information in doc_contents. This is different from the TextDocument fill function, because this will check for symbools in the values of `doc_content` and replace them to good XML codes before filling the templa...
Save the content of the. svg file in the chosen rendered format.
def render(self, file_path, **kwargs): """ Save the content of the .svg file in the chosen rendered format. Parameters ---------- file_path: str Path to the output file. Kwargs ------ file_type: str Choices: 'png', 'pdf', 'svg' ...
Save the content of the. text file in the PDF.
def render(self, file_path, **kwargs): """ Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file. """ temp = get_tempfile(suffix='.tex') self.save_content(temp.name) try: self....
Convert XML 1. 0 to MicroXML
def parse(source, handler): ''' Convert XML 1.0 to MicroXML source - XML 1.0 input handler - MicroXML events handler Returns uxml, extras uxml - MicroXML element extracted from the source extras - information to be preserved but not part of MicroXML, e.g. namespaces ''' h = expat_...
Start the optimisation/ search using the supplied optimisation method with the supplied inputs for the supplied function
def search(self): '''Start the optimisation/search using the supplied optimisation method with the supplied inputs for the supplied function''' search = self._method(inputs=self._inputs, function=self._function, state=self._state) search.run()
Parse an input source with HTML text into an Amara 3 tree
def parse(source, prefixes=None, model=None, encoding=None, use_xhtml_ns=False): ''' Parse an input source with HTML text into an Amara 3 tree >>> from amara3.uxml import html5 >>> import urllib.request >>> with urllib.request.urlopen('http://uche.ogbuji.net/') as response: ... html5.parse(...
Parse a fragment if markup in HTML mode and return a bindery node
def markup_fragment(source, encoding=None): ''' Parse a fragment if markup in HTML mode, and return a bindery node Warning: if you pass a string, you must make sure it's a byte string, not a Unicode object. You might also want to wrap it with amara.lib.inputsource.text if it's not obviously XML or HTML (f...
Insert data as text in the current node positioned before the start of node insertBefore or to the end of the node s text.
def insertText(self, data, insertBefore=None): """Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node's text. """ if insertBefore: self.insertBefore(tree.text(data), insertBefore) else: self.x...
Insert node as a child of the current node before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node
def insertBefore(self, node, refNode): """Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node""" offset = self.xml_children.index(refNode) self.xml_insert(node, offset)
Return a shallow copy of the current node i. e. a node with the same name and attributes but with no parent or child nodes
def cloneNode(self): """Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes """ attrs = self.xml_attributes.copy() return element(self.xml_name, attrs=attrs)
A script that melody calls with each valid set of options. This script runs the required code and returns the results.
def execute(option): '''A script that melody calls with each valid set of options. This script runs the required code and returns the results.''' namelist_option = [] makefile_option = [] flags = "" for entry in option: key = entry.keys()[0] if key == "Problem Size": ...
Create a vCard3. 0 string with the given parameters. Reference: http:// www. evenx. com/ vcard - 3 - 0 - format - specification
def create_vcard3_str(name, surname, displayname, email='', org='', title='', url='', note=''): """ Create a vCard3.0 string with the given parameters. Reference: http://www.evenx.com/vcard-3-0-format-specification """ vcard = [] vcard += ['BEGIN:VCARD'] vcard += ['VERSION:3.0'] if name and...
XPath - like string value of node
def strval(node, outermost=True): ''' XPath-like string value of node ''' if not isinstance(node, element): return node.xml_value if outermost else [node.xml_value] accumulator = [] for child in node.xml_children: if isinstance(child, text): accumulator.append(child.x...
Append a node as the last child
def xml_insert(self, child, index=-1): ''' Append a node as the last child child - the child to append. If a string, convert to a text node, for convenience ''' if isinstance(child, str): child = text(child, parent=self) else: child._xml_parent = ...
Commandline options arguments parsing.
def parse_options(): """ Commandline options arguments parsing. """ # build options and help version = "%%prog {version}".format(version=__version__) parser = OptionParser(version=version) parser.add_option( "-u", "--username", action="store", dest="username", type="string",...
Get settings from config file.
def parse_config(options): """ Get settings from config file. """ if os.path.exists(options.config): config = ConfigParser.ConfigParser() try: config.read(options.config) except Exception, err: if not options.quiet: sys.stderr.write("ERROR...
Get google API credentials for user.
def get_google_credentials(options, config): """ Get google API credentials for user. """ try: if options.get_google_credentials: flow = flow_from_clientsecrets(config["secrets"], scope=SCOPE, redirect_uri="oob") sys.stdout.write("Follow this URL: {url} and grant access ...
Create event start and end datetimes.
def create_event_datetimes(options, config): """ Create event start and end datetimes. """ now = datetime.datetime.now() return { "start": { "dateTime": (now + datetime.timedelta(minutes=int(config["start"]))).strftime(DT_FORMAT), "timeZone": options.timezone, ...