repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._generate_corpus_table
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'.join(html)
python
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'.join(html)
[ "def", "_generate_corpus_table", "(", "self", ",", "labels", ",", "ngrams", ")", ":", "html", "=", "[", "]", "for", "label", "in", "labels", ":", "html", ".", "append", "(", "self", ".", "_render_corpus_row", "(", "label", ",", "ngrams", ")", ")", "ret...
Returns an HTML table containing data on each corpus' n-grams.
[ "Returns", "an", "HTML", "table", "containing", "data", "on", "each", "corpus", "n", "-", "grams", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L42-L47
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._generate_ngram_table
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_template = self._generate_ngram_row_template(labels) for name, group in grouped: html.append(self._render_ngram_row(name, group, row_template, labels)) return '\n'.join(html)
python
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_template = self._generate_ngram_row_template(labels) for name, group in grouped: html.append(self._render_ngram_row(name, group, row_template, labels)) return '\n'.join(html)
[ "def", "_generate_ngram_table", "(", "self", ",", "output_dir", ",", "labels", ",", "results", ")", ":", "html", "=", "[", "]", "grouped", "=", "results", ".", "groupby", "(", "constants", ".", "NGRAM_FIELDNAME", ")", "row_template", "=", "self", ".", "_ge...
Returns an HTML table containing data on each n-gram in `results`.
[ "Returns", "an", "HTML", "table", "containing", "data", "on", "each", "n", "-", "gram", "in", "results", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L49-L58
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._generate_ngram_row_template
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'.join(cells)
python
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'.join(cells)
[ "def", "_generate_ngram_row_template", "(", "self", ",", "labels", ")", ":", "cells", "=", "[", "'<td>{ngram}</td>'", "]", "for", "label", "in", "labels", ":", "cells", ".", "append", "(", "'<td>{{{}}}</td>'", ".", "format", "(", "label", ")", ")", "return",...
Returns the HTML template for a row in the n-gram table.
[ "Returns", "the", "HTML", "template", "for", "a", "row", "in", "the", "n", "-", "gram", "table", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L60-L65
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._generate_results
def _generate_results(self, output_dir, labels, results): """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. """ ngrams = {} for idx, label in enumerate(labels): now_results = results[results[constants.LABEL_FIELDNAME] == label] earlier_labels = labels[:idx] earlier_ngrams = results[results[constants.LABEL_FIELDNAME].isin( earlier_labels)][constants.NGRAM_FIELDNAME].values later_labels = labels[idx + 1:] later_ngrams = results[results[constants.LABEL_FIELDNAME].isin( later_labels)][constants.NGRAM_FIELDNAME].values first_ngrams = [] only_ngrams = [] last_ngrams = [] for ngram in now_results[constants.NGRAM_FIELDNAME].unique(): if ngram in earlier_ngrams: if ngram not in later_ngrams: last_ngrams.append(ngram) elif ngram in later_ngrams: first_ngrams.append(ngram) else: only_ngrams.append(ngram) self._save_results(output_dir, label, now_results, first_ngrams, 'first') self._save_results(output_dir, label, now_results, only_ngrams, 'only') self._save_results(output_dir, label, now_results, last_ngrams, 'last') ngrams[label] = {'first': first_ngrams, 'last': last_ngrams, 'only': only_ngrams} return ngrams
python
def _generate_results(self, output_dir, labels, results): """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. """ ngrams = {} for idx, label in enumerate(labels): now_results = results[results[constants.LABEL_FIELDNAME] == label] earlier_labels = labels[:idx] earlier_ngrams = results[results[constants.LABEL_FIELDNAME].isin( earlier_labels)][constants.NGRAM_FIELDNAME].values later_labels = labels[idx + 1:] later_ngrams = results[results[constants.LABEL_FIELDNAME].isin( later_labels)][constants.NGRAM_FIELDNAME].values first_ngrams = [] only_ngrams = [] last_ngrams = [] for ngram in now_results[constants.NGRAM_FIELDNAME].unique(): if ngram in earlier_ngrams: if ngram not in later_ngrams: last_ngrams.append(ngram) elif ngram in later_ngrams: first_ngrams.append(ngram) else: only_ngrams.append(ngram) self._save_results(output_dir, label, now_results, first_ngrams, 'first') self._save_results(output_dir, label, now_results, only_ngrams, 'only') self._save_results(output_dir, label, now_results, last_ngrams, 'last') ngrams[label] = {'first': first_ngrams, 'last': last_ngrams, 'only': only_ngrams} return ngrams
[ "def", "_generate_results", "(", "self", ",", "output_dir", ",", "labels", ",", "results", ")", ":", "ngrams", "=", "{", "}", "for", "idx", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "now_results", "=", "results", "[", "results", "[", "c...
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.
[ "Creates", "multiple", "results", "files", "in", "output_dir", "based", "on", "results", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L67-L103
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._render_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', 'only', 'last'): cell_data[period] = ', '.join(ngrams[label][period]) return row.format(**cell_data)
python
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', 'only', 'last'): cell_data[period] = ', '.join(ngrams[label][period]) return row.format(**cell_data)
[ "def", "_render_corpus_row", "(", "self", ",", "label", ",", "ngrams", ")", ":", "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...
Returns the HTML for a corpus row.
[ "Returns", "the", "HTML", "for", "a", "corpus", "row", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L105-L112
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._render_ngram_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.groupby(constants.WORK_FIELDNAME) for work, group in work_grouped: min_count = group[constants.COUNT_FIELDNAME].min() max_count = group[constants.COUNT_FIELDNAME].max() if min_count == max_count: count = min_count else: count = '{}\N{EN DASH}{}'.format(min_count, max_count) label_data[group[constants.LABEL_FIELDNAME].iloc[0]].append( '{} ({})'.format(work, count)) for label, data in label_data.items(): label_data[label] = '; '.join(data) cell_data.update(label_data) html = row_template.format(**cell_data) return '<tr>\n{}\n</tr>'.format(html)
python
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.groupby(constants.WORK_FIELDNAME) for work, group in work_grouped: min_count = group[constants.COUNT_FIELDNAME].min() max_count = group[constants.COUNT_FIELDNAME].max() if min_count == max_count: count = min_count else: count = '{}\N{EN DASH}{}'.format(min_count, max_count) label_data[group[constants.LABEL_FIELDNAME].iloc[0]].append( '{} ({})'.format(work, count)) for label, data in label_data.items(): label_data[label] = '; '.join(data) cell_data.update(label_data) html = row_template.format(**cell_data) return '<tr>\n{}\n</tr>'.format(html)
[ "def", "_render_ngram_row", "(", "self", ",", "ngram", ",", "ngram_group", ",", "row_template", ",", "labels", ")", ":", "cell_data", "=", "{", "'ngram'", ":", "ngram", "}", "label_data", "=", "{", "}", "for", "label", "in", "labels", ":", "label_data", ...
Returns the HTML for an n-gram row.
[ "Returns", "the", "HTML", "for", "an", "n", "-", "gram", "row", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L114-L134
ajenhl/tacl
tacl/lifetime_report.py
LifetimeReport._save_results
def _save_results(self, output_dir, label, results, ngrams, type_label): """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 results: `pandas.DataFrame` :param ngrams: n-grams to save from results :type ngrams: `list` of `str` :param type_label: name of type of results, used in saved filename :type type_label: `str` """ path = os.path.join(output_dir, '{}-{}.csv'.format(label, type_label)) results[results[constants.NGRAM_FIELDNAME].isin( ngrams)].to_csv(path, encoding='utf-8', float_format='%d', index=False)
python
def _save_results(self, output_dir, label, results, ngrams, type_label): """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 results: `pandas.DataFrame` :param ngrams: n-grams to save from results :type ngrams: `list` of `str` :param type_label: name of type of results, used in saved filename :type type_label: `str` """ path = os.path.join(output_dir, '{}-{}.csv'.format(label, type_label)) results[results[constants.NGRAM_FIELDNAME].isin( ngrams)].to_csv(path, encoding='utf-8', float_format='%d', index=False)
[ "def", "_save_results", "(", "self", ",", "output_dir", ",", "label", ",", "results", ",", "ngrams", ",", "type_label", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'{}-{}.csv'", ".", "format", "(", "label", ",", "typ...
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 results: `pandas.DataFrame` :param ngrams: n-grams to save from results :type ngrams: `list` of `str` :param type_label: name of type of results, used in saved filename :type type_label: `str`
[ "Saves", "results", "filtered", "by", "label", "and", "ngram", "to", "output_dir", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L136-L154
SuperCowPowers/chains
chains/links/link.py
Link.link
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_stream else: raise RuntimeError('Calling link() with unknown instance type %s' % type(stream_instance))
python
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_stream else: raise RuntimeError('Calling link() with unknown instance type %s' % type(stream_instance))
[ "def", "link", "(", "self", ",", "stream_instance", ")", ":", "if", "isinstance", "(", "stream_instance", ",", "collections", ".", "Iterable", ")", ":", "self", ".", "input_stream", "=", "stream_instance", "elif", "getattr", "(", "stream_instance", ",", "'outp...
Set my input stream
[ "Set", "my", "input", "stream" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/link.py#L18-L25
ajenhl/tacl
tacl/catalogue.py
Catalogue.generate
def generate(self, path, label): """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` """ for filename in os.listdir(path): self[filename] = label
python
def generate(self, path, label): """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` """ for filename in os.listdir(path): self[filename] = label
[ "def", "generate", "(", "self", ",", "path", ",", "label", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "self", "[", "filename", "]", "=", "label" ]
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`
[ "Creates", "default", "data", "from", "the", "corpus", "at", "path", "marking", "all", "works", "with", "label", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L15-L26
ajenhl/tacl
tacl/catalogue.py
Catalogue.get_works_by_label
def get_works_by_label(self, label): """Returns a list of works associated with `label`. :param label: label of works to be returned :type label: `str` :rtype: `list` of `str` """ return [work for work, c_label in self.items() if c_label == label]
python
def get_works_by_label(self, label): """Returns a list of works associated with `label`. :param label: label of works to be returned :type label: `str` :rtype: `list` of `str` """ return [work for work, c_label in self.items() if c_label == label]
[ "def", "get_works_by_label", "(", "self", ",", "label", ")", ":", "return", "[", "work", "for", "work", ",", "c_label", "in", "self", ".", "items", "(", ")", "if", "c_label", "==", "label", "]" ]
Returns a list of works associated with `label`. :param label: label of works to be returned :type label: `str` :rtype: `list` of `str`
[ "Returns", "a", "list", "of", "works", "associated", "with", "label", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L28-L36
ajenhl/tacl
tacl/catalogue.py
Catalogue.load
def load(self, path): """Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` """ fieldnames = ['work', 'label'] with open(path, 'r', encoding='utf-8', newline='') as fh: reader = csv.DictReader(fh, delimiter=' ', fieldnames=fieldnames, skipinitialspace=True) for row in reader: work, label = row['work'], row['label'] if label: if label not in self._ordered_labels: self._ordered_labels.append(label) if work in self: raise MalformedCatalogueError( CATALOGUE_WORK_RELABELLED_ERROR.format(work)) self[work] = label
python
def load(self, path): """Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` """ fieldnames = ['work', 'label'] with open(path, 'r', encoding='utf-8', newline='') as fh: reader = csv.DictReader(fh, delimiter=' ', fieldnames=fieldnames, skipinitialspace=True) for row in reader: work, label = row['work'], row['label'] if label: if label not in self._ordered_labels: self._ordered_labels.append(label) if work in self: raise MalformedCatalogueError( CATALOGUE_WORK_RELABELLED_ERROR.format(work)) self[work] = label
[ "def", "load", "(", "self", ",", "path", ")", ":", "fieldnames", "=", "[", "'work'", ",", "'label'", "]", "with", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "'utf-8'", ",", "newline", "=", "''", ")", "as", "fh", ":", "reader", "=", "c...
Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str`
[ "Loads", "the", "data", "from", "path", "into", "the", "catalogue", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L60-L79
ajenhl/tacl
tacl/catalogue.py
Catalogue.relabel
def relabel(self, label_map): """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 new labels :type label_map: `dict` :rtype: `tacl.Catalogue` """ catalogue = copy.deepcopy(self) to_delete = set() for work, old_label in catalogue.items(): if old_label in label_map: catalogue[work] = label_map[old_label] else: to_delete.add(catalogue[work]) for label in to_delete: catalogue.remove_label(label) return catalogue
python
def relabel(self, label_map): """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 new labels :type label_map: `dict` :rtype: `tacl.Catalogue` """ catalogue = copy.deepcopy(self) to_delete = set() for work, old_label in catalogue.items(): if old_label in label_map: catalogue[work] = label_map[old_label] else: to_delete.add(catalogue[work]) for label in to_delete: catalogue.remove_label(label) return catalogue
[ "def", "relabel", "(", "self", ",", "label_map", ")", ":", "catalogue", "=", "copy", ".", "deepcopy", "(", "self", ")", "to_delete", "=", "set", "(", ")", "for", "work", ",", "old_label", "in", "catalogue", ".", "items", "(", ")", ":", "if", "old_lab...
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 new labels :type label_map: `dict` :rtype: `tacl.Catalogue`
[ "Returns", "a", "copy", "of", "the", "catalogue", "with", "the", "labels", "remapped", "according", "to", "label_map", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L81-L103
ajenhl/tacl
tacl/catalogue.py
Catalogue.remove_label
def remove_label(self, label): """Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type label: `str` """ works_to_delete = [] for work, work_label in self.items(): if work_label == label: works_to_delete.append(work) for work in works_to_delete: del self[work] if self._ordered_labels: self._ordered_labels.remove(label)
python
def remove_label(self, label): """Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type label: `str` """ works_to_delete = [] for work, work_label in self.items(): if work_label == label: works_to_delete.append(work) for work in works_to_delete: del self[work] if self._ordered_labels: self._ordered_labels.remove(label)
[ "def", "remove_label", "(", "self", ",", "label", ")", ":", "works_to_delete", "=", "[", "]", "for", "work", ",", "work_label", "in", "self", ".", "items", "(", ")", ":", "if", "work_label", "==", "label", ":", "works_to_delete", ".", "append", "(", "w...
Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type label: `str`
[ "Removes", "label", "from", "the", "catalogue", "by", "removing", "all", "works", "carrying", "it", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L105-L120
ajenhl/tacl
tacl/catalogue.py
Catalogue.save
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(open(path, 'w', newline=''), delimiter=' ') rows = list(self.items()) rows.sort(key=lambda x: x[0]) writer.writerows(rows)
python
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(open(path, 'w', newline=''), delimiter=' ') rows = list(self.items()) rows.sort(key=lambda x: x[0]) writer.writerows(rows)
[ "def", "save", "(", "self", ",", "path", ")", ":", "writer", "=", "csv", ".", "writer", "(", "open", "(", "path", ",", "'w'", ",", "newline", "=", "''", ")", ",", "delimiter", "=", "' '", ")", "rows", "=", "list", "(", "self", ".", "items", "("...
Saves this catalogue's data to `path`. :param path: file path to save catalogue data to :type path: `str`
[ "Saves", "this", "catalogue", "s", "data", "to", "path", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L122-L132
SuperCowPowers/chains
chains/links/dns_meta.py
DNSMeta.dns_meta_data
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/ICMP/IGMP/whatever) if 'transport' not in packet: continue try: dns_meta = dpkt.dns.DNS(packet['transport']['data']) _raw_info = data_utils.make_dict(dns_meta) packet['dns'] = self._dns_info_mapper(_raw_info) packet['dns']['_raw'] = _raw_info except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError): if 'dns' in packet: del packet['dns'] # All done yield packet
python
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/ICMP/IGMP/whatever) if 'transport' not in packet: continue try: dns_meta = dpkt.dns.DNS(packet['transport']['data']) _raw_info = data_utils.make_dict(dns_meta) packet['dns'] = self._dns_info_mapper(_raw_info) packet['dns']['_raw'] = _raw_info except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError): if 'dns' in packet: del packet['dns'] # All done yield packet
[ "def", "dns_meta_data", "(", "self", ")", ":", "# For each packet process the contents", "for", "packet", "in", "self", ".", "input_stream", ":", "# Skip packets without transport info (ARP/ICMP/IGMP/whatever)", "if", "'transport'", "not", "in", "packet", ":", "continue", ...
Pull out the dns metadata for packet/transport in the input_stream
[ "Pull", "out", "the", "dns", "metadata", "for", "packet", "/", "transport", "in", "the", "input_stream" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L43-L61
SuperCowPowers/chains
chains/links/dns_meta.py
DNSMeta._dns_info_mapper
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'] # Pull out all the flags flags = {} flags['type'] = 'query' if raw_dns['qr'] == 0 else 'response' flags['opcode'] = self.opcodes.get(raw_dns['opcode'], 'UNKNOWN') flags['authoritative'] = True if raw_dns['aa'] else False flags['truncated'] = True if raw_dns['tc'] else False flags['recursion_desired'] = True if raw_dns['rd'] else False flags['recursion_available'] = True if raw_dns['ra'] else False flags['zero'] = raw_dns['zero'] flags['return_code'] = self.rcodes.get(raw_dns['rcode'], 'UNKNOWN') output['flags'] = flags # Question/Answer Counts counts = {} counts['questions'] = len(raw_dns['qd']) counts['answers'] = len(raw_dns['an']) counts['auth_answers'] = len(raw_dns['ns']) counts['add_answers'] = len(raw_dns['ar']) output['counts'] = counts # Queries/Questions queries = [] for query in raw_dns['qd']: q = {'class': self.query_classes.get(query['cls'], 'UNKNOWN'), 'type': self.query_types.get(query['type'], 'UNKNOWN'), 'name': query['name'], 'data': query['data']} queries.append(q) output['queries'] = queries # Responses/Answers (Resource Record) output['answers'] = {} for section_name, section in zip(['answers', 'name_servers', 'additional'], ['an', 'ns', 'ar']): answers = [] for answer in raw_dns[section]: ans_output = {} ans_output['name'] = answer['name'] ans_output['type'] = self.query_types.get(answer['type'], 'UNKNOWN') ans_output['class'] = self.query_classes.get(answer['cls'], 'UNKNOWN') ans_output['ttl'] = answer['ttl'] # Get the return data for this answer type rdata_field = self._get_rdata_field(answer) if rdata_field != 'unknown': ans_output['rdata'] = answer[rdata_field] answers.append(ans_output) # Add data to this answer section output['answers'][section_name] = answers # Add any weird stuff weird = self._dns_weird(output) if weird: output['weird'] = weird return output
python
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'] # Pull out all the flags flags = {} flags['type'] = 'query' if raw_dns['qr'] == 0 else 'response' flags['opcode'] = self.opcodes.get(raw_dns['opcode'], 'UNKNOWN') flags['authoritative'] = True if raw_dns['aa'] else False flags['truncated'] = True if raw_dns['tc'] else False flags['recursion_desired'] = True if raw_dns['rd'] else False flags['recursion_available'] = True if raw_dns['ra'] else False flags['zero'] = raw_dns['zero'] flags['return_code'] = self.rcodes.get(raw_dns['rcode'], 'UNKNOWN') output['flags'] = flags # Question/Answer Counts counts = {} counts['questions'] = len(raw_dns['qd']) counts['answers'] = len(raw_dns['an']) counts['auth_answers'] = len(raw_dns['ns']) counts['add_answers'] = len(raw_dns['ar']) output['counts'] = counts # Queries/Questions queries = [] for query in raw_dns['qd']: q = {'class': self.query_classes.get(query['cls'], 'UNKNOWN'), 'type': self.query_types.get(query['type'], 'UNKNOWN'), 'name': query['name'], 'data': query['data']} queries.append(q) output['queries'] = queries # Responses/Answers (Resource Record) output['answers'] = {} for section_name, section in zip(['answers', 'name_servers', 'additional'], ['an', 'ns', 'ar']): answers = [] for answer in raw_dns[section]: ans_output = {} ans_output['name'] = answer['name'] ans_output['type'] = self.query_types.get(answer['type'], 'UNKNOWN') ans_output['class'] = self.query_classes.get(answer['cls'], 'UNKNOWN') ans_output['ttl'] = answer['ttl'] # Get the return data for this answer type rdata_field = self._get_rdata_field(answer) if rdata_field != 'unknown': ans_output['rdata'] = answer[rdata_field] answers.append(ans_output) # Add data to this answer section output['answers'][section_name] = answers # Add any weird stuff weird = self._dns_weird(output) if weird: output['weird'] = weird return output
[ "def", "_dns_info_mapper", "(", "self", ",", "raw_dns", ")", ":", "output", "=", "{", "}", "# Indentification", "output", "[", "'identification'", "]", "=", "raw_dns", "[", "'id'", "]", "# Pull out all the flags", "flags", "=", "{", "}", "flags", "[", "'type...
The method maps the specific fields/flags in a DNS record to human readable form
[ "The", "method", "maps", "the", "specific", "fields", "/", "flags", "in", "a", "DNS", "record", "to", "human", "readable", "form" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L63-L126
SuperCowPowers/chains
chains/links/dns_meta.py
DNSMeta._dns_weird
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: weird['zero'] = record['flags']['zero'] # Trucated may indicate an exfil if record['flags']['truncated']: weird['trucnated'] = True # Weird Query Types weird_types = set(['DNS_NULL', 'DNS_HINFO', 'DNS_TXT', 'UNKNOWN']) for query in record['queries']: if query['type'] in weird_types: weird['query_type'] = query['type'] # Weird Query Classes weird_classes = set(['DNS_CHAOS', 'DNS_HESIOD', 'DNS_NONE', 'DNS_ANY']) for query in record['queries']: if query['class'] in weird_classes: weird['query_class'] = query['class'] # Weird Answer Types for section_name in ['answers', 'name_servers', 'additional']: for answer in record['answers'][section_name]: if answer['type'] in weird_types: weird['answer_type'] = answer['type'] # Weird Answer Classes for section_name in ['answers', 'name_servers', 'additional']: for answer in record['answers'][section_name]: if answer['class'] in weird_classes: weird['answer_class'] = answer['class'] # Is the subdomain name especially long or have high entropy? for query in record['queries']: subdomain = '.'.join(query['name'].split('.')[:-2]) length = len(subdomain) entropy = self.entropy(subdomain) if length > 35 and entropy > 3.5: weird['subdomain_length'] = length weird['subdomain'] = subdomain weird['subdomain_entropy'] = entropy weird['subdomain'] = subdomain # Return the weird stuff return weird
python
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: weird['zero'] = record['flags']['zero'] # Trucated may indicate an exfil if record['flags']['truncated']: weird['trucnated'] = True # Weird Query Types weird_types = set(['DNS_NULL', 'DNS_HINFO', 'DNS_TXT', 'UNKNOWN']) for query in record['queries']: if query['type'] in weird_types: weird['query_type'] = query['type'] # Weird Query Classes weird_classes = set(['DNS_CHAOS', 'DNS_HESIOD', 'DNS_NONE', 'DNS_ANY']) for query in record['queries']: if query['class'] in weird_classes: weird['query_class'] = query['class'] # Weird Answer Types for section_name in ['answers', 'name_servers', 'additional']: for answer in record['answers'][section_name]: if answer['type'] in weird_types: weird['answer_type'] = answer['type'] # Weird Answer Classes for section_name in ['answers', 'name_servers', 'additional']: for answer in record['answers'][section_name]: if answer['class'] in weird_classes: weird['answer_class'] = answer['class'] # Is the subdomain name especially long or have high entropy? for query in record['queries']: subdomain = '.'.join(query['name'].split('.')[:-2]) length = len(subdomain) entropy = self.entropy(subdomain) if length > 35 and entropy > 3.5: weird['subdomain_length'] = length weird['subdomain'] = subdomain weird['subdomain_entropy'] = entropy weird['subdomain'] = subdomain # Return the weird stuff return weird
[ "def", "_dns_weird", "(", "self", ",", "record", ")", ":", "weird", "=", "{", "}", "# Zero should always be 0", "if", "record", "[", "'flags'", "]", "[", "'zero'", "]", "!=", "0", ":", "weird", "[", "'zero'", "]", "=", "record", "[", "'flags'", "]", ...
Look for weird stuff in dns record using a set of criteria to mark the weird stuff
[ "Look", "for", "weird", "stuff", "in", "dns", "record", "using", "a", "set", "of", "criteria", "to", "mark", "the", "weird", "stuff" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L128-L176
ajenhl/tacl
tacl/corpus.py
Corpus.get_sigla
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` """ return [os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(self._path, work, '*.txt'))]
python
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` """ return [os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(self._path, work, '*.txt'))]
[ "def", "get_sigla", "(", "self", ",", "work", ")", ":", "return", "[", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "[", "0", "]", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", ...
Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str`
[ "Returns", "a", "list", "of", "all", "of", "the", "sigla", "for", "work", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L24-L33
ajenhl/tacl
tacl/corpus.py
Corpus.get_witness
def get_witness(self, work, siglum, text_class=WitnessText): """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` :rtype: `WitnessText` """ filename = os.path.join(work, siglum + '.txt') self._logger.debug('Creating WitnessText object from {}'.format( filename)) with open(os.path.join(self._path, filename), encoding='utf-8') \ as fh: content = fh.read() return text_class(work, siglum, content, self._tokenizer)
python
def get_witness(self, work, siglum, text_class=WitnessText): """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` :rtype: `WitnessText` """ filename = os.path.join(work, siglum + '.txt') self._logger.debug('Creating WitnessText object from {}'.format( filename)) with open(os.path.join(self._path, filename), encoding='utf-8') \ as fh: content = fh.read() return text_class(work, siglum, content, self._tokenizer)
[ "def", "get_witness", "(", "self", ",", "work", ",", "siglum", ",", "text_class", "=", "WitnessText", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "work", ",", "siglum", "+", "'.txt'", ")", "self", ".", "_logger", ".", "debug", "("...
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` :rtype: `WitnessText`
[ "Returns", "a", "WitnessText", "representing", "the", "file", "associated", "with", "work", "and", "siglum", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L35-L55
ajenhl/tacl
tacl/corpus.py
Corpus.get_witnesses
def get_witnesses(self, name='*'): """Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` """ for filepath in glob.glob(os.path.join(self._path, name, '*.txt')): if os.path.isfile(filepath): name = os.path.split(os.path.split(filepath)[0])[1] siglum = os.path.splitext(os.path.basename(filepath))[0] yield self.get_witness(name, siglum)
python
def get_witnesses(self, name='*'): """Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` """ for filepath in glob.glob(os.path.join(self._path, name, '*.txt')): if os.path.isfile(filepath): name = os.path.split(os.path.split(filepath)[0])[1] siglum = os.path.splitext(os.path.basename(filepath))[0] yield self.get_witness(name, siglum)
[ "def", "get_witnesses", "(", "self", ",", "name", "=", "'*'", ")", ":", "for", "filepath", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "name", ",", "'*.txt'", ")", ")", ":", "if", "os", ".", "...
Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText`
[ "Returns", "a", "generator", "supplying", "WitnessText", "objects", "for", "each", "work", "in", "the", "corpus", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L57-L68
ajenhl/tacl
tacl/corpus.py
Corpus.get_works
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.join(self._path, '*')) if os.path.isdir(filepath)]
python
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.join(self._path, '*')) if os.path.isdir(filepath)]
[ "def", "get_works", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "split", "(", "filepath", ")", "[", "1", "]", "for", "filepath", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "...
Returns a list of the names of all works in the corpus. :rtype: `list` of `str`
[ "Returns", "a", "list", "of", "the", "names", "of", "all", "works", "in", "the", "corpus", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L70-L78
ajenhl/tacl
tacl/decorators.py
requires_columns
def requires_columns(required_cols): """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 dec(f): @wraps(f) def decorated_function(*args, **kwargs): actual_cols = list(args[0]._matches.columns) missing_cols = [] for required_col in required_cols: if required_col not in actual_cols: missing_cols.append('"{}"'.format(required_col)) if missing_cols: raise MalformedResultsError( constants.MISSING_REQUIRED_COLUMNS_ERROR.format( ', '.join(missing_cols))) return f(*args, **kwargs) return decorated_function return dec
python
def requires_columns(required_cols): """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 dec(f): @wraps(f) def decorated_function(*args, **kwargs): actual_cols = list(args[0]._matches.columns) missing_cols = [] for required_col in required_cols: if required_col not in actual_cols: missing_cols.append('"{}"'.format(required_col)) if missing_cols: raise MalformedResultsError( constants.MISSING_REQUIRED_COLUMNS_ERROR.format( ', '.join(missing_cols))) return f(*args, **kwargs) return decorated_function return dec
[ "def", "requires_columns", "(", "required_cols", ")", ":", "def", "dec", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "actual_cols", "=", "list", "(", "args", "[", ...
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`
[ "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", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/decorators.py#L7-L30
SuperCowPowers/chains
chains/links/reverse_dns.py
ReverseDNS.process_for_rdns
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 packet process the contents for item in self.input_stream: # Do for both the src and dst for endpoint in ['src', 'dst']: # Sanity check (might be an ARP, whatever... without a src/dst) if endpoint not in item['packet']: # Set the domain to None item['packet'][endpoint+self.domain_postfix] = None continue # Convert inet_address to str ip_address ip_address = net_utils.inet_to_str(item['packet'][endpoint]) # Is this already in our cache if self.ip_lookup_cache.get(ip_address): domain = self.ip_lookup_cache.get(ip_address) # Is the ip_address local or special elif net_utils.is_internal(ip_address): domain = 'internal' elif net_utils.is_special(ip_address): domain = net_utils.is_special(ip_address) # Look it up at this point else: domain = self._reverse_dns_lookup(ip_address) # Set the domain item['packet'][endpoint+self.domain_postfix] = domain # Cache it self.ip_lookup_cache.set(ip_address, domain) # All done yield item
python
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 packet process the contents for item in self.input_stream: # Do for both the src and dst for endpoint in ['src', 'dst']: # Sanity check (might be an ARP, whatever... without a src/dst) if endpoint not in item['packet']: # Set the domain to None item['packet'][endpoint+self.domain_postfix] = None continue # Convert inet_address to str ip_address ip_address = net_utils.inet_to_str(item['packet'][endpoint]) # Is this already in our cache if self.ip_lookup_cache.get(ip_address): domain = self.ip_lookup_cache.get(ip_address) # Is the ip_address local or special elif net_utils.is_internal(ip_address): domain = 'internal' elif net_utils.is_special(ip_address): domain = net_utils.is_special(ip_address) # Look it up at this point else: domain = self._reverse_dns_lookup(ip_address) # Set the domain item['packet'][endpoint+self.domain_postfix] = domain # Cache it self.ip_lookup_cache.set(ip_address, domain) # All done yield item
[ "def", "process_for_rdns", "(", "self", ")", ":", "# For each packet process the contents", "for", "item", "in", "self", ".", "input_stream", ":", "# Do for both the src and dst", "for", "endpoint", "in", "[", "'src'", ",", "'dst'", "]", ":", "# Sanity check (might be...
Look through my input stream for the fields in ip_field_list and try to do a reverse dns lookup on those fields.
[ "Look", "through", "my", "input", "stream", "for", "the", "fields", "in", "ip_field_list", "and", "try", "to", "do", "a", "reverse", "dns", "lookup", "on", "those", "fields", "." ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/reverse_dns.py#L26-L68
ajenhl/tacl
tacl/colour.py
hsv_to_rgb
def hsv_to_rgb(h, s, v): """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: value, a value between 0 and 1 :type v: `int` :rtype: `str` """ c = v * s hp = h*6 x = c * (1 - abs(hp % 2 - 1)) if hp < 1: r, g, b = c, x, 0 elif hp < 2: r, g, b = x, c, 0 elif hp < 3: r, g, b = 0, c, x elif hp < 4: r, g, b = 0, x, c elif hp < 5: r, g, b = x, 0, c elif hp < 6: r, g, b = c, 0, x m = v - c colour = (r + m, g + m, b + m) return 'rgb({}, {}, {})'.format(*[round(value * 255) for value in colour])
python
def hsv_to_rgb(h, s, v): """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: value, a value between 0 and 1 :type v: `int` :rtype: `str` """ c = v * s hp = h*6 x = c * (1 - abs(hp % 2 - 1)) if hp < 1: r, g, b = c, x, 0 elif hp < 2: r, g, b = x, c, 0 elif hp < 3: r, g, b = 0, c, x elif hp < 4: r, g, b = 0, x, c elif hp < 5: r, g, b = x, 0, c elif hp < 6: r, g, b = c, 0, x m = v - c colour = (r + m, g + m, b + m) return 'rgb({}, {}, {})'.format(*[round(value * 255) for value in colour])
[ "def", "hsv_to_rgb", "(", "h", ",", "s", ",", "v", ")", ":", "c", "=", "v", "*", "s", "hp", "=", "h", "*", "6", "x", "=", "c", "*", "(", "1", "-", "abs", "(", "hp", "%", "2", "-", "1", ")", ")", "if", "hp", "<", "1", ":", "r", ",", ...
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: value, a value between 0 and 1 :type v: `int` :rtype: `str`
[ "Convert", "a", "colour", "specified", "in", "HSV", "(", "hue", "saturation", "value", ")", "to", "an", "RGB", "string", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/colour.py#L4-L37
ajenhl/tacl
tacl/colour.py
generate_colours
def generate_colours(n): """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` """ colours = [] golden_ratio_conjugate = 0.618033988749895 h = 0.8 # Initial hue s = 0.7 # Fixed saturation v = 0.95 # Fixed value for i in range(n): h += golden_ratio_conjugate h %= 1 colours.append(hsv_to_rgb(h, s, v)) return colours
python
def generate_colours(n): """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` """ colours = [] golden_ratio_conjugate = 0.618033988749895 h = 0.8 # Initial hue s = 0.7 # Fixed saturation v = 0.95 # Fixed value for i in range(n): h += golden_ratio_conjugate h %= 1 colours.append(hsv_to_rgb(h, s, v)) return colours
[ "def", "generate_colours", "(", "n", ")", ":", "colours", "=", "[", "]", "golden_ratio_conjugate", "=", "0.618033988749895", "h", "=", "0.8", "# Initial hue", "s", "=", "0.7", "# Fixed saturation", "v", "=", "0.95", "# Fixed value", "for", "i", "in", "range", ...
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`
[ "Return", "a", "list", "of", "n", "distinct", "colours", "each", "represented", "as", "an", "RGB", "string", "suitable", "for", "use", "in", "CSS", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/colour.py#L40-L61
SuperCowPowers/chains
chains/links/packet_tags.py
PacketTags.tag_stuff
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) if 'tags' not in item: item['tags'] = set() # For each tag_methods run it on the item for tag_method in self.tag_methods: item['tags'].add(tag_method(item)) # Not interested in None tags if None in item['tags']: item['tags'].remove(None) # All done yield item
python
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) if 'tags' not in item: item['tags'] = set() # For each tag_methods run it on the item for tag_method in self.tag_methods: item['tags'].add(tag_method(item)) # Not interested in None tags if None in item['tags']: item['tags'].remove(None) # All done yield item
[ "def", "tag_stuff", "(", "self", ")", ":", "# 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)", "if", "'tags'", "not", "in", "item", ":", "item", "[", "'tags'", ...
Look through my input stream for the fields to be tagged
[ "Look", "through", "my", "input", "stream", "for", "the", "fields", "to", "be", "tagged" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L29-L47
SuperCowPowers/chains
chains/links/packet_tags.py
PacketTags._tag_net_direction
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 'multicast' in dst or 'broadcast' in dst: return 'internal' else: return 'outgoing' elif dst == 'internal': return 'incoming' else: return None
python
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 'multicast' in dst or 'broadcast' in dst: return 'internal' else: return 'outgoing' elif dst == 'internal': return 'incoming' else: return None
[ "def", "_tag_net_direction", "(", "data", ")", ":", "# IP or IPv6", "src", "=", "data", "[", "'packet'", "]", "[", "'src_domain'", "]", "dst", "=", "data", "[", "'packet'", "]", "[", "'dst_domain'", "]", "if", "src", "==", "'internal'", ":", "if", "dst",...
Create a tag based on the direction of the traffic
[ "Create", "a", "tag", "based", "on", "the", "direction", "of", "the", "traffic" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L50-L64
ajenhl/tacl
tacl/tei_corpus.py
TEICorpus.get_witnesses
def get_witnesses(self, source_tree): """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 """ witnesses = set() bearers = source_tree.xpath('//tei:app/tei:*[@wit]', namespaces=constants.NAMESPACES) for bearer in bearers: for witness in witnesses_splitter.split(bearer.get('wit')): if witness: witnesses.add(witness) return sorted(witnesses), bearers
python
def get_witnesses(self, source_tree): """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 """ witnesses = set() bearers = source_tree.xpath('//tei:app/tei:*[@wit]', namespaces=constants.NAMESPACES) for bearer in bearers: for witness in witnesses_splitter.split(bearer.get('wit')): if witness: witnesses.add(witness) return sorted(witnesses), bearers
[ "def", "get_witnesses", "(", "self", ",", "source_tree", ")", ":", "witnesses", "=", "set", "(", ")", "bearers", "=", "source_tree", ".", "xpath", "(", "'//tei:app/tei:*[@wit]'", ",", "namespaces", "=", "constants", ".", "NAMESPACES", ")", "for", "bearer", "...
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
[ "Returns", "a", "sorted", "list", "of", "all", "witnesses", "of", "readings", "in", "source_tree", "and", "the", "elements", "that", "bear", "@wit", "attributes", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L101-L117
ajenhl/tacl
tacl/tei_corpus.py
TEICorpus._handle_witnesses
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) if not witnesses: return root source_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:fileDesc/tei:sourceDesc', namespaces=constants.NAMESPACES)[0] wit_list = etree.SubElement(source_desc, TEI + 'listWit') for index, siglum in enumerate(witnesses): wit = etree.SubElement(wit_list, TEI + 'witness') xml_id = 'wit{}'.format(index+1) wit.set(constants.XML + 'id', xml_id) wit.text = siglum full_siglum = '【{}】'.format(siglum) self._update_refs(root, bearers, 'wit', full_siglum, xml_id) return root
python
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) if not witnesses: return root source_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:fileDesc/tei:sourceDesc', namespaces=constants.NAMESPACES)[0] wit_list = etree.SubElement(source_desc, TEI + 'listWit') for index, siglum in enumerate(witnesses): wit = etree.SubElement(wit_list, TEI + 'witness') xml_id = 'wit{}'.format(index+1) wit.set(constants.XML + 'id', xml_id) wit.text = siglum full_siglum = '【{}】'.format(siglum) self._update_refs(root, bearers, 'wit', full_siglum, xml_id) return root
[ "def", "_handle_witnesses", "(", "self", ",", "root", ")", ":", "witnesses", ",", "bearers", "=", "self", ".", "get_witnesses", "(", "root", ")", "if", "not", "witnesses", ":", "return", "root", "source_desc", "=", "root", ".", "xpath", "(", "'/tei:teiCorp...
Returns `root` with a witness list added to the TEI header and @wit values changed to references.
[ "Returns", "root", "with", "a", "witness", "list", "added", "to", "the", "TEI", "header", "and" ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L122-L139
ajenhl/tacl
tacl/tei_corpus.py
TEICorpus._output_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', pretty_print=True)
python
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', pretty_print=True)
[ "def", "_output_work", "(", "self", ",", "work", ",", "root", ")", ":", "output_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_output_dir", ",", "work", ")", "tree", "=", "etree", ".", "ElementTree", "(", "root", ")", "tree", "."...
Saves the TEI XML document `root` at the path `work`.
[ "Saves", "the", "TEI", "XML", "document", "root", "at", "the", "path", "work", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L141-L145
ajenhl/tacl
tacl/tei_corpus.py
TEICorpus._populate_header
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 should be handled via an XSLT. title_stmt = root.xpath( 'tei:teiHeader/tei:fileDesc/tei:titleStmt', namespaces=constants.NAMESPACES)[0] # There is no guarantee that a title or author is specified, # in which case do nothing. try: title_stmt[0].text = root.xpath( 'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/' 'tei:title', namespaces=constants.NAMESPACES)[0].text except IndexError: pass try: title_stmt[1].text = root.xpath( 'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/' 'tei:author', namespaces=constants.NAMESPACES)[0].text except IndexError: pass return root
python
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 should be handled via an XSLT. title_stmt = root.xpath( 'tei:teiHeader/tei:fileDesc/tei:titleStmt', namespaces=constants.NAMESPACES)[0] # There is no guarantee that a title or author is specified, # in which case do nothing. try: title_stmt[0].text = root.xpath( 'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/' 'tei:title', namespaces=constants.NAMESPACES)[0].text except IndexError: pass try: title_stmt[1].text = root.xpath( 'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/' 'tei:author', namespaces=constants.NAMESPACES)[0].text except IndexError: pass return root
[ "def", "_populate_header", "(", "self", ",", "root", ")", ":", "# If this gets more complicated, it should be handled via an XSLT.", "title_stmt", "=", "root", ".", "xpath", "(", "'tei:teiHeader/tei:fileDesc/tei:titleStmt'", ",", "namespaces", "=", "constants", ".", "NAMESP...
Populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part.
[ "Populate", "the", "teiHeader", "of", "the", "teiCorpus", "with", "useful", "information", "from", "the", "teiHeader", "of", "the", "first", "TEI", "part", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L147-L168
ajenhl/tacl
tacl/tei_corpus.py
TEICorpus._update_refs
def _update_refs(self, root, bearers, attribute, ref_text, xml_id): """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 ref_text: `str` :param xml_id: xml:id :type xml_id: `str` """ ref = ' #{} '.format(xml_id) for bearer in bearers: attribute_text = bearer.get(attribute).replace(ref_text, ref) refs = ' '.join(sorted(attribute_text.strip().split())) bearer.set(attribute, refs)
python
def _update_refs(self, root, bearers, attribute, ref_text, xml_id): """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 ref_text: `str` :param xml_id: xml:id :type xml_id: `str` """ ref = ' #{} '.format(xml_id) for bearer in bearers: attribute_text = bearer.get(attribute).replace(ref_text, ref) refs = ' '.join(sorted(attribute_text.strip().split())) bearer.set(attribute, refs)
[ "def", "_update_refs", "(", "self", ",", "root", ",", "bearers", ",", "attribute", ",", "ref_text", ",", "xml_id", ")", ":", "ref", "=", "' #{} '", ".", "format", "(", "xml_id", ")", "for", "bearer", "in", "bearers", ":", "attribute_text", "=", "bearer",...
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 ref_text: `str` :param xml_id: xml:id :type xml_id: `str`
[ "Change", "ref_text", "on", "bearers", "to", "xml", ":", "id", "references", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L189-L207
ajenhl/tacl
tacl/tei_corpus.py
TEICorpusCBETAGitHub._extract_work
def _extract_work(self, filename): """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` """ basename = os.path.splitext(os.path.basename(filename))[0] match = self.work_pattern.search(basename) if match is None: self._logger.warning('Found an anomalous filename "{}"'.format( filename)) return None, None work = '{}{}'.format(match.group('prefix'), match.group('work')) return work, match.group('part')
python
def _extract_work(self, filename): """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` """ basename = os.path.splitext(os.path.basename(filename))[0] match = self.work_pattern.search(basename) if match is None: self._logger.warning('Found an anomalous filename "{}"'.format( filename)) return None, None work = '{}{}'.format(match.group('prefix'), match.group('work')) return work, match.group('part')
[ "def", "_extract_work", "(", "self", ",", "filename", ")", ":", "basename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "[", "0", "]", "match", "=", "self", ".", "work_pattern", ".", ...
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`
[ "Returns", "the", "name", "of", "the", "work", "in", "filename", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L220-L238
ajenhl/tacl
tacl/tei_corpus.py
TEICorpusCBETAGitHub.get_resps
def get_resps(self, source_tree): """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` """ resps = set() bearers = source_tree.xpath('//*[@resp]', namespaces=constants.NAMESPACES) for bearer in bearers: for resp in resp_splitter.split(bearer.get('resp')): if resp: resps.add(tuple(resp.split('|', maxsplit=1))) return sorted(resps), bearers
python
def get_resps(self, source_tree): """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` """ resps = set() bearers = source_tree.xpath('//*[@resp]', namespaces=constants.NAMESPACES) for bearer in bearers: for resp in resp_splitter.split(bearer.get('resp')): if resp: resps.add(tuple(resp.split('|', maxsplit=1))) return sorted(resps), bearers
[ "def", "get_resps", "(", "self", ",", "source_tree", ")", ":", "resps", "=", "set", "(", ")", "bearers", "=", "source_tree", ".", "xpath", "(", "'//*[@resp]'", ",", "namespaces", "=", "constants", ".", "NAMESPACES", ")", "for", "bearer", "in", "bearers", ...
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`
[ "Returns", "a", "sorted", "list", "of", "all", "resps", "in", "source_tree", "and", "the", "elements", "that", "bear", "@resp", "attributes", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L240-L256
ajenhl/tacl
tacl/tei_corpus.py
TEICorpusCBETAGitHub._handle_resps
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: return root file_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:fileDesc', namespaces=constants.NAMESPACES)[0] edition_stmt = etree.Element(TEI + 'editionStmt') file_desc.insert(1, edition_stmt) for index, (resp_resp, resp_name) in enumerate(resps): resp_stmt = etree.SubElement(edition_stmt, TEI + 'respStmt') xml_id = 'resp{}'.format(index+1) resp_stmt.set(constants.XML + 'id', xml_id) resp = etree.SubElement(resp_stmt, TEI + 'resp') resp.text = resp_resp name = etree.SubElement(resp_stmt, TEI + 'name') name.text = resp_name resp_data = '{{{}|{}}}'.format(resp_resp, resp_name) self._update_refs(root, bearers, 'resp', resp_data, xml_id) return root
python
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: return root file_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:fileDesc', namespaces=constants.NAMESPACES)[0] edition_stmt = etree.Element(TEI + 'editionStmt') file_desc.insert(1, edition_stmt) for index, (resp_resp, resp_name) in enumerate(resps): resp_stmt = etree.SubElement(edition_stmt, TEI + 'respStmt') xml_id = 'resp{}'.format(index+1) resp_stmt.set(constants.XML + 'id', xml_id) resp = etree.SubElement(resp_stmt, TEI + 'resp') resp.text = resp_resp name = etree.SubElement(resp_stmt, TEI + 'name') name.text = resp_name resp_data = '{{{}|{}}}'.format(resp_resp, resp_name) self._update_refs(root, bearers, 'resp', resp_data, xml_id) return root
[ "def", "_handle_resps", "(", "self", ",", "root", ")", ":", "resps", ",", "bearers", "=", "self", ".", "get_resps", "(", "root", ")", "if", "not", "resps", ":", "return", "root", "file_desc", "=", "root", ".", "xpath", "(", "'/tei:teiCorpus/tei:teiHeader/t...
Returns `root` with a resp list added to the TEI header and @resp values changed to references.
[ "Returns", "root", "with", "a", "resp", "list", "added", "to", "the", "TEI", "header", "and" ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L258-L279
ajenhl/tacl
tacl/tei_corpus.py
TEICorpusCBETAGitHub._tidy
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 {} into {}'.format( file_path, output_file)) try: tei_doc = etree.parse(file_path) except etree.XMLSyntaxError as err: self._logger.error('XML file "{}" is invalid: {}'.format( file_path, err)) raise return self.transform(tei_doc).getroot()
python
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 {} into {}'.format( file_path, output_file)) try: tei_doc = etree.parse(file_path) except etree.XMLSyntaxError as err: self._logger.error('XML file "{}" is invalid: {}'.format( file_path, err)) raise return self.transform(tei_doc).getroot()
[ "def", "_tidy", "(", "self", ",", "work", ",", "file_path", ")", ":", "output_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_output_dir", ",", "work", ")", "self", ".", "_logger", ".", "info", "(", "'Tidying file {} into {}'", ".", "fo...
Transforms the file at `file_path` into simpler XML and returns that.
[ "Transforms", "the", "file", "at", "file_path", "into", "simpler", "XML", "and", "returns", "that", "." ]
train
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L281-L295
SuperCowPowers/chains
chains/utils/flow_utils.py
flow_tuple
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 None sport = data['transport'].get('sport') if data.get('transport') else None dport = data['transport'].get('dport') if data.get('transport') else None proto = data['transport'].get('type') if data.get('transport') else data['packet']['type'] return (src, dst, sport, dport, proto)
python
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 None sport = data['transport'].get('sport') if data.get('transport') else None dport = data['transport'].get('dport') if data.get('transport') else None proto = data['transport'].get('type') if data.get('transport') else data['packet']['type'] return (src, dst, sport, dport, proto)
[ "def", "flow_tuple", "(", "data", ")", ":", "src", "=", "net_utils", ".", "inet_to_str", "(", "data", "[", "'packet'", "]", ".", "get", "(", "'src'", ")", ")", "if", "data", "[", "'packet'", "]", ".", "get", "(", "'src'", ")", "else", "None", "dst"...
Tuple for flow (src, dst, sport, dport, proto)
[ "Tuple", "for", "flow", "(", "src", "dst", "sport", "dport", "proto", ")" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L11-L18
SuperCowPowers/chains
chains/utils/flow_utils.py
Flow.add_packet
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'][1] self.meta['src_domain'] = packet['packet']['src_domain'] self.meta['dst_domain'] = packet['packet']['dst_domain'] self.meta['sport'] = self.meta['flow_id'][2] self.meta['dport'] = self.meta['flow_id'][3] self.meta['protocol'] = self.meta['flow_id'][4] self.meta['direction'] = self._cts_or_stc(packet) self.meta['start'] = packet['timestamp'] self.meta['end'] = packet['timestamp'] # Add the packet self.meta['packet_list'].append(packet) if packet['timestamp'] < self.meta['start']: self.meta['start'] = packet['timestamp'] if packet['timestamp'] > self.meta['end']: self.meta['end'] = packet['timestamp'] # State of connection/flow if self.meta['protocol'] == 'TCP': flags = packet['transport']['flags'] if 'syn' in flags: self.meta['state'] = 'partial_syn' self.meta['direction'] = 'CTS' elif 'fin' in flags: # print('--- FIN RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'complete' if self.meta['state'] == 'partial_syn' else 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) elif 'syn_ack' in flags: self.meta['state'] = 'partial_syn' self.meta['direction'] = 'STC' elif 'fin_ack'in flags: # print('--- FIN_ACK RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'complete' if self.meta['state'] == 'partial_syn' else 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) elif 'rst' in flags: # print('--- RESET RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) # Only collect UDP and TCP if self.meta['protocol'] not in ['UDP', 'TCP']: self.meta['timeout'] = datetime.now()
python
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'][1] self.meta['src_domain'] = packet['packet']['src_domain'] self.meta['dst_domain'] = packet['packet']['dst_domain'] self.meta['sport'] = self.meta['flow_id'][2] self.meta['dport'] = self.meta['flow_id'][3] self.meta['protocol'] = self.meta['flow_id'][4] self.meta['direction'] = self._cts_or_stc(packet) self.meta['start'] = packet['timestamp'] self.meta['end'] = packet['timestamp'] # Add the packet self.meta['packet_list'].append(packet) if packet['timestamp'] < self.meta['start']: self.meta['start'] = packet['timestamp'] if packet['timestamp'] > self.meta['end']: self.meta['end'] = packet['timestamp'] # State of connection/flow if self.meta['protocol'] == 'TCP': flags = packet['transport']['flags'] if 'syn' in flags: self.meta['state'] = 'partial_syn' self.meta['direction'] = 'CTS' elif 'fin' in flags: # print('--- FIN RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'complete' if self.meta['state'] == 'partial_syn' else 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) elif 'syn_ack' in flags: self.meta['state'] = 'partial_syn' self.meta['direction'] = 'STC' elif 'fin_ack'in flags: # print('--- FIN_ACK RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'complete' if self.meta['state'] == 'partial_syn' else 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) elif 'rst' in flags: # print('--- RESET RECEIVED %s ---' % str(self.meta['flow_id)) self.meta['state'] = 'partial' self.meta['timeout'] = datetime.now() + timedelta(seconds=1) # Only collect UDP and TCP if self.meta['protocol'] not in ['UDP', 'TCP']: self.meta['timeout'] = datetime.now()
[ "def", "add_packet", "(", "self", ",", "packet", ")", ":", "# First packet?", "if", "not", "self", ".", "meta", "[", "'flow_id'", "]", ":", "self", ".", "meta", "[", "'flow_id'", "]", "=", "flow_tuple", "(", "packet", ")", "self", ".", "meta", "[", "...
Add a packet to this flow
[ "Add", "a", "packet", "to", "this", "flow" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L48-L96
SuperCowPowers/chains
chains/utils/flow_utils.py
Flow.get_flow
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']: self.meta['payload'] += packet['transport']['data'] return self.meta
python
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']: self.meta['payload'] += packet['transport']['data'] return self.meta
[ "def", "get_flow", "(", "self", ")", ":", "if", "self", ".", "meta", "[", "'protocol'", "]", "==", "'TCP'", ":", "self", ".", "meta", "[", "'packet_list'", "]", ".", "sort", "(", "key", "=", "lambda", "packet", ":", "packet", "[", "'transport'", "]",...
Reassemble the flow and return all the info/data
[ "Reassemble", "the", "flow", "and", "return", "all", "the", "info", "/", "data" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L98-L105
SuperCowPowers/chains
chains/utils/flow_utils.py
Flow._cts_or_stc
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'] == 'TCP': flags = data['transport']['flags'] # Syn/Ack or fin/ack is a server response if 'syn_ack' in flags or 'fin_ack' in flags: return 'STC' # Syn or fin is a client response if 'syn' in flags or 'fin' in flags: return 'CTS' # Source Port/Destination Port if 'sport' in data['transport']: sport = data['transport']['sport'] dport = data['transport']['dport'] # High port talking to low port if dport < 1024 and sport > dport: return 'CTS' # Low port talking to high port if sport < 1024 and sport < dport: return 'STC' # Wow... guessing return 'STC' if sport < dport else 'CTS' # Internal/External if 'src' in data['packet'] and 'dst' in data['packet']: src = net_utils.inet_to_str(data['packet']['src']) dst = net_utils.inet_to_str(data['packet']['dst']) # Internal talking to external? if net_utils.is_internal(src) and not net_utils.is_internal(dst): return 'CTS' # External talking to internal? if net_utils.is_internal(dst) and not net_utils.is_internal(src): return 'STC' # Okay we have no idea return 'CTS'
python
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'] == 'TCP': flags = data['transport']['flags'] # Syn/Ack or fin/ack is a server response if 'syn_ack' in flags or 'fin_ack' in flags: return 'STC' # Syn or fin is a client response if 'syn' in flags or 'fin' in flags: return 'CTS' # Source Port/Destination Port if 'sport' in data['transport']: sport = data['transport']['sport'] dport = data['transport']['dport'] # High port talking to low port if dport < 1024 and sport > dport: return 'CTS' # Low port talking to high port if sport < 1024 and sport < dport: return 'STC' # Wow... guessing return 'STC' if sport < dport else 'CTS' # Internal/External if 'src' in data['packet'] and 'dst' in data['packet']: src = net_utils.inet_to_str(data['packet']['src']) dst = net_utils.inet_to_str(data['packet']['dst']) # Internal talking to external? if net_utils.is_internal(src) and not net_utils.is_internal(dst): return 'CTS' # External talking to internal? if net_utils.is_internal(dst) and not net_utils.is_internal(src): return 'STC' # Okay we have no idea return 'CTS'
[ "def", "_cts_or_stc", "(", "data", ")", ":", "# UDP/TCP", "if", "data", "[", "'transport'", "]", ":", "# TCP flags", "if", "data", "[", "'transport'", "]", "[", "'type'", "]", "==", "'TCP'", ":", "flags", "=", "data", "[", "'transport'", "]", "[", "'fl...
Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?
[ "Does", "the", "data", "look", "like", "a", "Client", "to", "Server", "(", "cts", ")", "or", "Server", "to", "Client", "(", "stc", ")", "traffic?" ]
train
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L112-L160
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens._generate_tokens
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 enumerate(tokenize.generate_tokens(io.StringIO(text).readline)): tok_type, tok_str, start, end, line = tok yield Token(tok_type, tok_str, start, end, line, index, self._line_numbers.line_to_offset(start[0], start[1]), self._line_numbers.line_to_offset(end[0], end[1]))
python
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 enumerate(tokenize.generate_tokens(io.StringIO(text).readline)): tok_type, tok_str, start, end, line = tok yield Token(tok_type, tok_str, start, end, line, index, self._line_numbers.line_to_offset(start[0], start[1]), self._line_numbers.line_to_offset(end[0], end[1]))
[ "def", "_generate_tokens", "(", "self", ",", "text", ")", ":", "# 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", "enumerate", "(", "tokeni...
Generates tokens for the given code.
[ "Generates", "tokens", "for", "the", "given", "code", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L79-L89
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_token_from_offset
def get_token_from_offset(self, offset): """ Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. """ return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
python
def get_token_from_offset(self, offset): """ Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. """ return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
[ "def", "get_token_from_offset", "(", "self", ",", "offset", ")", ":", "return", "self", ".", "_tokens", "[", "bisect", ".", "bisect", "(", "self", ".", "_token_offsets", ",", "offset", ")", "-", "1", "]" ]
Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens.
[ "Returns", "the", "token", "containing", "the", "given", "character", "offset", "(", "0", "-", "based", "position", "in", "source", "text", ")", "or", "the", "preceeding", "token", "if", "the", "position", "is", "between", "tokens", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L111-L116
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_token
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. """ # TODO: add test for multibyte unicode. We need to translate offsets from ast module (which # are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets # but isn't explicit. return self.get_token_from_offset(self._line_numbers.line_to_offset(lineno, col_offset))
python
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. """ # TODO: add test for multibyte unicode. We need to translate offsets from ast module (which # are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets # but isn't explicit. return self.get_token_from_offset(self._line_numbers.line_to_offset(lineno, col_offset))
[ "def", "get_token", "(", "self", ",", "lineno", ",", "col_offset", ")", ":", "# TODO: add test for multibyte unicode. We need to translate offsets from ast module (which", "# are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets", "# but isn't explicit."...
Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens.
[ "Returns", "the", "token", "containing", "the", "given", "(", "lineno", "col_offset", ")", "position", "or", "the", "preceeding", "token", "if", "the", "position", "is", "between", "tokens", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L118-L126
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_token_from_utf8
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(lineno, col_offset))
python
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(lineno, col_offset))
[ "def", "get_token_from_utf8", "(", "self", ",", "lineno", ",", "col_offset", ")", ":", "return", "self", ".", "get_token", "(", "lineno", ",", "self", ".", "_line_numbers", ".", "from_utf8_col", "(", "lineno", ",", "col_offset", ")", ")" ]
Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses.
[ "Same", "as", "get_token", "()", "but", "interprets", "col_offset", "as", "a", "UTF8", "offset", "which", "is", "what", "ast", "uses", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L128-L132
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.next_token
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 the tokenize module, such as NL and COMMENT. """ i = tok.index + 1 if not include_extra: while is_non_coding_token(self._tokens[i].type): i += 1 return self._tokens[i]
python
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 the tokenize module, such as NL and COMMENT. """ i = tok.index + 1 if not include_extra: while is_non_coding_token(self._tokens[i].type): i += 1 return self._tokens[i]
[ "def", "next_token", "(", "self", ",", "tok", ",", "include_extra", "=", "False", ")", ":", "i", "=", "tok", ".", "index", "+", "1", "if", "not", "include_extra", ":", "while", "is_non_coding_token", "(", "self", ".", "_tokens", "[", "i", "]", ".", "...
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.
[ "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", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L134-L143
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.find_token
def find_token(self, start_token, tok_type, tok_str=None, reverse=False): """ 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)`. """ t = start_token advance = self.prev_token if reverse else self.next_token while not match_token(t, tok_type, tok_str) and not token.ISEOF(t.type): t = advance(t, include_extra=True) return t
python
def find_token(self, start_token, tok_type, tok_str=None, reverse=False): """ 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)`. """ t = start_token advance = self.prev_token if reverse else self.next_token while not match_token(t, tok_type, tok_str) and not token.ISEOF(t.type): t = advance(t, include_extra=True) return t
[ "def", "find_token", "(", "self", ",", "start_token", ",", "tok_type", ",", "tok_str", "=", "None", ",", "reverse", "=", "False", ")", ":", "t", "=", "start_token", "advance", "=", "self", ".", "prev_token", "if", "reverse", "else", "self", ".", "next_to...
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)`.
[ "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", ...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L156-L166
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.token_range
def token_range(self, first_token, last_token, include_extra=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. """ for i in xrange(first_token.index, last_token.index + 1): if include_extra or not is_non_coding_token(self._tokens[i].type): yield self._tokens[i]
python
def token_range(self, first_token, last_token, include_extra=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. """ for i in xrange(first_token.index, last_token.index + 1): if include_extra or not is_non_coding_token(self._tokens[i].type): yield self._tokens[i]
[ "def", "token_range", "(", "self", ",", "first_token", ",", "last_token", ",", "include_extra", "=", "False", ")", ":", "for", "i", "in", "xrange", "(", "first_token", ".", "index", ",", "last_token", ".", "index", "+", "1", ")", ":", "if", "include_extr...
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.
[ "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", "....
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L168-L175
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_tokens
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 and .COMMENT. """ return self.token_range(node.first_token, node.last_token, include_extra=include_extra)
python
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 and .COMMENT. """ return self.token_range(node.first_token, node.last_token, include_extra=include_extra)
[ "def", "get_tokens", "(", "self", ",", "node", ",", "include_extra", "=", "False", ")", ":", "return", "self", ".", "token_range", "(", "node", ".", "first_token", ",", "node", ".", "last_token", ",", "include_extra", "=", "include_extra", ")" ]
Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT.
[ "Yields", "all", "tokens", "making", "up", "the", "given", "node", ".", "If", "include_extra", "is", "True", "includes", "non", "-", "coding", "tokens", "such", "as", "tokenize", ".", "NL", "and", ".", "COMMENT", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L177-L182
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_text_range
def get_text_range(self, node): """ 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. """ if not hasattr(node, 'first_token'): return (0, 0) start = node.first_token.startpos if any(match_token(t, token.NEWLINE) for t in self.get_tokens(node)): # Multi-line nodes would be invalid unless we keep the indentation of the first node. start = self._text.rfind('\n', 0, start) + 1 return (start, node.last_token.endpos)
python
def get_text_range(self, node): """ 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. """ if not hasattr(node, 'first_token'): return (0, 0) start = node.first_token.startpos if any(match_token(t, token.NEWLINE) for t in self.get_tokens(node)): # Multi-line nodes would be invalid unless we keep the indentation of the first node. start = self._text.rfind('\n', 0, start) + 1 return (start, node.last_token.endpos)
[ "def", "get_text_range", "(", "self", ",", "node", ")", ":", "if", "not", "hasattr", "(", "node", ",", "'first_token'", ")", ":", "return", "(", "0", ",", "0", ")", "start", "=", "node", ".", "first_token", ".", "startpos", "if", "any", "(", "match_t...
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.
[ "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", ...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L184-L198
gristlabs/asttokens
asttokens/asttokens.py
ASTTokens.get_text
def get_text(self, node): """ 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. """ start, end = self.get_text_range(node) return self._text[start : end]
python
def get_text(self, node): """ 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. """ start, end = self.get_text_range(node) return self._text[start : end]
[ "def", "get_text", "(", "self", ",", "node", ")", ":", "start", ",", "end", "=", "self", ".", "get_text_range", "(", "node", ")", "return", "self", ".", "_text", "[", "start", ":", "end", "]" ]
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.
[ "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", "...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L200-L206
gristlabs/asttokens
asttokens/line_numbers.py
LineNumbers.from_utf8_col
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_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len line_text = self._text[self._line_offsets[line - 1] : end_offset] offsets = [i for i,c in enumerate(line_text) for byte in c.encode('utf8')] offsets.append(len(line_text)) self._utf8_offset_cache[line] = offsets return offsets[max(0, min(len(offsets)-1, utf8_column))]
python
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_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len line_text = self._text[self._line_offsets[line - 1] : end_offset] offsets = [i for i,c in enumerate(line_text) for byte in c.encode('utf8')] offsets.append(len(line_text)) self._utf8_offset_cache[line] = offsets return offsets[max(0, min(len(offsets)-1, utf8_column))]
[ "def", "from_utf8_col", "(", "self", ",", "line", ",", "utf8_column", ")", ":", "offsets", "=", "self", ".", "_utf8_offset_cache", ".", "get", "(", "line", ")", "if", "offsets", "is", "None", ":", "end_offset", "=", "self", ".", "_line_offsets", "[", "li...
Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column.
[ "Given", "a", "1", "-", "based", "line", "number", "and", "0", "-", "based", "utf8", "column", "returns", "a", "0", "-", "based", "unicode", "column", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L35-L48
gristlabs/asttokens
asttokens/line_numbers.py
LineNumbers.line_to_offset
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 elif line < 0: return 0 else: return min(self._line_offsets[line] + max(0, column), self._text_len)
python
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 elif line < 0: return 0 else: return min(self._line_offsets[line] + max(0, column), self._text_len)
[ "def", "line_to_offset", "(", "self", ",", "line", ",", "column", ")", ":", "line", "-=", "1", "if", "line", ">=", "len", "(", "self", ".", "_line_offsets", ")", ":", "return", "self", ".", "_text_len", "elif", "line", "<", "0", ":", "return", "0", ...
Converts 1-based line number and 0-based column to 0-based character offset into text.
[ "Converts", "1", "-", "based", "line", "number", "and", "0", "-", "based", "column", "to", "0", "-", "based", "character", "offset", "into", "text", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L50-L60
gristlabs/asttokens
asttokens/line_numbers.py
LineNumbers.offset_to_line
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_index = bisect.bisect_right(self._line_offsets, offset) - 1 return (line_index + 1, offset - self._line_offsets[line_index])
python
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_index = bisect.bisect_right(self._line_offsets, offset) - 1 return (line_index + 1, offset - self._line_offsets[line_index])
[ "def", "offset_to_line", "(", "self", ",", "offset", ")", ":", "offset", "=", "max", "(", "0", ",", "min", "(", "self", ".", "_text_len", ",", "offset", ")", ")", "line_index", "=", "bisect", ".", "bisect_right", "(", "self", ".", "_line_offsets", ",",...
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column numbers.
[ "Converts", "0", "-", "based", "character", "offset", "to", "pair", "(", "line", "col", ")", "of", "1", "-", "based", "line", "and", "0", "-", "based", "column", "numbers", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L62-L69
gristlabs/asttokens
asttokens/mark_tokens.py
MarkTokens._iter_non_child_tokens
def _iter_non_child_tokens(self, first_token, last_token, node): """ 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 `(`. """ tok = first_token for n in self._iter_children(node): for t in self._code.token_range(tok, self._code.prev_token(n.first_token)): yield t if n.last_token.index >= last_token.index: return tok = self._code.next_token(n.last_token) for t in self._code.token_range(tok, last_token): yield t
python
def _iter_non_child_tokens(self, first_token, last_token, node): """ 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 `(`. """ tok = first_token for n in self._iter_children(node): for t in self._code.token_range(tok, self._code.prev_token(n.first_token)): yield t if n.last_token.index >= last_token.index: return tok = self._code.next_token(n.last_token) for t in self._code.token_range(tok, last_token): yield t
[ "def", "_iter_non_child_tokens", "(", "self", ",", "first_token", ",", "last_token", ",", "node", ")", ":", "tok", "=", "first_token", "for", "n", "in", "self", ".", "_iter_children", "(", "node", ")", ":", "for", "t", "in", "self", ".", "_code", ".", ...
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 `(`.
[ "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", ...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/mark_tokens.py#L106-L120
gristlabs/asttokens
asttokens/mark_tokens.py
MarkTokens._expand_to_matching_pairs
def _expand_to_matching_pairs(self, first_token, last_token, node): """ 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. """ # We look for opening parens/braces among non-child tokens (i.e. tokens between our actual # child nodes). If we find any closing ones, we match them to the opens. to_match_right = [] to_match_left = [] for tok in self._iter_non_child_tokens(first_token, last_token, node): tok_info = tok[:2] if to_match_right and tok_info == to_match_right[-1]: to_match_right.pop() elif tok_info in _matching_pairs_left: to_match_right.append(_matching_pairs_left[tok_info]) elif tok_info in _matching_pairs_right: to_match_left.append(_matching_pairs_right[tok_info]) # Once done, extend `last_token` to match any unclosed parens/braces. for match in reversed(to_match_right): last = self._code.next_token(last_token) # Allow for a trailing comma before the closing delimiter. if util.match_token(last, token.OP, ','): last = self._code.next_token(last) # Now check for the actual closing delimiter. if util.match_token(last, *match): last_token = last # And extend `first_token` to match any unclosed opening parens/braces. for match in to_match_left: first = self._code.prev_token(first_token) if util.match_token(first, *match): first_token = first return (first_token, last_token)
python
def _expand_to_matching_pairs(self, first_token, last_token, node): """ 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. """ # We look for opening parens/braces among non-child tokens (i.e. tokens between our actual # child nodes). If we find any closing ones, we match them to the opens. to_match_right = [] to_match_left = [] for tok in self._iter_non_child_tokens(first_token, last_token, node): tok_info = tok[:2] if to_match_right and tok_info == to_match_right[-1]: to_match_right.pop() elif tok_info in _matching_pairs_left: to_match_right.append(_matching_pairs_left[tok_info]) elif tok_info in _matching_pairs_right: to_match_left.append(_matching_pairs_right[tok_info]) # Once done, extend `last_token` to match any unclosed parens/braces. for match in reversed(to_match_right): last = self._code.next_token(last_token) # Allow for a trailing comma before the closing delimiter. if util.match_token(last, token.OP, ','): last = self._code.next_token(last) # Now check for the actual closing delimiter. if util.match_token(last, *match): last_token = last # And extend `first_token` to match any unclosed opening parens/braces. for match in to_match_left: first = self._code.prev_token(first_token) if util.match_token(first, *match): first_token = first return (first_token, last_token)
[ "def", "_expand_to_matching_pairs", "(", "self", ",", "first_token", ",", "last_token", ",", "node", ")", ":", "# We look for opening parens/braces among non-child tokens (i.e. tokens between our actual", "# child nodes). If we find any closing ones, we match them to the opens.", "to_mat...
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.
[ "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", "." ...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/mark_tokens.py#L122-L156
gristlabs/asttokens
asttokens/util.py
match_token
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)
python
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)
[ "def", "match_token", "(", "token", ",", "tok_type", ",", "tok_str", "=", "None", ")", ":", "return", "token", ".", "type", "==", "tok_type", "and", "(", "tok_str", "is", "None", "or", "token", ".", "string", "==", "tok_str", ")" ]
Returns true if token is of the given type and, if a string is given, has that string.
[ "Returns", "true", "if", "token", "is", "of", "the", "given", "type", "and", "if", "a", "string", "is", "given", "has", "that", "string", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L45-L47
gristlabs/asttokens
asttokens/util.py
expect_token
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 string is verified too. If the token doesn't match, raises an informative ValueError. """ if not match_token(token, tok_type, tok_str): raise ValueError("Expected token %s, got %s on line %s col %s" % ( token_repr(tok_type, tok_str), str(token), token.start[0], token.start[1] + 1))
python
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 string is verified too. If the token doesn't match, raises an informative ValueError. """ if not match_token(token, tok_type, tok_str): raise ValueError("Expected token %s, got %s on line %s col %s" % ( token_repr(tok_type, tok_str), str(token), token.start[0], token.start[1] + 1))
[ "def", "expect_token", "(", "token", ",", "tok_type", ",", "tok_str", "=", "None", ")", ":", "if", "not", "match_token", "(", "token", ",", "tok_type", ",", "tok_str", ")", ":", "raise", "ValueError", "(", "\"Expected token %s, got %s on line %s col %s\"", "%", ...
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.
[ "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", "...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L50-L58
gristlabs/asttokens
asttokens/util.py
visit_tree
def visit_tree(node, previsit, postvisit): """ 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)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. Either ``previsit`` and ``postvisit`` may be None. """ if not previsit: previsit = lambda node, pvalue: (None, None) if not postvisit: postvisit = lambda node, pvalue, value: None iter_children = iter_children_func(node) done = set() ret = None stack = [(node, None, _PREVISIT)] while stack: current, par_value, value = stack.pop() if value is _PREVISIT: assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) pvalue, post_value = previsit(current, par_value) stack.append((current, par_value, post_value)) # Insert all children in reverse order (so that first child ends up on top of the stack). ins = len(stack) for n in iter_children(current): stack.insert(ins, (n, pvalue, _PREVISIT)) else: ret = postvisit(current, par_value, value) return ret
python
def visit_tree(node, previsit, postvisit): """ 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)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. Either ``previsit`` and ``postvisit`` may be None. """ if not previsit: previsit = lambda node, pvalue: (None, None) if not postvisit: postvisit = lambda node, pvalue, value: None iter_children = iter_children_func(node) done = set() ret = None stack = [(node, None, _PREVISIT)] while stack: current, par_value, value = stack.pop() if value is _PREVISIT: assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) pvalue, post_value = previsit(current, par_value) stack.append((current, par_value, post_value)) # Insert all children in reverse order (so that first child ends up on top of the stack). ins = len(stack) for n in iter_children(current): stack.insert(ins, (n, pvalue, _PREVISIT)) else: ret = postvisit(current, par_value, value) return ret
[ "def", "visit_tree", "(", "node", ",", "previsit", ",", "postvisit", ")", ":", "if", "not", "previsit", ":", "previsit", "=", "lambda", "node", ",", "pvalue", ":", "(", "None", ",", "None", ")", "if", "not", "postvisit", ":", "postvisit", "=", "lambda"...
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)`` ``par_value`` is as returned from ``previsit()`` of the parent. * ``postvisit(node, par_value, value)`` - should return ``value`` ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as returned from ``previsit()`` of this node itself. The return ``value`` is ignored except the one for the root node, which is returned from the overall ``visit_tree()`` call. For the initial node, ``par_value`` is None. Either ``previsit`` and ``postvisit`` may be None.
[ "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", "ex...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L144-L185
gristlabs/asttokens
asttokens/util.py
walk
def walk(node): """ 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_children()``, it skips singleton nodes generated by ``ast``. """ iter_children = iter_children_func(node) done = set() stack = [node] while stack: current = stack.pop() assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) yield current # Insert all children in reverse order (so that first child ends up on top of the stack). # This is faster than building a list and reversing it. ins = len(stack) for c in iter_children(current): stack.insert(ins, c)
python
def walk(node): """ 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_children()``, it skips singleton nodes generated by ``ast``. """ iter_children = iter_children_func(node) done = set() stack = [node] while stack: current = stack.pop() assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) yield current # Insert all children in reverse order (so that first child ends up on top of the stack). # This is faster than building a list and reversing it. ins = len(stack) for c in iter_children(current): stack.insert(ins, c)
[ "def", "walk", "(", "node", ")", ":", "iter_children", "=", "iter_children_func", "(", "node", ")", "done", "=", "set", "(", ")", "stack", "=", "[", "node", "]", "while", "stack", ":", "current", "=", "stack", ".", "pop", "(", ")", "assert", "current...
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_children()``, it skips singleton nodes generated by ``ast``.
[ "Recursively", "yield", "all", "descendant", "nodes", "in", "the", "tree", "starting", "at", "node", "(", "including", "node", "itself", ")", "using", "depth", "-", "first", "pre", "-", "order", "traversal", "(", "yieling", "parents", "before", "their", "chi...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L189-L211
gristlabs/asttokens
asttokens/util.py
replace
def replace(text, replacements): """ 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")])`` produces ``"X is THE test"``. """ p = 0 parts = [] for (start, end, new_text) in sorted(replacements): parts.append(text[p:start]) parts.append(new_text) p = end parts.append(text[p:]) return ''.join(parts)
python
def replace(text, replacements): """ 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")])`` produces ``"X is THE test"``. """ p = 0 parts = [] for (start, end, new_text) in sorted(replacements): parts.append(text[p:start]) parts.append(new_text) p = end parts.append(text[p:]) return ''.join(parts)
[ "def", "replace", "(", "text", ",", "replacements", ")", ":", "p", "=", "0", "parts", "=", "[", "]", "for", "(", "start", ",", "end", ",", "new_text", ")", "in", "sorted", "(", "replacements", ")", ":", "parts", ".", "append", "(", "text", "[", "...
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")])`` produces ``"X is THE test"``.
[ "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_rang...
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L214-L230
gristlabs/asttokens
asttokens/util.py
NodeMethods.get
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-specific method is not found. """ method = self._cache.get(cls) if not method: name = "visit_" + cls.__name__.lower() method = getattr(obj, name, obj.visit_default) self._cache[cls] = method return method
python
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-specific method is not found. """ method = self._cache.get(cls) if not method: name = "visit_" + cls.__name__.lower() method = getattr(obj, name, obj.visit_default) self._cache[cls] = method return method
[ "def", "get", "(", "self", ",", "obj", ",", "cls", ")", ":", "method", "=", "self", ".", "_cache", ".", "get", "(", "cls", ")", "if", "not", "method", ":", "name", "=", "\"visit_\"", "+", "cls", ".", "__name__", ".", "lower", "(", ")", "method", ...
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.
[ "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", "." ]
train
https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L240-L250
robin900/gspread-dataframe
gspread_dataframe.py
_cellrepr
def _cellrepr(value, allow_formulas): """ 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. """ if pd.isnull(value) is True: return "" if isinstance(value, float): value = repr(value) else: value = str(value) if (not allow_formulas) and value.startswith('='): value = "'%s" % value return value
python
def _cellrepr(value, allow_formulas): """ 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. """ if pd.isnull(value) is True: return "" if isinstance(value, float): value = repr(value) else: value = str(value) if (not allow_formulas) and value.startswith('='): value = "'%s" % value return value
[ "def", "_cellrepr", "(", "value", ",", "allow_formulas", ")", ":", "if", "pd", ".", "isnull", "(", "value", ")", "is", "True", ":", "return", "\"\"", "if", "isinstance", "(", "value", ",", "float", ")", ":", "value", "=", "repr", "(", "value", ")", ...
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.
[ "Get", "a", "string", "representation", "of", "dataframe", "value", "." ]
train
https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L40-L57
robin900/gspread-dataframe
gspread_dataframe.py
_resize_to_minimum
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 optional. """ # get the current size current_cols, current_rows = ( worksheet.col_count, worksheet.row_count ) if rows is not None and rows <= current_rows: rows = None if cols is not None and cols <= current_cols: cols = None if cols is not None or rows is not None: worksheet.resize(rows, cols)
python
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 optional. """ # get the current size current_cols, current_rows = ( worksheet.col_count, worksheet.row_count ) if rows is not None and rows <= current_rows: rows = None if cols is not None and cols <= current_cols: cols = None if cols is not None or rows is not None: worksheet.resize(rows, cols)
[ "def", "_resize_to_minimum", "(", "worksheet", ",", "rows", "=", "None", ",", "cols", "=", "None", ")", ":", "# get the current size", "current_cols", ",", "current_rows", "=", "(", "worksheet", ".", "col_count", ",", "worksheet", ".", "row_count", ")", "if", ...
Resize the worksheet to guarantee a minimum size, either in rows, or columns, or both. Both rows and cols are optional.
[ "Resize", "the", "worksheet", "to", "guarantee", "a", "minimum", "size", "either", "in", "rows", "or", "columns", "or", "both", "." ]
train
https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L59-L77
robin900/gspread-dataframe
gspread_dataframe.py
get_as_dataframe
def get_as_dataframe(worksheet, evaluate_formulas=False, **options): """ 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.parsers.TextParser, according to the version of pandas that is installed. (Note: TextParser supports only the default 'python' parser engine, not the C engine.) :returns: pandas.DataFrame """ all_values = _get_all_values(worksheet, evaluate_formulas) return TextParser(all_values, **options).read()
python
def get_as_dataframe(worksheet, evaluate_formulas=False, **options): """ 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.parsers.TextParser, according to the version of pandas that is installed. (Note: TextParser supports only the default 'python' parser engine, not the C engine.) :returns: pandas.DataFrame """ all_values = _get_all_values(worksheet, evaluate_formulas) return TextParser(all_values, **options).read()
[ "def", "get_as_dataframe", "(", "worksheet", ",", "evaluate_formulas", "=", "False", ",", "*", "*", "options", ")", ":", "all_values", "=", "_get_all_values", "(", "worksheet", ",", "evaluate_formulas", ")", "return", "TextParser", "(", "all_values", ",", "*", ...
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.parsers.TextParser, according to the version of pandas that is installed. (Note: TextParser supports only the default 'python' parser engine, not the C engine.) :returns: pandas.DataFrame
[ "Returns", "the", "worksheet", "contents", "as", "a", "DataFrame", "." ]
train
https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L118-L135
robin900/gspread-dataframe
gspread_dataframe.py
set_with_dataframe
def set_with_dataframe(worksheet, dataframe, row=1, col=1, include_index=False, include_column_header=True, resize=False, allow_formulas=True): """ 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 additional column. Defaults to False. :param include_column_header: if True, add a header row before data with column names. (If include_index is True, the index's name will be used as its column's header.) Defaults to True. :param resize: if True, changes the worksheet's size to match the shape of the provided DataFrame. If False, worksheet will only be resized as necessary to contain the DataFrame contents. Defaults to False. :param allow_formulas: if True, interprets `=foo` as a formula in cell values; otherwise all text beginning with `=` is escaped to avoid its interpretation as a formula. Defaults to True. """ # x_pos, y_pos refers to the position of data rows only, # excluding any header rows in the google sheet. # If header-related params are True, the values are adjusted # to allow space for the headers. y, x = dataframe.shape if include_index: x += 1 if include_column_header: y += 1 if resize: worksheet.resize(y, x) else: _resize_to_minimum(worksheet, y, x) updates = [] if include_column_header: elts = list(dataframe.columns) if include_index: elts = [ dataframe.index.name ] + elts for idx, val in enumerate(elts): updates.append( (row, col+idx, _cellrepr(val, allow_formulas)) ) row += 1 values = [] for value_row, index_value in zip_longest(dataframe.values, dataframe.index): if include_index: value_row = [index_value] + list(value_row) values.append(value_row) for y_idx, value_row in enumerate(values): for x_idx, cell_value in enumerate(value_row): updates.append( (y_idx+row, x_idx+col, _cellrepr(cell_value, allow_formulas)) ) if not updates: logger.debug("No updates to perform on worksheet.") return cells_to_update = [ Cell(row, col, value) for row, col, value in updates ] logger.debug("%d cell updates to send", len(cells_to_update)) resp = worksheet.update_cells(cells_to_update, value_input_option='USER_ENTERED') logger.debug("Cell update response: %s", resp)
python
def set_with_dataframe(worksheet, dataframe, row=1, col=1, include_index=False, include_column_header=True, resize=False, allow_formulas=True): """ 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 additional column. Defaults to False. :param include_column_header: if True, add a header row before data with column names. (If include_index is True, the index's name will be used as its column's header.) Defaults to True. :param resize: if True, changes the worksheet's size to match the shape of the provided DataFrame. If False, worksheet will only be resized as necessary to contain the DataFrame contents. Defaults to False. :param allow_formulas: if True, interprets `=foo` as a formula in cell values; otherwise all text beginning with `=` is escaped to avoid its interpretation as a formula. Defaults to True. """ # x_pos, y_pos refers to the position of data rows only, # excluding any header rows in the google sheet. # If header-related params are True, the values are adjusted # to allow space for the headers. y, x = dataframe.shape if include_index: x += 1 if include_column_header: y += 1 if resize: worksheet.resize(y, x) else: _resize_to_minimum(worksheet, y, x) updates = [] if include_column_header: elts = list(dataframe.columns) if include_index: elts = [ dataframe.index.name ] + elts for idx, val in enumerate(elts): updates.append( (row, col+idx, _cellrepr(val, allow_formulas)) ) row += 1 values = [] for value_row, index_value in zip_longest(dataframe.values, dataframe.index): if include_index: value_row = [index_value] + list(value_row) values.append(value_row) for y_idx, value_row in enumerate(values): for x_idx, cell_value in enumerate(value_row): updates.append( (y_idx+row, x_idx+col, _cellrepr(cell_value, allow_formulas)) ) if not updates: logger.debug("No updates to perform on worksheet.") return cells_to_update = [ Cell(row, col, value) for row, col, value in updates ] logger.debug("%d cell updates to send", len(cells_to_update)) resp = worksheet.update_cells(cells_to_update, value_input_option='USER_ENTERED') logger.debug("Cell update response: %s", resp)
[ "def", "set_with_dataframe", "(", "worksheet", ",", "dataframe", ",", "row", "=", "1", ",", "col", "=", "1", ",", "include_index", "=", "False", ",", "include_column_header", "=", "True", ",", "resize", "=", "False", ",", "allow_formulas", "=", "True", ")"...
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 additional column. Defaults to False. :param include_column_header: if True, add a header row before data with column names. (If include_index is True, the index's name will be used as its column's header.) Defaults to True. :param resize: if True, changes the worksheet's size to match the shape of the provided DataFrame. If False, worksheet will only be resized as necessary to contain the DataFrame contents. Defaults to False. :param allow_formulas: if True, interprets `=foo` as a formula in cell values; otherwise all text beginning with `=` is escaped to avoid its interpretation as a formula. Defaults to True.
[ "Sets", "the", "values", "of", "a", "given", "DataFrame", "anchoring", "its", "upper", "-", "left", "corner", "at", "(", "row", "col", ")", ".", "(", "Default", "is", "row", "1", "column", "1", ".", ")" ]
train
https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L137-L213
openregister/openregister-python
openregister/entry.py
Entry.timestamp
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 = datetime.strptime(timestamp, fmt)
python
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 = datetime.strptime(timestamp, fmt)
[ "def", "timestamp", "(", "self", ",", "timestamp", ")", ":", "if", "timestamp", "is", "None", ":", "self", ".", "_timestamp", "=", "datetime", ".", "utcnow", "(", ")", "elif", "isinstance", "(", "timestamp", ",", "datetime", ")", ":", "self", ".", "_ti...
Entry timestamp as datetime.
[ "Entry", "timestamp", "as", "datetime", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L27-L34
openregister/openregister-python
openregister/entry.py
Entry.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 primitive['timestamp'] = self.timestamp.strftime(fmt) return primitive
python
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 primitive['timestamp'] = self.timestamp.strftime(fmt) return primitive
[ "def", "primitive", "(", "self", ")", ":", "primitive", "=", "{", "}", "if", "self", ".", "entry_number", "is", "not", "None", ":", "primitive", "[", "'entry-number'", "]", "=", "self", ".", "entry_number", "if", "self", ".", "item_hash", "is", "not", ...
Entry as Python primitive.
[ "Entry", "as", "Python", "primitive", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L37-L47
openregister/openregister-python
openregister/entry.py
Entry.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']
python
def primitive(self, primitive): """Entry from Python primitive.""" self.entry_number = primitive['entry-number'] self.item_hash = primitive['item-hash'] self.timestamp = primitive['timestamp']
[ "def", "primitive", "(", "self", ",", "primitive", ")", ":", "self", ".", "entry_number", "=", "primitive", "[", "'entry-number'", "]", "self", ".", "item_hash", "=", "primitive", "[", "'item-hash'", "]", "self", ".", "timestamp", "=", "primitive", "[", "'...
Entry from Python primitive.
[ "Entry", "from", "Python", "primitive", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L50-L54
openregister/openregister-python
openregister/client.py
Client.config
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] return os.environ[var]
python
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] return os.environ[var]
[ "def", "config", "(", "self", ",", "name", ",", "suffix", ")", ":", "var", "=", "'%s_%s'", "%", "(", "name", ",", "suffix", ")", "var", "=", "var", ".", "upper", "(", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", "if", "var", "in", "self", ...
Return config variable value, defaulting to environment
[ "Return", "config", "variable", "value", "defaulting", "to", "environment" ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L16-L22
openregister/openregister-python
openregister/client.py
Client.index
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']}" % (field.replace('-', '_')) } response = self.get(self.config(index, 'search_url'), params=params) results = [hit['fields'] for hit in response.json()['hits']['hit']] for result in results: for key in result: result[key.replace('_', '-')] = result.pop(key) return results
python
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']}" % (field.replace('-', '_')) } response = self.get(self.config(index, 'search_url'), params=params) results = [hit['fields'] for hit in response.json()['hits']['hit']] for result in results: for key in result: result[key.replace('_', '-')] = result.pop(key) return results
[ "def", "index", "(", "self", ",", "index", ",", "field", ",", "value", ")", ":", "params", "=", "{", "\"q\"", ":", "value", ",", "# search index has '_' instead of '-' in field names ..", "\"q.options\"", ":", "\"{fields:['%s']}\"", "%", "(", "field", ".", "repl...
Search for records matching a value in an index service
[ "Search", "for", "records", "matching", "a", "value", "in", "an", "index", "service" ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L41-L56
openregister/openregister-python
openregister/item.py
Item.primitive
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)): dict[key] = sorted(list(dict[key])) return dict
python
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)): dict[key] = sorted(list(dict[key])) return dict
[ "def", "primitive", "(", "self", ")", ":", "dict", "=", "{", "}", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "'_'", ")", ":", "dict", "[", "key", "]", "=",...
Python primitive representation.
[ "Python", "primitive", "representation", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L49-L60
openregister/openregister-python
openregister/item.py
Item.primitive
def primitive(self, dictionary): """Item from Python primitive.""" self.__dict__ = {k: v for k, v in dictionary.items() if v}
python
def primitive(self, dictionary): """Item from Python primitive.""" self.__dict__ = {k: v for k, v in dictionary.items() if v}
[ "def", "primitive", "(", "self", ",", "dictionary", ")", ":", "self", ".", "__dict__", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "dictionary", ".", "items", "(", ")", "if", "v", "}" ]
Item from Python primitive.
[ "Item", "from", "Python", "primitive", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L63-L65
openregister/openregister-python
openregister/record.py
Record.primitive
def primitive(self): """Record as Python primitive.""" primitive = copy(self.item.primitive) primitive.update(self.entry.primitive) return primitive
python
def primitive(self): """Record as Python primitive.""" primitive = copy(self.item.primitive) primitive.update(self.entry.primitive) return primitive
[ "def", "primitive", "(", "self", ")", ":", "primitive", "=", "copy", "(", "self", ".", "item", ".", "primitive", ")", "primitive", ".", "update", "(", "self", ".", "entry", ".", "primitive", ")", "return", "primitive" ]
Record as Python primitive.
[ "Record", "as", "Python", "primitive", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L19-L23
openregister/openregister-python
openregister/record.py
Record.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() self.item.primitive = primitive
python
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() self.item.primitive = primitive
[ "def", "primitive", "(", "self", ",", "primitive", ")", ":", "self", ".", "entry", "=", "Entry", "(", ")", "self", ".", "entry", ".", "primitive", "=", "primitive", "primitive", "=", "copy", "(", "primitive", ")", "for", "field", "in", "self", ".", "...
Record from Python primitive.
[ "Record", "from", "Python", "primitive", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L26-L36
openregister/openregister-python
openregister/representations/tsv.py
load
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))
python
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))
[ "def", "load", "(", "self", ",", "text", ",", "fieldnames", "=", "None", ")", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "fieldnames", "=", "load_line", "(", "lines", "[", "0", "]", ")", "values", "=", "load_line", "(", "lines", "[...
Item from TSV representation.
[ "Item", "from", "TSV", "representation", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L43-L48
openregister/openregister-python
openregister/representations/tsv.py
reader
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(fieldnames, values)) yield item
python
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(fieldnames, values)) yield item
[ "def", "reader", "(", "stream", ",", "fieldnames", "=", "None", ")", ":", "if", "not", "fieldnames", ":", "fieldnames", "=", "load_line", "(", "stream", ".", "readline", "(", ")", ")", "for", "line", "in", "stream", ":", "values", "=", "load_line", "("...
Read Items from a stream containing TSV.
[ "Read", "Items", "from", "a", "stream", "containing", "TSV", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L51-L59
openregister/openregister-python
openregister/representations/tsv.py
dump
def dump(self): """TSV representation.""" dict = self.primitive if not dict: return '' return dump_line(self.keys) + dump_line(self.values)
python
def dump(self): """TSV representation.""" dict = self.primitive if not dict: return '' return dump_line(self.keys) + dump_line(self.values)
[ "def", "dump", "(", "self", ")", ":", "dict", "=", "self", ".", "primitive", "if", "not", "dict", ":", "return", "''", "return", "dump_line", "(", "self", ".", "keys", ")", "+", "dump_line", "(", "self", ".", "values", ")" ]
TSV representation.
[ "TSV", "representation", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L66-L71
openregister/openregister-python
openregister/representations/csv.py
load
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_NONE reader = csv.DictReader( f, delimiter=delimiter, quotechar=quotechar, quoting=quoting, lineterminator=lineterminator) if reader.fieldnames: reader.fieldnames = [field.strip() for field in reader.fieldnames] try: self.primitive = next(reader) except StopIteration: self.primitive = {}
python
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_NONE reader = csv.DictReader( f, delimiter=delimiter, quotechar=quotechar, quoting=quoting, lineterminator=lineterminator) if reader.fieldnames: reader.fieldnames = [field.strip() for field in reader.fieldnames] try: self.primitive = next(reader) except StopIteration: self.primitive = {}
[ "def", "load", "(", "self", ",", "text", ",", "lineterminator", "=", "'\\r\\n'", ",", "quotechar", "=", "'\"'", ",", "delimiter", "=", "\",\"", ",", "escapechar", "=", "escapechar", ",", "quoting", "=", "csv", ".", "QUOTE_MINIMAL", ")", ":", "f", "=", ...
Item from CSV representation.
[ "Item", "from", "CSV", "representation", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L14-L40
openregister/openregister-python
openregister/representations/csv.py
dump
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
python
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
[ "def", "dump", "(", "self", ",", "*", "*", "kwargs", ")", ":", "f", "=", "io", ".", "StringIO", "(", ")", "w", "=", "Writer", "(", "f", ",", "self", ".", "keys", ",", "*", "*", "kwargs", ")", "w", ".", "write", "(", "self", ")", "text", "="...
CSV representation of a item.
[ "CSV", "representation", "of", "a", "item", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L70-L79
openregister/openregister-python
openregister/datatypes/digest.py
git_hash
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()
python
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()
[ "def", "git_hash", "(", "blob", ")", ":", "head", "=", "str", "(", "\"blob \"", "+", "str", "(", "len", "(", "blob", ")", ")", "+", "\"\\0\"", ")", ".", "encode", "(", "\"utf-8\"", ")", "return", "sha1", "(", "head", "+", "blob", ")", ".", "hexdi...
Return git-hash compatible SHA-1 hexdigits for a blob of data.
[ "Return", "git", "-", "hash", "compatible", "SHA", "-", "1", "hexdigits", "for", "a", "blob", "of", "data", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/datatypes/digest.py#L5-L8
openregister/openregister-python
openregister/representations/json.py
dump
def dump(self): """Item as a JSON representation.""" return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
python
def dump(self): """Item as a JSON representation.""" return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
[ "def", "dump", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "primitive", ",", "sort_keys", "=", "True", ",", "ensure_ascii", "=", "False", ",", "separators", "=", "(", "','", ",", "':'", ")", ")" ]
Item as a JSON representation.
[ "Item", "as", "a", "JSON", "representation", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L17-L23
openregister/openregister-python
openregister/representations/json.py
reader
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) item = Item() item.primitive = obj yield item index = END.match(string, end).end()
python
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) item = Item() item.primitive = obj yield item index = END.match(string, end).end()
[ "def", "reader", "(", "stream", ")", ":", "string", "=", "stream", ".", "read", "(", ")", "decoder", "=", "json", ".", "JSONDecoder", "(", ")", ".", "raw_decode", "index", "=", "START", ".", "match", "(", "string", ",", "0", ")", ".", "end", "(", ...
Read Items from a stream containing a JSON array.
[ "Read", "Items", "from", "a", "stream", "containing", "a", "JSON", "array", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L26-L37
openregister/openregister-python
openregister/representations/jsonl.py
reader
def reader(stream): """Read Items from a stream containing lines of JSON.""" for line in stream: item = Item() item.json = line yield item
python
def reader(stream): """Read Items from a stream containing lines of JSON.""" for line in stream: item = Item() item.json = line yield item
[ "def", "reader", "(", "stream", ")", ":", "for", "line", "in", "stream", ":", "item", "=", "Item", "(", ")", "item", ".", "json", "=", "line", "yield", "item" ]
Read Items from a stream containing lines of JSON.
[ "Read", "Items", "from", "a", "stream", "containing", "lines", "of", "JSON", "." ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/jsonl.py#L8-L13
openregister/openregister-python
openregister/store.py
Store.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['total'] = total meta['page_size'] = page_size meta['pages'] = math.ceil(meta['total']/page_size) meta['page'] = page meta['skip'] = page_size * (page-1) return meta
python
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['total'] = total meta['page_size'] = page_size meta['pages'] = math.ceil(meta['total']/page_size) meta['page'] = page meta['skip'] = page_size * (page-1) return meta
[ "def", "meta", "(", "self", ",", "total", ",", "page", "=", "1", ",", "page_size", "=", "None", ")", ":", "if", "page_size", "is", "None", "or", "page_size", "<", "0", ":", "page_size", "=", "self", ".", "page_size", "meta", "=", "{", "}", "meta", ...
Calculate statistics for a collection return: meta
[ "Calculate", "statistics", "for", "a", "collection", "return", ":", "meta" ]
train
https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/store.py#L12-L26
sdispater/cachy
cachy/tag_set.py
TagSet.tag_id
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._store.get(self.tag_key(name)) or self.reset_tag(name)
python
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._store.get(self.tag_key(name)) or self.reset_tag(name)
[ "def", "tag_id", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_store", ".", "get", "(", "self", ".", "tag_key", "(", "name", ")", ")", "or", "self", ".", "reset_tag", "(", "name", ")" ]
Get the unique tag identifier for a given tag. :param name: The tag :type name: str :rtype: str
[ "Get", "the", "unique", "tag", "identifier", "for", "a", "given", "tag", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L25-L34
sdispater/cachy
cachy/tag_set.py
TagSet.reset_tag
def reset_tag(self, name): """ Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str """ id_ = str(uuid.uuid4()).replace('-', '') self._store.forever(self.tag_key(name), id_) return id_
python
def reset_tag(self, name): """ Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str """ id_ = str(uuid.uuid4()).replace('-', '') self._store.forever(self.tag_key(name), id_) return id_
[ "def", "reset_tag", "(", "self", ",", "name", ")", ":", "id_", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "'-'", ",", "''", ")", "self", ".", "_store", ".", "forever", "(", "self", ".", "tag_key", "(", "name", ")...
Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str
[ "Reset", "the", "tag", "and", "return", "the", "new", "tag", "identifier", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L52-L65
inveniosoftware/invenio-logging
invenio_logging/fs.py
InvenioLoggingFS.init_app
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
python
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
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "init_config", "(", "app", ")", "if", "app", ".", "config", "[", "'LOGGING_FS_LOGFILE'", "]", "is", "None", ":", "return", "self", ".", "install_handler", "(", "app", ")", "app", ".", ...
Flask application initialization.
[ "Flask", "application", "initialization", "." ]
train
https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L30-L36
inveniosoftware/invenio-logging
invenio_logging/fs.py
InvenioLoggingFS.init_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, getattr(config, k)) # Support injecting instance path and/or sys.prefix if app.config['LOGGING_FS_LOGFILE'] is not None: app.config['LOGGING_FS_LOGFILE'] = \ app.config['LOGGING_FS_LOGFILE'].format( instance_path=app.instance_path, sys_prefix=sys.prefix, )
python
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, getattr(config, k)) # Support injecting instance path and/or sys.prefix if app.config['LOGGING_FS_LOGFILE'] is not None: app.config['LOGGING_FS_LOGFILE'] = \ app.config['LOGGING_FS_LOGFILE'].format( instance_path=app.instance_path, sys_prefix=sys.prefix, )
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "setdefault", "(", "'LOGGING_FS_LEVEL'", ",", "'DEBUG'", "if", "app", ".", "debug", "else", "'WARNING'", ")", "for", "k", "in", "dir", "(", "config", ")", ":", "if", ...
Initialize config.
[ "Initialize", "config", "." ]
train
https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L38-L54
inveniosoftware/invenio-logging
invenio_logging/fs.py
InvenioLoggingFS.install_handler
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 {0} does not exists.'.format(basedir)) handler = RotatingFileHandler( app.config['LOGGING_FS_LOGFILE'], backupCount=app.config['LOGGING_FS_BACKUPCOUNT'], maxBytes=app.config['LOGGING_FS_MAXBYTES'], delay=True, ) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) handler.setLevel(app.config['LOGGING_FS_LEVEL']) # Add handler to application logger app.logger.addHandler(handler) if app.config['LOGGING_FS_PYWARNINGS']: self.capture_pywarnings(handler) # Add request_id to log record app.logger.addFilter(add_request_id_filter)
python
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 {0} does not exists.'.format(basedir)) handler = RotatingFileHandler( app.config['LOGGING_FS_LOGFILE'], backupCount=app.config['LOGGING_FS_BACKUPCOUNT'], maxBytes=app.config['LOGGING_FS_MAXBYTES'], delay=True, ) handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) handler.setLevel(app.config['LOGGING_FS_LEVEL']) # Add handler to application logger app.logger.addHandler(handler) if app.config['LOGGING_FS_PYWARNINGS']: self.capture_pywarnings(handler) # Add request_id to log record app.logger.addFilter(add_request_id_filter)
[ "def", "install_handler", "(", "self", ",", "app", ")", ":", "# Check if directory exists.", "basedir", "=", "dirname", "(", "app", ".", "config", "[", "'LOGGING_FS_LOGFILE'", "]", ")", "if", "not", "exists", "(", "basedir", ")", ":", "raise", "ValueError", ...
Install log handler on Flask application.
[ "Install", "log", "handler", "on", "Flask", "application", "." ]
train
https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L56-L83
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.put
def put(self, key, value, minutes): """ 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 """ minutes = self._get_minutes(minutes) if minutes is not None: return self._store.put(self.tagged_item_key(key), value, minutes)
python
def put(self, key, value, minutes): """ 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 """ minutes = self._get_minutes(minutes) if minutes is not None: return self._store.put(self.tagged_item_key(key), value, minutes)
[ "def", "put", "(", "self", ",", "key", ",", "value", ",", "minutes", ")", ":", "minutes", "=", "self", ".", "_get_minutes", "(", "minutes", ")", "if", "minutes", "is", "not", "None", ":", "return", "self", ".", "_store", ".", "put", "(", "self", "....
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
[ "Store", "an", "item", "in", "the", "cache", "for", "a", "given", "number", "of", "minutes", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L56-L72
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.add
def add(self, key, val, minutes): """ 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 """ if not self.has(key): self.put(key, val, minutes) return True return False
python
def add(self, key, val, minutes): """ 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 """ if not self.has(key): self.put(key, val, minutes) return True return False
[ "def", "add", "(", "self", ",", "key", ",", "val", ",", "minutes", ")", ":", "if", "not", "self", ".", "has", "(", "key", ")", ":", "self", ".", "put", "(", "key", ",", "val", ",", "minutes", ")", "return", "True", "return", "False" ]
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
[ "Store", "an", "item", "in", "the", "cache", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L74-L94
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.increment
def increment(self, key, value=1): """ 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 """ self._store.increment(self.tagged_item_key(key), value)
python
def increment(self, key, value=1): """ 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 """ self._store.increment(self.tagged_item_key(key), value)
[ "def", "increment", "(", "self", ",", "key", ",", "value", "=", "1", ")", ":", "self", ".", "_store", ".", "increment", "(", "self", ".", "tagged_item_key", "(", "key", ")", ",", "value", ")" ]
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
[ "Increment", "the", "value", "of", "an", "item", "in", "the", "cache", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L96-L108
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.decrement
def decrement(self, key, value=1): """ 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 """ self._store.decrement(self.tagged_item_key(key), value)
python
def decrement(self, key, value=1): """ 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 """ self._store.decrement(self.tagged_item_key(key), value)
[ "def", "decrement", "(", "self", ",", "key", ",", "value", "=", "1", ")", ":", "self", ".", "_store", ".", "decrement", "(", "self", ".", "tagged_item_key", "(", "key", ")", ",", "value", ")" ]
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
[ "Decrement", "the", "value", "of", "an", "item", "in", "the", "cache", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L110-L122
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.forever
def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed """ self._store.forever(self.tagged_item_key(key), value)
python
def forever(self, key, value): """ Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed """ self._store.forever(self.tagged_item_key(key), value)
[ "def", "forever", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "_store", ".", "forever", "(", "self", ".", "tagged_item_key", "(", "key", ")", ",", "value", ")" ]
Store an item in the cache indefinitely. :param key: The cache key :type key: str :param value: The value :type value: mixed
[ "Store", "an", "item", "in", "the", "cache", "indefinitely", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L124-L134
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.remember
def remember(self, key, minutes, callback): """ 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: mixed """ # If the item exists in the cache we will just return this immediately # otherwise we will execute the given callback and cache the result # of that execution for the given number of minutes in storage. val = self.get(key) if val is not None: return val val = value(callback) self.put(key, val, minutes) return val
python
def remember(self, key, minutes, callback): """ 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: mixed """ # If the item exists in the cache we will just return this immediately # otherwise we will execute the given callback and cache the result # of that execution for the given number of minutes in storage. val = self.get(key) if val is not None: return val val = value(callback) self.put(key, val, minutes) return val
[ "def", "remember", "(", "self", ",", "key", ",", "minutes", ",", "callback", ")", ":", "# If the item exists in the cache we will just return this immediately", "# otherwise we will execute the given callback and cache the result", "# of that execution for the given number of minutes in ...
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: mixed
[ "Get", "an", "item", "from", "the", "cache", "or", "store", "the", "default", "value", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L153-L179
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.remember_forever
def remember_forever(self, key, callback): """ 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 """ # If the item exists in the cache we will just return this immediately # otherwise we will execute the given callback and cache the result # of that execution forever. val = self.get(key) if val is not None: return val val = value(callback) self.forever(key, val) return val
python
def remember_forever(self, key, callback): """ 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 """ # If the item exists in the cache we will just return this immediately # otherwise we will execute the given callback and cache the result # of that execution forever. val = self.get(key) if val is not None: return val val = value(callback) self.forever(key, val) return val
[ "def", "remember_forever", "(", "self", ",", "key", ",", "callback", ")", ":", "# If the item exists in the cache we will just return this immediately", "# otherwise we will execute the given callback and cache the result", "# of that execution forever.", "val", "=", "self", ".", "...
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
[ "Get", "an", "item", "from", "the", "cache", "or", "store", "the", "default", "value", "forever", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L181-L204
sdispater/cachy
cachy/tagged_cache.py
TaggedCache.tagged_item_key
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 """ return '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key)
python
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 """ return '%s:%s' % (hashlib.sha1(encode(self._tags.get_namespace())).hexdigest(), key)
[ "def", "tagged_item_key", "(", "self", ",", "key", ")", ":", "return", "'%s:%s'", "%", "(", "hashlib", ".", "sha1", "(", "encode", "(", "self", ".", "_tags", ".", "get_namespace", "(", ")", ")", ")", ".", "hexdigest", "(", ")", ",", "key", ")" ]
Get a fully qualified key for a tagged item. :param key: The cache key :type key: str :rtype: str
[ "Get", "a", "fully", "qualified", "key", "for", "a", "tagged", "item", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L206-L215
sdispater/cachy
cachy/tagged_cache.py
TaggedCache._get_minutes
def _get_minutes(self, duration): """ Calculate the number of minutes with the given duration. :param duration: The duration :type duration: int or datetime :rtype: int or None """ if isinstance(duration, datetime.datetime): from_now = (duration - datetime.datetime.now()).total_seconds() from_now = math.ceil(from_now / 60) if from_now > 0: return from_now return return duration
python
def _get_minutes(self, duration): """ Calculate the number of minutes with the given duration. :param duration: The duration :type duration: int or datetime :rtype: int or None """ if isinstance(duration, datetime.datetime): from_now = (duration - datetime.datetime.now()).total_seconds() from_now = math.ceil(from_now / 60) if from_now > 0: return from_now return return duration
[ "def", "_get_minutes", "(", "self", ",", "duration", ")", ":", "if", "isinstance", "(", "duration", ",", "datetime", ".", "datetime", ")", ":", "from_now", "=", "(", "duration", "-", "datetime", ".", "datetime", ".", "now", "(", ")", ")", ".", "total_s...
Calculate the number of minutes with the given duration. :param duration: The duration :type duration: int or datetime :rtype: int or None
[ "Calculate", "the", "number", "of", "minutes", "with", "the", "given", "duration", "." ]
train
https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L225-L243
fabaff/python-netdata
example.py
main
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)) # Print the current value of the system's CPU print("CPU System:", round(data.values['system'], 2)) with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session, data='alarms') await data.get_alarms() print(data.alarms) with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session) await data.get_allmetrics() print(data.metrics) # Print the current value for the system's CPU print("CPU System:", round(data.metrics['system.cpu'] ['dimensions']['system']['value'], 2))
python
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)) # Print the current value of the system's CPU print("CPU System:", round(data.values['system'], 2)) with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session, data='alarms') await data.get_alarms() print(data.alarms) with aiohttp.ClientSession() as session: data = Netdata('localhost', loop, session) await data.get_allmetrics() print(data.metrics) # Print the current value for the system's CPU print("CPU System:", round(data.metrics['system.cpu'] ['dimensions']['system']['value'], 2))
[ "async", "def", "main", "(", ")", ":", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "data", "=", "Netdata", "(", "'localhost'", ",", "loop", ",", "session", ",", "data", "=", "'data'", ")", "await", "data", ".", "get_data", ...
Get the data from a Netdata instance.
[ "Get", "the", "data", "from", "a", "Netdata", "instance", "." ]
train
https://github.com/fabaff/python-netdata/blob/bca5d58f84a0fc849b9bb16a00959a0b33d13a67/example.py#L9-L34
inveniosoftware/invenio-logging
invenio_logging/console.py
InvenioLoggingConsole.install_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: for h in app.logger.handlers: h.setLevel(app.config['LOGGING_CONSOLE_LEVEL']) # Add request_id to log record app.logger.addFilter(add_request_id_filter)
python
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: for h in app.logger.handlers: h.setLevel(app.config['LOGGING_CONSOLE_LEVEL']) # Add request_id to log record app.logger.addFilter(add_request_id_filter)
[ "def", "install_handler", "(", "self", ",", "app", ")", ":", "# Configure python logging", "if", "app", ".", "config", "[", "'LOGGING_CONSOLE_PYWARNINGS'", "]", ":", "self", ".", "capture_pywarnings", "(", "logging", ".", "StreamHandler", "(", ")", ")", "if", ...
Install logging handler.
[ "Install", "logging", "handler", "." ]
train
https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/console.py#L46-L57