repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ajenhl/tacl | tacl/sequence.py | Sequence._format_alignment | def _format_alignment(self, a1, a2):
"""Returns `a1` marked up with HTML spans around characters that are
also at the same index in `a2`.
:param a1: text sequence from one witness
:type a1: `str`
:param a2: text sequence from another witness
:type a2: `str`
:rtype: `str`
"""
html = []
for index, char in enumerate(a1):
output = self._substitutes.get(char, char)
if a2[index] == char:
html.append('<span class="match">{}</span>'.format(output))
elif char != '-':
html.append(output)
return ''.join(html) | python | def _format_alignment(self, a1, a2):
"""Returns `a1` marked up with HTML spans around characters that are
also at the same index in `a2`.
:param a1: text sequence from one witness
:type a1: `str`
:param a2: text sequence from another witness
:type a2: `str`
:rtype: `str`
"""
html = []
for index, char in enumerate(a1):
output = self._substitutes.get(char, char)
if a2[index] == char:
html.append('<span class="match">{}</span>'.format(output))
elif char != '-':
html.append(output)
return ''.join(html) | [
"def",
"_format_alignment",
"(",
"self",
",",
"a1",
",",
"a2",
")",
":",
"html",
"=",
"[",
"]",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"a1",
")",
":",
"output",
"=",
"self",
".",
"_substitutes",
".",
"get",
"(",
"char",
",",
"char",
... | Returns `a1` marked up with HTML spans around characters that are
also at the same index in `a2`.
:param a1: text sequence from one witness
:type a1: `str`
:param a2: text sequence from another witness
:type a2: `str`
:rtype: `str` | [
"Returns",
"a1",
"marked",
"up",
"with",
"HTML",
"spans",
"around",
"characters",
"that",
"are",
"also",
"at",
"the",
"same",
"index",
"in",
"a2",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L24-L42 | train | 48,400 |
ajenhl/tacl | tacl/sequence.py | Sequence.render | def render(self):
"""Returns a tuple of HTML fragments rendering each element of the
sequence."""
f1 = self._format_alignment(self._alignment[0], self._alignment[1])
f2 = self._format_alignment(self._alignment[1], self._alignment[0])
return f1, f2 | python | def render(self):
"""Returns a tuple of HTML fragments rendering each element of the
sequence."""
f1 = self._format_alignment(self._alignment[0], self._alignment[1])
f2 = self._format_alignment(self._alignment[1], self._alignment[0])
return f1, f2 | [
"def",
"render",
"(",
"self",
")",
":",
"f1",
"=",
"self",
".",
"_format_alignment",
"(",
"self",
".",
"_alignment",
"[",
"0",
"]",
",",
"self",
".",
"_alignment",
"[",
"1",
"]",
")",
"f2",
"=",
"self",
".",
"_format_alignment",
"(",
"self",
".",
"... | Returns a tuple of HTML fragments rendering each element of the
sequence. | [
"Returns",
"a",
"tuple",
"of",
"HTML",
"fragments",
"rendering",
"each",
"element",
"of",
"the",
"sequence",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L44-L49 | train | 48,401 |
ajenhl/tacl | tacl/sequence.py | SequenceReport.generate | def generate(self, output_dir, minimum_size):
"""Generates sequence reports and writes them to the output directory.
:param output_dir: directory to output reports to
:type output_dir: `str`
:param minimum_size: minimum size of n-grams to create sequences for
:type minimum_size: `int`
"""
self._output_dir = output_dir
# Get a list of the files in the matches, grouped by label
# (ordered by number of works).
labels = list(self._matches.groupby([constants.LABEL_FIELDNAME])[
constants.WORK_FIELDNAME].nunique().index)
original_ngrams = self._matches[
self._matches[
constants.SIZE_FIELDNAME] >= minimum_size].sort_values(
by=constants.SIZE_FIELDNAME, ascending=False)[
constants.NGRAM_FIELDNAME].unique()
ngrams = []
for original_ngram in original_ngrams:
ngrams.append(self._get_text(Text(original_ngram,
self._tokenizer)))
# Generate sequences for each witness in every combination of
# (different) labels.
for index, primary_label in enumerate(labels):
for secondary_label in labels[index+1:]:
self._generate_sequences(primary_label, secondary_label,
ngrams) | python | def generate(self, output_dir, minimum_size):
"""Generates sequence reports and writes them to the output directory.
:param output_dir: directory to output reports to
:type output_dir: `str`
:param minimum_size: minimum size of n-grams to create sequences for
:type minimum_size: `int`
"""
self._output_dir = output_dir
# Get a list of the files in the matches, grouped by label
# (ordered by number of works).
labels = list(self._matches.groupby([constants.LABEL_FIELDNAME])[
constants.WORK_FIELDNAME].nunique().index)
original_ngrams = self._matches[
self._matches[
constants.SIZE_FIELDNAME] >= minimum_size].sort_values(
by=constants.SIZE_FIELDNAME, ascending=False)[
constants.NGRAM_FIELDNAME].unique()
ngrams = []
for original_ngram in original_ngrams:
ngrams.append(self._get_text(Text(original_ngram,
self._tokenizer)))
# Generate sequences for each witness in every combination of
# (different) labels.
for index, primary_label in enumerate(labels):
for secondary_label in labels[index+1:]:
self._generate_sequences(primary_label, secondary_label,
ngrams) | [
"def",
"generate",
"(",
"self",
",",
"output_dir",
",",
"minimum_size",
")",
":",
"self",
".",
"_output_dir",
"=",
"output_dir",
"# Get a list of the files in the matches, grouped by label",
"# (ordered by number of works).",
"labels",
"=",
"list",
"(",
"self",
".",
"_m... | Generates sequence reports and writes them to the output directory.
:param output_dir: directory to output reports to
:type output_dir: `str`
:param minimum_size: minimum size of n-grams to create sequences for
:type minimum_size: `int` | [
"Generates",
"sequence",
"reports",
"and",
"writes",
"them",
"to",
"the",
"output",
"directory",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L68-L96 | train | 48,402 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._generate_sequences | def _generate_sequences(self, primary_label, secondary_label, ngrams):
"""Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
witnesses to align
:type primary_label: `str`
:param secondary_label: label for the other side of the pairs
of witnesses to align
:type secondary_label: `str`
:param ngrams: n-grams to base sequences off
:type ngrams: `list` of `str`
"""
cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME]
primary_works = self._matches[self._matches[
constants.LABEL_FIELDNAME] == primary_label][
cols].drop_duplicates()
secondary_works = self._matches[self._matches[
constants.LABEL_FIELDNAME] == secondary_label][
cols].drop_duplicates()
for index, (work1, siglum1) in primary_works.iterrows():
text1 = self._get_text(self._corpus.get_witness(work1, siglum1))
label1 = '{}_{}'.format(work1, siglum1)
for index, (work2, siglum2) in secondary_works.iterrows():
text2 = self._get_text(self._corpus.get_witness(
work2, siglum2))
label2 = '{}_{}'.format(work2, siglum2)
self._generate_sequences_for_texts(label1, text1, label2,
text2, ngrams) | python | def _generate_sequences(self, primary_label, secondary_label, ngrams):
"""Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
witnesses to align
:type primary_label: `str`
:param secondary_label: label for the other side of the pairs
of witnesses to align
:type secondary_label: `str`
:param ngrams: n-grams to base sequences off
:type ngrams: `list` of `str`
"""
cols = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME]
primary_works = self._matches[self._matches[
constants.LABEL_FIELDNAME] == primary_label][
cols].drop_duplicates()
secondary_works = self._matches[self._matches[
constants.LABEL_FIELDNAME] == secondary_label][
cols].drop_duplicates()
for index, (work1, siglum1) in primary_works.iterrows():
text1 = self._get_text(self._corpus.get_witness(work1, siglum1))
label1 = '{}_{}'.format(work1, siglum1)
for index, (work2, siglum2) in secondary_works.iterrows():
text2 = self._get_text(self._corpus.get_witness(
work2, siglum2))
label2 = '{}_{}'.format(work2, siglum2)
self._generate_sequences_for_texts(label1, text1, label2,
text2, ngrams) | [
"def",
"_generate_sequences",
"(",
"self",
",",
"primary_label",
",",
"secondary_label",
",",
"ngrams",
")",
":",
"cols",
"=",
"[",
"constants",
".",
"WORK_FIELDNAME",
",",
"constants",
".",
"SIGLUM_FIELDNAME",
"]",
"primary_works",
"=",
"self",
".",
"_matches",... | Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
witnesses to align
:type primary_label: `str`
:param secondary_label: label for the other side of the pairs
of witnesses to align
:type secondary_label: `str`
:param ngrams: n-grams to base sequences off
:type ngrams: `list` of `str` | [
"Generates",
"aligned",
"sequences",
"between",
"each",
"witness",
"labelled",
"primary_label",
"and",
"each",
"witness",
"labelled",
"secondary_label",
"based",
"around",
"ngrams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L151-L181 | train | 48,403 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._generate_sequences_for_ngram | def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans):
"""Generates aligned sequences for the texts `t1` and `t2`, based
around `ngram`.
Does not generate sequences that occur within `covered_spans`.
:param t1: text content of first witness
:type t1: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngram: n-gram to base sequences on
:type ngram: `str`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
"""
self._logger.debug('Generating sequences for n-gram "{}"'.format(
ngram))
pattern = re.compile(re.escape(ngram))
context_length = len(ngram)
t1_spans = [match.span() for match in pattern.finditer(t1)]
t2_spans = [match.span() for match in pattern.finditer(t2)]
sequences = []
self._logger.debug(t1)
for t1_span in t1_spans:
for t2_span in t2_spans:
if self._is_inside(t1_span, t2_span, covered_spans):
self._logger.debug(
'Skipping match due to existing coverage')
continue
sequence = self._generate_sequence(
t1, t1_span, t2, t2_span, context_length, covered_spans)
if sequence:
sequences.append(sequence)
return sequences | python | def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans):
"""Generates aligned sequences for the texts `t1` and `t2`, based
around `ngram`.
Does not generate sequences that occur within `covered_spans`.
:param t1: text content of first witness
:type t1: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngram: n-gram to base sequences on
:type ngram: `str`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
"""
self._logger.debug('Generating sequences for n-gram "{}"'.format(
ngram))
pattern = re.compile(re.escape(ngram))
context_length = len(ngram)
t1_spans = [match.span() for match in pattern.finditer(t1)]
t2_spans = [match.span() for match in pattern.finditer(t2)]
sequences = []
self._logger.debug(t1)
for t1_span in t1_spans:
for t2_span in t2_spans:
if self._is_inside(t1_span, t2_span, covered_spans):
self._logger.debug(
'Skipping match due to existing coverage')
continue
sequence = self._generate_sequence(
t1, t1_span, t2, t2_span, context_length, covered_spans)
if sequence:
sequences.append(sequence)
return sequences | [
"def",
"_generate_sequences_for_ngram",
"(",
"self",
",",
"t1",
",",
"t2",
",",
"ngram",
",",
"covered_spans",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Generating sequences for n-gram \"{}\"'",
".",
"format",
"(",
"ngram",
")",
")",
"pattern",
"=... | Generates aligned sequences for the texts `t1` and `t2`, based
around `ngram`.
Does not generate sequences that occur within `covered_spans`.
:param t1: text content of first witness
:type t1: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngram: n-gram to base sequences on
:type ngram: `str`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int` | [
"Generates",
"aligned",
"sequences",
"for",
"the",
"texts",
"t1",
"and",
"t2",
"based",
"around",
"ngram",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L183-L218 | train | 48,404 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._generate_sequences_for_texts | def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams):
"""Generates and outputs aligned sequences for the texts `t1` and `t2`
from `ngrams`.
:param l1: label of first witness
:type l1: `str`
:param t1: text content of first witness
:type t1: `str`
:param l2: label of second witness
:type l2: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngrams: n-grams to base sequences on
:type ngrams: `list` of `str`
"""
# self._subsitutes is gradually populated as each text is
# processed, so this needs to be regenerated each time.
self._reverse_substitutes = dict((v, k) for k, v in
self._substitutes.items())
sequences = []
# Keep track of spans within each text that have been covered
# by an aligned sequence, to ensure that they aren't reported
# more than once. The first sub-list contains span indices for
# text t1, the second for t2.
covered_spans = [[], []]
for ngram in ngrams:
sequences.extend(self._generate_sequences_for_ngram(
t1, t2, ngram, covered_spans))
if sequences:
sequences.sort(key=lambda x: x.start_index)
context = {'l1': l1, 'l2': l2, 'sequences': sequences}
report_name = '{}-{}.html'.format(l1, l2)
os.makedirs(self._output_dir, exist_ok=True)
self._write(context, self._output_dir, report_name) | python | def _generate_sequences_for_texts(self, l1, t1, l2, t2, ngrams):
"""Generates and outputs aligned sequences for the texts `t1` and `t2`
from `ngrams`.
:param l1: label of first witness
:type l1: `str`
:param t1: text content of first witness
:type t1: `str`
:param l2: label of second witness
:type l2: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngrams: n-grams to base sequences on
:type ngrams: `list` of `str`
"""
# self._subsitutes is gradually populated as each text is
# processed, so this needs to be regenerated each time.
self._reverse_substitutes = dict((v, k) for k, v in
self._substitutes.items())
sequences = []
# Keep track of spans within each text that have been covered
# by an aligned sequence, to ensure that they aren't reported
# more than once. The first sub-list contains span indices for
# text t1, the second for t2.
covered_spans = [[], []]
for ngram in ngrams:
sequences.extend(self._generate_sequences_for_ngram(
t1, t2, ngram, covered_spans))
if sequences:
sequences.sort(key=lambda x: x.start_index)
context = {'l1': l1, 'l2': l2, 'sequences': sequences}
report_name = '{}-{}.html'.format(l1, l2)
os.makedirs(self._output_dir, exist_ok=True)
self._write(context, self._output_dir, report_name) | [
"def",
"_generate_sequences_for_texts",
"(",
"self",
",",
"l1",
",",
"t1",
",",
"l2",
",",
"t2",
",",
"ngrams",
")",
":",
"# self._subsitutes is gradually populated as each text is",
"# processed, so this needs to be regenerated each time.",
"self",
".",
"_reverse_substitutes... | Generates and outputs aligned sequences for the texts `t1` and `t2`
from `ngrams`.
:param l1: label of first witness
:type l1: `str`
:param t1: text content of first witness
:type t1: `str`
:param l2: label of second witness
:type l2: `str`
:param t2: text content of second witness
:type t2: `str`
:param ngrams: n-grams to base sequences on
:type ngrams: `list` of `str` | [
"Generates",
"and",
"outputs",
"aligned",
"sequences",
"for",
"the",
"texts",
"t1",
"and",
"t2",
"from",
"ngrams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L220-L254 | train | 48,405 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._get_text | def _get_text(self, text):
"""Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str`
"""
tokens = text.get_tokens()
for i, token in enumerate(tokens):
if len(token) > 1:
char = chr(self._char_code)
substitute = self._substitutes.setdefault(token, char)
if substitute == char:
self._char_code += 1
tokens[i] = substitute
return self._tokenizer.joiner.join(tokens) | python | def _get_text(self, text):
"""Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str`
"""
tokens = text.get_tokens()
for i, token in enumerate(tokens):
if len(token) > 1:
char = chr(self._char_code)
substitute = self._substitutes.setdefault(token, char)
if substitute == char:
self._char_code += 1
tokens[i] = substitute
return self._tokenizer.joiner.join(tokens) | [
"def",
"_get_text",
"(",
"self",
",",
"text",
")",
":",
"tokens",
"=",
"text",
".",
"get_tokens",
"(",
")",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"if",
"len",
"(",
"token",
")",
">",
"1",
":",
"char",
"=",
"chr",
... | Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str` | [
"Returns",
"the",
"text",
"content",
"of",
"text",
"with",
"all",
"multi",
"-",
"character",
"tokens",
"replaced",
"with",
"a",
"single",
"character",
".",
"Substitutions",
"are",
"recorded",
"in",
"self",
".",
"_substitutes",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L256-L274 | train | 48,406 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._get_text_sequence | def _get_text_sequence(self, text, span, context_length):
"""Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
:type span: 2-`tuple` of `int`
:param context_length: length of context on either side of
`span` to include in the extract
:type context_length: `int`
"""
start = max(0, span[0] - context_length)
end = min(len(text), span[1] + context_length)
return text[start:end], (start, end) | python | def _get_text_sequence(self, text, span, context_length):
"""Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
:type span: 2-`tuple` of `int`
:param context_length: length of context on either side of
`span` to include in the extract
:type context_length: `int`
"""
start = max(0, span[0] - context_length)
end = min(len(text), span[1] + context_length)
return text[start:end], (start, end) | [
"def",
"_get_text_sequence",
"(",
"self",
",",
"text",
",",
"span",
",",
"context_length",
")",
":",
"start",
"=",
"max",
"(",
"0",
",",
"span",
"[",
"0",
"]",
"-",
"context_length",
")",
"end",
"=",
"min",
"(",
"len",
"(",
"text",
")",
",",
"span"... | Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
:type span: 2-`tuple` of `int`
:param context_length: length of context on either side of
`span` to include in the extract
:type context_length: `int` | [
"Returns",
"the",
"subset",
"of",
"text",
"encompassed",
"by",
"span",
"plus",
"context_length",
"characters",
"before",
"and",
"after",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L276-L291 | train | 48,407 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._is_inside | def _is_inside(self, span1, span2, covered_spans):
"""Returns True if both `span1` and `span2` fall within
`covered_spans`.
:param span1: start and end indices of a span
:type span1: 2-`tuple` of `int`
:param span2: start and end indices of a span
:type span2: 2-`tuple` of `int`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
:rtype: `bool`
"""
if self._is_span_inside(span1, covered_spans[0]) and \
self._is_span_inside(span2, covered_spans[1]):
return True
return False | python | def _is_inside(self, span1, span2, covered_spans):
"""Returns True if both `span1` and `span2` fall within
`covered_spans`.
:param span1: start and end indices of a span
:type span1: 2-`tuple` of `int`
:param span2: start and end indices of a span
:type span2: 2-`tuple` of `int`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
:rtype: `bool`
"""
if self._is_span_inside(span1, covered_spans[0]) and \
self._is_span_inside(span2, covered_spans[1]):
return True
return False | [
"def",
"_is_inside",
"(",
"self",
",",
"span1",
",",
"span2",
",",
"covered_spans",
")",
":",
"if",
"self",
".",
"_is_span_inside",
"(",
"span1",
",",
"covered_spans",
"[",
"0",
"]",
")",
"and",
"self",
".",
"_is_span_inside",
"(",
"span2",
",",
"covered... | Returns True if both `span1` and `span2` fall within
`covered_spans`.
:param span1: start and end indices of a span
:type span1: 2-`tuple` of `int`
:param span2: start and end indices of a span
:type span2: 2-`tuple` of `int`
:param covered_spans: lists of start and end indices for parts
of the texts already covered by a sequence
:type covered_spans: `list` of two `list`s of 2-`tuple` of `int`
:rtype: `bool` | [
"Returns",
"True",
"if",
"both",
"span1",
"and",
"span2",
"fall",
"within",
"covered_spans",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L293-L310 | train | 48,408 |
ajenhl/tacl | tacl/sequence.py | SequenceReport._is_span_inside | def _is_span_inside(self, span, covered_spans):
"""Returns True if `span` falls within `covered_spans`.
:param span: start and end indices of a span
:type span: 2-`tuple` of `int`
:param covered_spans: list of start and end indices for parts
of the text already covered by a sequence
:type covered_spans: `list` of 2-`tuple` of `int`
:rtype: `bool`
"""
start = span[0]
end = span[1]
for c_start, c_end in covered_spans:
if start >= c_start and end <= c_end:
return True
return False | python | def _is_span_inside(self, span, covered_spans):
"""Returns True if `span` falls within `covered_spans`.
:param span: start and end indices of a span
:type span: 2-`tuple` of `int`
:param covered_spans: list of start and end indices for parts
of the text already covered by a sequence
:type covered_spans: `list` of 2-`tuple` of `int`
:rtype: `bool`
"""
start = span[0]
end = span[1]
for c_start, c_end in covered_spans:
if start >= c_start and end <= c_end:
return True
return False | [
"def",
"_is_span_inside",
"(",
"self",
",",
"span",
",",
"covered_spans",
")",
":",
"start",
"=",
"span",
"[",
"0",
"]",
"end",
"=",
"span",
"[",
"1",
"]",
"for",
"c_start",
",",
"c_end",
"in",
"covered_spans",
":",
"if",
"start",
">=",
"c_start",
"a... | Returns True if `span` falls within `covered_spans`.
:param span: start and end indices of a span
:type span: 2-`tuple` of `int`
:param covered_spans: list of start and end indices for parts
of the text already covered by a sequence
:type covered_spans: `list` of 2-`tuple` of `int`
:rtype: `bool` | [
"Returns",
"True",
"if",
"span",
"falls",
"within",
"covered_spans",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/sequence.py#L312-L328 | train | 48,409 |
ajenhl/tacl | tacl/cli/utils.py | add_corpus_arguments | def add_corpus_arguments(parser):
"""Adds common arguments for commands making use of a corpus to
`parser`."""
add_tokenizer_argument(parser)
parser.add_argument('corpus', help=constants.DB_CORPUS_HELP,
metavar='CORPUS') | python | def add_corpus_arguments(parser):
"""Adds common arguments for commands making use of a corpus to
`parser`."""
add_tokenizer_argument(parser)
parser.add_argument('corpus', help=constants.DB_CORPUS_HELP,
metavar='CORPUS') | [
"def",
"add_corpus_arguments",
"(",
"parser",
")",
":",
"add_tokenizer_argument",
"(",
"parser",
")",
"parser",
".",
"add_argument",
"(",
"'corpus'",
",",
"help",
"=",
"constants",
".",
"DB_CORPUS_HELP",
",",
"metavar",
"=",
"'CORPUS'",
")"
] | Adds common arguments for commands making use of a corpus to
`parser`. | [
"Adds",
"common",
"arguments",
"for",
"commands",
"making",
"use",
"of",
"a",
"corpus",
"to",
"parser",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L18-L23 | train | 48,410 |
ajenhl/tacl | tacl/cli/utils.py | add_db_arguments | def add_db_arguments(parser, db_option=False):
"""Adds common arguments for the database sub-commands to
`parser`.
`db_option` provides a means to work around
https://bugs.python.org/issue9338 whereby a positional argument
that follows an optional argument with nargs='+' will not be
recognised. When `db_optional` is True, create the database
argument as a required optional argument, rather than a positional
argument.
"""
parser.add_argument('-m', '--memory', action='store_true',
help=constants.DB_MEMORY_HELP)
parser.add_argument('-r', '--ram', default=3, help=constants.DB_RAM_HELP,
type=int)
if db_option:
parser.add_argument('-d', '--db', help=constants.DB_DATABASE_HELP,
metavar='DATABASE', required=True)
else:
parser.add_argument('db', help=constants.DB_DATABASE_HELP,
metavar='DATABASE') | python | def add_db_arguments(parser, db_option=False):
"""Adds common arguments for the database sub-commands to
`parser`.
`db_option` provides a means to work around
https://bugs.python.org/issue9338 whereby a positional argument
that follows an optional argument with nargs='+' will not be
recognised. When `db_optional` is True, create the database
argument as a required optional argument, rather than a positional
argument.
"""
parser.add_argument('-m', '--memory', action='store_true',
help=constants.DB_MEMORY_HELP)
parser.add_argument('-r', '--ram', default=3, help=constants.DB_RAM_HELP,
type=int)
if db_option:
parser.add_argument('-d', '--db', help=constants.DB_DATABASE_HELP,
metavar='DATABASE', required=True)
else:
parser.add_argument('db', help=constants.DB_DATABASE_HELP,
metavar='DATABASE') | [
"def",
"add_db_arguments",
"(",
"parser",
",",
"db_option",
"=",
"False",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-m'",
",",
"'--memory'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"constants",
".",
"DB_MEMORY_HELP",
")",
"parser",
".",
... | Adds common arguments for the database sub-commands to
`parser`.
`db_option` provides a means to work around
https://bugs.python.org/issue9338 whereby a positional argument
that follows an optional argument with nargs='+' will not be
recognised. When `db_optional` is True, create the database
argument as a required optional argument, rather than a positional
argument. | [
"Adds",
"common",
"arguments",
"for",
"the",
"database",
"sub",
"-",
"commands",
"to",
"parser",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L26-L47 | train | 48,411 |
ajenhl/tacl | tacl/cli/utils.py | add_supplied_query_arguments | def add_supplied_query_arguments(parser):
"""Adds common arguments for supplied query sub-commands to
`parser`."""
parser.add_argument('-l', '--labels', help=constants.SUPPLIED_LABELS_HELP,
nargs='+', required=True)
parser.add_argument('-s', '--supplied',
help=constants.SUPPLIED_RESULTS_HELP,
metavar='RESULTS', nargs='+', required=True) | python | def add_supplied_query_arguments(parser):
"""Adds common arguments for supplied query sub-commands to
`parser`."""
parser.add_argument('-l', '--labels', help=constants.SUPPLIED_LABELS_HELP,
nargs='+', required=True)
parser.add_argument('-s', '--supplied',
help=constants.SUPPLIED_RESULTS_HELP,
metavar='RESULTS', nargs='+', required=True) | [
"def",
"add_supplied_query_arguments",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-l'",
",",
"'--labels'",
",",
"help",
"=",
"constants",
".",
"SUPPLIED_LABELS_HELP",
",",
"nargs",
"=",
"'+'",
",",
"required",
"=",
"True",
")",
"parser",
... | Adds common arguments for supplied query sub-commands to
`parser`. | [
"Adds",
"common",
"arguments",
"for",
"supplied",
"query",
"sub",
"-",
"commands",
"to",
"parser",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L56-L63 | train | 48,412 |
ajenhl/tacl | tacl/cli/utils.py | configure_logging | def configure_logging(verbose, logger):
"""Configures the logging used."""
if not verbose:
log_level = logging.WARNING
elif verbose == 1:
log_level = logging.INFO
else:
log_level = logging.DEBUG
logger.setLevel(log_level)
ch = colorlog.StreamHandler()
ch.setLevel(log_level)
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(asctime)s %(name)s %(levelname)s: %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch) | python | def configure_logging(verbose, logger):
"""Configures the logging used."""
if not verbose:
log_level = logging.WARNING
elif verbose == 1:
log_level = logging.INFO
else:
log_level = logging.DEBUG
logger.setLevel(log_level)
ch = colorlog.StreamHandler()
ch.setLevel(log_level)
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(asctime)s %(name)s %(levelname)s: %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch) | [
"def",
"configure_logging",
"(",
"verbose",
",",
"logger",
")",
":",
"if",
"not",
"verbose",
":",
"log_level",
"=",
"logging",
".",
"WARNING",
"elif",
"verbose",
"==",
"1",
":",
"log_level",
"=",
"logging",
".",
"INFO",
"else",
":",
"log_level",
"=",
"lo... | Configures the logging used. | [
"Configures",
"the",
"logging",
"used",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L73-L87 | train | 48,413 |
ajenhl/tacl | tacl/cli/utils.py | get_catalogue | def get_catalogue(args):
"""Returns a `tacl.Catalogue`."""
catalogue = tacl.Catalogue()
catalogue.load(args.catalogue)
return catalogue | python | def get_catalogue(args):
"""Returns a `tacl.Catalogue`."""
catalogue = tacl.Catalogue()
catalogue.load(args.catalogue)
return catalogue | [
"def",
"get_catalogue",
"(",
"args",
")",
":",
"catalogue",
"=",
"tacl",
".",
"Catalogue",
"(",
")",
"catalogue",
".",
"load",
"(",
"args",
".",
"catalogue",
")",
"return",
"catalogue"
] | Returns a `tacl.Catalogue`. | [
"Returns",
"a",
"tacl",
".",
"Catalogue",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L90-L94 | train | 48,414 |
ajenhl/tacl | tacl/cli/utils.py | get_corpus | def get_corpus(args):
"""Returns a `tacl.Corpus`."""
tokenizer = get_tokenizer(args)
return tacl.Corpus(args.corpus, tokenizer) | python | def get_corpus(args):
"""Returns a `tacl.Corpus`."""
tokenizer = get_tokenizer(args)
return tacl.Corpus(args.corpus, tokenizer) | [
"def",
"get_corpus",
"(",
"args",
")",
":",
"tokenizer",
"=",
"get_tokenizer",
"(",
"args",
")",
"return",
"tacl",
".",
"Corpus",
"(",
"args",
".",
"corpus",
",",
"tokenizer",
")"
] | Returns a `tacl.Corpus`. | [
"Returns",
"a",
"tacl",
".",
"Corpus",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L97-L100 | train | 48,415 |
ajenhl/tacl | tacl/cli/utils.py | get_data_store | def get_data_store(args):
"""Returns a `tacl.DataStore`."""
return tacl.DataStore(args.db, args.memory, args.ram) | python | def get_data_store(args):
"""Returns a `tacl.DataStore`."""
return tacl.DataStore(args.db, args.memory, args.ram) | [
"def",
"get_data_store",
"(",
"args",
")",
":",
"return",
"tacl",
".",
"DataStore",
"(",
"args",
".",
"db",
",",
"args",
".",
"memory",
",",
"args",
".",
"ram",
")"
] | Returns a `tacl.DataStore`. | [
"Returns",
"a",
"tacl",
".",
"DataStore",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L103-L105 | train | 48,416 |
ajenhl/tacl | tacl/cli/utils.py | get_ngrams | def get_ngrams(path):
"""Returns a list of n-grams read from the file at `path`."""
with open(path, encoding='utf-8') as fh:
ngrams = [ngram.strip() for ngram in fh.readlines()]
return ngrams | python | def get_ngrams(path):
"""Returns a list of n-grams read from the file at `path`."""
with open(path, encoding='utf-8') as fh:
ngrams = [ngram.strip() for ngram in fh.readlines()]
return ngrams | [
"def",
"get_ngrams",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"ngrams",
"=",
"[",
"ngram",
".",
"strip",
"(",
")",
"for",
"ngram",
"in",
"fh",
".",
"readlines",
"(",
")",
"]",
"ret... | Returns a list of n-grams read from the file at `path`. | [
"Returns",
"a",
"list",
"of",
"n",
"-",
"grams",
"read",
"from",
"the",
"file",
"at",
"path",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L108-L112 | train | 48,417 |
ajenhl/tacl | tacl/text.py | Text.excise | def excise(self, ngrams, replacement):
"""Returns the token content of this text with every occurrence of
each n-gram in `ngrams` replaced with `replacement`.
The replacing is performed on each n-gram by descending order
of length.
:param ngrams: n-grams to be replaced
:type ngrams: `list` of `str`
:param replacement: replacement string
:type replacement: `str`
:rtype: `str`
"""
content = self.get_token_content()
ngrams.sort(key=len, reverse=True)
for ngram in ngrams:
content = content.replace(ngram, replacement)
return content | python | def excise(self, ngrams, replacement):
"""Returns the token content of this text with every occurrence of
each n-gram in `ngrams` replaced with `replacement`.
The replacing is performed on each n-gram by descending order
of length.
:param ngrams: n-grams to be replaced
:type ngrams: `list` of `str`
:param replacement: replacement string
:type replacement: `str`
:rtype: `str`
"""
content = self.get_token_content()
ngrams.sort(key=len, reverse=True)
for ngram in ngrams:
content = content.replace(ngram, replacement)
return content | [
"def",
"excise",
"(",
"self",
",",
"ngrams",
",",
"replacement",
")",
":",
"content",
"=",
"self",
".",
"get_token_content",
"(",
")",
"ngrams",
".",
"sort",
"(",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"for",
"ngram",
"in",
"ngrams",
":... | Returns the token content of this text with every occurrence of
each n-gram in `ngrams` replaced with `replacement`.
The replacing is performed on each n-gram by descending order
of length.
:param ngrams: n-grams to be replaced
:type ngrams: `list` of `str`
:param replacement: replacement string
:type replacement: `str`
:rtype: `str` | [
"Returns",
"the",
"token",
"content",
"of",
"this",
"text",
"with",
"every",
"occurrence",
"of",
"each",
"n",
"-",
"gram",
"in",
"ngrams",
"replaced",
"with",
"replacement",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L22-L40 | train | 48,418 |
ajenhl/tacl | tacl/text.py | Text._ngrams | def _ngrams(self, sequence, degree):
"""Returns the n-grams generated from `sequence`.
Based on the ngrams function from the Natural Language
Toolkit.
Each n-gram in the returned list is a string with whitespace
removed.
:param sequence: the source data to be converted into n-grams
:type sequence: sequence
:param degree: the degree of the n-grams
:type degree: `int`
:rtype: `list` of `str`
"""
count = max(0, len(sequence) - degree + 1)
# The extra split and join are due to having to handle
# whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]).
return [self._tokenizer.joiner.join(
self._tokenizer.joiner.join(sequence[i:i+degree]).split())
for i in range(count)] | python | def _ngrams(self, sequence, degree):
"""Returns the n-grams generated from `sequence`.
Based on the ngrams function from the Natural Language
Toolkit.
Each n-gram in the returned list is a string with whitespace
removed.
:param sequence: the source data to be converted into n-grams
:type sequence: sequence
:param degree: the degree of the n-grams
:type degree: `int`
:rtype: `list` of `str`
"""
count = max(0, len(sequence) - degree + 1)
# The extra split and join are due to having to handle
# whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]).
return [self._tokenizer.joiner.join(
self._tokenizer.joiner.join(sequence[i:i+degree]).split())
for i in range(count)] | [
"def",
"_ngrams",
"(",
"self",
",",
"sequence",
",",
"degree",
")",
":",
"count",
"=",
"max",
"(",
"0",
",",
"len",
"(",
"sequence",
")",
"-",
"degree",
"+",
"1",
")",
"# The extra split and join are due to having to handle",
"# whitespace within a CBETA token (eg... | Returns the n-grams generated from `sequence`.
Based on the ngrams function from the Natural Language
Toolkit.
Each n-gram in the returned list is a string with whitespace
removed.
:param sequence: the source data to be converted into n-grams
:type sequence: sequence
:param degree: the degree of the n-grams
:type degree: `int`
:rtype: `list` of `str` | [
"Returns",
"the",
"n",
"-",
"grams",
"generated",
"from",
"sequence",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L91-L112 | train | 48,419 |
ajenhl/tacl | tacl/text.py | FilteredWitnessText.get_filter_ngrams_pattern | def get_filter_ngrams_pattern(filter_ngrams):
"""Returns a compiled regular expression matching on any of the
n-grams in `filter_ngrams`.
:param filter_ngrams: n-grams to use in regular expression
:type filter_ngrams: `list` of `str`
:rtype: `_sre.SRE_Pattern`
"""
return re.compile('|'.join([re.escape(ngram) for ngram in
filter_ngrams])) | python | def get_filter_ngrams_pattern(filter_ngrams):
"""Returns a compiled regular expression matching on any of the
n-grams in `filter_ngrams`.
:param filter_ngrams: n-grams to use in regular expression
:type filter_ngrams: `list` of `str`
:rtype: `_sre.SRE_Pattern`
"""
return re.compile('|'.join([re.escape(ngram) for ngram in
filter_ngrams])) | [
"def",
"get_filter_ngrams_pattern",
"(",
"filter_ngrams",
")",
":",
"return",
"re",
".",
"compile",
"(",
"'|'",
".",
"join",
"(",
"[",
"re",
".",
"escape",
"(",
"ngram",
")",
"for",
"ngram",
"in",
"filter_ngrams",
"]",
")",
")"
] | Returns a compiled regular expression matching on any of the
n-grams in `filter_ngrams`.
:param filter_ngrams: n-grams to use in regular expression
:type filter_ngrams: `list` of `str`
:rtype: `_sre.SRE_Pattern` | [
"Returns",
"a",
"compiled",
"regular",
"expression",
"matching",
"on",
"any",
"of",
"the",
"n",
"-",
"grams",
"in",
"filter_ngrams",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/text.py#L161-L171 | train | 48,420 |
peeringdb/django-peeringdb | django_peeringdb/client_adaptor/backend.py | Backend.set_relation_many_to_many | def set_relation_many_to_many(self, obj, field_name, objs):
"Set a many-to-many field on an object"
relation = getattr(obj, field_name)
if hasattr(relation, 'set'):
relation.set(objs) # Django 2.x
else:
setattr(obj, field_name, objs) | python | def set_relation_many_to_many(self, obj, field_name, objs):
"Set a many-to-many field on an object"
relation = getattr(obj, field_name)
if hasattr(relation, 'set'):
relation.set(objs) # Django 2.x
else:
setattr(obj, field_name, objs) | [
"def",
"set_relation_many_to_many",
"(",
"self",
",",
"obj",
",",
"field_name",
",",
"objs",
")",
":",
"relation",
"=",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"if",
"hasattr",
"(",
"relation",
",",
"'set'",
")",
":",
"relation",
".",
"set",
"(",
... | Set a many-to-many field on an object | [
"Set",
"a",
"many",
"-",
"to",
"-",
"many",
"field",
"on",
"an",
"object"
] | 2a32aae8a7e1c11ab6e5a873bb19619c641098c8 | https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L136-L142 | train | 48,421 |
peeringdb/django-peeringdb | django_peeringdb/client_adaptor/backend.py | Backend.detect_uniqueness_error | def detect_uniqueness_error(self, exc):
"""
Parse error, and if it describes any violations of a uniqueness constraint,
return the corresponding fields, else None
"""
pattern = r"(\w+) with this (\w+) already exists"
fields = []
if isinstance(exc, IntegrityError):
return self._detect_integrity_error(exc)
assert isinstance(exc, ValidationError), TypeError
for name, err in exc.error_dict.items():
if re.search(pattern, str(err)):
fields.append(name)
return fields or None | python | def detect_uniqueness_error(self, exc):
"""
Parse error, and if it describes any violations of a uniqueness constraint,
return the corresponding fields, else None
"""
pattern = r"(\w+) with this (\w+) already exists"
fields = []
if isinstance(exc, IntegrityError):
return self._detect_integrity_error(exc)
assert isinstance(exc, ValidationError), TypeError
for name, err in exc.error_dict.items():
if re.search(pattern, str(err)):
fields.append(name)
return fields or None | [
"def",
"detect_uniqueness_error",
"(",
"self",
",",
"exc",
")",
":",
"pattern",
"=",
"r\"(\\w+) with this (\\w+) already exists\"",
"fields",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"exc",
",",
"IntegrityError",
")",
":",
"return",
"self",
".",
"_detect_integrity_... | Parse error, and if it describes any violations of a uniqueness constraint,
return the corresponding fields, else None | [
"Parse",
"error",
"and",
"if",
"it",
"describes",
"any",
"violations",
"of",
"a",
"uniqueness",
"constraint",
"return",
"the",
"corresponding",
"fields",
"else",
"None"
] | 2a32aae8a7e1c11ab6e5a873bb19619c641098c8 | https://github.com/peeringdb/django-peeringdb/blob/2a32aae8a7e1c11ab6e5a873bb19619c641098c8/django_peeringdb/client_adaptor/backend.py#L173-L188 | train | 48,422 |
SuperCowPowers/chains | chains/links/tls_meta.py | TLSMeta.tls_meta_data | def tls_meta_data(self):
"""Pull out the TLS metadata for each flow in the input_stream"""
# For each flow process the contents
for flow in self.input_stream:
# Just TCP for now
if flow['protocol'] != 'TCP':
continue
# Client to Server
if flow['direction'] == 'CTS':
# Try to process the payload as a set of TLS records
try:
tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload'])
if bytes_consumed != len(flow['payload']):
logger.warning('Incomplete TLS record at the end...')
# Process the TLS records
flow['tls'] = {'type':'TLS_CTS', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception):
flow['tls'] = None
# Server to Client
else:
try:
tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload'])
if bytes_consumed != len(flow['payload']):
logger.warning('Incomplete TLS record at the end...')
# Process the TLS records
flow['tls'] = {'type':'TLS_STC', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception):
flow['tls'] = None
# All done
yield flow | python | def tls_meta_data(self):
"""Pull out the TLS metadata for each flow in the input_stream"""
# For each flow process the contents
for flow in self.input_stream:
# Just TCP for now
if flow['protocol'] != 'TCP':
continue
# Client to Server
if flow['direction'] == 'CTS':
# Try to process the payload as a set of TLS records
try:
tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload'])
if bytes_consumed != len(flow['payload']):
logger.warning('Incomplete TLS record at the end...')
# Process the TLS records
flow['tls'] = {'type':'TLS_CTS', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception):
flow['tls'] = None
# Server to Client
else:
try:
tls_records, bytes_consumed = dpkt.ssl.tls_multi_factory(flow['payload'])
if bytes_consumed != len(flow['payload']):
logger.warning('Incomplete TLS record at the end...')
# Process the TLS records
flow['tls'] = {'type':'TLS_STC', 'data':{'tls_records': tls_records, 'uri':None, 'headers':None}}
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError, dpkt.ssl.SSL3Exception):
flow['tls'] = None
# All done
yield flow | [
"def",
"tls_meta_data",
"(",
"self",
")",
":",
"# For each flow process the contents",
"for",
"flow",
"in",
"self",
".",
"input_stream",
":",
"# Just TCP for now",
"if",
"flow",
"[",
"'protocol'",
"]",
"!=",
"'TCP'",
":",
"continue",
"# Client to Server",
"if",
"f... | Pull out the TLS metadata for each flow in the input_stream | [
"Pull",
"out",
"the",
"TLS",
"metadata",
"for",
"each",
"flow",
"in",
"the",
"input_stream"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/tls_meta.py#L22-L59 | train | 48,423 |
SuperCowPowers/chains | chains/utils/data_utils.py | make_dict | def make_dict(obj):
"""This method creates a dictionary out of a non-builtin object"""
# Recursion base case
if is_builtin(obj) or isinstance(obj, OrderedDict):
return obj
output_dict = {}
for key in dir(obj):
if not key.startswith('__') and not callable(getattr(obj, key)):
attr = getattr(obj, key)
if isinstance(attr, list):
output_dict[key] = []
for item in attr:
output_dict[key].append(make_dict(item))
else:
output_dict[key] = make_dict(attr)
# All done
return output_dict | python | def make_dict(obj):
"""This method creates a dictionary out of a non-builtin object"""
# Recursion base case
if is_builtin(obj) or isinstance(obj, OrderedDict):
return obj
output_dict = {}
for key in dir(obj):
if not key.startswith('__') and not callable(getattr(obj, key)):
attr = getattr(obj, key)
if isinstance(attr, list):
output_dict[key] = []
for item in attr:
output_dict[key].append(make_dict(item))
else:
output_dict[key] = make_dict(attr)
# All done
return output_dict | [
"def",
"make_dict",
"(",
"obj",
")",
":",
"# Recursion base case",
"if",
"is_builtin",
"(",
"obj",
")",
"or",
"isinstance",
"(",
"obj",
",",
"OrderedDict",
")",
":",
"return",
"obj",
"output_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"dir",
"(",
"obj",
... | This method creates a dictionary out of a non-builtin object | [
"This",
"method",
"creates",
"a",
"dictionary",
"out",
"of",
"a",
"non",
"-",
"builtin",
"object"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/data_utils.py#L9-L28 | train | 48,424 |
SuperCowPowers/chains | chains/utils/data_utils.py | get_value | def get_value(data, key):
"""Follow the dot notation to get the proper field, then perform the action
Args:
data: the data as a dictionary (required to be a dictionary)
key: the key (as dot notation) into the data that gives the field (IP.src)
Returns:
the value of the field(subfield) if it exist, otherwise None
"""
ref = data
try:
for subkey in key.split('.'):
if isinstance(ref, dict):
ref = ref[subkey]
else:
print('CRITICAL: Cannot use subkey %s on non-dictionary element' % subkey)
return None
return ref
# In general KeyErrors are expected
except KeyError:
return None | python | def get_value(data, key):
"""Follow the dot notation to get the proper field, then perform the action
Args:
data: the data as a dictionary (required to be a dictionary)
key: the key (as dot notation) into the data that gives the field (IP.src)
Returns:
the value of the field(subfield) if it exist, otherwise None
"""
ref = data
try:
for subkey in key.split('.'):
if isinstance(ref, dict):
ref = ref[subkey]
else:
print('CRITICAL: Cannot use subkey %s on non-dictionary element' % subkey)
return None
return ref
# In general KeyErrors are expected
except KeyError:
return None | [
"def",
"get_value",
"(",
"data",
",",
"key",
")",
":",
"ref",
"=",
"data",
"try",
":",
"for",
"subkey",
"in",
"key",
".",
"split",
"(",
"'.'",
")",
":",
"if",
"isinstance",
"(",
"ref",
",",
"dict",
")",
":",
"ref",
"=",
"ref",
"[",
"subkey",
"]... | Follow the dot notation to get the proper field, then perform the action
Args:
data: the data as a dictionary (required to be a dictionary)
key: the key (as dot notation) into the data that gives the field (IP.src)
Returns:
the value of the field(subfield) if it exist, otherwise None | [
"Follow",
"the",
"dot",
"notation",
"to",
"get",
"the",
"proper",
"field",
"then",
"perform",
"the",
"action"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/data_utils.py#L33-L55 | train | 48,425 |
ajenhl/tacl | tacl/statistics_report.py | StatisticsReport.csv | def csv(self, fh):
"""Writes the report data to `fh` in CSV format and returns it.
:param fh: file to write data to
:type fh: file object
:rtype: file object
"""
self._stats.to_csv(fh, encoding='utf-8', index=False)
return fh | python | def csv(self, fh):
"""Writes the report data to `fh` in CSV format and returns it.
:param fh: file to write data to
:type fh: file object
:rtype: file object
"""
self._stats.to_csv(fh, encoding='utf-8', index=False)
return fh | [
"def",
"csv",
"(",
"self",
",",
"fh",
")",
":",
"self",
".",
"_stats",
".",
"to_csv",
"(",
"fh",
",",
"encoding",
"=",
"'utf-8'",
",",
"index",
"=",
"False",
")",
"return",
"fh"
] | Writes the report data to `fh` in CSV format and returns it.
:param fh: file to write data to
:type fh: file object
:rtype: file object | [
"Writes",
"the",
"report",
"data",
"to",
"fh",
"in",
"CSV",
"format",
"and",
"returns",
"it",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L19-L28 | train | 48,426 |
ajenhl/tacl | tacl/statistics_report.py | StatisticsReport.generate_statistics | def generate_statistics(self):
"""Replaces result rows with summary statistics about the results.
These statistics give the filename, total matching tokens,
percentage of matching tokens and label for each witness in
the results.
"""
matches = self._matches
witness_fields = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME]
witnesses = matches[witness_fields].drop_duplicates()
rows = []
for index, (work, siglum, label) in witnesses.iterrows():
witness = self._corpus.get_witness(work, siglum)
witness_matches = matches[
(matches[constants.WORK_FIELDNAME] == work) &
(matches[constants.SIGLUM_FIELDNAME] == siglum)]
total_count, matching_count = self._process_witness(
witness, witness_matches)
percentage = matching_count / total_count * 100
rows.append({constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.COUNT_TOKENS_FIELDNAME: matching_count,
constants.TOTAL_TOKENS_FIELDNAME: total_count,
constants.PERCENTAGE_FIELDNAME: percentage,
constants.LABEL_FIELDNAME: label})
self._stats = pd.DataFrame(
rows, columns=constants.STATISTICS_FIELDNAMES) | python | def generate_statistics(self):
"""Replaces result rows with summary statistics about the results.
These statistics give the filename, total matching tokens,
percentage of matching tokens and label for each witness in
the results.
"""
matches = self._matches
witness_fields = [constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME,
constants.LABEL_FIELDNAME]
witnesses = matches[witness_fields].drop_duplicates()
rows = []
for index, (work, siglum, label) in witnesses.iterrows():
witness = self._corpus.get_witness(work, siglum)
witness_matches = matches[
(matches[constants.WORK_FIELDNAME] == work) &
(matches[constants.SIGLUM_FIELDNAME] == siglum)]
total_count, matching_count = self._process_witness(
witness, witness_matches)
percentage = matching_count / total_count * 100
rows.append({constants.WORK_FIELDNAME: work,
constants.SIGLUM_FIELDNAME: siglum,
constants.COUNT_TOKENS_FIELDNAME: matching_count,
constants.TOTAL_TOKENS_FIELDNAME: total_count,
constants.PERCENTAGE_FIELDNAME: percentage,
constants.LABEL_FIELDNAME: label})
self._stats = pd.DataFrame(
rows, columns=constants.STATISTICS_FIELDNAMES) | [
"def",
"generate_statistics",
"(",
"self",
")",
":",
"matches",
"=",
"self",
".",
"_matches",
"witness_fields",
"=",
"[",
"constants",
".",
"WORK_FIELDNAME",
",",
"constants",
".",
"SIGLUM_FIELDNAME",
",",
"constants",
".",
"LABEL_FIELDNAME",
"]",
"witnesses",
"... | Replaces result rows with summary statistics about the results.
These statistics give the filename, total matching tokens,
percentage of matching tokens and label for each witness in
the results. | [
"Replaces",
"result",
"rows",
"with",
"summary",
"statistics",
"about",
"the",
"results",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L30-L58 | train | 48,427 |
ajenhl/tacl | tacl/statistics_report.py | StatisticsReport._generate_text_from_slices | def _generate_text_from_slices(self, full_text, slices):
"""Return a single string consisting of the parts specified in
`slices` joined together by the tokenizer's joining string.
:param full_text: the text to be sliced
:type full_text: `str`
:param slices: list of slice indices to apply to `full_text`
:type slices: `list` of `list`\s
:rtype: `str`
"""
sliced_text = []
for start, end in slices:
sliced_text.append(full_text[start:end])
return self._tokenizer.joiner.join(sliced_text) | python | def _generate_text_from_slices(self, full_text, slices):
"""Return a single string consisting of the parts specified in
`slices` joined together by the tokenizer's joining string.
:param full_text: the text to be sliced
:type full_text: `str`
:param slices: list of slice indices to apply to `full_text`
:type slices: `list` of `list`\s
:rtype: `str`
"""
sliced_text = []
for start, end in slices:
sliced_text.append(full_text[start:end])
return self._tokenizer.joiner.join(sliced_text) | [
"def",
"_generate_text_from_slices",
"(",
"self",
",",
"full_text",
",",
"slices",
")",
":",
"sliced_text",
"=",
"[",
"]",
"for",
"start",
",",
"end",
"in",
"slices",
":",
"sliced_text",
".",
"append",
"(",
"full_text",
"[",
"start",
":",
"end",
"]",
")"... | Return a single string consisting of the parts specified in
`slices` joined together by the tokenizer's joining string.
:param full_text: the text to be sliced
:type full_text: `str`
:param slices: list of slice indices to apply to `full_text`
:type slices: `list` of `list`\s
:rtype: `str` | [
"Return",
"a",
"single",
"string",
"consisting",
"of",
"the",
"parts",
"specified",
"in",
"slices",
"joined",
"together",
"by",
"the",
"tokenizer",
"s",
"joining",
"string",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L60-L74 | train | 48,428 |
ajenhl/tacl | tacl/statistics_report.py | StatisticsReport._merge_slices | def _merge_slices(match_slices):
"""Return a list of slice indices lists derived from `match_slices`
with no overlaps."""
# Sort by earliest range, then by largest range.
match_slices.sort(key=lambda x: (x[0], -x[1]))
merged_slices = [match_slices.pop(0)]
for slice_indices in match_slices:
last_end = merged_slices[-1][1]
if slice_indices[0] <= last_end:
if slice_indices[1] > last_end:
merged_slices[-1][1] = slice_indices[1]
else:
merged_slices.append(slice_indices)
return merged_slices | python | def _merge_slices(match_slices):
"""Return a list of slice indices lists derived from `match_slices`
with no overlaps."""
# Sort by earliest range, then by largest range.
match_slices.sort(key=lambda x: (x[0], -x[1]))
merged_slices = [match_slices.pop(0)]
for slice_indices in match_slices:
last_end = merged_slices[-1][1]
if slice_indices[0] <= last_end:
if slice_indices[1] > last_end:
merged_slices[-1][1] = slice_indices[1]
else:
merged_slices.append(slice_indices)
return merged_slices | [
"def",
"_merge_slices",
"(",
"match_slices",
")",
":",
"# Sort by earliest range, then by largest range.",
"match_slices",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
"[",
"0",
"]",
",",
"-",
"x",
"[",
"1",
"]",
")",
")",
"merged_slices",
"... | Return a list of slice indices lists derived from `match_slices`
with no overlaps. | [
"Return",
"a",
"list",
"of",
"slice",
"indices",
"lists",
"derived",
"from",
"match_slices",
"with",
"no",
"overlaps",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L77-L90 | train | 48,429 |
ajenhl/tacl | tacl/statistics_report.py | StatisticsReport._process_witness | def _process_witness(self, witness, matches):
"""Return the counts of total tokens and matching tokens in `witness`.
:param witness: witness text
:type witness: `tacl.WitnessText`
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:rtype: `tuple` of `int`
"""
# In order to provide a correct count of matched tokens,
# avoiding the twin dangers of counting the same token
# multiple times due to being part of multiple n-grams (which
# can happen even in reduced results) and not counting tokens
# due to an n-gram overlapping with itself or another n-gram,
# a bit of work is required.
#
# Using regular expressions, get the slice indices for all
# matches (including overlapping ones) for all matching
# n-grams. Merge these slices together (without overlap) and
# create a Text using that text, which can then be tokenised
# and the tokens counted.
tokens = witness.get_tokens()
full_text = witness.get_token_content()
fields = [constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME]
match_slices = []
for index, (ngram, size) in matches[fields].iterrows():
pattern = re.compile(re.escape(ngram))
# Because the same n-gram may overlap itself ("heh" in the
# string "heheh"), re.findall cannot be used.
start = 0
while True:
match = pattern.search(full_text, start)
if match is None:
break
match_slices.append([match.start(), match.end()])
start = match.start() + 1
merged_slices = self._merge_slices(match_slices)
match_content = self._generate_text_from_slices(
full_text, merged_slices)
match_text = Text(match_content, self._tokenizer)
return len(tokens), len(match_text.get_tokens()) | python | def _process_witness(self, witness, matches):
"""Return the counts of total tokens and matching tokens in `witness`.
:param witness: witness text
:type witness: `tacl.WitnessText`
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:rtype: `tuple` of `int`
"""
# In order to provide a correct count of matched tokens,
# avoiding the twin dangers of counting the same token
# multiple times due to being part of multiple n-grams (which
# can happen even in reduced results) and not counting tokens
# due to an n-gram overlapping with itself or another n-gram,
# a bit of work is required.
#
# Using regular expressions, get the slice indices for all
# matches (including overlapping ones) for all matching
# n-grams. Merge these slices together (without overlap) and
# create a Text using that text, which can then be tokenised
# and the tokens counted.
tokens = witness.get_tokens()
full_text = witness.get_token_content()
fields = [constants.NGRAM_FIELDNAME, constants.SIZE_FIELDNAME]
match_slices = []
for index, (ngram, size) in matches[fields].iterrows():
pattern = re.compile(re.escape(ngram))
# Because the same n-gram may overlap itself ("heh" in the
# string "heheh"), re.findall cannot be used.
start = 0
while True:
match = pattern.search(full_text, start)
if match is None:
break
match_slices.append([match.start(), match.end()])
start = match.start() + 1
merged_slices = self._merge_slices(match_slices)
match_content = self._generate_text_from_slices(
full_text, merged_slices)
match_text = Text(match_content, self._tokenizer)
return len(tokens), len(match_text.get_tokens()) | [
"def",
"_process_witness",
"(",
"self",
",",
"witness",
",",
"matches",
")",
":",
"# In order to provide a correct count of matched tokens,",
"# avoiding the twin dangers of counting the same token",
"# multiple times due to being part of multiple n-grams (which",
"# can happen even in red... | Return the counts of total tokens and matching tokens in `witness`.
:param witness: witness text
:type witness: `tacl.WitnessText`
:param matches: n-gram matches
:type matches: `pandas.DataFrame`
:rtype: `tuple` of `int` | [
"Return",
"the",
"counts",
"of",
"total",
"tokens",
"and",
"matching",
"tokens",
"in",
"witness",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/statistics_report.py#L92-L133 | train | 48,430 |
ajenhl/tacl | tacl/stripper.py | Stripper.get_witnesses | def get_witnesses(self, source_tree):
"""Returns a list of all witnesses of variant readings in
`source_tree` along with their XML ids.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `list` of `tuple`
"""
witnesses = []
witness_elements = source_tree.xpath(
'/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/'
'tei:listWit/tei:witness', namespaces=constants.NAMESPACES)
for witness_element in witness_elements:
witnesses.append((witness_element.text,
witness_element.get(constants.XML + 'id')))
if not witnesses:
witnesses = [(constants.BASE_WITNESS, constants.BASE_WITNESS_ID)]
return witnesses | python | def get_witnesses(self, source_tree):
"""Returns a list of all witnesses of variant readings in
`source_tree` along with their XML ids.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `list` of `tuple`
"""
witnesses = []
witness_elements = source_tree.xpath(
'/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/'
'tei:listWit/tei:witness', namespaces=constants.NAMESPACES)
for witness_element in witness_elements:
witnesses.append((witness_element.text,
witness_element.get(constants.XML + 'id')))
if not witnesses:
witnesses = [(constants.BASE_WITNESS, constants.BASE_WITNESS_ID)]
return witnesses | [
"def",
"get_witnesses",
"(",
"self",
",",
"source_tree",
")",
":",
"witnesses",
"=",
"[",
"]",
"witness_elements",
"=",
"source_tree",
".",
"xpath",
"(",
"'/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/'",
"'tei:listWit/tei:witness'",
",",
"namespaces",
"=",
"constan... | Returns a list of all witnesses of variant readings in
`source_tree` along with their XML ids.
:param source_tree: XML tree of source document
:type source_tree: `etree._ElementTree`
:rtype: `list` of `tuple` | [
"Returns",
"a",
"list",
"of",
"all",
"witnesses",
"of",
"variant",
"readings",
"in",
"source_tree",
"along",
"with",
"their",
"XML",
"ids",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/stripper.py#L31-L49 | train | 48,431 |
SuperCowPowers/chains | examples/tag_example.py | run | def run(iface_name=None, bpf=None, summary=None, max_packets=50):
"""Run the Simple Packet Printer Example"""
# Create the classes
streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets)
meta = packet_meta.PacketMeta()
rdns = reverse_dns.ReverseDNS()
tags = packet_tags.PacketTags()
tmeta = transport_meta.TransportMeta()
printer = packet_summary.PacketSummary()
# Set up the chain
meta.link(streamer)
rdns.link(meta)
tags.link(rdns)
tmeta.link(tags)
printer.link(tmeta)
# Pull the chain
printer.pull() | python | def run(iface_name=None, bpf=None, summary=None, max_packets=50):
"""Run the Simple Packet Printer Example"""
# Create the classes
streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets)
meta = packet_meta.PacketMeta()
rdns = reverse_dns.ReverseDNS()
tags = packet_tags.PacketTags()
tmeta = transport_meta.TransportMeta()
printer = packet_summary.PacketSummary()
# Set up the chain
meta.link(streamer)
rdns.link(meta)
tags.link(rdns)
tmeta.link(tags)
printer.link(tmeta)
# Pull the chain
printer.pull() | [
"def",
"run",
"(",
"iface_name",
"=",
"None",
",",
"bpf",
"=",
"None",
",",
"summary",
"=",
"None",
",",
"max_packets",
"=",
"50",
")",
":",
"# Create the classes",
"streamer",
"=",
"packet_streamer",
".",
"PacketStreamer",
"(",
"iface_name",
"=",
"iface_nam... | Run the Simple Packet Printer Example | [
"Run",
"the",
"Simple",
"Packet",
"Printer",
"Example"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/examples/tag_example.py#L10-L29 | train | 48,432 |
ajenhl/tacl | tacl/lifetime_report.py | LifetimeReport.generate | def generate(self, output_dir, catalogue, results, label):
"""Generates the report, writing it to `output_dir`."""
data = results.get_raw_data()
labels = catalogue.ordered_labels
ngrams = self._generate_results(output_dir, labels, data)
ngram_table = self._generate_ngram_table(output_dir, labels, data)
corpus_table = self._generate_corpus_table(labels, ngrams)
context = {'corpus_table': corpus_table, 'focus_label': label,
'labels': labels, 'ngram_table': ngram_table, 'sep': os.sep}
report_name = 'lifetime-{}.html'.format(label)
self._write(context, output_dir, report_name) | python | def generate(self, output_dir, catalogue, results, label):
"""Generates the report, writing it to `output_dir`."""
data = results.get_raw_data()
labels = catalogue.ordered_labels
ngrams = self._generate_results(output_dir, labels, data)
ngram_table = self._generate_ngram_table(output_dir, labels, data)
corpus_table = self._generate_corpus_table(labels, ngrams)
context = {'corpus_table': corpus_table, 'focus_label': label,
'labels': labels, 'ngram_table': ngram_table, 'sep': os.sep}
report_name = 'lifetime-{}.html'.format(label)
self._write(context, output_dir, report_name) | [
"def",
"generate",
"(",
"self",
",",
"output_dir",
",",
"catalogue",
",",
"results",
",",
"label",
")",
":",
"data",
"=",
"results",
".",
"get_raw_data",
"(",
")",
"labels",
"=",
"catalogue",
".",
"ordered_labels",
"ngrams",
"=",
"self",
".",
"_generate_re... | Generates the report, writing it to `output_dir`. | [
"Generates",
"the",
"report",
"writing",
"it",
"to",
"output_dir",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L30-L40 | train | 48,433 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L42-L47 | train | 48,434 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L49-L58 | train | 48,435 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L60-L65 | train | 48,436 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L67-L103 | train | 48,437 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L105-L112 | train | 48,438 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L114-L134 | train | 48,439 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/lifetime_report.py#L136-L154 | train | 48,440 |
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"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/link.py#L18-L25 | train | 48,441 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L15-L26 | train | 48,442 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L28-L36 | train | 48,443 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L60-L79 | train | 48,444 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L81-L103 | train | 48,445 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L105-L120 | train | 48,446 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/catalogue.py#L122-L132 | train | 48,447 |
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"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/dns_meta.py#L128-L176 | train | 48,448 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L24-L33 | train | 48,449 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L35-L55 | train | 48,450 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L57-L68 | train | 48,451 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/corpus.py#L70-L78 | train | 48,452 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/decorators.py#L7-L30 | train | 48,453 |
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",
"."
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/reverse_dns.py#L26-L68 | train | 48,454 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/colour.py#L40-L61 | train | 48,455 |
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"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L29-L47 | train | 48,456 |
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"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/packet_tags.py#L50-L64 | train | 48,457 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L141-L145 | train | 48,458 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L147-L168 | train | 48,459 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L220-L238 | train | 48,460 |
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"
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L258-L279 | train | 48,461 |
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",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L281-L295 | train | 48,462 |
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"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L48-L96 | train | 48,463 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L79-L89 | train | 48,464 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L134-L143 | train | 48,465 |
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",
".... | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L168-L175 | train | 48,466 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/asttokens.py#L177-L182 | train | 48,467 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L35-L48 | train | 48,468 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/line_numbers.py#L50-L60 | train | 48,469 |
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",
"."
] | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L45-L47 | train | 48,470 |
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",
"... | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L50-L58 | train | 48,471 |
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... | c8697dcf799a63d432727abb1d972adb3e85970a | https://github.com/gristlabs/asttokens/blob/c8697dcf799a63d432727abb1d972adb3e85970a/asttokens/util.py#L144-L185 | train | 48,472 |
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",
"."
] | b64fef7ec196bfed69362aa35c593f448830a735 | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L40-L57 | train | 48,473 |
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",
"."
] | b64fef7ec196bfed69362aa35c593f448830a735 | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L59-L77 | train | 48,474 |
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",
"."
] | b64fef7ec196bfed69362aa35c593f448830a735 | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L118-L135 | train | 48,475 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L27-L34 | train | 48,476 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L37-L47 | train | 48,477 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/entry.py#L50-L54 | train | 48,478 |
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"
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L16-L22 | train | 48,479 |
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"
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/client.py#L41-L56 | train | 48,480 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L49-L60 | train | 48,481 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/item.py#L63-L65 | train | 48,482 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L19-L23 | train | 48,483 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/record.py#L26-L36 | train | 48,484 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L43-L48 | train | 48,485 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L51-L59 | train | 48,486 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/tsv.py#L66-L71 | train | 48,487 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L14-L40 | train | 48,488 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/csv.py#L70-L79 | train | 48,489 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/datatypes/digest.py#L5-L8 | train | 48,490 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L17-L23 | train | 48,491 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/json.py#L26-L37 | train | 48,492 |
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",
"."
] | cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4 | https://github.com/openregister/openregister-python/blob/cdb3ed9b454ff42cffdff4f25f7dbf8c22c517e4/openregister/representations/jsonl.py#L8-L13 | train | 48,493 |
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",
"."
] | ee4b044d6aafa80125730a00b1f679a7bd852b8a | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L25-L34 | train | 48,494 |
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",
"."
] | ee4b044d6aafa80125730a00b1f679a7bd852b8a | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tag_set.py#L52-L65 | train | 48,495 |
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",
"."
] | 59ee171ad4f9809f62a822964b5c68e5be672dd8 | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L38-L54 | train | 48,496 |
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",
"."
] | 59ee171ad4f9809f62a822964b5c68e5be672dd8 | https://github.com/inveniosoftware/invenio-logging/blob/59ee171ad4f9809f62a822964b5c68e5be672dd8/invenio_logging/fs.py#L56-L83 | train | 48,497 |
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",
"."
] | ee4b044d6aafa80125730a00b1f679a7bd852b8a | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L153-L179 | train | 48,498 |
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",
"."
] | ee4b044d6aafa80125730a00b1f679a7bd852b8a | https://github.com/sdispater/cachy/blob/ee4b044d6aafa80125730a00b1f679a7bd852b8a/cachy/tagged_cache.py#L181-L204 | train | 48,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.