text
stringlengths
81
112k
Returns an HTML table containing data on each corpus' n-grams. def _generate_corpus_table(self, labels, ngrams): """Returns an HTML table containing data on each corpus' n-grams.""" html = [] for label in labels: html.append(self._render_corpus_row(label, ngrams)) return '\n...
Returns an HTML table containing data on each n-gram in `results`. def _generate_ngram_table(self, output_dir, labels, results): """Returns an HTML table containing data on each n-gram in `results`.""" html = [] grouped = results.groupby(constants.NGRAM_FIELDNAME) row_te...
Returns the HTML template for a row in the n-gram table. def _generate_ngram_row_template(self, labels): """Returns the HTML template for a row in the n-gram table.""" cells = ['<td>{ngram}</td>'] for label in labels: cells.append('<td>{{{}}}</td>'.format(label)) return '\n'...
Creates multiple results files in `output_dir` based on `results`. For each label in `labels`, create three results file, containing those n-grams with that label that first occurred, only occurred, and last occurred in that label. def _generate_results(self, output_dir, labels, results): ...
Returns the HTML for a corpus row. def _render_corpus_row(self, label, ngrams): """Returns the HTML for a corpus row.""" row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n' '<td>{last}</td>\n</tr>') cell_data = {'label': label} for period in ('first', 'on...
Returns the HTML for an n-gram row. def _render_ngram_row(self, ngram, ngram_group, row_template, labels): """Returns the HTML for an n-gram row.""" cell_data = {'ngram': ngram} label_data = {} for label in labels: label_data[label] = [] work_grouped = ngram_group.gr...
Saves `results` filtered by `label` and `ngram` to `output_dir`. :param output_dir: directory to save results to :type output_dir: `str` :param label: catalogue label of results, used in saved filename :type label: `str` :param results: results to filter and save :type r...
Set my input stream def link(self, stream_instance): """Set my input stream""" if isinstance(stream_instance, collections.Iterable): self.input_stream = stream_instance elif getattr(stream_instance, 'output_stream', None): self.input_stream = stream_instance.output_strea...
Creates default data from the corpus at `path`, marking all works with `label`. :param path: path to a corpus directory :type path: `str` :param label: label to categorise each work as :type label: `str` def generate(self, path, label): """Creates default data from the ...
Returns a list of works associated with `label`. :param label: label of works to be returned :type label: `str` :rtype: `list` of `str` def get_works_by_label(self, label): """Returns a list of works associated with `label`. :param label: label of works to be returned ...
Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` def load(self, path): """Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` """ fieldnames = ['work', 'label'...
Returns a copy of the catalogue with the labels remapped according to `label_map`. `label_map` is a dictionary mapping existing labels to new labels. Any existing label that is not given a mapping is deleted from the resulting catalogue. :param label_map: mapping of labels to n...
Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type label: `str` def remove_label(self, label): """Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type ...
Saves this catalogue's data to `path`. :param path: file path to save catalogue data to :type path: `str` def save(self, path): """Saves this catalogue's data to `path`. :param path: file path to save catalogue data to :type path: `str` """ writer = csv.writer...
Pull out the dns metadata for packet/transport in the input_stream def dns_meta_data(self): """Pull out the dns metadata for packet/transport in the input_stream""" # For each packet process the contents for packet in self.input_stream: # Skip packets without transport info (ARP/IC...
The method maps the specific fields/flags in a DNS record to human readable form def _dns_info_mapper(self, raw_dns): """The method maps the specific fields/flags in a DNS record to human readable form""" output = {} # Indentification output['identification'] = raw_dns['id'] #...
Look for weird stuff in dns record using a set of criteria to mark the weird stuff def _dns_weird(self, record): """Look for weird stuff in dns record using a set of criteria to mark the weird stuff""" weird = {} # Zero should always be 0 if record['flags']['zero'] != 0: we...
Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str` def get_sigla(self, work): """Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str` ...
Returns a `WitnessText` representing the file associated with `work` and `siglum`. Combined, `work` and `siglum` form the basis of a filename for retrieving the text. :param work: name of work :type work: `str` :param siglum: siglum of witness :type siglum: `str...
Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` def get_witnesses(self, name='*'): """Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` ...
Returns a list of the names of all works in the corpus. :rtype: `list` of `str` def get_works(self): """Returns a list of the names of all works in the corpus. :rtype: `list` of `str` """ return [os.path.split(filepath)[1] for filepath in glob.glob(os.path.joi...
Decorator that raises a `MalformedResultsError` if any of `required_cols` is not present as a column in the matches of the `Results` object bearing the decorated method. :param required_cols: names of required columns :type required_cols: `list` of `str` def requires_columns(required_cols): """Dec...
Look through my input stream for the fields in ip_field_list and try to do a reverse dns lookup on those fields. def process_for_rdns(self): """Look through my input stream for the fields in ip_field_list and try to do a reverse dns lookup on those fields. """ # For each ...
Convert a colour specified in HSV (hue, saturation, value) to an RGB string. Based on the algorithm at https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB :param h: hue, a value between 0 and 1 :type h: `int` :param s: saturation, a value between 0 and 1 :type s: `int` :param v...
Return a list of `n` distinct colours, each represented as an RGB string suitable for use in CSS. Based on the code at http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ :param n: number of colours to generate :type n: `int` :rtype: `list` of `str` def generate_...
Look through my input stream for the fields to be tagged def tag_stuff(self): """Look through my input stream for the fields to be tagged""" # For each packet in the pcap process the contents for item in self.input_stream: # Make sure it has a tags field (which is a set) ...
Create a tag based on the direction of the traffic def _tag_net_direction(data): """Create a tag based on the direction of the traffic""" # IP or IPv6 src = data['packet']['src_domain'] dst = data['packet']['dst_domain'] if src == 'internal': if dst == 'internal' or...
Returns a sorted list of all witnesses of readings in `source_tree`, and the elements that bear @wit attributes. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `tuple` of `list`\s def get_witnesses(self, source_tree): """Returns ...
Returns `root` with a witness list added to the TEI header and @wit values changed to references. def _handle_witnesses(self, root): """Returns `root` with a witness list added to the TEI header and @wit values changed to references.""" witnesses, bearers = self.get_witnesses(root) ...
Saves the TEI XML document `root` at the path `work`. def _output_work(self, work, root): """Saves the TEI XML document `root` at the path `work`.""" output_filename = os.path.join(self._output_dir, work) tree = etree.ElementTree(root) tree.write(output_filename, encoding='utf-8', prett...
Populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part. def _populate_header(self, root): """Populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part.""" # If this gets more complicated, it...
Change `ref_text` on `bearers` to xml:id references. :param root: root of TEI document :type root: `etree._Element` :param bearers: elements bearing `attribute` :param attribute: attribute to update :type attribute: `str` :param ref_text: text to replace :type re...
Returns the name of the work in `filename`. Some works are divided into multiple parts that need to be joined together. :param filename: filename of TEI :type filename: `str` :rtype: `tuple` of `str` def _extract_work(self, filename): """Returns the name of the work in...
Returns a sorted list of all resps in `source_tree`, and the elements that bear @resp attributes. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `tuple` of `lists` def get_resps(self, source_tree): """Returns a sorted list of all...
Returns `root` with a resp list added to the TEI header and @resp values changed to references. def _handle_resps(self, root): """Returns `root` with a resp list added to the TEI header and @resp values changed to references.""" resps, bearers = self.get_resps(root) if not resps...
Transforms the file at `file_path` into simpler XML and returns that. def _tidy(self, work, file_path): """Transforms the file at `file_path` into simpler XML and returns that. """ output_file = os.path.join(self._output_dir, work) self._logger.info('Tidying file {} int...
Tuple for flow (src, dst, sport, dport, proto) def flow_tuple(data): """Tuple for flow (src, dst, sport, dport, proto)""" src = net_utils.inet_to_str(data['packet'].get('src')) if data['packet'].get('src') else None dst = net_utils.inet_to_str(data['packet'].get('dst')) if data['packet'].get('dst') else No...
Add a packet to this flow def add_packet(self, packet): """Add a packet to this flow""" # First packet? if not self.meta['flow_id']: self.meta['flow_id'] = flow_tuple(packet) self.meta['src'] = self.meta['flow_id'][0] self.meta['dst'] = self.meta['flow_id'][...
Reassemble the flow and return all the info/data def get_flow(self): """Reassemble the flow and return all the info/data""" if self.meta['protocol'] == 'TCP': self.meta['packet_list'].sort(key=lambda packet: packet['transport']['seq']) for packet in self.meta['packet_list']: ...
Does the data look like a Client to Server (cts) or Server to Client (stc) traffic? def _cts_or_stc(data): """Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?""" # UDP/TCP if data['transport']: # TCP flags if data['transport']['type']...
Generates tokens for the given code. def _generate_tokens(self, text): """ Generates tokens for the given code. """ # This is technically an undocumented API for Python3, but allows us to use the same API as for # Python2. See http://stackoverflow.com/a/4952291/328565. for index, tok in enumera...
Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. def get_token_from_offset(self, offset): """ Returns the token containing the given character offset (0-based position in source text), or the preceeding...
Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens. def get_token(self, lineno, col_offset): """ Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens. ...
Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses. def get_token_from_utf8(self, lineno, col_offset): """ Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses. """ return self.get_token(lineno, self._line_numbers.from_utf8_col...
Returns the next token after the given one. If include_extra is True, includes non-coding tokens from the tokenize module, such as NL and COMMENT. def next_token(self, tok, include_extra=False): """ Returns the next token after the given one. If include_extra is True, includes non-coding tokens from th...
Looks for the first token, starting at start_token, that matches tok_type and, if given, the token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you can check it with `token.ISEOF(t.type)`. def find_token(self, start_token, tok_type, tok_str=None, reverse=False): """ ...
Yields all tokens in order from first_token through and including last_token. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. def token_range(self, first_token, last_token, include_extra=False): """ Yields all tokens in order from first_token through and including las...
Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. def get_tokens(self, node, include_extra=False): """ Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL an...
After mark_tokens() has been called, returns the (startpos, endpos) positions in source text corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don't correspond to any particular text. def get_text_range(self, node): """ After mark_tokens() has been called, returns the (startp...
After mark_tokens() has been called, returns the text corresponding to the given node. Returns '' for nodes (like `Load`) that don't correspond to any particular text. def get_text(self, node): """ After mark_tokens() has been called, returns the text corresponding to the given node. Returns '' for nod...
Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column. def from_utf8_col(self, line, utf8_column): """ Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column. """ offsets = self._utf8_offset_cache.get(line) if offsets is None: end...
Converts 1-based line number and 0-based column to 0-based character offset into text. def line_to_offset(self, line, column): """ Converts 1-based line number and 0-based column to 0-based character offset into text. """ line -= 1 if line >= len(self._line_offsets): return self._text_len ...
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column numbers. def offset_to_line(self, offset): """ Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column numbers. """ offset = max(0, min(self._text_len, offset)) line_ind...
Generates all tokens in [first_token, last_token] range that do not belong to any children of node. E.g. `foo(bar)` has children `foo` and `bar`, but we would yield the `(`. def _iter_non_child_tokens(self, first_token, last_token, node): """ Generates all tokens in [first_token, last_token] range that do ...
Scan tokens in [first_token, last_token] range that are between node's children, and for any unmatched brackets, adjust first/last tokens to include the closing pair. def _expand_to_matching_pairs(self, first_token, last_token, node): """ Scan tokens in [first_token, last_token] range that are between node...
Returns true if token is of the given type and, if a string is given, has that string. def match_token(token, tok_type, tok_str=None): """Returns true if token is of the given type and, if a string is given, has that string.""" return token.type == tok_type and (tok_str is None or token.string == tok_str)
Verifies that the given token is of the expected type. If tok_str is given, the token string is verified too. If the token doesn't match, raises an informative ValueError. def expect_token(token, tok_type, tok_str=None): """ Verifies that the given token is of the expected type. If tok_str is given, the token st...
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par_value)`` - should return ``(par_value, value)`` ...
Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node`` itself), using depth-first pre-order traversal (yieling parents before their children). This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and ``astroid`` trees. Also, as ``iter_c...
Replaces multiple slices of text with new values. This is a convenience method for making code modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is an iterable of ``(start, end, new_text)`` tuples. For example, ``replace("this is a test", [(0, 4, "X"), (8, 1, "THE")])...
Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`, or `obj.visit_default` if the type-specific method is not found. def get(self, obj, cls): """ Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`, or `obj.visit_default` if the type-spec...
Get a string representation of dataframe value. :param :value: the value to represent :param :allow_formulas: if True, allow values starting with '=' to be interpreted as formulas; otherwise, escape them with an apostrophe to avoid formula interpretation. def _cellrepr(value, allow_for...
Resize the worksheet to guarantee a minimum size, either in rows, or columns, or both. Both rows and cols are optional. def _resize_to_minimum(worksheet, rows=None, cols=None): """ Resize the worksheet to guarantee a minimum size, either in rows, or columns, or both. Both rows and cols are op...
Returns the worksheet contents as a DataFrame. :param worksheet: the worksheet. :param evaluate_formulas: if True, get the value of a cell after formula evaluation; otherwise get the formula itself if present. Defaults to False. :param \*\*options: all the options for pandas.io.pars...
Sets the values of a given DataFrame, anchoring its upper-left corner at (row, col). (Default is row 1, column 1.) :param worksheet: the gspread worksheet to set with content of DataFrame. :param dataframe: the DataFrame. :param include_index: if True, include the DataFrame's index as an ad...
Entry timestamp as datetime. def timestamp(self, timestamp): """Entry timestamp as datetime.""" if timestamp is None: self._timestamp = datetime.utcnow() elif isinstance(timestamp, datetime): self._timestamp = timestamp else: self._timestamp = datetim...
Entry as Python primitive. def primitive(self): """Entry as Python primitive.""" primitive = {} if self.entry_number is not None: primitive['entry-number'] = self.entry_number if self.item_hash is not None: primitive['item-hash'] = self.item_hash primit...
Entry from Python primitive. def primitive(self, primitive): """Entry from Python primitive.""" self.entry_number = primitive['entry-number'] self.item_hash = primitive['item-hash'] self.timestamp = primitive['timestamp']
Return config variable value, defaulting to environment def config(self, name, suffix): "Return config variable value, defaulting to environment" var = '%s_%s' % (name, suffix) var = var.upper().replace('-', '_') if var in self._config: return self._config[var] retur...
Search for records matching a value in an index service def index(self, index, field, value): "Search for records matching a value in an index service" params = { "q": value, # search index has '_' instead of '-' in field names .. "q.options": "{fields:['%s']}" % (fi...
Python primitive representation. def primitive(self): """Python primitive representation.""" dict = {} for key, value in self.__dict__.items(): if not key.startswith('_'): dict[key] = copy(value) for key in dict: if isinstance(dict[key], (set)): ...
Item from Python primitive. def primitive(self, dictionary): """Item from Python primitive.""" self.__dict__ = {k: v for k, v in dictionary.items() if v}
Record as Python primitive. def primitive(self): """Record as Python primitive.""" primitive = copy(self.item.primitive) primitive.update(self.entry.primitive) return primitive
Record from Python primitive. def primitive(self, primitive): """Record from Python primitive.""" self.entry = Entry() self.entry.primitive = primitive primitive = copy(primitive) for field in self.entry.fields: del primitive[field] self.item = Item() ...
Item from TSV representation. def load(self, text, fieldnames=None): """Item from TSV representation.""" lines = text.split('\n') fieldnames = load_line(lines[0]) values = load_line(lines[1]) self.__dict__ = dict(zip(fieldnames, values))
Read Items from a stream containing TSV. def reader(stream, fieldnames=None): """Read Items from a stream containing TSV.""" if not fieldnames: fieldnames = load_line(stream.readline()) for line in stream: values = load_line(line) item = Item() item.__dict__ = dict(zip(field...
TSV representation. def dump(self): """TSV representation.""" dict = self.primitive if not dict: return '' return dump_line(self.keys) + dump_line(self.values)
Item from CSV representation. def load(self, text, lineterminator='\r\n', quotechar='"', delimiter=",", escapechar=escapechar, quoting=csv.QUOTE_MINIMAL): """Item from CSV representation.""" f = io.StringIO(text) if not quotechar: quoting = csv.QUOTE_N...
CSV representation of a item. def dump(self, **kwargs): """CSV representation of a item.""" f = io.StringIO() w = Writer(f, self.keys, **kwargs) w.write(self) text = f.getvalue().lstrip() f.close() return text
Return git-hash compatible SHA-1 hexdigits for a blob of data. def git_hash(blob): """Return git-hash compatible SHA-1 hexdigits for a blob of data.""" head = str("blob " + str(len(blob)) + "\0").encode("utf-8") return sha1(head + blob).hexdigest()
Item as a JSON representation. def dump(self): """Item as a JSON representation.""" return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
Read Items from a stream containing a JSON array. def reader(stream): """Read Items from a stream containing a JSON array.""" string = stream.read() decoder = json.JSONDecoder().raw_decode index = START.match(string, 0).end() while index < len(string): obj, end = decoder(string, index) ...
Read Items from a stream containing lines of JSON. def reader(stream): """Read Items from a stream containing lines of JSON.""" for line in stream: item = Item() item.json = line yield item
Calculate statistics for a collection return: meta def meta(self, total, page=1, page_size=None): """ Calculate statistics for a collection return: meta """ if page_size is None or page_size < 0: page_size = self.page_size meta = {} meta['tot...
Get the unique tag identifier for a given tag. :param name: The tag :type name: str :rtype: str def tag_id(self, name): """ Get the unique tag identifier for a given tag. :param name: The tag :type name: str :rtype: str """ return self...
Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str def reset_tag(self, name): """ Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str """ id_ ...
Flask application initialization. def init_app(self, app): """Flask application initialization.""" self.init_config(app) if app.config['LOGGING_FS_LOGFILE'] is None: return self.install_handler(app) app.extensions['invenio-logging-fs'] = self
Initialize config. def init_config(self, app): """Initialize config.""" app.config.setdefault( 'LOGGING_FS_LEVEL', 'DEBUG' if app.debug else 'WARNING' ) for k in dir(config): if k.startswith('LOGGING_FS'): app.config.setdefault(k, geta...
Install log handler on Flask application. def install_handler(self, app): """Install log handler on Flask application.""" # Check if directory exists. basedir = dirname(app.config['LOGGING_FS_LOGFILE']) if not exists(basedir): raise ValueError( 'Log directory...
Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int or datetime def put(self, key, value, min...
Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|datetime :rtype: bool def add(self, key, val,...
Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key...
Decrement the value of an item in the cache. :param key: The cache key :type key: str :param value: The decrement value :type value: int :rtype: int or bool def decrement(self, key, value=1): """ Decrement the value of an item in the cache. :param key...
Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :...
Get an item from the cache, or store the default value. :param key: The cache key :type key: str :param minutes: The lifetime in minutes of the cached value :type minutes: int or datetime :param callback: The default function :type callback: mixed :rtype: mixe...
Get an item from the cache, or store the default value forever. :param key: The cache key :type key: str :param callback: The default function :type callback: mixed :rtype: mixed def remember_forever(self, key, callback): """ Get an item from the cache, or sto...
Get a fully qualified key for a tagged item. :param key: The cache key :type key: str :rtype: str def tagged_item_key(self, key): """ Get a fully qualified key for a tagged item. :param key: The cache key :type key: str :rtype: str """ ...
Calculate the number of minutes with the given duration. :param duration: The duration :type duration: int or datetime :rtype: int or None def _get_minutes(self, duration): """ Calculate the number of minutes with the given duration. :param duration: The duration ...
Get the data from a Netdata instance. async def main(): """Get the data from a Netdata instance.""" with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session, data='data') await data.get_data('system.cpu') print(json.dumps(data.values, indent=4, sort_keys=True)...
Install logging handler. def install_handler(self, app): """Install logging handler.""" # Configure python logging if app.config['LOGGING_CONSOLE_PYWARNINGS']: self.capture_pywarnings(logging.StreamHandler()) if app.config['LOGGING_CONSOLE_LEVEL'] is not None: f...