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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
dr-leo/pandaSDMX | pandasdmx/reader/sdmxjson.py | Reader.write_source | def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | python | def write_source(self, filename):
'''
Save source to file by calling `write` on the root element.
'''
with open(filename, 'w') as fp:
return json.dump(self.message._elem, fp, indent=4, sort_keys=True) | [
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"return",
"json",
".",
"dump",
"(",
"self",
".",
"message",
".",
"_elem",
",",
"fp",
",",
"indent",
"=",
"4",
",",
"... | Save source to file by calling `write` on the root element. | [
"Save",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
] | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxjson.py#L86-L91 | train |
dr-leo/pandaSDMX | pandasdmx/reader/sdmxml.py | Reader.write_source | def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8') | python | def write_source(self, filename):
'''
Save XML source to file by calling `write` on the root element.
'''
return self.message._elem.getroottree().write(filename, encoding='utf8') | [
"def",
"write_source",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"message",
".",
"_elem",
".",
"getroottree",
"(",
")",
".",
"write",
"(",
"filename",
",",
"encoding",
"=",
"'utf8'",
")"
] | Save XML source to file by calling `write` on the root element. | [
"Save",
"XML",
"source",
"to",
"file",
"by",
"calling",
"write",
"on",
"the",
"root",
"element",
"."
] | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/sdmxml.py#L52-L56 | train |
dr-leo/pandaSDMX | pandasdmx/model.py | Series.group_attrib | def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if ... | python | def group_attrib(self):
'''
return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member
'''
group_attributes = [g.attrib for g in self.dataset.groups if self in g]
if ... | [
"def",
"group_attrib",
"(",
"self",
")",
":",
"group_attributes",
"=",
"[",
"g",
".",
"attrib",
"for",
"g",
"in",
"self",
".",
"dataset",
".",
"groups",
"if",
"self",
"in",
"g",
"]",
"if",
"group_attributes",
":",
"return",
"concat_namedtuples",
"(",
"*"... | return a namedtuple containing all attributes attached
to groups of which the given series is a member
for each group of which the series is a member | [
"return",
"a",
"namedtuple",
"containing",
"all",
"attributes",
"attached",
"to",
"groups",
"of",
"which",
"the",
"given",
"series",
"is",
"a",
"member",
"for",
"each",
"group",
"of",
"which",
"the",
"series",
"is",
"a",
"member"
] | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/model.py#L632-L640 | train |
dr-leo/pandaSDMX | pandasdmx/reader/__init__.py | BaseReader.read_instance | def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return... | python | def read_instance(self, cls, sdmxobj, offset=None, first_only=True):
'''
If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return... | [
"def",
"read_instance",
"(",
"self",
",",
"cls",
",",
"sdmxobj",
",",
"offset",
"=",
"None",
",",
"first_only",
"=",
"True",
")",
":",
"if",
"offset",
":",
"try",
":",
"base",
"=",
"self",
".",
"_paths",
"[",
"offset",
"]",
"(",
"sdmxobj",
".",
"_e... | If cls in _paths and matches,
return an instance of cls with the first XML element,
or, if first_only is False, a list of cls instances
for all elements found,
If no matches were found, return None. | [
"If",
"cls",
"in",
"_paths",
"and",
"matches",
"return",
"an",
"instance",
"of",
"cls",
"with",
"the",
"first",
"XML",
"element",
"or",
"if",
"first_only",
"is",
"False",
"a",
"list",
"of",
"cls",
"instances",
"for",
"all",
"elements",
"found",
"If",
"no... | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/__init__.py#L54-L74 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.load_agency_profile | def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated w... | python | def load_agency_profile(cls, source):
'''
Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated w... | [
"def",
"load_agency_profile",
"(",
"cls",
",",
"source",
")",
":",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str_type",
")",
":",
"# so it must be a text file",
"source",
"=",
"source",
".",
"read",
"(",
")",
"new_agencies",
"=",
"json",
".",
"loads",
... | Classmethod loading metadata on a data provider. ``source`` must
be a json-formated string or file-like object describing one or more data providers
(URL of the SDMX web API, resource types etc.
The dict ``Request._agencies`` is updated with the metadata from the
source.
Returns... | [
"Classmethod",
"loading",
"metadata",
"on",
"a",
"data",
"provider",
".",
"source",
"must",
"be",
"a",
"json",
"-",
"formated",
"string",
"or",
"file",
"-",
"like",
"object",
"describing",
"one",
"or",
"more",
"data",
"providers",
"(",
"URL",
"of",
"the",
... | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L63-L77 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.series_keys | def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series ke... | python | def series_keys(self, flow_id, cache=True):
'''
Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow.
'''
# Check if requested series ke... | [
"def",
"series_keys",
"(",
"self",
",",
"flow_id",
",",
"cache",
"=",
"True",
")",
":",
"# Check if requested series keys are already cached",
"cache_id",
"=",
"'series_keys_'",
"+",
"flow_id",
"if",
"cache_id",
"in",
"self",
".",
"cache",
":",
"return",
"self",
... | Get an empty dataset with all possible series keys.
Return a pandas DataFrame. Each
column represents a dimension, each row
a series key of datasets of
the given dataflow. | [
"Get",
"an",
"empty",
"dataset",
"with",
"all",
"possible",
"series",
"keys",
"."
] | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L150-L170 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Request.preview_data | def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. Th... | python | def preview_data(self, flow_id, key=None, count=True, total=True):
'''
Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. Th... | [
"def",
"preview_data",
"(",
"self",
",",
"flow_id",
",",
"key",
"=",
"None",
",",
"count",
"=",
"True",
",",
"total",
"=",
"True",
")",
":",
"all_keys",
"=",
"self",
".",
"series_keys",
"(",
"flow_id",
")",
"# Handle the special case that no key is provided",
... | Get keys or number of series for a prospective dataset query allowing for
keys with multiple values per dimension.
It downloads the complete list of series keys for a dataflow rather than using constraints and DSD. This feature is,
however, not supported by all data providers.
ECB and UN... | [
"Get",
"keys",
"or",
"number",
"of",
"series",
"for",
"a",
"prospective",
"dataset",
"query",
"allowing",
"for",
"keys",
"with",
"multiple",
"values",
"per",
"dimension",
".",
"It",
"downloads",
"the",
"complete",
"list",
"of",
"series",
"keys",
"for",
"a",
... | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L495-L564 | train |
dr-leo/pandaSDMX | pandasdmx/api.py | Response.write | def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to... | python | def write(self, source=None, **kwargs):
'''Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to... | [
"def",
"write",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"source",
":",
"source",
"=",
"self",
".",
"msg",
"return",
"self",
".",
"_writer",
".",
"write",
"(",
"source",
"=",
"source",
",",
"*",
"*"... | Wrappe r to call the writer's write method if present.
Args:
source(pandasdmx.model.Message, iterable): stuff to be written.
If a :class:`pandasdmx.model.Message` is given, the writer
itself must determine what to write unless specified in the
keyw... | [
"Wrappe",
"r",
"to",
"call",
"the",
"writer",
"s",
"write",
"method",
"if",
"present",
"."
] | 71dd81ebb0d5169e5adcb8b52d516573d193f2d6 | https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/api.py#L618-L635 | train |
dropbox/pyannotate | pyannotate_tools/annotations/parse.py | parse_json | def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type... | python | def parse_json(path):
# type: (str) -> List[FunctionInfo]
"""Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items.
"""
with open(path) as f:
data = json.load(f) # type: List[RawEntry]
result = []
def assert_type... | [
"def",
"parse_json",
"(",
"path",
")",
":",
"# type: (str) -> List[FunctionInfo]",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"# type: List[RawEntry]",
"result",
"=",
"[",
"]",
"def",
"assert_type",
"... | Deserialize a JSON file containing runtime collected types.
The input JSON is expected to to have a list of RawEntry items. | [
"Deserialize",
"a",
"JSON",
"file",
"containing",
"runtime",
"collected",
"types",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L96-L133 | train |
dropbox/pyannotate | pyannotate_tools/annotations/parse.py | tokenize | def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0]... | python | def tokenize(s):
# type: (str) -> List[Token]
"""Translate a type comment into a list of tokens."""
original = s
tokens = [] # type: List[Token]
while True:
if not s:
tokens.append(End())
return tokens
elif s[0] == ' ':
s = s[1:]
elif s[0]... | [
"def",
"tokenize",
"(",
"s",
")",
":",
"# type: (str) -> List[Token]",
"original",
"=",
"s",
"tokens",
"=",
"[",
"]",
"# type: List[Token]",
"while",
"True",
":",
"if",
"not",
"s",
":",
"tokens",
".",
"append",
"(",
"End",
"(",
")",
")",
"return",
"token... | Translate a type comment into a list of tokens. | [
"Translate",
"a",
"type",
"comment",
"into",
"a",
"list",
"of",
"tokens",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/parse.py#L173-L210 | train |
dropbox/pyannotate | pyannotate_tools/annotations/main.py | generate_annotations_json_string | def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The ... | python | def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The ... | [
"def",
"generate_annotations_json_string",
"(",
"source_path",
",",
"only_simple",
"=",
"False",
")",
":",
"# type: (str, bool) -> List[FunctionData]",
"items",
"=",
"parse_json",
"(",
"source_path",
")",
"results",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
... | Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items. | [
"Produce",
"annotation",
"data",
"JSON",
"file",
"from",
"a",
"JSON",
"file",
"with",
"runtime",
"-",
"collected",
"types",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/main.py#L48-L70 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _my_hash | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res | python | def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res | [
"def",
"_my_hash",
"(",
"arg_list",
")",
":",
"# type: (List[Any]) -> int",
"res",
"=",
"0",
"for",
"arg",
"in",
"arg_list",
":",
"res",
"=",
"res",
"*",
"31",
"+",
"hash",
"(",
"arg",
")",
"return",
"res"
] | Simple helper hash function | [
"Simple",
"helper",
"hash",
"function"
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L69-L75 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | name_from_type | def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'Non... | python | def name_from_type(type_):
# type: (InternalType) -> str
"""
Helper function to get PEP-484 compatible string representation of our internal types.
"""
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):
return repr(type_)
else:
if type_.__name__ != 'Non... | [
"def",
"name_from_type",
"(",
"type_",
")",
":",
"# type: (InternalType) -> str",
"if",
"isinstance",
"(",
"type_",
",",
"(",
"DictType",
",",
"ListType",
",",
"TupleType",
",",
"SetType",
",",
"IteratorType",
")",
")",
":",
"return",
"repr",
"(",
"type_",
"... | Helper function to get PEP-484 compatible string representation of our internal types. | [
"Helper",
"function",
"to",
"get",
"PEP",
"-",
"484",
"compatible",
"string",
"representation",
"of",
"our",
"internal",
"types",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L417-L437 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | resolve_type | def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure... | python | def resolve_type(arg):
# type: (object) -> InternalType
"""
Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve
"""
arg_type = type(arg)
if arg_type == list:
assert isinstance(arg, list) # this line helps mypy figure... | [
"def",
"resolve_type",
"(",
"arg",
")",
":",
"# type: (object) -> InternalType",
"arg_type",
"=",
"type",
"(",
"arg",
")",
"if",
"arg_type",
"==",
"list",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"list",
")",
"# this line helps mypy figure out types",
"sample... | Resolve object to one of our internal collection types or generic built-in type.
Args:
arg: object to resolve | [
"Resolve",
"object",
"to",
"one",
"of",
"our",
"internal",
"collection",
"types",
"or",
"generic",
"built",
"-",
"in",
"type",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L498-L549 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | prep_args | def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's ... | python | def prep_args(arg_info):
# type: (ArgInfo) -> ResolvedTypes
"""
Resolve types from ArgInfo
"""
# pull out any varargs declarations
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
# we don't care about self/cls first params (perhaps we can test if it's ... | [
"def",
"prep_args",
"(",
"arg_info",
")",
":",
"# type: (ArgInfo) -> ResolvedTypes",
"# pull out any varargs declarations",
"filtered_args",
"=",
"[",
"a",
"for",
"a",
"in",
"arg_info",
".",
"args",
"if",
"getattr",
"(",
"arg_info",
",",
"'varargs'",
",",
"None",
... | Resolve types from ArgInfo | [
"Resolve",
"types",
"from",
"ArgInfo"
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L552-L583 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _flush_signature | def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side... | python | def _flush_signature(key, return_type):
# type: (FunctionKey, InternalType) -> None
"""Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side... | [
"def",
"_flush_signature",
"(",
"key",
",",
"return_type",
")",
":",
"# type: (FunctionKey, InternalType) -> None",
"signatures",
"=",
"collected_signatures",
".",
"setdefault",
"(",
"key",
",",
"set",
"(",
")",
")",
"args_info",
"=",
"collected_args",
".",
"pop",
... | Store signature for a function.
Assume that argument types have been stored previously to
'collected_args'. As the 'return_type' argument provides the return
type, we now have a complete signature.
As a side effect, removes the argument types for the function from
'collected_args'. | [
"Store",
"signature",
"for",
"a",
"function",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L656-L671 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | type_consumer | def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
... | python | def type_consumer():
# type: () -> None
"""
Infinite loop of the type consumer thread.
It gets types to process from the task query.
"""
# we are not interested in profiling type_consumer itself
# but we start it before any other thread
while True:
item = _task_queue.get()
... | [
"def",
"type_consumer",
"(",
")",
":",
"# type: () -> None",
"# we are not interested in profiling type_consumer itself",
"# but we start it before any other thread",
"while",
"True",
":",
"item",
"=",
"_task_queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"item",
... | Infinite loop of the type consumer thread.
It gets types to process from the task query. | [
"Infinite",
"loop",
"of",
"the",
"type",
"consumer",
"thread",
".",
"It",
"gets",
"types",
"to",
"process",
"from",
"the",
"task",
"query",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L674-L696 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _make_sampling_sequence | def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
s... | python | def _make_sampling_sequence(n):
# type: (int) -> List[int]
"""
Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n.
"""
s... | [
"def",
"_make_sampling_sequence",
"(",
"n",
")",
":",
"# type: (int) -> List[int]",
"seq",
"=",
"list",
"(",
"range",
"(",
"5",
")",
")",
"i",
"=",
"50",
"while",
"len",
"(",
"seq",
")",
"<",
"n",
":",
"seq",
".",
"append",
"(",
"i",
")",
"i",
"+="... | Return a list containing the proposed call event sampling sequence.
Return events are paired with call events and not counted separately.
This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc.
The total list size is n. | [
"Return",
"a",
"list",
"containing",
"the",
"proposed",
"call",
"event",
"sampling",
"sequence",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L711-L727 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | default_filter_filename | def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_D... | python | def default_filter_filename(filename):
# type: (Optional[str]) -> Optional[str]
"""Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection().
"""
if filename is None:
return None
elif filename.startswith(TOP_D... | [
"def",
"default_filter_filename",
"(",
"filename",
")",
":",
"# type: (Optional[str]) -> Optional[str]",
"if",
"filename",
"is",
"None",
":",
"return",
"None",
"elif",
"filename",
".",
"startswith",
"(",
"TOP_DIR",
")",
":",
"if",
"filename",
".",
"startswith",
"(... | Default filter for filenames.
Returns either a normalized filename or None.
You can pass your own filter to init_types_collection(). | [
"Default",
"filter",
"for",
"filenames",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L787-L807 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _filter_types | def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v... | python | def _filter_types(types_dict):
# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]
"""Filter type info before dumping it to the file."""
def exclude(k):
# type: (FunctionKey) -> bool
"""Exclude filter"""
return k.path.startswith('<') or k.func_name == '<module>'
return {k: v... | [
"def",
"_filter_types",
"(",
"types_dict",
")",
":",
"# type: (Dict[FunctionKey, T]) -> Dict[FunctionKey, T]",
"def",
"exclude",
"(",
"k",
")",
":",
"# type: (FunctionKey) -> bool",
"\"\"\"Exclude filter\"\"\"",
"return",
"k",
".",
"path",
".",
"startswith",
"(",
"'<'",
... | Filter type info before dumping it to the file. | [
"Filter",
"type",
"info",
"before",
"dumping",
"it",
"to",
"the",
"file",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L909-L918 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | _dump_impl | def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_na... | python | def _dump_impl():
# type: () -> List[FunctionData]
"""Internal implementation for dump_stats and dumps_stats"""
filtered_signatures = _filter_types(collected_signatures)
sorted_by_file = sorted(iteritems(filtered_signatures),
key=(lambda p: (p[0].path, p[0].line, p[0].func_na... | [
"def",
"_dump_impl",
"(",
")",
":",
"# type: () -> List[FunctionData]",
"filtered_signatures",
"=",
"_filter_types",
"(",
"collected_signatures",
")",
"sorted_by_file",
"=",
"sorted",
"(",
"iteritems",
"(",
"filtered_signatures",
")",
",",
"key",
"=",
"(",
"lambda",
... | Internal implementation for dump_stats and dumps_stats | [
"Internal",
"implementation",
"for",
"dump_stats",
"and",
"dumps_stats"
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L921-L939 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | dump_stats | def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close() | python | def dump_stats(filename):
# type: (str) -> None
"""
Write collected information to file.
Args:
filename: absolute filename
"""
res = _dump_impl()
f = open(filename, 'w')
json.dump(res, f, indent=4)
f.close() | [
"def",
"dump_stats",
"(",
"filename",
")",
":",
"# type: (str) -> None",
"res",
"=",
"_dump_impl",
"(",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"json",
".",
"dump",
"(",
"res",
",",
"f",
",",
"indent",
"=",
"4",
")",
"f",
".",
"clo... | Write collected information to file.
Args:
filename: absolute filename | [
"Write",
"collected",
"information",
"to",
"file",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L942-L953 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | init_types_collection | def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filena... | python | def init_types_collection(filter_filename=default_filter_filename):
# type: (Callable[[Optional[str]], Optional[str]]) -> None
"""
Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filena... | [
"def",
"init_types_collection",
"(",
"filter_filename",
"=",
"default_filter_filename",
")",
":",
"# type: (Callable[[Optional[str]], Optional[str]]) -> None",
"global",
"_filter_filename",
"_filter_filename",
"=",
"filter_filename",
"sys",
".",
"setprofile",
"(",
"_trace_dispatc... | Setup profiler hooks to enable type collection.
Call this one time from the main thread.
The optional argument is a filter that maps a filename (from
code.co_filename) to either a normalized filename or None.
For the default filter see default_filter_filename(). | [
"Setup",
"profiler",
"hooks",
"to",
"enable",
"type",
"collection",
".",
"Call",
"this",
"one",
"time",
"from",
"the",
"main",
"thread",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L965-L978 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | TentativeType.add | def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
el... | python | def add(self, type):
# type: (InternalType) -> None
"""
Add type to the runtime type samples.
"""
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
el... | [
"def",
"add",
"(",
"self",
",",
"type",
")",
":",
"# type: (InternalType) -> None",
"try",
":",
"if",
"isinstance",
"(",
"type",
",",
"SetType",
")",
":",
"if",
"EMPTY_SET_TYPE",
"in",
"self",
".",
"types_hashable",
":",
"self",
".",
"types_hashable",
".",
... | Add type to the runtime type samples. | [
"Add",
"type",
"to",
"the",
"runtime",
"type",
"samples",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L336-L367 | train |
dropbox/pyannotate | pyannotate_runtime/collect_types.py | TentativeType.merge | def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | python | def merge(self, other):
# type: (TentativeType) -> None
"""
Merge two TentativeType instances
"""
for hashables in other.types_hashable:
self.add(hashables)
for non_hashbles in other.types:
self.add(non_hashbles) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"# type: (TentativeType) -> None",
"for",
"hashables",
"in",
"other",
".",
"types_hashable",
":",
"self",
".",
"add",
"(",
"hashables",
")",
"for",
"non_hashbles",
"in",
"other",
".",
"types",
":",
"self",... | Merge two TentativeType instances | [
"Merge",
"two",
"TentativeType",
"instances"
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_runtime/collect_types.py#L369-L377 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | infer_annotation | def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
... | python | def infer_annotation(type_comments):
# type: (List[str]) -> Tuple[List[Argument], AbstractType]
"""Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type).
"""
... | [
"def",
"infer_annotation",
"(",
"type_comments",
")",
":",
"# type: (List[str]) -> Tuple[List[Argument], AbstractType]",
"assert",
"type_comments",
"args",
"=",
"{",
"}",
"# type: Dict[int, Set[Argument]]",
"returns",
"=",
"set",
"(",
")",
"for",
"comment",
"in",
"type_co... | Given some type comments, return a single inferred signature.
Args:
type_comments: Strings of form '(arg1, ... argN) -> ret'
Returns: Tuple of (argument types and kinds, return type). | [
"Given",
"some",
"type",
"comments",
"return",
"a",
"single",
"inferred",
"signature",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L32-L66 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | argument_kind | def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
r... | python | def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
r... | [
"def",
"argument_kind",
"(",
"args",
")",
":",
"# type: (List[Argument]) -> Optional[str]",
"kinds",
"=",
"set",
"(",
"arg",
".",
"kind",
"for",
"arg",
"in",
"args",
")",
"if",
"len",
"(",
"kinds",
")",
"!=",
"1",
":",
"return",
"None",
"return",
"kinds",
... | Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind. | [
"Return",
"the",
"kind",
"of",
"an",
"argument",
"based",
"on",
"one",
"or",
"more",
"descriptions",
"of",
"the",
"argument",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L69-L78 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | combine_types | def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if... | python | def combine_types(types):
# type: (Iterable[AbstractType]) -> AbstractType
"""Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'.
"""
items = simplify_types(types)
if... | [
"def",
"combine_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> AbstractType",
"items",
"=",
"simplify_types",
"(",
"types",
")",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"return",
"items",
"[",
"0",
"]",
"else",
":",
"return",
"U... | Given some types, return a combined and simplified type.
For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given
'int' and 'int', return just 'int'. | [
"Given",
"some",
"types",
"return",
"a",
"combined",
"and",
"simplified",
"type",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L81-L92 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | simplify_types | def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = m... | python | def simplify_types(types):
# type: (Iterable[AbstractType]) -> List[AbstractType]
"""Given some types, give simplified types representing the union of types."""
flattened = flatten_types(types)
items = filter_ignored_items(flattened)
items = [simplify_recursive(item) for item in items]
items = m... | [
"def",
"simplify_types",
"(",
"types",
")",
":",
"# type: (Iterable[AbstractType]) -> List[AbstractType]",
"flattened",
"=",
"flatten_types",
"(",
"types",
")",
"items",
"=",
"filter_ignored_items",
"(",
"flattened",
")",
"items",
"=",
"[",
"simplify_recursive",
"(",
... | Given some types, give simplified types representing the union of types. | [
"Given",
"some",
"types",
"give",
"simplified",
"types",
"representing",
"the",
"union",
"of",
"types",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L95-L109 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | simplify_recursive | def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
... | python | def simplify_recursive(typ):
# type: (AbstractType) -> AbstractType
"""Simplify all components of a type."""
if isinstance(typ, UnionType):
return combine_types(typ.items)
elif isinstance(typ, ClassType):
simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
... | [
"def",
"simplify_recursive",
"(",
"typ",
")",
":",
"# type: (AbstractType) -> AbstractType",
"if",
"isinstance",
"(",
"typ",
",",
"UnionType",
")",
":",
"return",
"combine_types",
"(",
"typ",
".",
"items",
")",
"elif",
"isinstance",
"(",
"typ",
",",
"ClassType",... | Simplify all components of a type. | [
"Simplify",
"all",
"components",
"of",
"a",
"type",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L112-L128 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | remove_redundant_items | def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
... | python | def remove_redundant_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Filter out redundant union items."""
result = []
for item in items:
for other in items:
if item is not other and is_redundant_union_item(item, other):
break
else:
... | [
"def",
"remove_redundant_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"for",
"other",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"other",
"and",
"is_redundan... | Filter out redundant union items. | [
"Filter",
"out",
"redundant",
"union",
"items",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L153-L163 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | is_redundant_union_item | def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinsta... | python | def is_redundant_union_item(first, other):
# type: (AbstractType, AbstractType) -> bool
"""If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False.
"""
if isinstance(first, ClassType) and isinsta... | [
"def",
"is_redundant_union_item",
"(",
"first",
",",
"other",
")",
":",
"# type: (AbstractType, AbstractType) -> bool",
"if",
"isinstance",
"(",
"first",
",",
"ClassType",
")",
"and",
"isinstance",
"(",
"other",
",",
"ClassType",
")",
":",
"if",
"first",
".",
"n... | If union has both items, is the first one redundant?
For example, if first is 'str' and the other is 'Text', return True.
If items are equal, return False. | [
"If",
"union",
"has",
"both",
"items",
"is",
"the",
"first",
"one",
"redundant?"
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L166-L191 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | merge_items | def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
... | python | def merge_items(items):
# type: (List[AbstractType]) -> List[AbstractType]
"""Merge union items that can be merged."""
result = []
while items:
item = items.pop()
merged = None
for i, other in enumerate(items):
merged = merged_type(item, other)
if merged:
... | [
"def",
"merge_items",
"(",
"items",
")",
":",
"# type: (List[AbstractType]) -> List[AbstractType]",
"result",
"=",
"[",
"]",
"while",
"items",
":",
"item",
"=",
"items",
".",
"pop",
"(",
")",
"merged",
"=",
"None",
"for",
"i",
",",
"other",
"in",
"enumerate"... | Merge union items that can be merged. | [
"Merge",
"union",
"items",
"that",
"can",
"be",
"merged",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L194-L210 | train |
dropbox/pyannotate | pyannotate_tools/annotations/infer.py | merged_type | def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) ... | python | def merged_type(t, s):
# type: (AbstractType, AbstractType) -> Optional[AbstractType]
"""Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible.
"""
if isinstance(t, TupleType) and isinstance(s, TupleType):
if len(t.items) ... | [
"def",
"merged_type",
"(",
"t",
",",
"s",
")",
":",
"# type: (AbstractType, AbstractType) -> Optional[AbstractType]",
"if",
"isinstance",
"(",
"t",
",",
"TupleType",
")",
"and",
"isinstance",
"(",
"s",
",",
"TupleType",
")",
":",
"if",
"len",
"(",
"t",
".",
... | Return merged type if two items can be merged in to a different, more general type.
Return None if merging is not possible. | [
"Return",
"merged",
"type",
"if",
"two",
"items",
"can",
"be",
"merged",
"in",
"to",
"a",
"different",
"more",
"general",
"type",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/infer.py#L213-L243 | train |
dropbox/pyannotate | pyannotate_tools/annotations/__main__.py | dump_annotations | def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
... | python | def dump_annotations(type_info, files):
"""Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path.
"""
with open(type_info) as f:
... | [
"def",
"dump_annotations",
"(",
"type_info",
",",
"files",
")",
":",
"with",
"open",
"(",
"type_info",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"for",
"item",
"in",
"data",
":",
"path",
",",
"line",
",",
"func_name",
"=... | Dump annotations out of type_info, filtered by files.
If files is non-empty, only dump items either if the path in the
item matches one of the files exactly, or else if one of the files
is a path prefix of the path. | [
"Dump",
"annotations",
"out",
"of",
"type_info",
"filtered",
"by",
"files",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/annotations/__main__.py#L60-L82 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate_json.py | strip_py | def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None | python | def strip_py(arg):
# type: (str) -> Optional[str]
"""Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found.
"""
for ext in PY_EXTENSIONS:
if arg.endswith(ext):
return arg[:-len(ext)]
return None | [
"def",
"strip_py",
"(",
"arg",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"ext",
"in",
"PY_EXTENSIONS",
":",
"if",
"arg",
".",
"endswith",
"(",
"ext",
")",
":",
"return",
"arg",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"]",
"return",
"None"
] | Strip a trailing .py or .pyi suffix.
Return None if no such suffix is found. | [
"Strip",
"a",
"trailing",
".",
"py",
"or",
".",
"pyi",
"suffix",
".",
"Return",
"None",
"if",
"no",
"such",
"suffix",
"is",
"found",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate_json.py#L61-L69 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate.py | FixAnnotate.get_decorators | def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
... | python | def get_decorators(self, node):
"""Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return [].
"""
... | [
"def",
"get_decorators",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"parent",
"is",
"None",
":",
"return",
"[",
"]",
"results",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"decorated",
".",
"match",
"(",
"node",
".",
"parent",
",",
"result... | Return a list of decorators found on a function definition.
This is a list of strings; only simple decorators
(e.g. @staticmethod) are returned.
If the function is undecorated or only non-simple decorators
are found, return []. | [
"Return",
"a",
"list",
"of",
"decorators",
"found",
"on",
"a",
"function",
"definition",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L418-L438 | train |
dropbox/pyannotate | pyannotate_tools/fixes/fix_annotate.py | FixAnnotate.has_return_exprs | def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, result... | python | def has_return_exprs(self, node):
"""Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.)
"""
results = {}
if self.return_expr.match(node, result... | [
"def",
"has_return_exprs",
"(",
"self",
",",
"node",
")",
":",
"results",
"=",
"{",
"}",
"if",
"self",
".",
"return_expr",
".",
"match",
"(",
"node",
",",
"results",
")",
":",
"return",
"True",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if"... | Traverse the tree below node looking for 'return expr'.
Return True if at least 'return expr' is found, False if not.
(If both 'return' and 'return expr' are found, return True.) | [
"Traverse",
"the",
"tree",
"below",
"node",
"looking",
"for",
"return",
"expr",
"."
] | d128c76b8a86f208e5c78716f2a917003650cebc | https://github.com/dropbox/pyannotate/blob/d128c76b8a86f208e5c78716f2a917003650cebc/pyannotate_tools/fixes/fix_annotate.py#L454-L467 | train |
srsudar/eg | eg/config.py | inform_if_paths_invalid | def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
retu... | python | def inform_if_paths_invalid(egrc_path, examples_dir, custom_dir, debug=True):
"""
If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line.
"""
if (not debug):
retu... | [
"def",
"inform_if_paths_invalid",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"debug",
"=",
"True",
")",
":",
"if",
"(",
"not",
"debug",
")",
":",
"return",
"if",
"(",
"egrc_path",
")",
":",
"_inform_if_path_does_not_exist",
"(",
"egrc_path"... | If egrc_path, examples_dir, or custom_dir is truthy and debug is True,
informs the user that a path is not set.
This should be used to verify input arguments from the command line. | [
"If",
"egrc_path",
"examples_dir",
"or",
"custom_dir",
"is",
"truthy",
"and",
"debug",
"is",
"True",
"informs",
"the",
"user",
"that",
"a",
"path",
"is",
"not",
"set",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L131-L148 | train |
srsudar/eg | eg/config.py | get_egrc_config | def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the comm... | python | def get_egrc_config(cli_egrc_path):
"""
Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the comm... | [
"def",
"get_egrc_config",
"(",
"cli_egrc_path",
")",
":",
"resolved_path",
"=",
"get_priority",
"(",
"cli_egrc_path",
",",
"DEFAULT_EGRC_PATH",
",",
"None",
")",
"expanded_path",
"=",
"get_expanded_path",
"(",
"resolved_path",
")",
"# Start as if nothing was defined in th... | Return a Config namedtuple based on the contents of the egrc.
If the egrc is not present, it returns an empty default Config.
This method tries to use the egrc at cli_egrc_path, then the default path.
cli_egrc_path: the path to the egrc as given on the command line via
--config-file | [
"Return",
"a",
"Config",
"namedtuple",
"based",
"on",
"the",
"contents",
"of",
"the",
"egrc",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L151-L171 | train |
srsudar/eg | eg/config.py | get_resolved_config | def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in argument... | python | def get_resolved_config(
egrc_path,
examples_dir,
custom_dir,
use_color,
pager_cmd,
squeeze,
debug=True,
):
"""
Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in argument... | [
"def",
"get_resolved_config",
"(",
"egrc_path",
",",
"examples_dir",
",",
"custom_dir",
",",
"use_color",
",",
"pager_cmd",
",",
"squeeze",
",",
"debug",
"=",
"True",
",",
")",
":",
"# Call this with the passed in values, NOT the resolved values. We are",
"# informing the... | Create a Config namedtuple. Passed in values will override defaults.
This function is responsible for producing a Config that is correct for the
passed in arguments. In general, it prefers first command line options,
then values from the egrc, and finally defaults.
examples_dir and custom_dir when ret... | [
"Create",
"a",
"Config",
"namedtuple",
".",
"Passed",
"in",
"values",
"will",
"override",
"defaults",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L174-L276 | train |
srsudar/eg | eg/config.py | get_config_tuple_from_egrc | def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... | python | def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... | [
"def",
"get_config_tuple_from_egrc",
"(",
"egrc_path",
")",
":",
"with",
"open",
"(",
"egrc_path",
",",
"'r'",
")",
"as",
"egrc",
":",
"try",
":",
"config",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"except",
"AttributeError",
":",
"config",
"="... | Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None. | [
"Create",
"a",
"Config",
"named",
"tuple",
"from",
"the",
"values",
"specified",
"in",
"the",
".",
"egrc",
".",
"Expands",
"any",
"paths",
"as",
"necessary",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L279-L342 | train |
srsudar/eg | eg/config.py | get_expanded_path | def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None | python | def get_expanded_path(path):
"""Expand ~ and variables in a path. If path is not truthy, return None."""
if path:
result = path
result = os.path.expanduser(result)
result = os.path.expandvars(result)
return result
else:
return None | [
"def",
"get_expanded_path",
"(",
"path",
")",
":",
"if",
"path",
":",
"result",
"=",
"path",
"result",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"result",
")",
"result",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"result",
")",
"return",
"... | Expand ~ and variables in a path. If path is not truthy, return None. | [
"Expand",
"~",
"and",
"variables",
"in",
"a",
"path",
".",
"If",
"path",
"is",
"not",
"truthy",
"return",
"None",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L345-L353 | train |
srsudar/eg | eg/config.py | get_editor_cmd_from_environment | def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
... | python | def get_editor_cmd_from_environment():
"""
Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None.
"""
result = os.getenv(ENV_VISUAL)
if (not result):
... | [
"def",
"get_editor_cmd_from_environment",
"(",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_VISUAL",
")",
"if",
"(",
"not",
"result",
")",
":",
"result",
"=",
"os",
".",
"getenv",
"(",
"ENV_EDITOR",
")",
"return",
"result"
] | Gets and editor command from environment variables.
It first tries $VISUAL, then $EDITOR, following the same order git uses
when it looks up edits. If neither is available, it returns None. | [
"Gets",
"and",
"editor",
"command",
"from",
"environment",
"variables",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L356-L366 | train |
srsudar/eg | eg/config.py | _inform_if_path_does_not_exist | def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could n... | python | def _inform_if_path_does_not_exist(path):
"""
If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find.
"""
expanded_path = get_expanded_path(path)
if not os.path.exists(expanded_path):
print('Could n... | [
"def",
"_inform_if_path_does_not_exist",
"(",
"path",
")",
":",
"expanded_path",
"=",
"get_expanded_path",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"expanded_path",
")",
":",
"print",
"(",
"'Could not find custom path at: {}'",
".",
... | If the path does not exist, print a message saying so. This is intended to
be helpful to users if they specify a custom path that eg cannot find. | [
"If",
"the",
"path",
"does",
"not",
"exist",
"print",
"a",
"message",
"saying",
"so",
".",
"This",
"is",
"intended",
"to",
"be",
"helpful",
"to",
"users",
"if",
"they",
"specify",
"a",
"custom",
"path",
"that",
"eg",
"cannot",
"find",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L383-L390 | train |
srsudar/eg | eg/config.py | get_custom_color_config_from_egrc | def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config... | python | def get_custom_color_config_from_egrc(config):
"""
Get the ColorConfig from the egrc config object. Any colors not defined
will be None.
"""
pound = _get_color_from_config(config, CONFIG_NAMES.pound)
heading = _get_color_from_config(config, CONFIG_NAMES.heading)
code = _get_color_from_config... | [
"def",
"get_custom_color_config_from_egrc",
"(",
"config",
")",
":",
"pound",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"pound",
")",
"heading",
"=",
"_get_color_from_config",
"(",
"config",
",",
"CONFIG_NAMES",
".",
"heading",
")",
"... | Get the ColorConfig from the egrc config object. Any colors not defined
will be None. | [
"Get",
"the",
"ColorConfig",
"from",
"the",
"egrc",
"config",
"object",
".",
"Any",
"colors",
"not",
"defined",
"will",
"be",
"None",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L393-L428 | train |
srsudar/eg | eg/config.py | _get_color_from_config | def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not conf... | python | def _get_color_from_config(config, option):
"""
Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc.
"""
if not conf... | [
"def",
"_get_color_from_config",
"(",
"config",
",",
"option",
")",
":",
"if",
"not",
"config",
".",
"has_option",
"(",
"COLOR_SECTION",
",",
"option",
")",
":",
"return",
"None",
"else",
":",
"return",
"ast",
".",
"literal_eval",
"(",
"config",
".",
"get"... | Helper method to uet an option from the COLOR_SECTION of the config.
Returns None if the value is not present. If the value is present, it tries
to parse the value as a raw string literal, allowing escape sequences in
the egrc. | [
"Helper",
"method",
"to",
"uet",
"an",
"option",
"from",
"the",
"COLOR_SECTION",
"of",
"the",
"config",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L431-L442 | train |
srsudar/eg | eg/config.py | parse_substitution_from_list | def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
... | python | def parse_substitution_from_list(list_rep):
"""
Parse a substitution from the list representation in the config file.
"""
# We are expecting [pattern, replacement [, is_multiline]]
if type(list_rep) is not list:
raise SyntaxError('Substitution must be a list')
if len(list_rep) < 2:
... | [
"def",
"parse_substitution_from_list",
"(",
"list_rep",
")",
":",
"# We are expecting [pattern, replacement [, is_multiline]]",
"if",
"type",
"(",
"list_rep",
")",
"is",
"not",
"list",
":",
"raise",
"SyntaxError",
"(",
"'Substitution must be a list'",
")",
"if",
"len",
... | Parse a substitution from the list representation in the config file. | [
"Parse",
"a",
"substitution",
"from",
"the",
"list",
"representation",
"in",
"the",
"config",
"file",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L445-L466 | train |
srsudar/eg | eg/config.py | get_substitutions_from_config | def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
... | python | def get_substitutions_from_config(config):
"""
Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown.
... | [
"def",
"get_substitutions_from_config",
"(",
"config",
")",
":",
"result",
"=",
"[",
"]",
"pattern_names",
"=",
"config",
".",
"options",
"(",
"SUBSTITUTION_SECTION",
")",
"pattern_names",
".",
"sort",
"(",
")",
"for",
"name",
"in",
"pattern_names",
":",
"patt... | Return a list of Substitution objects from the config, sorted
alphabetically by pattern name. Returns an empty list if no Substitutions
are specified. If there are problems parsing the values, a help message
will be printed and an error will be thrown. | [
"Return",
"a",
"list",
"of",
"Substitution",
"objects",
"from",
"the",
"config",
"sorted",
"alphabetically",
"by",
"pattern",
"name",
".",
"Returns",
"an",
"empty",
"list",
"if",
"no",
"Substitutions",
"are",
"specified",
".",
"If",
"there",
"are",
"problems",... | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L469-L484 | train |
srsudar/eg | eg/config.py | get_default_color_config | def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_re... | python | def get_default_color_config():
"""Get a color config object with all the defaults."""
result = ColorConfig(
pound=DEFAULT_COLOR_POUND,
heading=DEFAULT_COLOR_HEADING,
code=DEFAULT_COLOR_CODE,
backticks=DEFAULT_COLOR_BACKTICKS,
prompt=DEFAULT_COLOR_PROMPT,
pound_re... | [
"def",
"get_default_color_config",
"(",
")",
":",
"result",
"=",
"ColorConfig",
"(",
"pound",
"=",
"DEFAULT_COLOR_POUND",
",",
"heading",
"=",
"DEFAULT_COLOR_HEADING",
",",
"code",
"=",
"DEFAULT_COLOR_CODE",
",",
"backticks",
"=",
"DEFAULT_COLOR_BACKTICKS",
",",
"pr... | Get a color config object with all the defaults. | [
"Get",
"a",
"color",
"config",
"object",
"with",
"all",
"the",
"defaults",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L487-L501 | train |
srsudar/eg | eg/config.py | get_empty_config | def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
edito... | python | def get_empty_config():
"""
Return an empty Config object with no options set.
"""
empty_color_config = get_empty_color_config()
result = Config(
examples_dir=None,
custom_dir=None,
color_config=empty_color_config,
use_color=None,
pager_cmd=None,
edito... | [
"def",
"get_empty_config",
"(",
")",
":",
"empty_color_config",
"=",
"get_empty_color_config",
"(",
")",
"result",
"=",
"Config",
"(",
"examples_dir",
"=",
"None",
",",
"custom_dir",
"=",
"None",
",",
"color_config",
"=",
"empty_color_config",
",",
"use_color",
... | Return an empty Config object with no options set. | [
"Return",
"an",
"empty",
"Config",
"object",
"with",
"no",
"options",
"set",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L504-L519 | train |
srsudar/eg | eg/config.py | get_empty_color_config | def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
... | python | def get_empty_color_config():
"""Return a color_config with all values set to None."""
empty_color_config = ColorConfig(
pound=None,
heading=None,
code=None,
backticks=None,
prompt=None,
pound_reset=None,
heading_reset=None,
code_reset=None,
... | [
"def",
"get_empty_color_config",
"(",
")",
":",
"empty_color_config",
"=",
"ColorConfig",
"(",
"pound",
"=",
"None",
",",
"heading",
"=",
"None",
",",
"code",
"=",
"None",
",",
"backticks",
"=",
"None",
",",
"prompt",
"=",
"None",
",",
"pound_reset",
"=",
... | Return a color_config with all values set to None. | [
"Return",
"a",
"color_config",
"with",
"all",
"values",
"set",
"to",
"None",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L522-L536 | train |
srsudar/eg | eg/config.py | merge_color_configs | def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
hea... | python | def merge_color_configs(first, second):
"""
Merge the color configs.
Values in the first will overwrite non-None values in the second.
"""
# We have to get the desired values first and simultaneously, as nametuple
# is immutable.
pound = get_priority(first.pound, second.pound, None)
hea... | [
"def",
"merge_color_configs",
"(",
"first",
",",
"second",
")",
":",
"# We have to get the desired values first and simultaneously, as nametuple",
"# is immutable.",
"pound",
"=",
"get_priority",
"(",
"first",
".",
"pound",
",",
"second",
".",
"pound",
",",
"None",
")",... | Merge the color configs.
Values in the first will overwrite non-None values in the second. | [
"Merge",
"the",
"color",
"configs",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/config.py#L539-L591 | train |
srsudar/eg | eg/substitute.py | Substitution.apply_and_get_result | def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile... | python | def apply_and_get_result(self, string):
"""
Perform the substitution represented by this object on string and return
the result.
"""
if self.is_multiline:
compiled_pattern = re.compile(self.pattern, re.MULTILINE)
else:
compiled_pattern = re.compile... | [
"def",
"apply_and_get_result",
"(",
"self",
",",
"string",
")",
":",
"if",
"self",
".",
"is_multiline",
":",
"compiled_pattern",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"pattern",
",",
"re",
".",
"MULTILINE",
")",
"else",
":",
"compiled_pattern",
"=",... | Perform the substitution represented by this object on string and return
the result. | [
"Perform",
"the",
"substitution",
"represented",
"by",
"this",
"object",
"on",
"string",
"and",
"return",
"the",
"result",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/substitute.py#L23-L34 | train |
srsudar/eg | eg/color.py | EgColorizer.colorize_text | def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few s... | python | def colorize_text(self, text):
"""Colorize the text."""
# As originally implemented, this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package. I believe this was ostensibly for performance reasons, but
# it has a few s... | [
"def",
"colorize_text",
"(",
"self",
",",
"text",
")",
":",
"# As originally implemented, this method acts upon all the contents of",
"# the file as a single string using the MULTILINE option of the re",
"# package. I believe this was ostensibly for performance reasons, but",
"# it has a few s... | Colorize the text. | [
"Colorize",
"the",
"text",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/color.py#L67-L85 | train |
srsudar/eg | eg/util.py | _recursive_get_all_file_names | def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for ba... | python | def _recursive_get_all_file_names(dir):
"""
Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list.
"""
if not dir:
return []
result = []
for ba... | [
"def",
"_recursive_get_all_file_names",
"(",
"dir",
")",
":",
"if",
"not",
"dir",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"basedir",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"result",
".",
"extend",
... | Get all the file names in the directory. Gets all the top level file names
only, not the full path.
dir: a directory or string, as to hand to os.walk(). If None, returns empty
list. | [
"Get",
"all",
"the",
"file",
"names",
"in",
"the",
"directory",
".",
"Gets",
"all",
"the",
"top",
"level",
"file",
"names",
"only",
"not",
"the",
"full",
"path",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L49-L64 | train |
srsudar/eg | eg/util.py | edit_custom_examples | def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved... | python | def edit_custom_examples(program, config):
"""
Edit custom examples for the given program, creating the file if it does
not exist.
"""
if (not config.custom_dir) or (not os.path.exists(config.custom_dir)):
_inform_cannot_edit_no_custom_dir()
return
# resolve aliases
resolved... | [
"def",
"edit_custom_examples",
"(",
"program",
",",
"config",
")",
":",
"if",
"(",
"not",
"config",
".",
"custom_dir",
")",
"or",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config",
".",
"custom_dir",
")",
")",
":",
"_inform_cannot_edit_no_custom_... | Edit custom examples for the given program, creating the file if it does
not exist. | [
"Edit",
"custom",
"examples",
"for",
"the",
"given",
"program",
"creating",
"the",
"file",
"if",
"it",
"does",
"not",
"exist",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L67-L90 | train |
srsudar/eg | eg/util.py | get_file_paths_for_program | def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (... | python | def get_file_paths_for_program(program, dir_to_search):
"""
Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (... | [
"def",
"get_file_paths_for_program",
"(",
"program",
",",
"dir_to_search",
")",
":",
"if",
"dir_to_search",
"is",
"None",
":",
"return",
"[",
"]",
"else",
":",
"wanted_file_name",
"=",
"program",
"+",
"EXAMPLE_FILE_SUFFIX",
"result",
"=",
"[",
"]",
"for",
"bas... | Return an array of full paths matching the given program. If no directory is
present, returns an empty list.
Path is not guaranteed to exist. Just says where it should be if it
existed. Paths must be fully expanded before being passed in (i.e. no ~ or
variables). | [
"Return",
"an",
"array",
"of",
"full",
"paths",
"matching",
"the",
"given",
"program",
".",
"If",
"no",
"directory",
"is",
"present",
"returns",
"an",
"empty",
"list",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L131-L150 | train |
srsudar/eg | eg/util.py | page_string | def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have less on their machine, odds are they're
# just using the default value. In this case the pager will fail, so we'll... | python | def page_string(str_to_page, pager_cmd):
"""
Page str_to_page via the pager.
"""
# By default, we expect the command to be `less -R`. If that is the
# pager_cmd, but they don't have less on their machine, odds are they're
# just using the default value. In this case the pager will fail, so we'll... | [
"def",
"page_string",
"(",
"str_to_page",
",",
"pager_cmd",
")",
":",
"# By default, we expect the command to be `less -R`. If that is the",
"# pager_cmd, but they don't have less on their machine, odds are they're",
"# just using the default value. In this case the pager will fail, so we'll",
... | Page str_to_page via the pager. | [
"Page",
"str_to_page",
"via",
"the",
"pager",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L167-L189 | train |
srsudar/eg | eg/util.py | get_list_of_all_supported_commands | def get_list_of_all_supported_commands(config):
"""
Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains addition... | python | def get_list_of_all_supported_commands(config):
"""
Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains addition... | [
"def",
"get_list_of_all_supported_commands",
"(",
"config",
")",
":",
"default_files",
"=",
"_recursive_get_all_file_names",
"(",
"config",
".",
"examples_dir",
")",
"custom_files",
"=",
"_recursive_get_all_file_names",
"(",
"config",
".",
"custom_dir",
")",
"# Now filter... | Generate a list of all the commands that have examples known to eg. The
format of the list is the command names. The fact that there are examples
for 'cp', for example, would mean that 'cp' was in the list.
The format of the list contains additional information to say if there are
only default examples... | [
"Generate",
"a",
"list",
"of",
"all",
"the",
"commands",
"that",
"have",
"examples",
"known",
"to",
"eg",
".",
"The",
"format",
"of",
"the",
"list",
"is",
"the",
"command",
"names",
".",
"The",
"fact",
"that",
"there",
"are",
"examples",
"for",
"cp",
"... | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L206-L280 | train |
srsudar/eg | eg/util.py | get_squeezed_contents | def get_squeezed_contents(contents):
"""
Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections.
"""
line_between_example_code = substitute.Substitution(
'\n\n ',
'\n ',
True
)
lines_b... | python | def get_squeezed_contents(contents):
"""
Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections.
"""
line_between_example_code = substitute.Substitution(
'\n\n ',
'\n ',
True
)
lines_b... | [
"def",
"get_squeezed_contents",
"(",
"contents",
")",
":",
"line_between_example_code",
"=",
"substitute",
".",
"Substitution",
"(",
"'\\n\\n '",
",",
"'\\n '",
",",
"True",
")",
"lines_between_examples",
"=",
"substitute",
".",
"Substitution",
"(",
"'\\n\\n\\n'... | Squeeze the contents by removing blank lines between definition and example
and remove duplicate blank lines except between sections. | [
"Squeeze",
"the",
"contents",
"by",
"removing",
"blank",
"lines",
"between",
"definition",
"and",
"example",
"and",
"remove",
"duplicate",
"blank",
"lines",
"except",
"between",
"sections",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L283-L302 | train |
srsudar/eg | eg/util.py | get_colorized_contents | def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.colorize_text(contents)
return result | python | def get_colorized_contents(contents, color_config):
"""Colorize the contents based on the color_config."""
colorizer = color.EgColorizer(color_config)
result = colorizer.colorize_text(contents)
return result | [
"def",
"get_colorized_contents",
"(",
"contents",
",",
"color_config",
")",
":",
"colorizer",
"=",
"color",
".",
"EgColorizer",
"(",
"color_config",
")",
"result",
"=",
"colorizer",
".",
"colorize_text",
"(",
"contents",
")",
"return",
"result"
] | Colorize the contents based on the color_config. | [
"Colorize",
"the",
"contents",
"based",
"on",
"the",
"color_config",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L305-L309 | train |
srsudar/eg | eg/util.py | get_substituted_contents | def get_substituted_contents(contents, substitutions):
"""
Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution.
"""
... | python | def get_substituted_contents(contents, substitutions):
"""
Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution.
"""
... | [
"def",
"get_substituted_contents",
"(",
"contents",
",",
"substitutions",
")",
":",
"result",
"=",
"contents",
"for",
"sub",
"in",
"substitutions",
":",
"result",
"=",
"sub",
".",
"apply_and_get_result",
"(",
"result",
")",
"return",
"result"
] | Perform a list of substitutions and return the result.
contents: the starting string on which to beging substitutions
substitutions: list of Substitution objects to call, in order, with the
result of the previous substitution. | [
"Perform",
"a",
"list",
"of",
"substitutions",
"and",
"return",
"the",
"result",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L312-L323 | train |
srsudar/eg | eg/util.py | get_resolved_program | def get_resolved_program(program, config_obj):
"""
Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias.
... | python | def get_resolved_program(program, config_obj):
"""
Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias.
... | [
"def",
"get_resolved_program",
"(",
"program",
",",
"config_obj",
")",
":",
"alias_dict",
"=",
"get_alias_dict",
"(",
"config_obj",
")",
"if",
"program",
"in",
"alias_dict",
":",
"return",
"alias_dict",
"[",
"program",
"]",
"else",
":",
"return",
"program"
] | Take a program that may be an alias for another program and return the
resolved program.
It only ever resolves a single level of aliasing, so does not support
aliasing to an alias.
Returns the original program if the program is not an alias. | [
"Take",
"a",
"program",
"that",
"may",
"be",
"an",
"alias",
"for",
"another",
"program",
"and",
"return",
"the",
"resolved",
"program",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L351-L365 | train |
srsudar/eg | eg/util.py | get_alias_dict | def get_alias_dict(config_obj):
"""
Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict.
"""
if not config_obj.examples_dir:
return {}
alias_file_path = _get_alias_file_pa... | python | def get_alias_dict(config_obj):
"""
Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict.
"""
if not config_obj.examples_dir:
return {}
alias_file_path = _get_alias_file_pa... | [
"def",
"get_alias_dict",
"(",
"config_obj",
")",
":",
"if",
"not",
"config_obj",
".",
"examples_dir",
":",
"return",
"{",
"}",
"alias_file_path",
"=",
"_get_alias_file_path",
"(",
"config_obj",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"alias_... | Return a dictionary consisting of all aliases known to eg.
The format is {'alias': 'resolved_program'}.
If the aliases file does not exist, returns an empty dict. | [
"Return",
"a",
"dictionary",
"consisting",
"of",
"all",
"aliases",
"known",
"to",
"eg",
"."
] | 96142a74f4416b4a7000c85032c070df713b849e | https://github.com/srsudar/eg/blob/96142a74f4416b4a7000c85032c070df713b849e/eg/util.py#L368-L385 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_not_called | def assert_not_called(_mock_self):
"""assert that the mock was never called.
"""
self = _mock_self
if self.call_count != 0:
msg = ("Expected '%s' to not have been called. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise As... | python | def assert_not_called(_mock_self):
"""assert that the mock was never called.
"""
self = _mock_self
if self.call_count != 0:
msg = ("Expected '%s' to not have been called. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise As... | [
"def",
"assert_not_called",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"self",
".",
"call_count",
"!=",
"0",
":",
"msg",
"=",
"(",
"\"Expected '%s' to not have been called. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",
"'mock'"... | assert that the mock was never called. | [
"assert",
"that",
"the",
"mock",
"was",
"never",
"called",
"."
] | 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L889-L896 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called | def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
raise AssertionError(msg) | python | def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
raise AssertionError(msg) | [
"def",
"assert_called",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"self",
".",
"call_count",
"==",
"0",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called.\"",
"%",
"self",
".",
"_mock_name",
"or",
"'mock'",
")",
"raise",
"Assertion... | assert that the mock was called at least once | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"at",
"least",
"once"
] | 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L898-L905 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called_once | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
... | python | def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
... | [
"def",
"assert_called_once",
"(",
"_mock_self",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to have been called once. Called %s times.\"",
"%",
"(",
"self",
".",
"_mock_name",
"or",... | assert that the mock was called only once. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"only",
"once",
"."
] | 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L907-L914 | train |
testing-cabal/mock | mock/mock.py | NonCallableMock.assert_called_once_with | def assert_called_once_with(_mock_self, *args, **kwargs):
"""assert that the mock was called exactly once and with the specified
arguments."""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to be called once. Called %s times." %
(self.... | python | def assert_called_once_with(_mock_self, *args, **kwargs):
"""assert that the mock was called exactly once and with the specified
arguments."""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to be called once. Called %s times." %
(self.... | [
"def",
"assert_called_once_with",
"(",
"_mock_self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"_mock_self",
"if",
"not",
"self",
".",
"call_count",
"==",
"1",
":",
"msg",
"=",
"(",
"\"Expected '%s' to be called once. Called %s times.\"",... | assert that the mock was called exactly once and with the specified
arguments. | [
"assert",
"that",
"the",
"mock",
"was",
"called",
"exactly",
"once",
"and",
"with",
"the",
"specified",
"arguments",
"."
] | 2f356b28d42a1fd0057c9d8763d3a2cac2284165 | https://github.com/testing-cabal/mock/blob/2f356b28d42a1fd0057c9d8763d3a2cac2284165/mock/mock.py#L939-L947 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/html_entity.py | HTMLEntity.normalize | def normalize(self):
"""Return the unicode character represented by the HTML entity."""
chrfunc = chr if py3k else HTMLEntity._unichr
if self.named:
return chrfunc(htmlentities.name2codepoint[self.value])
if self.hexadecimal:
return chrfunc(int(self.value, 16))
... | python | def normalize(self):
"""Return the unicode character represented by the HTML entity."""
chrfunc = chr if py3k else HTMLEntity._unichr
if self.named:
return chrfunc(htmlentities.name2codepoint[self.value])
if self.hexadecimal:
return chrfunc(int(self.value, 16))
... | [
"def",
"normalize",
"(",
"self",
")",
":",
"chrfunc",
"=",
"chr",
"if",
"py3k",
"else",
"HTMLEntity",
".",
"_unichr",
"if",
"self",
".",
"named",
":",
"return",
"chrfunc",
"(",
"htmlentities",
".",
"name2codepoint",
"[",
"self",
".",
"value",
"]",
")",
... | Return the unicode character represented by the HTML entity. | [
"Return",
"the",
"unicode",
"character",
"represented",
"by",
"the",
"HTML",
"entity",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/html_entity.py#L174-L181 | train |
earwig/mwparserfromhell | mwparserfromhell/smart_list.py | SmartList._detach_children | def _detach_children(self):
"""Remove all children and give them independent parent copies."""
children = [val[0] for val in self._children.values()]
for child in children:
child()._parent = list(self)
self._children.clear() | python | def _detach_children(self):
"""Remove all children and give them independent parent copies."""
children = [val[0] for val in self._children.values()]
for child in children:
child()._parent = list(self)
self._children.clear() | [
"def",
"_detach_children",
"(",
"self",
")",
":",
"children",
"=",
"[",
"val",
"[",
"0",
"]",
"for",
"val",
"in",
"self",
".",
"_children",
".",
"values",
"(",
")",
"]",
"for",
"child",
"in",
"children",
":",
"child",
"(",
")",
".",
"_parent",
"=",... | Remove all children and give them independent parent copies. | [
"Remove",
"all",
"children",
"and",
"give",
"them",
"independent",
"parent",
"copies",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/smart_list.py#L158-L163 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_parameter | def _handle_parameter(self, default):
"""Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined.
"""
key = None
showkey = False
self._push()
while self._tokens:
token = self._tokens.... | python | def _handle_parameter(self, default):
"""Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined.
"""
key = None
showkey = False
self._push()
while self._tokens:
token = self._tokens.... | [
"def",
"_handle_parameter",
"(",
"self",
",",
"default",
")",
":",
"key",
"=",
"None",
"showkey",
"=",
"False",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
... | Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined. | [
"Handle",
"a",
"case",
"where",
"a",
"parameter",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L76-L99 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_template | def _handle_template(self, token):
"""Handle a case where a template is at the head of the tokens."""
params = []
default = 1
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamSeparator):
i... | python | def _handle_template(self, token):
"""Handle a case where a template is at the head of the tokens."""
params = []
default = 1
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TemplateParamSeparator):
i... | [
"def",
"_handle_template",
"(",
"self",
",",
"token",
")",
":",
"params",
"=",
"[",
"]",
"default",
"=",
"1",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
... | Handle a case where a template is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"template",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L102-L122 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_argument | def _handle_argument(self, token):
"""Handle a case where an argument is at the head of the tokens."""
name = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ArgumentSeparator):
name = self._pop()
... | python | def _handle_argument(self, token):
"""Handle a case where an argument is at the head of the tokens."""
name = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ArgumentSeparator):
name = self._pop()
... | [
"def",
"_handle_argument",
"(",
"self",
",",
"token",
")",
":",
"name",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
... | Handle a case where an argument is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"argument",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L125-L140 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_wikilink | def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
... | python | def _handle_wikilink(self, token):
"""Handle a case where a wikilink is at the head of the tokens."""
title = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.WikilinkSeparator):
title = self._pop()
... | [
"def",
"_handle_wikilink",
"(",
"self",
",",
"token",
")",
":",
"title",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
... | Handle a case where a wikilink is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"wikilink",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L143-L158 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_external_link | def _handle_external_link(self, token):
"""Handle when an external link is at the head of the tokens."""
brackets, url = token.brackets, None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ExternalLinkSeparator):
... | python | def _handle_external_link(self, token):
"""Handle when an external link is at the head of the tokens."""
brackets, url = token.brackets, None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.ExternalLinkSeparator):
... | [
"def",
"_handle_external_link",
"(",
"self",
",",
"token",
")",
":",
"brackets",
",",
"url",
"=",
"token",
".",
"brackets",
",",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
... | Handle when an external link is at the head of the tokens. | [
"Handle",
"when",
"an",
"external",
"link",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L161-L176 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_entity | def _handle_entity(self, token):
"""Handle a case where an HTML entity is at the head of the tokens."""
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityNumeric):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityHex):
text =... | python | def _handle_entity(self, token):
"""Handle a case where an HTML entity is at the head of the tokens."""
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityNumeric):
token = self._tokens.pop()
if isinstance(token, tokens.HTMLEntityHex):
text =... | [
"def",
"_handle_entity",
"(",
"self",
",",
"token",
")",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"HTMLEntityNumeric",
")",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
... | Handle a case where an HTML entity is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"HTML",
"entity",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L179-L192 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_heading | def _handle_heading(self, token):
"""Handle a case where a heading is at the head of the tokens."""
level = token.level
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.HeadingEnd):
title = self._pop()
... | python | def _handle_heading(self, token):
"""Handle a case where a heading is at the head of the tokens."""
level = token.level
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.HeadingEnd):
title = self._pop()
... | [
"def",
"_handle_heading",
"(",
"self",
",",
"token",
")",
":",
"level",
"=",
"token",
".",
"level",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
... | Handle a case where a heading is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"heading",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L195-L206 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_comment | def _handle_comment(self, token):
"""Handle a case where an HTML comment is at the head of the tokens."""
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.CommentEnd):
contents = self._pop()
return Com... | python | def _handle_comment(self, token):
"""Handle a case where an HTML comment is at the head of the tokens."""
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.CommentEnd):
contents = self._pop()
return Com... | [
"def",
"_handle_comment",
"(",
"self",
",",
"token",
")",
":",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"token",
",",
"tokens",
".",
"... | Handle a case where an HTML comment is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"an",
"HTML",
"comment",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L209-L219 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_attribute | def _handle_attribute(self, start):
"""Handle a case where a tag attribute is at the head of the tokens."""
name = quotes = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrEquals):
name = self._po... | python | def _handle_attribute(self, start):
"""Handle a case where a tag attribute is at the head of the tokens."""
name = quotes = None
self._push()
while self._tokens:
token = self._tokens.pop()
if isinstance(token, tokens.TagAttrEquals):
name = self._po... | [
"def",
"_handle_attribute",
"(",
"self",
",",
"start",
")",
":",
"name",
"=",
"quotes",
"=",
"None",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
"isinstance",... | Handle a case where a tag attribute is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"tag",
"attribute",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L221-L243 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_tag | def _handle_tag(self, token):
"""Handle a case where a tag is at the head of the tokens."""
close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
implicit, attrs, contents, closing_tag = False, [], None, None
wiki_markup, invalid = token.wiki_markup, token.invalid or False
... | python | def _handle_tag(self, token):
"""Handle a case where a tag is at the head of the tokens."""
close_tokens = (tokens.TagCloseSelfclose, tokens.TagCloseClose)
implicit, attrs, contents, closing_tag = False, [], None, None
wiki_markup, invalid = token.wiki_markup, token.invalid or False
... | [
"def",
"_handle_tag",
"(",
"self",
",",
"token",
")",
":",
"close_tokens",
"=",
"(",
"tokens",
".",
"TagCloseSelfclose",
",",
"tokens",
".",
"TagCloseClose",
")",
"implicit",
",",
"attrs",
",",
"contents",
",",
"closing_tag",
"=",
"False",
",",
"[",
"]",
... | Handle a case where a tag is at the head of the tokens. | [
"Handle",
"a",
"case",
"where",
"a",
"tag",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L246-L281 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder._handle_token | def _handle_token(self, token):
"""Handle a single token."""
try:
return _HANDLERS[type(token)](self, token)
except KeyError:
err = "_handle_token() got unexpected {0}"
raise ParserError(err.format(type(token).__name__)) | python | def _handle_token(self, token):
"""Handle a single token."""
try:
return _HANDLERS[type(token)](self, token)
except KeyError:
err = "_handle_token() got unexpected {0}"
raise ParserError(err.format(type(token).__name__)) | [
"def",
"_handle_token",
"(",
"self",
",",
"token",
")",
":",
"try",
":",
"return",
"_HANDLERS",
"[",
"type",
"(",
"token",
")",
"]",
"(",
"self",
",",
"token",
")",
"except",
"KeyError",
":",
"err",
"=",
"\"_handle_token() got unexpected {0}\"",
"raise",
"... | Handle a single token. | [
"Handle",
"a",
"single",
"token",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L283-L289 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | Builder.build | def build(self, tokenlist):
"""Build a Wikicode object from a list tokens and return it."""
self._tokens = tokenlist
self._tokens.reverse()
self._push()
while self._tokens:
node = self._handle_token(self._tokens.pop())
self._write(node)
return self... | python | def build(self, tokenlist):
"""Build a Wikicode object from a list tokens and return it."""
self._tokens = tokenlist
self._tokens.reverse()
self._push()
while self._tokens:
node = self._handle_token(self._tokens.pop())
self._write(node)
return self... | [
"def",
"build",
"(",
"self",
",",
"tokenlist",
")",
":",
"self",
".",
"_tokens",
"=",
"tokenlist",
"self",
".",
"_tokens",
".",
"reverse",
"(",
")",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"node",
"=",
"self",
".",
"_h... | Build a Wikicode object from a list tokens and return it. | [
"Build",
"a",
"Wikicode",
"object",
"from",
"a",
"list",
"tokens",
"and",
"return",
"it",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L291-L299 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._select_theory | def _select_theory(theories):
"""Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style.
"""
... | python | def _select_theory(theories):
"""Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style.
"""
... | [
"def",
"_select_theory",
"(",
"theories",
")",
":",
"if",
"theories",
":",
"values",
"=",
"tuple",
"(",
"theories",
".",
"values",
"(",
")",
")",
"best",
"=",
"max",
"(",
"values",
")",
"confidence",
"=",
"float",
"(",
"best",
")",
"/",
"sum",
"(",
... | Return the most likely spacing convention given different options.
Given a dictionary of convention options as keys and their occurrence
as values, return the convention that occurs the most, or ``None`` if
there is no clear preferred style. | [
"Return",
"the",
"most",
"likely",
"spacing",
"convention",
"given",
"different",
"options",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L93-L105 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._get_spacing_conventions | def _get_spacing_conventions(self, use_names):
"""Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value.... | python | def _get_spacing_conventions(self, use_names):
"""Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value.... | [
"def",
"_get_spacing_conventions",
"(",
"self",
",",
"use_names",
")",
":",
"before_theories",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"after_theories",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"param",
"in",
"self",
".",
"params",
... | Try to determine the whitespace conventions for parameters.
This will examine the existing parameters and use
:meth:`_select_theory` to determine if there are any preferred styles
for how much whitespace to put before or after the value. | [
"Try",
"to",
"determine",
"the",
"whitespace",
"conventions",
"for",
"parameters",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L123-L151 | train |
earwig/mwparserfromhell | mwparserfromhell/nodes/template.py | Template._should_remove | def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
"""
if self.params[i].showkey:
following = self.params[i + 1:]
better_matches = [after.name.str... | python | def _should_remove(self, i, name):
"""Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it.
"""
if self.params[i].showkey:
following = self.params[i + 1:]
better_matches = [after.name.str... | [
"def",
"_should_remove",
"(",
"self",
",",
"i",
",",
"name",
")",
":",
"if",
"self",
".",
"params",
"[",
"i",
"]",
".",
"showkey",
":",
"following",
"=",
"self",
".",
"params",
"[",
"i",
"+",
"1",
":",
"]",
"better_matches",
"=",
"[",
"after",
".... | Look ahead for a parameter with the same name, but hidden.
If one exists, we should remove the given one rather than blanking it. | [
"Look",
"ahead",
"for",
"a",
"parameter",
"with",
"the",
"same",
"name",
"but",
"hidden",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/nodes/template.py#L172-L182 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._push | def _push(self, context=0):
"""Add a new token stack, context, and textbuffer to the list."""
new_ident = (self._head, context)
if new_ident in self._bad_routes:
raise BadRoute(context)
self._stacks.append([[], context, [], new_ident])
self._depth += 1 | python | def _push(self, context=0):
"""Add a new token stack, context, and textbuffer to the list."""
new_ident = (self._head, context)
if new_ident in self._bad_routes:
raise BadRoute(context)
self._stacks.append([[], context, [], new_ident])
self._depth += 1 | [
"def",
"_push",
"(",
"self",
",",
"context",
"=",
"0",
")",
":",
"new_ident",
"=",
"(",
"self",
".",
"_head",
",",
"context",
")",
"if",
"new_ident",
"in",
"self",
".",
"_bad_routes",
":",
"raise",
"BadRoute",
"(",
"context",
")",
"self",
".",
"_stac... | Add a new token stack, context, and textbuffer to the list. | [
"Add",
"a",
"new",
"token",
"stack",
"context",
"and",
"textbuffer",
"to",
"the",
"list",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L113-L120 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._push_textbuffer | def _push_textbuffer(self):
"""Push the textbuffer onto the stack as a Text node and clear it."""
if self._textbuffer:
self._stack.append(tokens.Text(text="".join(self._textbuffer)))
self._textbuffer = [] | python | def _push_textbuffer(self):
"""Push the textbuffer onto the stack as a Text node and clear it."""
if self._textbuffer:
self._stack.append(tokens.Text(text="".join(self._textbuffer)))
self._textbuffer = [] | [
"def",
"_push_textbuffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_textbuffer",
":",
"self",
".",
"_stack",
".",
"append",
"(",
"tokens",
".",
"Text",
"(",
"text",
"=",
"\"\"",
".",
"join",
"(",
"self",
".",
"_textbuffer",
")",
")",
")",
"self",
... | Push the textbuffer onto the stack as a Text node and clear it. | [
"Push",
"the",
"textbuffer",
"onto",
"the",
"stack",
"as",
"a",
"Text",
"node",
"and",
"clear",
"it",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L122-L126 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._fail_route | def _fail_route(self):
"""Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`.
"""
context = self._context
self._memoize_bad_route()
self._pop()
raise BadRoute(context) | python | def _fail_route(self):
"""Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`.
"""
context = self._context
self._memoize_bad_route()
self._pop()
raise BadRoute(context) | [
"def",
"_fail_route",
"(",
"self",
")",
":",
"context",
"=",
"self",
".",
"_context",
"self",
".",
"_memoize_bad_route",
"(",
")",
"self",
".",
"_pop",
"(",
")",
"raise",
"BadRoute",
"(",
"context",
")"
] | Fail the current tokenization route.
Discards the current stack/context/textbuffer and raises
:exc:`.BadRoute`. | [
"Fail",
"the",
"current",
"tokenization",
"route",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L155-L164 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._emit_all | def _emit_all(self, tokenlist):
"""Write a series of tokens to the current stack at once."""
if tokenlist and isinstance(tokenlist[0], tokens.Text):
self._emit_text(tokenlist.pop(0).text)
self._push_textbuffer()
self._stack.extend(tokenlist) | python | def _emit_all(self, tokenlist):
"""Write a series of tokens to the current stack at once."""
if tokenlist and isinstance(tokenlist[0], tokens.Text):
self._emit_text(tokenlist.pop(0).text)
self._push_textbuffer()
self._stack.extend(tokenlist) | [
"def",
"_emit_all",
"(",
"self",
",",
"tokenlist",
")",
":",
"if",
"tokenlist",
"and",
"isinstance",
"(",
"tokenlist",
"[",
"0",
"]",
",",
"tokens",
".",
"Text",
")",
":",
"self",
".",
"_emit_text",
"(",
"tokenlist",
".",
"pop",
"(",
"0",
")",
".",
... | Write a series of tokens to the current stack at once. | [
"Write",
"a",
"series",
"of",
"tokens",
"to",
"the",
"current",
"stack",
"at",
"once",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L180-L185 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._read | def _read(self, delta=0, wrap=False, strict=False):
"""Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the ... | python | def _read(self, delta=0, wrap=False, strict=False):
"""Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the ... | [
"def",
"_read",
"(",
"self",
",",
"delta",
"=",
"0",
",",
"wrap",
"=",
"False",
",",
"strict",
"=",
"False",
")",
":",
"index",
"=",
"self",
".",
"_head",
"+",
"delta",
"if",
"index",
"<",
"0",
"and",
"(",
"not",
"wrap",
"or",
"abs",
"(",
"inde... | Read the value at a relative point in the wikicode.
The value is read from :attr:`self._head <_head>` plus the value of
*delta* (which can be negative). If *wrap* is ``False``, we will not
allow attempts to read from the end of the string if ``self._head +
delta`` is negative. If *stric... | [
"Read",
"the",
"value",
"at",
"a",
"relative",
"point",
"in",
"the",
"wikicode",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L195-L215 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_template | def _parse_template(self, has_content):
"""Parse a template at the head of the wikicode string."""
reset = self._head
context = contexts.TEMPLATE_NAME
if has_content:
context |= contexts.HAS_TEMPLATE
try:
template = self._parse(context)
except BadR... | python | def _parse_template(self, has_content):
"""Parse a template at the head of the wikicode string."""
reset = self._head
context = contexts.TEMPLATE_NAME
if has_content:
context |= contexts.HAS_TEMPLATE
try:
template = self._parse(context)
except BadR... | [
"def",
"_parse_template",
"(",
"self",
",",
"has_content",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"context",
"=",
"contexts",
".",
"TEMPLATE_NAME",
"if",
"has_content",
":",
"context",
"|=",
"contexts",
".",
"HAS_TEMPLATE",
"try",
":",
"template",
"="... | Parse a template at the head of the wikicode string. | [
"Parse",
"a",
"template",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L217-L230 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_argument | def _parse_argument(self):
"""Parse an argument at the head of the wikicode string."""
reset = self._head
try:
argument = self._parse(contexts.ARGUMENT_NAME)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.ArgumentOpen())
... | python | def _parse_argument(self):
"""Parse an argument at the head of the wikicode string."""
reset = self._head
try:
argument = self._parse(contexts.ARGUMENT_NAME)
except BadRoute:
self._head = reset
raise
self._emit_first(tokens.ArgumentOpen())
... | [
"def",
"_parse_argument",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"try",
":",
"argument",
"=",
"self",
".",
"_parse",
"(",
"contexts",
".",
"ARGUMENT_NAME",
")",
"except",
"BadRoute",
":",
"self",
".",
"_head",
"=",
"reset",
"raise",
... | Parse an argument at the head of the wikicode string. | [
"Parse",
"an",
"argument",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L232-L242 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_template_or_argument | def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
... | python | def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
... | [
"def",
"_parse_template_or_argument",
"(",
"self",
")",
":",
"self",
".",
"_head",
"+=",
"2",
"braces",
"=",
"2",
"while",
"self",
".",
"_read",
"(",
")",
"==",
"\"{\"",
":",
"self",
".",
"_head",
"+=",
"1",
"braces",
"+=",
"1",
"has_content",
"=",
"... | Parse a template or argument at the head of the wikicode string. | [
"Parse",
"a",
"template",
"or",
"argument",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L244-L278 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_param | def _handle_template_param(self):
"""Handle a template parameter at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
self._context ^= contexts.TEMPLATE_NAME... | python | def _handle_template_param(self):
"""Handle a template parameter at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
self._context ^= contexts.TEMPLATE_NAME... | [
"def",
"_handle_template_param",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_NAME",
":",
"if",
"not",
"self",
".",
"_context",
"&",
"(",
"contexts",
".",
"HAS_TEXT",
"|",
"contexts",
".",
"HAS_TEMPLATE",
")",
":",
... | Handle a template parameter at the head of the string. | [
"Handle",
"a",
"template",
"parameter",
"at",
"the",
"head",
"of",
"the",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L280-L292 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_param_value | def _handle_template_param_value(self):
"""Handle a template parameter's value at the head of the string."""
self._emit_all(self._pop())
self._context ^= contexts.TEMPLATE_PARAM_KEY
self._context |= contexts.TEMPLATE_PARAM_VALUE
self._emit(tokens.TemplateParamEquals()) | python | def _handle_template_param_value(self):
"""Handle a template parameter's value at the head of the string."""
self._emit_all(self._pop())
self._context ^= contexts.TEMPLATE_PARAM_KEY
self._context |= contexts.TEMPLATE_PARAM_VALUE
self._emit(tokens.TemplateParamEquals()) | [
"def",
"_handle_template_param_value",
"(",
"self",
")",
":",
"self",
".",
"_emit_all",
"(",
"self",
".",
"_pop",
"(",
")",
")",
"self",
".",
"_context",
"^=",
"contexts",
".",
"TEMPLATE_PARAM_KEY",
"self",
".",
"_context",
"|=",
"contexts",
".",
"TEMPLATE_P... | Handle a template parameter's value at the head of the string. | [
"Handle",
"a",
"template",
"parameter",
"s",
"value",
"at",
"the",
"head",
"of",
"the",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L294-L299 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_template_end | def _handle_template_end(self):
"""Handle the end of a template at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
elif self._context & contexts.TEMPLATE_PARAM... | python | def _handle_template_end(self):
"""Handle the end of a template at the head of the string."""
if self._context & contexts.TEMPLATE_NAME:
if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
self._fail_route()
elif self._context & contexts.TEMPLATE_PARAM... | [
"def",
"_handle_template_end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"&",
"contexts",
".",
"TEMPLATE_NAME",
":",
"if",
"not",
"self",
".",
"_context",
"&",
"(",
"contexts",
".",
"HAS_TEXT",
"|",
"contexts",
".",
"HAS_TEMPLATE",
")",
":",
... | Handle the end of a template at the head of the string. | [
"Handle",
"the",
"end",
"of",
"a",
"template",
"at",
"the",
"head",
"of",
"the",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L301-L309 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_argument_separator | def _handle_argument_separator(self):
"""Handle the separator between an argument's name and default."""
self._context ^= contexts.ARGUMENT_NAME
self._context |= contexts.ARGUMENT_DEFAULT
self._emit(tokens.ArgumentSeparator()) | python | def _handle_argument_separator(self):
"""Handle the separator between an argument's name and default."""
self._context ^= contexts.ARGUMENT_NAME
self._context |= contexts.ARGUMENT_DEFAULT
self._emit(tokens.ArgumentSeparator()) | [
"def",
"_handle_argument_separator",
"(",
"self",
")",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"ARGUMENT_NAME",
"self",
".",
"_context",
"|=",
"contexts",
".",
"ARGUMENT_DEFAULT",
"self",
".",
"_emit",
"(",
"tokens",
".",
"ArgumentSeparator",
"(",
... | Handle the separator between an argument's name and default. | [
"Handle",
"the",
"separator",
"between",
"an",
"argument",
"s",
"name",
"and",
"default",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L311-L315 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._parse_wikilink | def _parse_wikilink(self):
"""Parse an internal wikilink at the head of the wikicode string."""
reset = self._head + 1
self._head += 2
try:
# If the wikilink looks like an external link, parse it as such:
link, extra, delta = self._really_parse_external_link(True)... | python | def _parse_wikilink(self):
"""Parse an internal wikilink at the head of the wikicode string."""
reset = self._head + 1
self._head += 2
try:
# If the wikilink looks like an external link, parse it as such:
link, extra, delta = self._really_parse_external_link(True)... | [
"def",
"_parse_wikilink",
"(",
"self",
")",
":",
"reset",
"=",
"self",
".",
"_head",
"+",
"1",
"self",
".",
"_head",
"+=",
"2",
"try",
":",
"# If the wikilink looks like an external link, parse it as such:",
"link",
",",
"extra",
",",
"delta",
"=",
"self",
"."... | Parse an internal wikilink at the head of the wikicode string. | [
"Parse",
"an",
"internal",
"wikilink",
"at",
"the",
"head",
"of",
"the",
"wikicode",
"string",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L322-L351 | train |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | Tokenizer._handle_wikilink_separator | def _handle_wikilink_separator(self):
"""Handle the separator between a wikilink's title and its text."""
self._context ^= contexts.WIKILINK_TITLE
self._context |= contexts.WIKILINK_TEXT
self._emit(tokens.WikilinkSeparator()) | python | def _handle_wikilink_separator(self):
"""Handle the separator between a wikilink's title and its text."""
self._context ^= contexts.WIKILINK_TITLE
self._context |= contexts.WIKILINK_TEXT
self._emit(tokens.WikilinkSeparator()) | [
"def",
"_handle_wikilink_separator",
"(",
"self",
")",
":",
"self",
".",
"_context",
"^=",
"contexts",
".",
"WIKILINK_TITLE",
"self",
".",
"_context",
"|=",
"contexts",
".",
"WIKILINK_TEXT",
"self",
".",
"_emit",
"(",
"tokens",
".",
"WikilinkSeparator",
"(",
"... | Handle the separator between a wikilink's title and its text. | [
"Handle",
"the",
"separator",
"between",
"a",
"wikilink",
"s",
"title",
"and",
"its",
"text",
"."
] | 98dc30902d35c714a70aca8e6616f49d71cb24cc | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L353-L357 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.