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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
graphql-python/graphql-core | graphql/utils/suggestion_list.py | lexical_distance | def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or ... | python | def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or ... | [
"def",
"lexical_distance",
"(",
"a",
",",
"b",
")",
":",
"d",
"=",
"[",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
"+",
"1",
")",
"]",
"or",
"[",
"]",
"d_len",
"=",
"len",
"(",
"d",
")",
"or",
"1",
"for",
"i",
... | Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
... | [
"Computes",
"the",
"lexical",
"distance",
"between",
"strings",
"A",
"and",
"B",
".",
"The",
"distance",
"between",
"two",
"strings",
"is",
"given",
"by",
"counting",
"the",
"minimum",
"number",
"of",
"edits",
"needed",
"to",
"transform",
"string",
"A",
"int... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/suggestion_list.py#L23-L52 | train |
graphql-python/graphql-core | graphql/pyutils/version.py | get_complete_version | def get_complete_version(version=None):
"""Returns a tuple of the graphql version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version is None:
from graphql import VERSION as version
else:
assert len(version) == 5
assert version... | python | def get_complete_version(version=None):
"""Returns a tuple of the graphql version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version is None:
from graphql import VERSION as version
else:
assert len(version) == 5
assert version... | [
"def",
"get_complete_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"from",
"graphql",
"import",
"VERSION",
"as",
"version",
"else",
":",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
"3"... | Returns a tuple of the graphql version. If version argument is non-empty,
then checks for correctness of the tuple provided. | [
"Returns",
"a",
"tuple",
"of",
"the",
"graphql",
"version",
".",
"If",
"version",
"argument",
"is",
"non",
"-",
"empty",
"then",
"checks",
"for",
"correctness",
"of",
"the",
"tuple",
"provided",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/pyutils/version.py#L40-L50 | train |
graphql-python/graphql-core | graphql/language/lexer.py | read_token | def read_token(source, from_position):
# type: (Source, int) -> Token
"""Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for... | python | def read_token(source, from_position):
# type: (Source, int) -> Token
"""Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for... | [
"def",
"read_token",
"(",
"source",
",",
"from_position",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"position_after_whitespace",
"(",
"body",
",",
"from_position",
... | Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for more complicated tokens. | [
"Gets",
"the",
"next",
"token",
"from",
"the",
"source",
"starting",
"at",
"the",
"given",
"position",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L152-L198 | train |
graphql-python/graphql-core | graphql/language/lexer.py | position_after_whitespace | def position_after_whitespace(body, start_position):
# type: (str, int) -> int
"""Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing."""
body_length = len(body)
position = start_position
wh... | python | def position_after_whitespace(body, start_position):
# type: (str, int) -> int
"""Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing."""
body_length = len(body)
position = start_position
wh... | [
"def",
"position_after_whitespace",
"(",
"body",
",",
"start_position",
")",
":",
"# type: (str, int) -> int",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"start_position",
"while",
"position",
"<",
"body_length",
":",
"code",
"=",
"char_code_at",
... | Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing. | [
"Reads",
"from",
"body",
"starting",
"at",
"start_position",
"until",
"it",
"finds",
"a",
"non",
"-",
"whitespace",
"or",
"commented",
"character",
"then",
"returns",
"the",
"position",
"of",
"that",
"character",
"for",
"lexing",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L217-L243 | train |
graphql-python/graphql-core | graphql/language/lexer.py | read_number | def read_number(source, start, first_code):
# type: (Source, int, Optional[int]) -> Token
r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?"""
cod... | python | def read_number(source, start, first_code):
# type: (Source, int, Optional[int]) -> Token
r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?"""
cod... | [
"def",
"read_number",
"(",
"source",
",",
"start",
",",
"first_code",
")",
":",
"# type: (Source, int, Optional[int]) -> Token",
"code",
"=",
"first_code",
"body",
"=",
"source",
".",
"body",
"position",
"=",
"start",
"is_float",
"=",
"False",
"if",
"code",
"=="... | r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? | [
"r",
"Reads",
"a",
"number",
"token",
"from",
"the",
"source",
"file",
"either",
"a",
"float",
"or",
"an",
"int",
"depending",
"on",
"whether",
"a",
"decimal",
"point",
"appears",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L246-L301 | train |
graphql-python/graphql-core | graphql/language/lexer.py | read_string | def read_string(source, start):
# type: (Source, int) -> Token
"""Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
"""
body = source.body
body_length = len(body)
position = start + 1
chunk_start = position
code = 0 # ... | python | def read_string(source, start):
# type: (Source, int) -> Token
"""Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
"""
body = source.body
body_length = len(body)
position = start + 1
chunk_start = position
code = 0 # ... | [
"def",
"read_string",
"(",
"source",
",",
"start",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"start",
"+",
"1",
"chunk_start",
"=",
"position",
"code",
"=",
... | Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" | [
"Reads",
"a",
"string",
"token",
"from",
"the",
"source",
"file",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L339-L417 | train |
graphql-python/graphql-core | graphql/language/lexer.py | read_name | def read_name(source, position):
# type: (Source, int) -> Token
"""Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]*"""
body = source.body
body_length = len(body)
end = position + 1
while end != body_length:
code = char_code_at(body, end)
if no... | python | def read_name(source, position):
# type: (Source, int) -> Token
"""Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]*"""
body = source.body
body_length = len(body)
end = position + 1
while end != body_length:
code = char_code_at(body, end)
if no... | [
"def",
"read_name",
"(",
"source",
",",
"position",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"end",
"=",
"position",
"+",
"1",
"while",
"end",
"!=",
"body_length",
":",
"co... | Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]* | [
"Reads",
"an",
"alphanumeric",
"+",
"underscore",
"name",
"from",
"the",
"source",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L451-L475 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_value | def complete_value(
exe_context, # type: ExecutionContext
return_type, # type: Any
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Implements the instructions for completeValue as defi... | python | def complete_value(
exe_context, # type: ExecutionContext
return_type, # type: Any
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Implements the instructions for completeValue as defi... | [
"def",
"complete_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: Any",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: Any",
")",
... | Implements the instructions for completeValue as defined in the
"Field entries" section of the spec.
If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
error if that completion returns null, as per the "Nullability" section of the spec.
If th... | [
"Implements",
"the",
"instructions",
"for",
"completeValue",
"as",
"defined",
"in",
"the",
"Field",
"entries",
"section",
"of",
"the",
"spec",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L498-L571 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_list_value | def complete_list_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLList
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> List[Any]
"""
Complete a list value by completin... | python | def complete_list_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLList
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> List[Any]
"""
Complete a list value by completin... | [
"def",
"complete_list_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLList",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: An... | Complete a list value by completing each item in the list with the inner type | [
"Complete",
"a",
"list",
"value",
"by",
"completing",
"each",
"item",
"in",
"the",
"list",
"with",
"the",
"inner",
"type"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L574-L605 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_leaf_value | def complete_leaf_value(
return_type, # type: Union[GraphQLEnumType, GraphQLScalarType]
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Union[int, str, float, bool]
"""
Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is no... | python | def complete_leaf_value(
return_type, # type: Union[GraphQLEnumType, GraphQLScalarType]
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Union[int, str, float, bool]
"""
Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is no... | [
"def",
"complete_leaf_value",
"(",
"return_type",
",",
"# type: Union[GraphQLEnumType, GraphQLScalarType]",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: Any",
")",
":",
"# type: (...) -> Union[int, str, float, bool]",
"assert",
"hasattr",
"(",
"return_typ... | Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible. | [
"Complete",
"a",
"Scalar",
"or",
"Enum",
"by",
"serializing",
"to",
"a",
"valid",
"value",
"returning",
"null",
"if",
"serialization",
"is",
"not",
"possible",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L608-L627 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_abstract_value | def complete_abstract_value(
exe_context, # type: ExecutionContext
return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType]
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
... | python | def complete_abstract_value(
exe_context, # type: ExecutionContext
return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType]
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
... | [
"def",
"complete_abstract_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: Union[GraphQLInterfaceType, GraphQLUnionType]",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, st... | Complete an value of an abstract type by determining the runtime type of that value, then completing based
on that type. | [
"Complete",
"an",
"value",
"of",
"an",
"abstract",
"type",
"by",
"determining",
"the",
"runtime",
"type",
"of",
"that",
"value",
"then",
"completing",
"based",
"on",
"that",
"type",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L630-L676 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_object_value | def complete_object_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLObjectType
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
"""
Complete an Object va... | python | def complete_object_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLObjectType
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
"""
Complete an Object va... | [
"def",
"complete_object_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLObjectType",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ... | Complete an Object value by evaluating all sub-selections. | [
"Complete",
"an",
"Object",
"value",
"by",
"evaluating",
"all",
"sub",
"-",
"selections",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L692-L714 | train |
graphql-python/graphql-core | graphql/execution/executor.py | complete_nonnull_value | def complete_nonnull_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLNonNull
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Complete a NonNull value by comple... | python | def complete_nonnull_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLNonNull
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Complete a NonNull value by comple... | [
"def",
"complete_nonnull_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLNonNull",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ty... | Complete a NonNull value by completing the inner type | [
"Complete",
"a",
"NonNull",
"value",
"by",
"completing",
"the",
"inner",
"type"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L717-L741 | train |
graphql-python/graphql-core | graphql/utils/value_from_ast.py | value_from_ast | def value_from_ast(value_ast, type, variables=None):
# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and a value AST node known to match this type, build a
runtime value."""
if is... | python | def value_from_ast(value_ast, type, variables=None):
# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and a value AST node known to match this type, build a
runtime value."""
if is... | [
"def",
"value_from_ast",
"(",
"value_ast",
",",
"type",
",",
"variables",
"=",
"None",
")",
":",
"# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]",
"if",
"isinstance",
"(",
"t... | Given a type and a value AST node known to match this type, build a
runtime value. | [
"Given",
"a",
"type",
"and",
"a",
"value",
"AST",
"node",
"known",
"to",
"match",
"this",
"type",
"build",
"a",
"runtime",
"value",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/value_from_ast.py#L17-L81 | train |
graphql-python/graphql-core | graphql/utils/ast_to_code.py | ast_to_code | def ast_to_code(ast, indent=0):
# type: (Any, int) -> str
"""
Converts an ast into a python code representation of the AST.
"""
code = []
def append(line):
# type: (str) -> None
code.append((" " * indent) + line)
if isinstance(ast, Node):
append("ast.{}(".format(... | python | def ast_to_code(ast, indent=0):
# type: (Any, int) -> str
"""
Converts an ast into a python code representation of the AST.
"""
code = []
def append(line):
# type: (str) -> None
code.append((" " * indent) + line)
if isinstance(ast, Node):
append("ast.{}(".format(... | [
"def",
"ast_to_code",
"(",
"ast",
",",
"indent",
"=",
"0",
")",
":",
"# type: (Any, int) -> str",
"code",
"=",
"[",
"]",
"def",
"append",
"(",
"line",
")",
":",
"# type: (str) -> None",
"code",
".",
"append",
"(",
"(",
"\" \"",
"*",
"indent",
")",
"+"... | Converts an ast into a python code representation of the AST. | [
"Converts",
"an",
"ast",
"into",
"a",
"python",
"code",
"representation",
"of",
"the",
"AST",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/ast_to_code.py#L9-L52 | train |
graphql-python/graphql-core | scripts/casing.py | snake | def snake(s):
"""Convert from title or camelCase to snake_case."""
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += "_"
c = c.lower()
out += c
return out | python | def snake(s):
"""Convert from title or camelCase to snake_case."""
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += "_"
c = c.lower()
out += c
return out | [
"def",
"snake",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
":",
"return",
"s",
".",
"lower",
"(",
")",
"out",
"=",
"s",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"s",
"[",
"1",
":",
"]",
":",
"if",
"c",
"... | Convert from title or camelCase to snake_case. | [
"Convert",
"from",
"title",
"or",
"camelCase",
"to",
"snake_case",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/scripts/casing.py#L19-L29 | train |
graphql-python/graphql-core | graphql/backend/quiver_cloud.py | GraphQLQuiverCloudBackend.make_post_request | def make_post_request(self, url, auth, json_payload):
"""This function executes the request with the provided
json payload and return the json response"""
response = requests.post(url, auth=auth, json=json_payload)
return response.json() | python | def make_post_request(self, url, auth, json_payload):
"""This function executes the request with the provided
json payload and return the json response"""
response = requests.post(url, auth=auth, json=json_payload)
return response.json() | [
"def",
"make_post_request",
"(",
"self",
",",
"url",
",",
"auth",
",",
"json_payload",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"json",
"=",
"json_payload",
")",
"return",
"response",
".",
"json",
"... | This function executes the request with the provided
json payload and return the json response | [
"This",
"function",
"executes",
"the",
"request",
"with",
"the",
"provided",
"json",
"payload",
"and",
"return",
"the",
"json",
"response"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/quiver_cloud.py#L64-L68 | train |
graphql-python/graphql-core | graphql/utils/get_field_def.py | get_field_def | def get_field_def(
schema, # type: GraphQLSchema
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType]
field_ast, # type: Field
):
# type: (...) -> Optional[GraphQLField]
"""Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environm... | python | def get_field_def(
schema, # type: GraphQLSchema
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType]
field_ast, # type: Field
):
# type: (...) -> Optional[GraphQLField]
"""Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environm... | [
"def",
"get_field_def",
"(",
"schema",
",",
"# type: GraphQLSchema",
"parent_type",
",",
"# type: Union[GraphQLInterfaceType, GraphQLObjectType]",
"field_ast",
",",
"# type: Field",
")",
":",
"# type: (...) -> Optional[GraphQLField]",
"name",
"=",
"field_ast",
".",
"name",
".... | Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environment we do not always have an Object type,
and need to handle Interface and Union types. | [
"Not",
"exactly",
"the",
"same",
"as",
"the",
"executor",
"s",
"definition",
"of",
"get_field_def",
"in",
"this",
"statically",
"evaluated",
"environment",
"we",
"do",
"not",
"always",
"have",
"an",
"Object",
"type",
"and",
"need",
"to",
"handle",
"Interface",... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/get_field_def.py#L16-L38 | train |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflicts_within_selection_set | def _find_conflicts_within_selection_set(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_typ... | python | def _find_conflicts_within_selection_set(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_typ... | [
"def",
"_find_conflicts_within_selection_set",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compared_fra... | Find all conflicts found "within" a selection set, including those found via spreading in fragments.
Called when visiting each SelectionSet in the GraphQL Document. | [
"Find",
"all",
"conflicts",
"found",
"within",
"a",
"selection",
"set",
"including",
"those",
"found",
"via",
"spreading",
"in",
"fragments",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L167-L222 | train |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflicts_between_sub_selection_sets | def _find_conflicts_between_sub_selection_sets(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
are_... | python | def _find_conflicts_between_sub_selection_sets(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
are_... | [
"def",
"_find_conflicts_between_sub_selection_sets",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compar... | Find all conflicts found between two selection sets.
Includes those found via spreading in fragments. Called when determining if conflicts exist
between the sub-fields of two overlapping fields. | [
"Find",
"all",
"conflicts",
"found",
"between",
"two",
"selection",
"sets",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L348-L426 | train |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflict | def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclu... | python | def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclu... | [
"def",
"_find_conflict",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compared_fragments",
",",
"# t... | Determines if there is a conflict between two particular fields. | [
"Determines",
"if",
"there",
"is",
"a",
"conflict",
"between",
"two",
"particular",
"fields",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L504-L583 | train |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _get_referenced_fields_and_fragment_names | def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (..... | python | def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (..... | [
"def",
"_get_referenced_fields_and_fragment_names",
"(",
"context",
",",
"# ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"fragment",
... | Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads. | [
"Given",
"a",
"reference",
"to",
"a",
"fragment",
"return",
"the",
"represented",
"collection",
"of",
"fields",
"as",
"well",
"as",
"a",
"list",
"of",
"nested",
"fragment",
"names",
"referenced",
"via",
"fragment",
"spreads",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L609-L630 | train |
graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _subfield_conflicts | def _subfield_conflicts(
conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
response_name, # type: str
ast1, # type: Node
ast2, # type: Node
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Given a series of Conflicts which occurred between... | python | def _subfield_conflicts(
conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
response_name, # type: str
ast1, # type: Node
ast2, # type: Node
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Given a series of Conflicts which occurred between... | [
"def",
"_subfield_conflicts",
"(",
"conflicts",
",",
"# type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]",
"response_name",
",",
"# type: str",
"ast1",
",",
"# type: Node",
"ast2",
",",
"# type: Node",
")",
":",
"# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node]... | Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict. | [
"Given",
"a",
"series",
"of",
"Conflicts",
"which",
"occurred",
"between",
"two",
"sub",
"-",
"fields",
"generate",
"a",
"single",
"Conflict",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L677-L691 | train |
graphql-python/graphql-core | graphql/execution/utils.py | collect_fields | def collect_fields(
ctx, # type: ExecutionContext
runtime_type, # type: GraphQLObjectType
selection_set, # type: SelectionSet
fields, # type: DefaultOrderedDict
prev_fragment_names, # type: Set[str]
):
# type: (...) -> DefaultOrderedDict
"""
Given a selectionSet, adds all of the fie... | python | def collect_fields(
ctx, # type: ExecutionContext
runtime_type, # type: GraphQLObjectType
selection_set, # type: SelectionSet
fields, # type: DefaultOrderedDict
prev_fragment_names, # type: Set[str]
):
# type: (...) -> DefaultOrderedDict
"""
Given a selectionSet, adds all of the fie... | [
"def",
"collect_fields",
"(",
"ctx",
",",
"# type: ExecutionContext",
"runtime_type",
",",
"# type: GraphQLObjectType",
"selection_set",
",",
"# type: SelectionSet",
"fields",
",",
"# type: DefaultOrderedDict",
"prev_fragment_names",
",",
"# type: Set[str]",
")",
":",
"# type... | Given a selectionSet, adds all of the fields in that selection to
the passed in map of fields, and returns it at the end.
collect_fields requires the "runtime type" of an object. For a field which
returns and Interface or Union type, the "runtime type" will be the actual
Object type returned by that fi... | [
"Given",
"a",
"selectionSet",
"adds",
"all",
"of",
"the",
"fields",
"in",
"that",
"selection",
"to",
"the",
"passed",
"in",
"map",
"of",
"fields",
"and",
"returns",
"it",
"at",
"the",
"end",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L224-L282 | train |
graphql-python/graphql-core | graphql/execution/utils.py | should_include_node | def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
"""Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include."""
# TODO: Refactor based on latest code
if directives:
... | python | def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
"""Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include."""
# TODO: Refactor based on latest code
if directives:
... | [
"def",
"should_include_node",
"(",
"ctx",
",",
"directives",
")",
":",
"# type: (ExecutionContext, Optional[List[Directive]]) -> bool",
"# TODO: Refactor based on latest code",
"if",
"directives",
":",
"skip_ast",
"=",
"None",
"for",
"directive",
"in",
"directives",
":",
"i... | Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include. | [
"Determines",
"if",
"a",
"field",
"should",
"be",
"included",
"based",
"on",
"the"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L285-L320 | train |
graphql-python/graphql-core | graphql/execution/utils.py | default_resolve_fn | def default_resolve_fn(source, info, **args):
# type: (Any, ResolveInfo, **Any) -> Optional[Any]
"""If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, ret... | python | def default_resolve_fn(source, info, **args):
# type: (Any, ResolveInfo, **Any) -> Optional[Any]
"""If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, ret... | [
"def",
"default_resolve_fn",
"(",
"source",
",",
"info",
",",
"*",
"*",
"args",
")",
":",
"# type: (Any, ResolveInfo, **Any) -> Optional[Any]",
"name",
"=",
"info",
".",
"field_name",
"if",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"property",
"=",
"... | If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function. | [
"If",
"a",
"resolve",
"function",
"is",
"not",
"given",
"then",
"a",
"default",
"resolve",
"behavior",
"is",
"used",
"which",
"takes",
"the",
"property",
"of",
"the",
"source",
"object",
"of",
"the",
"same",
"name",
"as",
"the",
"field",
"and",
"returns",
... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L351-L362 | train |
graphql-python/graphql-core | graphql/execution/values.py | get_variable_values | def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the inp... | python | def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the inp... | [
"def",
"get_variable_values",
"(",
"schema",
",",
"# type: GraphQLSchema",
"definition_asts",
",",
"# type: List[VariableDefinition]",
"inputs",
",",
"# type: Any",
")",
":",
"# type: (...) -> Dict[str, Any]",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"{",
"}",
... | Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown. | [
"Prepares",
"an",
"object",
"map",
"of",
"variables",
"of",
"the",
"correct",
"type",
"based",
"on",
"the",
"provided",
"variable",
"definitions",
"and",
"arbitrary",
"input",
".",
"If",
"the",
"input",
"cannot",
"be",
"parsed",
"to",
"match",
"the",
"variab... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L34-L86 | train |
graphql-python/graphql-core | graphql/execution/values.py | get_argument_values | def get_argument_values(
arg_defs, # type: Union[Dict[str, GraphQLArgument], Dict]
arg_asts, # type: Optional[List[Argument]]
variables=None, # type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of argument values... | python | def get_argument_values(
arg_defs, # type: Union[Dict[str, GraphQLArgument], Dict]
arg_asts, # type: Optional[List[Argument]]
variables=None, # type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of argument values... | [
"def",
"get_argument_values",
"(",
"arg_defs",
",",
"# type: Union[Dict[str, GraphQLArgument], Dict]",
"arg_asts",
",",
"# type: Optional[List[Argument]]",
"variables",
"=",
"None",
",",
"# type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]",
")",
":",
"# type:... | Prepares an object map of argument values given a list of argument
definitions and list of argument AST nodes. | [
"Prepares",
"an",
"object",
"map",
"of",
"argument",
"values",
"given",
"a",
"list",
"of",
"argument",
"definitions",
"and",
"list",
"of",
"argument",
"AST",
"nodes",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L89-L148 | train |
graphql-python/graphql-core | graphql/execution/values.py | coerce_value | def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime value coerced to match the type."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null... | python | def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime value coerced to match the type."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null... | [
"def",
"coerce_value",
"(",
"type",
",",
"value",
")",
":",
"# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]",
"if",
"isinstance",
"(",
"type",
",",
"GraphQLNonNull",
")",
":",
"# Note: we're not checking that the result of coerceValue is",
"# non-null.",
"... | Given a type and any value, return a runtime value coerced to match the type. | [
"Given",
"a",
"type",
"and",
"any",
"value",
"return",
"a",
"runtime",
"value",
"coerced",
"to",
"match",
"the",
"type",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L151-L186 | train |
graphql-python/graphql-core | graphql/language/parser.py | parse | def parse(source, **kwargs):
# type: (Union[Source, str], **Any) -> Document
"""Given a GraphQL source, parses it into a Document."""
options = {"no_location": False, "no_source": False}
options.update(kwargs)
if isinstance(source, string_types):
source_obj = Source(source) # type: Source
... | python | def parse(source, **kwargs):
# type: (Union[Source, str], **Any) -> Document
"""Given a GraphQL source, parses it into a Document."""
options = {"no_location": False, "no_source": False}
options.update(kwargs)
if isinstance(source, string_types):
source_obj = Source(source) # type: Source
... | [
"def",
"parse",
"(",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Union[Source, str], **Any) -> Document",
"options",
"=",
"{",
"\"no_location\"",
":",
"False",
",",
"\"no_source\"",
":",
"False",
"}",
"options",
".",
"update",
"(",
"kwargs",
")",
"i... | Given a GraphQL source, parses it into a Document. | [
"Given",
"a",
"GraphQL",
"source",
"parses",
"it",
"into",
"a",
"Document",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L52-L64 | train |
graphql-python/graphql-core | graphql/language/parser.py | loc | def loc(parser, start):
# type: (Parser, int) -> Optional[Loc]
"""Returns a location object, used to identify the place in
the source that created a given parsed object."""
if parser.options["no_location"]:
return None
if parser.options["no_source"]:
return Loc(start, parser.prev_en... | python | def loc(parser, start):
# type: (Parser, int) -> Optional[Loc]
"""Returns a location object, used to identify the place in
the source that created a given parsed object."""
if parser.options["no_location"]:
return None
if parser.options["no_source"]:
return Loc(start, parser.prev_en... | [
"def",
"loc",
"(",
"parser",
",",
"start",
")",
":",
"# type: (Parser, int) -> Optional[Loc]",
"if",
"parser",
".",
"options",
"[",
"\"no_location\"",
"]",
":",
"return",
"None",
"if",
"parser",
".",
"options",
"[",
"\"no_source\"",
"]",
":",
"return",
"Loc",
... | Returns a location object, used to identify the place in
the source that created a given parsed object. | [
"Returns",
"a",
"location",
"object",
"used",
"to",
"identify",
"the",
"place",
"in",
"the",
"source",
"that",
"created",
"a",
"given",
"parsed",
"object",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L114-L124 | train |
graphql-python/graphql-core | graphql/language/parser.py | advance | def advance(parser):
# type: (Parser) -> None
"""Moves the internal parser object to the next lexed token."""
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | python | def advance(parser):
# type: (Parser) -> None
"""Moves the internal parser object to the next lexed token."""
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | [
"def",
"advance",
"(",
"parser",
")",
":",
"# type: (Parser) -> None",
"prev_end",
"=",
"parser",
".",
"token",
".",
"end",
"parser",
".",
"prev_end",
"=",
"prev_end",
"parser",
".",
"token",
"=",
"parser",
".",
"lexer",
".",
"next_token",
"(",
"prev_end",
... | Moves the internal parser object to the next lexed token. | [
"Moves",
"the",
"internal",
"parser",
"object",
"to",
"the",
"next",
"lexed",
"token",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L127-L132 | train |
graphql-python/graphql-core | graphql/language/parser.py | skip | def skip(parser, kind):
# type: (Parser, int) -> bool
"""If the next token is of the given kind, return true after advancing
the parser. Otherwise, do not change the parser state
and throw an error."""
match = parser.token.kind == kind
if match:
advance(parser)
return match | python | def skip(parser, kind):
# type: (Parser, int) -> bool
"""If the next token is of the given kind, return true after advancing
the parser. Otherwise, do not change the parser state
and throw an error."""
match = parser.token.kind == kind
if match:
advance(parser)
return match | [
"def",
"skip",
"(",
"parser",
",",
"kind",
")",
":",
"# type: (Parser, int) -> bool",
"match",
"=",
"parser",
".",
"token",
".",
"kind",
"==",
"kind",
"if",
"match",
":",
"advance",
"(",
"parser",
")",
"return",
"match"
] | If the next token is of the given kind, return true after advancing
the parser. Otherwise, do not change the parser state
and throw an error. | [
"If",
"the",
"next",
"token",
"is",
"of",
"the",
"given",
"kind",
"return",
"true",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"throw",
"an",
"error",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L141-L150 | train |
graphql-python/graphql-core | graphql/language/parser.py | expect | def expect(parser, kind):
# type: (Parser, int) -> Token
"""If the next token is of the given kind, return that token after
advancing the parser. Otherwise, do not change the parser state and
return False."""
token = parser.token
if token.kind == kind:
advance(parser)
return toke... | python | def expect(parser, kind):
# type: (Parser, int) -> Token
"""If the next token is of the given kind, return that token after
advancing the parser. Otherwise, do not change the parser state and
return False."""
token = parser.token
if token.kind == kind:
advance(parser)
return toke... | [
"def",
"expect",
"(",
"parser",
",",
"kind",
")",
":",
"# type: (Parser, int) -> Token",
"token",
"=",
"parser",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"kind",
":",
"advance",
"(",
"parser",
")",
"return",
"token",
"raise",
"GraphQLSyntaxError",
"("... | If the next token is of the given kind, return that token after
advancing the parser. Otherwise, do not change the parser state and
return False. | [
"If",
"the",
"next",
"token",
"is",
"of",
"the",
"given",
"kind",
"return",
"that",
"token",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"return",
"False",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L153-L169 | train |
graphql-python/graphql-core | graphql/language/parser.py | expect_keyword | def expect_keyword(parser, value):
# type: (Parser, str) -> Token
"""If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False."""
token = parser.token
if token.kind == TokenKind.NAME and token.va... | python | def expect_keyword(parser, value):
# type: (Parser, str) -> Token
"""If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False."""
token = parser.token
if token.kind == TokenKind.NAME and token.va... | [
"def",
"expect_keyword",
"(",
"parser",
",",
"value",
")",
":",
"# type: (Parser, str) -> Token",
"token",
"=",
"parser",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"TokenKind",
".",
"NAME",
"and",
"token",
".",
"value",
"==",
"value",
":",
"advance",
... | If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False. | [
"If",
"the",
"next",
"token",
"is",
"a",
"keyword",
"with",
"the",
"given",
"value",
"return",
"that",
"token",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"return",
"False",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L172-L186 | train |
graphql-python/graphql-core | graphql/language/parser.py | unexpected | def unexpected(parser, at_token=None):
# type: (Parser, Optional[Any]) -> GraphQLSyntaxError
"""Helper function for creating an error when an unexpected lexed token
is encountered."""
token = at_token or parser.token
return GraphQLSyntaxError(
parser.source, token.start, u"Unexpected {}".for... | python | def unexpected(parser, at_token=None):
# type: (Parser, Optional[Any]) -> GraphQLSyntaxError
"""Helper function for creating an error when an unexpected lexed token
is encountered."""
token = at_token or parser.token
return GraphQLSyntaxError(
parser.source, token.start, u"Unexpected {}".for... | [
"def",
"unexpected",
"(",
"parser",
",",
"at_token",
"=",
"None",
")",
":",
"# type: (Parser, Optional[Any]) -> GraphQLSyntaxError",
"token",
"=",
"at_token",
"or",
"parser",
".",
"token",
"return",
"GraphQLSyntaxError",
"(",
"parser",
".",
"source",
",",
"token",
... | Helper function for creating an error when an unexpected lexed token
is encountered. | [
"Helper",
"function",
"for",
"creating",
"an",
"error",
"when",
"an",
"unexpected",
"lexed",
"token",
"is",
"encountered",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L189-L196 | train |
graphql-python/graphql-core | graphql/language/parser.py | any | def any(parser, open_kind, parse_fn, close_kind):
# type: (Parser, int, Callable, int) -> Any
"""Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token a... | python | def any(parser, open_kind, parse_fn, close_kind):
# type: (Parser, int, Callable, int) -> Any
"""Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token a... | [
"def",
"any",
"(",
"parser",
",",
"open_kind",
",",
"parse_fn",
",",
"close_kind",
")",
":",
"# type: (Parser, int, Callable, int) -> Any",
"expect",
"(",
"parser",
",",
"open_kind",
")",
"nodes",
"=",
"[",
"]",
"while",
"not",
"skip",
"(",
"parser",
",",
"c... | Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token after the closing token. | [
"Returns",
"a",
"possibly",
"empty",
"list",
"of",
"parse",
"nodes",
"determined",
"by",
"the",
"parse_fn",
".",
"This",
"list",
"begins",
"with",
"a",
"lex",
"token",
"of",
"openKind",
"and",
"ends",
"with",
"a",
"lex",
"token",
"of",
"closeKind",
".",
... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L199-L210 | train |
graphql-python/graphql-core | graphql/language/parser.py | parse_name | def parse_name(parser):
# type: (Parser) -> Name
"""Converts a name lex token into a name parse node."""
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | python | def parse_name(parser):
# type: (Parser) -> Name
"""Converts a name lex token into a name parse node."""
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | [
"def",
"parse_name",
"(",
"parser",
")",
":",
"# type: (Parser) -> Name",
"token",
"=",
"expect",
"(",
"parser",
",",
"TokenKind",
".",
"NAME",
")",
"return",
"ast",
".",
"Name",
"(",
"value",
"=",
"token",
".",
"value",
",",
"loc",
"=",
"loc",
"(",
"p... | Converts a name lex token into a name parse node. | [
"Converts",
"a",
"name",
"lex",
"token",
"into",
"a",
"name",
"parse",
"node",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L227-L231 | train |
kieferk/dfply | dfply/summary_functions.py | mean | def mean(series):
"""
Returns the mean of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.mean()
else:
return np.nan | python | def mean(series):
"""
Returns the mean of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.mean()
else:
return np.nan | [
"def",
"mean",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"mean",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the mean of a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"mean",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L11-L22 | train |
kieferk/dfply | dfply/summary_functions.py | first | def first(series, order_by=None):
"""
Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is... | python | def first(series, order_by=None):
"""
Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is... | [
"def",
"first",
"(",
"series",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"first_s",
"=",
"series",
".",
"iloc",
"[",
"0",
"]",
"return",
... | Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | [
"Returns",
"the",
"first",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L26-L41 | train |
kieferk/dfply | dfply/summary_functions.py | last | def last(series, order_by=None):
"""
Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is n... | python | def last(series, order_by=None):
"""
Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is n... | [
"def",
"last",
"(",
"series",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"last_s",
"=",
"series",
".",
"iloc",
"[",
"series",
".",
"size",
... | Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | [
"Returns",
"the",
"last",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L45-L60 | train |
kieferk/dfply | dfply/summary_functions.py | nth | def nth(series, n, order_by=None):
"""
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
... | python | def nth(series, n, order_by=None):
"""
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
... | [
"def",
"nth",
"(",
"series",
",",
"n",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"try",
":",
"return",
"series",
".",
"iloc",
"[",
"n",
... | Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarizati... | [
"Returns",
"the",
"nth",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L64-L82 | train |
kieferk/dfply | dfply/summary_functions.py | median | def median(series):
"""
Returns the median value of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.median()
else:
return np.nan | python | def median(series):
"""
Returns the median value of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.median()
else:
return np.nan | [
"def",
"median",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"median",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the median value of a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"median",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L153-L164 | train |
kieferk/dfply | dfply/summary_functions.py | var | def var(series):
"""
Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.var()
else:
return np.nan | python | def var(series):
"""
Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.var()
else:
return np.nan | [
"def",
"var",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"var",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"variance",
"of",
"values",
"in",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L168-L178 | train |
kieferk/dfply | dfply/summary_functions.py | sd | def sd(series):
"""
Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.std()
else:
return np.nan | python | def sd(series):
"""
Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.std()
else:
return np.nan | [
"def",
"sd",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"std",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"standard",
"deviation",
"of",
"values",
"in",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L182-L193 | train |
kieferk/dfply | dfply/join.py | get_join_parameters | def get_join_parameters(join_kwargs):
"""
Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns.
"""
by = join_kwargs.get('by', None)
suffixes = join_kwargs.get('suffixes', ('_x', '_y'))
if isinstance(by, tuple):
... | python | def get_join_parameters(join_kwargs):
"""
Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns.
"""
by = join_kwargs.get('by', None)
suffixes = join_kwargs.get('suffixes', ('_x', '_y'))
if isinstance(by, tuple):
... | [
"def",
"get_join_parameters",
"(",
"join_kwargs",
")",
":",
"by",
"=",
"join_kwargs",
".",
"get",
"(",
"'by'",
",",
"None",
")",
"suffixes",
"=",
"join_kwargs",
".",
"get",
"(",
"'suffixes'",
",",
"(",
"'_x'",
",",
"'_y'",
")",
")",
"if",
"isinstance",
... | Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns. | [
"Convenience",
"function",
"to",
"determine",
"the",
"columns",
"to",
"join",
"the",
"right",
"and",
"left",
"DataFrames",
"on",
"as",
"well",
"as",
"any",
"suffixes",
"for",
"the",
"columns",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L8-L23 | train |
kieferk/dfply | dfply/join.py | inner_join | def inner_join(df, other, **kwargs):
"""
Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
... | python | def inner_join(df, other, **kwargs):
"""
Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
... | [
"def",
"inner_join",
"(",
"df",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"left_on",
",",
"right_on",
",",
"suffixes",
"=",
"get_join_parameters",
"(",
"kwargs",
")",
"joined",
"=",
"df",
".",
"merge",
"(",
"other",
",",
"how",
"=",
"'inner'",
... | Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contai... | [
"Joins",
"on",
"values",
"present",
"in",
"both",
"DataFrames",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L27-L53 | train |
kieferk/dfply | dfply/join.py | anti_join | def anti_join(df, other, **kwargs):
"""
Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Column... | python | def anti_join(df, other, **kwargs):
"""
Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Column... | [
"def",
"anti_join",
"(",
"df",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"left_on",
",",
"right_on",
",",
"suffixes",
"=",
"get_join_parameters",
"(",
"kwargs",
")",
"if",
"not",
"right_on",
":",
"right_on",
"=",
"[",
"col_name",
"for",
"col_name"... | Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
... | [
"Returns",
"all",
"of",
"the",
"rows",
"in",
"the",
"left",
"DataFrame",
"that",
"do",
"not",
"have",
"a",
"match",
"in",
"the",
"right",
"DataFrame",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L219-L250 | train |
kieferk/dfply | dfply/join.py | bind_rows | def bind_rows(df, other, join='outer', ignore_index=False):
"""
Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwarg... | python | def bind_rows(df, other, join='outer', ignore_index=False):
"""
Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwarg... | [
"def",
"bind_rows",
"(",
"df",
",",
"other",
",",
"join",
"=",
"'outer'",
",",
"ignore_index",
"=",
"False",
")",
":",
"df",
"=",
"pd",
".",
"concat",
"(",
"[",
"df",
",",
"other",
"]",
",",
"join",
"=",
"join",
",",
"ignore_index",
"=",
"ignore_in... | Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will pr... | [
"Binds",
"DataFrames",
"vertically",
"stacking",
"them",
"together",
".",
"This",
"is",
"equivalent",
"to",
"pd",
".",
"concat",
"with",
"axis",
"=",
"0",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L258-L276 | train |
kieferk/dfply | dfply/reshape.py | arrange | def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in ... | python | def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in ... | [
"def",
"arrange",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"flat_args",
"=",
"[",
"a",
"for",
"a",
"in",
"flatten",
"(",
"args",
")",
"]",
"series",
"=",
"[",
"df",
"[",
"arg",
"]",
"if",
"isinstance",
"(",
"arg",
",",
... | Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbo... | [
"Calls",
"pandas",
".",
"DataFrame",
".",
"sort_values",
"to",
"sort",
"a",
"DataFrame",
"according",
"to",
"criteria",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L10-L37 | train |
kieferk/dfply | dfply/reshape.py | rename | def rename(df, **kwargs):
"""Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
... | python | def rename(df, **kwargs):
"""Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
... | [
"def",
"rename",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"df",
".",
"rename",
"(",
"columns",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
")"
] | Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
values are current names... | [
"Renames",
"columns",
"where",
"keyword",
"argument",
"values",
"are",
"the",
"current",
"names",
"of",
"columns",
"and",
"keys",
"are",
"the",
"new",
"names",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L46-L58 | train |
kieferk/dfply | dfply/reshape.py | convert_type | def convert_type(df, columns):
"""
Helper function that attempts to convert columns into their appropriate
data type.
"""
# taken in part from the dplython package
out_df = df.copy()
for col in columns:
column_values = pd.Series(out_df[col].unique())
column_values = column_va... | python | def convert_type(df, columns):
"""
Helper function that attempts to convert columns into their appropriate
data type.
"""
# taken in part from the dplython package
out_df = df.copy()
for col in columns:
column_values = pd.Series(out_df[col].unique())
column_values = column_va... | [
"def",
"convert_type",
"(",
"df",
",",
"columns",
")",
":",
"# taken in part from the dplython package",
"out_df",
"=",
"df",
".",
"copy",
"(",
")",
"for",
"col",
"in",
"columns",
":",
"column_values",
"=",
"pd",
".",
"Series",
"(",
"out_df",
"[",
"col",
"... | Helper function that attempts to convert columns into their appropriate
data type. | [
"Helper",
"function",
"that",
"attempts",
"to",
"convert",
"columns",
"into",
"their",
"appropriate",
"data",
"type",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L111-L138 | train |
kieferk/dfply | dfply/reshape.py | spread | def spread(df, key, values, convert=False):
"""
Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want t... | python | def spread(df, key, values, convert=False):
"""
Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want t... | [
"def",
"spread",
"(",
"df",
",",
"key",
",",
"values",
",",
"convert",
"=",
"False",
")",
":",
"# Taken mostly from dplython package",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"id_cols",
"=",
"[",
"col",
"for",
"col",
"in",
"columns... | Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want to try to convert dtypes when spreading, you can set
... | [
"Transforms",
"a",
"long",
"DataFrame",
"into",
"a",
"wide",
"format",
"using",
"a",
"key",
"and",
"value",
"column",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L143-L201 | train |
kieferk/dfply | dfply/reshape.py | separate | def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (lis... | python | def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (lis... | [
"def",
"separate",
"(",
"df",
",",
"column",
",",
"into",
",",
"sep",
"=",
"\"[\\W_]+\"",
",",
"remove",
"=",
"True",
",",
"convert",
"=",
"False",
",",
"extra",
"=",
"'drop'",
",",
"fill",
"=",
"'right'",
")",
":",
"assert",
"isinstance",
"(",
"into... | Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (list): List of string names for new columns.
Kwargs:
sep (str or list): If a string, the regex string used to split t... | [
"Splits",
"columns",
"into",
"multiple",
"columns",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L210-L272 | train |
kieferk/dfply | dfply/reshape.py | unite | def unite(df, colname, *args, **kwargs):
"""
Does the inverse of `separate`, joining columns together by a specified
separator.
Any columns that are not strings will be converted to strings.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
colname (str): the name ... | python | def unite(df, colname, *args, **kwargs):
"""
Does the inverse of `separate`, joining columns together by a specified
separator.
Any columns that are not strings will be converted to strings.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
colname (str): the name ... | [
"def",
"unite",
"(",
"df",
",",
"colname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"to_unite",
"=",
"list",
"(",
"[",
"a",
"for",
"a",
"in",
"flatten",
"(",
"args",
")",
"]",
")",
"sep",
"=",
"kwargs",
".",
"get",
"(",
"'sep'",
"... | Does the inverse of `separate`, joining columns together by a specified
separator.
Any columns that are not strings will be converted to strings.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
colname (str): the name of the new joined column.
*args: list of colu... | [
"Does",
"the",
"inverse",
"of",
"separate",
"joining",
"columns",
"together",
"by",
"a",
"specified",
"separator",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L281-L329 | train |
kieferk/dfply | dfply/set_ops.py | validate_set_ops | def validate_set_ops(df, other):
"""
Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names.
"""
if df.columns.values.tolist() != other.columns.values.tolist():
... | python | def validate_set_ops(df, other):
"""
Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names.
"""
if df.columns.values.tolist() != other.columns.values.tolist():
... | [
"def",
"validate_set_ops",
"(",
"df",
",",
"other",
")",
":",
"if",
"df",
".",
"columns",
".",
"values",
".",
"tolist",
"(",
")",
"!=",
"other",
".",
"columns",
".",
"values",
".",
"tolist",
"(",
")",
":",
"not_in_df",
"=",
"[",
"col",
"for",
"col"... | Helper function to ensure that DataFrames are valid for set operations.
Columns must be the same name in the same order, and indices must be of the
same dimension with the same names. | [
"Helper",
"function",
"to",
"ensure",
"that",
"DataFrames",
"are",
"valid",
"for",
"set",
"operations",
".",
"Columns",
"must",
"be",
"the",
"same",
"name",
"in",
"the",
"same",
"order",
"and",
"indices",
"must",
"be",
"of",
"the",
"same",
"dimension",
"wi... | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/set_ops.py#L6-L27 | train |
kieferk/dfply | dfply/set_ops.py | union | def union(df, other, index=False, keep='first'):
"""
Returns rows that appear in either DataFrame.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): ... | python | def union(df, other, index=False, keep='first'):
"""
Returns rows that appear in either DataFrame.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): ... | [
"def",
"union",
"(",
"df",
",",
"other",
",",
"index",
"=",
"False",
",",
"keep",
"=",
"'first'",
")",
":",
"validate_set_ops",
"(",
"df",
",",
"other",
")",
"stacked",
"=",
"df",
".",
"append",
"(",
"other",
")",
"if",
"index",
":",
"stacked_reset_i... | Returns rows that appear in either DataFrame.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
... | [
"Returns",
"rows",
"that",
"appear",
"in",
"either",
"DataFrame",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/set_ops.py#L35-L60 | train |
kieferk/dfply | dfply/set_ops.py | intersect | def intersect(df, other, index=False, keep='first'):
"""
Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool... | python | def intersect(df, other, index=False, keep='first'):
"""
Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool... | [
"def",
"intersect",
"(",
"df",
",",
"other",
",",
"index",
"=",
"False",
",",
"keep",
"=",
"'first'",
")",
":",
"validate_set_ops",
"(",
"df",
",",
"other",
")",
"if",
"index",
":",
"df_reset_index",
"=",
"df",
".",
"reset_index",
"(",
")",
"other_rese... | Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool): Boolean indicating whether to consider the pandas index
... | [
"Returns",
"rows",
"that",
"appear",
"in",
"both",
"DataFrames",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/set_ops.py#L69-L105 | train |
kieferk/dfply | dfply/transform.py | transmute | def transmute(df, *keep_columns, **kwargs):
"""
Creates columns and then returns those new columns and optionally specified
original columns from the DataFrame.
This works like `mutate`, but designed to discard the original columns used
to create the new ones.
Args:
*keep_columns: Colu... | python | def transmute(df, *keep_columns, **kwargs):
"""
Creates columns and then returns those new columns and optionally specified
original columns from the DataFrame.
This works like `mutate`, but designed to discard the original columns used
to create the new ones.
Args:
*keep_columns: Colu... | [
"def",
"transmute",
"(",
"df",
",",
"*",
"keep_columns",
",",
"*",
"*",
"kwargs",
")",
":",
"keep_cols",
"=",
"[",
"]",
"for",
"col",
"in",
"flatten",
"(",
"keep_columns",
")",
":",
"try",
":",
"keep_cols",
".",
"append",
"(",
"col",
".",
"name",
"... | Creates columns and then returns those new columns and optionally specified
original columns from the DataFrame.
This works like `mutate`, but designed to discard the original columns used
to create the new ones.
Args:
*keep_columns: Column labels to keep. Can be string, symbolic, or
... | [
"Creates",
"columns",
"and",
"then",
"returns",
"those",
"new",
"columns",
"and",
"optionally",
"specified",
"original",
"columns",
"from",
"the",
"DataFrame",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/transform.py#L64-L101 | train |
kieferk/dfply | dfply/vector.py | coalesce | def coalesce(*series):
"""
Takes the first non-NaN value in order across the specified series,
returning a new series. Mimics the coalesce function in dplyr and SQL.
Args:
*series: Series objects, typically represented in their symbolic form
(like X.series).
Example:
df... | python | def coalesce(*series):
"""
Takes the first non-NaN value in order across the specified series,
returning a new series. Mimics the coalesce function in dplyr and SQL.
Args:
*series: Series objects, typically represented in their symbolic form
(like X.series).
Example:
df... | [
"def",
"coalesce",
"(",
"*",
"series",
")",
":",
"series",
"=",
"[",
"pd",
".",
"Series",
"(",
"s",
")",
"for",
"s",
"in",
"series",
"]",
"coalescer",
"=",
"pd",
".",
"concat",
"(",
"series",
",",
"axis",
"=",
"1",
")",
"min_nonna",
"=",
"np",
... | Takes the first non-NaN value in order across the specified series,
returning a new series. Mimics the coalesce function in dplyr and SQL.
Args:
*series: Series objects, typically represented in their symbolic form
(like X.series).
Example:
df = pd.DataFrame({
'a':[... | [
"Takes",
"the",
"first",
"non",
"-",
"NaN",
"value",
"in",
"order",
"across",
"the",
"specified",
"series",
"returning",
"a",
"new",
"series",
".",
"Mimics",
"the",
"coalesce",
"function",
"in",
"dplyr",
"and",
"SQL",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/vector.py#L80-L110 | train |
kieferk/dfply | dfply/vector.py | case_when | def case_when(*conditions):
"""
Functions as a switch statement, creating a new series out of logical
conditions specified by 2-item lists where the left-hand item is the
logical condition and the right-hand item is the value where that
condition is true.
Conditions should go from the most spec... | python | def case_when(*conditions):
"""
Functions as a switch statement, creating a new series out of logical
conditions specified by 2-item lists where the left-hand item is the
logical condition and the right-hand item is the value where that
condition is true.
Conditions should go from the most spec... | [
"def",
"case_when",
"(",
"*",
"conditions",
")",
":",
"lengths",
"=",
"[",
"]",
"for",
"logical",
",",
"outcome",
"in",
"conditions",
":",
"if",
"isinstance",
"(",
"logical",
",",
"collections",
".",
"Iterable",
")",
":",
"lengths",
".",
"append",
"(",
... | Functions as a switch statement, creating a new series out of logical
conditions specified by 2-item lists where the left-hand item is the
logical condition and the right-hand item is the value where that
condition is true.
Conditions should go from the most specific to the most general. A
conditio... | [
"Functions",
"as",
"a",
"switch",
"statement",
"creating",
"a",
"new",
"series",
"out",
"of",
"logical",
"conditions",
"specified",
"by",
"2",
"-",
"item",
"lists",
"where",
"the",
"left",
"-",
"hand",
"item",
"is",
"the",
"logical",
"condition",
"and",
"t... | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/vector.py#L118-L189 | train |
kieferk/dfply | dfply/vector.py | if_else | def if_else(condition, when_true, otherwise):
"""
Wraps creation of a series based on if-else conditional logic into a function
call.
Provide a boolean vector condition, value(s) when true, and value(s)
when false, and a vector will be returned the same length as the conditional
vector accordin... | python | def if_else(condition, when_true, otherwise):
"""
Wraps creation of a series based on if-else conditional logic into a function
call.
Provide a boolean vector condition, value(s) when true, and value(s)
when false, and a vector will be returned the same length as the conditional
vector accordin... | [
"def",
"if_else",
"(",
"condition",
",",
"when_true",
",",
"otherwise",
")",
":",
"if",
"not",
"isinstance",
"(",
"when_true",
",",
"collections",
".",
"Iterable",
")",
"or",
"isinstance",
"(",
"when_true",
",",
"str",
")",
":",
"when_true",
"=",
"np",
"... | Wraps creation of a series based on if-else conditional logic into a function
call.
Provide a boolean vector condition, value(s) when true, and value(s)
when false, and a vector will be returned the same length as the conditional
vector according to the logical statement.
Args:
condition: ... | [
"Wraps",
"creation",
"of",
"a",
"series",
"based",
"on",
"if",
"-",
"else",
"conditional",
"logic",
"into",
"a",
"function",
"call",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/vector.py#L197-L231 | train |
kieferk/dfply | dfply/vector.py | na_if | def na_if(series, *values):
"""
If values in a series match a specified value, change them to `np.nan`.
Args:
series: Series or vector, often symbolic.
*values: Value(s) to convert to `np.nan` in the series.
"""
series = pd.Series(series)
series[series.isin(values)] = np.nan
... | python | def na_if(series, *values):
"""
If values in a series match a specified value, change them to `np.nan`.
Args:
series: Series or vector, often symbolic.
*values: Value(s) to convert to `np.nan` in the series.
"""
series = pd.Series(series)
series[series.isin(values)] = np.nan
... | [
"def",
"na_if",
"(",
"series",
",",
"*",
"values",
")",
":",
"series",
"=",
"pd",
".",
"Series",
"(",
"series",
")",
"series",
"[",
"series",
".",
"isin",
"(",
"values",
")",
"]",
"=",
"np",
".",
"nan",
"return",
"series"
] | If values in a series match a specified value, change them to `np.nan`.
Args:
series: Series or vector, often symbolic.
*values: Value(s) to convert to `np.nan` in the series. | [
"If",
"values",
"in",
"a",
"series",
"match",
"a",
"specified",
"value",
"change",
"them",
"to",
"np",
".",
"nan",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/vector.py#L239-L250 | train |
kieferk/dfply | dfply/window_functions.py | between | def between(series, a, b, inclusive=False):
"""
Returns a boolean series specifying whether rows of the input series
are between values `a` and `b`.
Args:
series: column to compare, typically symbolic.
a: value series must be greater than (or equal to if `inclusive=True`)
fo... | python | def between(series, a, b, inclusive=False):
"""
Returns a boolean series specifying whether rows of the input series
are between values `a` and `b`.
Args:
series: column to compare, typically symbolic.
a: value series must be greater than (or equal to if `inclusive=True`)
fo... | [
"def",
"between",
"(",
"series",
",",
"a",
",",
"b",
",",
"inclusive",
"=",
"False",
")",
":",
"if",
"inclusive",
"==",
"True",
":",
"met_condition",
"=",
"(",
"series",
">=",
"a",
")",
"&",
"(",
"series",
"<=",
"b",
")",
"elif",
"inclusive",
"==",... | Returns a boolean series specifying whether rows of the input series
are between values `a` and `b`.
Args:
series: column to compare, typically symbolic.
a: value series must be greater than (or equal to if `inclusive=True`)
for the output series to be `True` at that position.
... | [
"Returns",
"a",
"boolean",
"series",
"specifying",
"whether",
"rows",
"of",
"the",
"input",
"series",
"are",
"between",
"values",
"a",
"and",
"b",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/window_functions.py#L43-L64 | train |
euske/pdfminer | pdfminer/psparser.py | PSBaseParser.seek | def seek(self, pos):
"""Seeks the parser to the given position.
"""
if self.debug:
logging.debug('seek: %r' % pos)
self.fp.seek(pos)
# reset the status for nextline()
self.bufpos = pos
self.buf = b''
self.charpos = 0
# reset the status ... | python | def seek(self, pos):
"""Seeks the parser to the given position.
"""
if self.debug:
logging.debug('seek: %r' % pos)
self.fp.seek(pos)
# reset the status for nextline()
self.bufpos = pos
self.buf = b''
self.charpos = 0
# reset the status ... | [
"def",
"seek",
"(",
"self",
",",
"pos",
")",
":",
"if",
"self",
".",
"debug",
":",
"logging",
".",
"debug",
"(",
"'seek: %r'",
"%",
"pos",
")",
"self",
".",
"fp",
".",
"seek",
"(",
"pos",
")",
"# reset the status for nextline()",
"self",
".",
"bufpos",... | Seeks the parser to the given position. | [
"Seeks",
"the",
"parser",
"to",
"the",
"given",
"position",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/psparser.py#L191-L206 | train |
euske/pdfminer | pdfminer/psparser.py | PSBaseParser.nextline | def nextline(self):
"""Fetches a next line that ends either with \\r or \\n.
"""
linebuf = b''
linepos = self.bufpos + self.charpos
eol = False
while 1:
self.fillbuf()
if eol:
c = self.buf[self.charpos]
# handle b'\r... | python | def nextline(self):
"""Fetches a next line that ends either with \\r or \\n.
"""
linebuf = b''
linepos = self.bufpos + self.charpos
eol = False
while 1:
self.fillbuf()
if eol:
c = self.buf[self.charpos]
# handle b'\r... | [
"def",
"nextline",
"(",
"self",
")",
":",
"linebuf",
"=",
"b''",
"linepos",
"=",
"self",
".",
"bufpos",
"+",
"self",
".",
"charpos",
"eol",
"=",
"False",
"while",
"1",
":",
"self",
".",
"fillbuf",
"(",
")",
"if",
"eol",
":",
"c",
"=",
"self",
"."... | Fetches a next line that ends either with \\r or \\n. | [
"Fetches",
"a",
"next",
"line",
"that",
"ends",
"either",
"with",
"\\\\",
"r",
"or",
"\\\\",
"n",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/psparser.py#L219-L247 | train |
euske/pdfminer | pdfminer/psparser.py | PSBaseParser.revreadlines | def revreadlines(self):
"""Fetches a next line backward.
This is used to locate the trailers at the end of a file.
"""
self.fp.seek(0, 2)
pos = self.fp.tell()
buf = b''
while 0 < pos:
prevpos = pos
pos = max(0, pos-self.BUFSIZ)
... | python | def revreadlines(self):
"""Fetches a next line backward.
This is used to locate the trailers at the end of a file.
"""
self.fp.seek(0, 2)
pos = self.fp.tell()
buf = b''
while 0 < pos:
prevpos = pos
pos = max(0, pos-self.BUFSIZ)
... | [
"def",
"revreadlines",
"(",
"self",
")",
":",
"self",
".",
"fp",
".",
"seek",
"(",
"0",
",",
"2",
")",
"pos",
"=",
"self",
".",
"fp",
".",
"tell",
"(",
")",
"buf",
"=",
"b''",
"while",
"0",
"<",
"pos",
":",
"prevpos",
"=",
"pos",
"pos",
"=",
... | Fetches a next line backward.
This is used to locate the trailers at the end of a file. | [
"Fetches",
"a",
"next",
"line",
"backward",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/psparser.py#L249-L272 | train |
euske/pdfminer | pdfminer/psparser.py | PSStackParser.nextobject | def nextobject(self):
"""Yields a list of objects.
Returns keywords, literals, strings, numbers, arrays and dictionaries.
Arrays and dictionaries are represented as Python lists and dictionaries.
"""
while not self.results:
(pos, token) = self.nexttoken()
... | python | def nextobject(self):
"""Yields a list of objects.
Returns keywords, literals, strings, numbers, arrays and dictionaries.
Arrays and dictionaries are represented as Python lists and dictionaries.
"""
while not self.results:
(pos, token) = self.nexttoken()
... | [
"def",
"nextobject",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"results",
":",
"(",
"pos",
",",
"token",
")",
"=",
"self",
".",
"nexttoken",
"(",
")",
"#print (pos,token), (self.curtype, self.curstack)",
"if",
"isinstance",
"(",
"token",
",",
"(",
... | Yields a list of objects.
Returns keywords, literals, strings, numbers, arrays and dictionaries.
Arrays and dictionaries are represented as Python lists and dictionaries. | [
"Yields",
"a",
"list",
"of",
"objects",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/psparser.py#L567-L626 | train |
euske/pdfminer | pdfminer/encodingdb.py | name2unicode | def name2unicode(name):
"""Converts Adobe glyph names to Unicode numbers."""
if name in glyphname2unicode:
return glyphname2unicode[name]
m = STRIP_NAME.search(name)
if not m:
raise KeyError(name)
return unichr(int(m.group(0))) | python | def name2unicode(name):
"""Converts Adobe glyph names to Unicode numbers."""
if name in glyphname2unicode:
return glyphname2unicode[name]
m = STRIP_NAME.search(name)
if not m:
raise KeyError(name)
return unichr(int(m.group(0))) | [
"def",
"name2unicode",
"(",
"name",
")",
":",
"if",
"name",
"in",
"glyphname2unicode",
":",
"return",
"glyphname2unicode",
"[",
"name",
"]",
"m",
"=",
"STRIP_NAME",
".",
"search",
"(",
"name",
")",
"if",
"not",
"m",
":",
"raise",
"KeyError",
"(",
"name",... | Converts Adobe glyph names to Unicode numbers. | [
"Converts",
"Adobe",
"glyph",
"names",
"to",
"Unicode",
"numbers",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/encodingdb.py#L13-L20 | train |
euske/pdfminer | pdfminer/pdftypes.py | resolve1 | def resolve1(x, default=None):
"""Resolves an object.
If this is an array or dictionary, it may still contains
some indirect objects inside.
"""
while isinstance(x, PDFObjRef):
x = x.resolve(default=default)
return x | python | def resolve1(x, default=None):
"""Resolves an object.
If this is an array or dictionary, it may still contains
some indirect objects inside.
"""
while isinstance(x, PDFObjRef):
x = x.resolve(default=default)
return x | [
"def",
"resolve1",
"(",
"x",
",",
"default",
"=",
"None",
")",
":",
"while",
"isinstance",
"(",
"x",
",",
"PDFObjRef",
")",
":",
"x",
"=",
"x",
".",
"resolve",
"(",
"default",
"=",
"default",
")",
"return",
"x"
] | Resolves an object.
If this is an array or dictionary, it may still contains
some indirect objects inside. | [
"Resolves",
"an",
"object",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdftypes.py#L73-L81 | train |
euske/pdfminer | pdfminer/pdftypes.py | resolve_all | def resolve_all(x, default=None):
"""Recursively resolves the given object and all the internals.
Make sure there is no indirect reference within the nested object.
This procedure might be slow.
"""
while isinstance(x, PDFObjRef):
x = x.resolve(default=default)
if isinstance(x, list):
... | python | def resolve_all(x, default=None):
"""Recursively resolves the given object and all the internals.
Make sure there is no indirect reference within the nested object.
This procedure might be slow.
"""
while isinstance(x, PDFObjRef):
x = x.resolve(default=default)
if isinstance(x, list):
... | [
"def",
"resolve_all",
"(",
"x",
",",
"default",
"=",
"None",
")",
":",
"while",
"isinstance",
"(",
"x",
",",
"PDFObjRef",
")",
":",
"x",
"=",
"x",
".",
"resolve",
"(",
"default",
"=",
"default",
")",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
... | Recursively resolves the given object and all the internals.
Make sure there is no indirect reference within the nested object.
This procedure might be slow. | [
"Recursively",
"resolves",
"the",
"given",
"object",
"and",
"all",
"the",
"internals",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdftypes.py#L84-L97 | train |
euske/pdfminer | pdfminer/pdftypes.py | decipher_all | def decipher_all(decipher, objid, genno, x):
"""Recursively deciphers the given object.
"""
if isinstance(x, str):
return decipher(objid, genno, x)
if isinstance(x, list):
x = [decipher_all(decipher, objid, genno, v) for v in x]
elif isinstance(x, dict):
for (k, v) in x.iteri... | python | def decipher_all(decipher, objid, genno, x):
"""Recursively deciphers the given object.
"""
if isinstance(x, str):
return decipher(objid, genno, x)
if isinstance(x, list):
x = [decipher_all(decipher, objid, genno, v) for v in x]
elif isinstance(x, dict):
for (k, v) in x.iteri... | [
"def",
"decipher_all",
"(",
"decipher",
",",
"objid",
",",
"genno",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"decipher",
"(",
"objid",
",",
"genno",
",",
"x",
")",
"if",
"isinstance",
"(",
"x",
",",
"list",
... | Recursively deciphers the given object. | [
"Recursively",
"deciphers",
"the",
"given",
"object",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdftypes.py#L100-L110 | train |
euske/pdfminer | pdfminer/pdfdocument.py | PDFDocument.find_xref | def find_xref(self, parser):
"""Internal function used to locate the first XRef."""
# search the last xref table by scanning the file backwards.
prev = None
for line in parser.revreadlines():
line = line.strip()
if self.debug:
logging.debug('find_x... | python | def find_xref(self, parser):
"""Internal function used to locate the first XRef."""
# search the last xref table by scanning the file backwards.
prev = None
for line in parser.revreadlines():
line = line.strip()
if self.debug:
logging.debug('find_x... | [
"def",
"find_xref",
"(",
"self",
",",
"parser",
")",
":",
"# search the last xref table by scanning the file backwards.",
"prev",
"=",
"None",
"for",
"line",
"in",
"parser",
".",
"revreadlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",... | Internal function used to locate the first XRef. | [
"Internal",
"function",
"used",
"to",
"locate",
"the",
"first",
"XRef",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdfdocument.py#L755-L771 | train |
euske/pdfminer | pdfminer/pdfdocument.py | PDFDocument.read_xref_from | def read_xref_from(self, parser, start, xrefs):
"""Reads XRefs from the given location."""
parser.seek(start)
parser.reset()
try:
(pos, token) = parser.nexttoken()
except PSEOF:
raise PDFNoValidXRef('Unexpected EOF')
if self.debug:
logg... | python | def read_xref_from(self, parser, start, xrefs):
"""Reads XRefs from the given location."""
parser.seek(start)
parser.reset()
try:
(pos, token) = parser.nexttoken()
except PSEOF:
raise PDFNoValidXRef('Unexpected EOF')
if self.debug:
logg... | [
"def",
"read_xref_from",
"(",
"self",
",",
"parser",
",",
"start",
",",
"xrefs",
")",
":",
"parser",
".",
"seek",
"(",
"start",
")",
"parser",
".",
"reset",
"(",
")",
"try",
":",
"(",
"pos",
",",
"token",
")",
"=",
"parser",
".",
"nexttoken",
"(",
... | Reads XRefs from the given location. | [
"Reads",
"XRefs",
"from",
"the",
"given",
"location",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdfdocument.py#L774-L806 | train |
euske/pdfminer | pdfminer/utils.py | mult_matrix | def mult_matrix(m1, m0):
(a1, b1, c1, d1, e1, f1) = m1
(a0, b0, c0, d0, e0, f0) = m0
"""Returns the multiplication of two matrices."""
return (a0*a1+c0*b1, b0*a1+d0*b1,
a0*c1+c0*d1, b0*c1+d0*d1,
a0*e1+c0*f1+e0, b0*e1+d0*f1+f0) | python | def mult_matrix(m1, m0):
(a1, b1, c1, d1, e1, f1) = m1
(a0, b0, c0, d0, e0, f0) = m0
"""Returns the multiplication of two matrices."""
return (a0*a1+c0*b1, b0*a1+d0*b1,
a0*c1+c0*d1, b0*c1+d0*d1,
a0*e1+c0*f1+e0, b0*e1+d0*f1+f0) | [
"def",
"mult_matrix",
"(",
"m1",
",",
"m0",
")",
":",
"(",
"a1",
",",
"b1",
",",
"c1",
",",
"d1",
",",
"e1",
",",
"f1",
")",
"=",
"m1",
"(",
"a0",
",",
"b0",
",",
"c0",
",",
"d0",
",",
"e0",
",",
"f0",
")",
"=",
"m0",
"return",
"(",
"a0... | Returns the multiplication of two matrices. | [
"Returns",
"the",
"multiplication",
"of",
"two",
"matrices",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L57-L63 | train |
euske/pdfminer | pdfminer/utils.py | uniq | def uniq(objs):
"""Eliminates duplicated elements."""
done = set()
for obj in objs:
if obj in done:
continue
done.add(obj)
yield obj
return | python | def uniq(objs):
"""Eliminates duplicated elements."""
done = set()
for obj in objs:
if obj in done:
continue
done.add(obj)
yield obj
return | [
"def",
"uniq",
"(",
"objs",
")",
":",
"done",
"=",
"set",
"(",
")",
"for",
"obj",
"in",
"objs",
":",
"if",
"obj",
"in",
"done",
":",
"continue",
"done",
".",
"add",
"(",
"obj",
")",
"yield",
"obj",
"return"
] | Eliminates duplicated elements. | [
"Eliminates",
"duplicated",
"elements",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L95-L103 | train |
euske/pdfminer | pdfminer/utils.py | csort | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) | python | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) | [
"def",
"csort",
"(",
"objs",
",",
"key",
")",
":",
"idxs",
"=",
"dict",
"(",
"(",
"obj",
",",
"i",
")",
"for",
"(",
"i",
",",
"obj",
")",
"in",
"enumerate",
"(",
"objs",
")",
")",
"return",
"sorted",
"(",
"objs",
",",
"key",
"=",
"lambda",
"o... | Order-preserving sorting function. | [
"Order",
"-",
"preserving",
"sorting",
"function",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L107-L110 | train |
euske/pdfminer | pdfminer/utils.py | fsplit | def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) | python | def fsplit(pred, objs):
"""Split a list into two classes according to the predicate."""
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f) | [
"def",
"fsplit",
"(",
"pred",
",",
"objs",
")",
":",
"t",
"=",
"[",
"]",
"f",
"=",
"[",
"]",
"for",
"obj",
"in",
"objs",
":",
"if",
"pred",
"(",
"obj",
")",
":",
"t",
".",
"append",
"(",
"obj",
")",
"else",
":",
"f",
".",
"append",
"(",
"... | Split a list into two classes according to the predicate. | [
"Split",
"a",
"list",
"into",
"two",
"classes",
"according",
"to",
"the",
"predicate",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L114-L123 | train |
euske/pdfminer | pdfminer/utils.py | drange | def drange(v0, v1, d):
"""Returns a discrete range."""
assert v0 < v1
return xrange(int(v0)//d, int(v1+d)//d) | python | def drange(v0, v1, d):
"""Returns a discrete range."""
assert v0 < v1
return xrange(int(v0)//d, int(v1+d)//d) | [
"def",
"drange",
"(",
"v0",
",",
"v1",
",",
"d",
")",
":",
"assert",
"v0",
"<",
"v1",
"return",
"xrange",
"(",
"int",
"(",
"v0",
")",
"//",
"d",
",",
"int",
"(",
"v1",
"+",
"d",
")",
"//",
"d",
")"
] | Returns a discrete range. | [
"Returns",
"a",
"discrete",
"range",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L127-L130 | train |
euske/pdfminer | pdfminer/utils.py | get_bound | def get_bound(pts):
"""Compute a minimal rectangle that covers all the points."""
(x0, y0, x1, y1) = (INF, INF, -INF, -INF)
for (x, y) in pts:
x0 = min(x0, x)
y0 = min(y0, y)
x1 = max(x1, x)
y1 = max(y1, y)
return (x0, y0, x1, y1) | python | def get_bound(pts):
"""Compute a minimal rectangle that covers all the points."""
(x0, y0, x1, y1) = (INF, INF, -INF, -INF)
for (x, y) in pts:
x0 = min(x0, x)
y0 = min(y0, y)
x1 = max(x1, x)
y1 = max(y1, y)
return (x0, y0, x1, y1) | [
"def",
"get_bound",
"(",
"pts",
")",
":",
"(",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
"=",
"(",
"INF",
",",
"INF",
",",
"-",
"INF",
",",
"-",
"INF",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"pts",
":",
"x0",
"=",
"min",
"(",
"x0"... | Compute a minimal rectangle that covers all the points. | [
"Compute",
"a",
"minimal",
"rectangle",
"that",
"covers",
"all",
"the",
"points",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L134-L142 | train |
euske/pdfminer | pdfminer/utils.py | choplist | def choplist(n, seq):
"""Groups every n elements of the list."""
r = []
for x in seq:
r.append(x)
if len(r) == n:
yield tuple(r)
r = []
return | python | def choplist(n, seq):
"""Groups every n elements of the list."""
r = []
for x in seq:
r.append(x)
if len(r) == n:
yield tuple(r)
r = []
return | [
"def",
"choplist",
"(",
"n",
",",
"seq",
")",
":",
"r",
"=",
"[",
"]",
"for",
"x",
"in",
"seq",
":",
"r",
".",
"append",
"(",
"x",
")",
"if",
"len",
"(",
"r",
")",
"==",
"n",
":",
"yield",
"tuple",
"(",
"r",
")",
"r",
"=",
"[",
"]",
"re... | Groups every n elements of the list. | [
"Groups",
"every",
"n",
"elements",
"of",
"the",
"list",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L157-L165 | train |
euske/pdfminer | pdfminer/utils.py | decode_text | def decode_text(s):
"""Decodes a PDFDocEncoding string to Unicode."""
if s.startswith(b'\xfe\xff'):
return unicode(s[2:], 'utf-16be', 'ignore')
else:
return ''.join(PDFDocEncoding[ord(c)] for c in s) | python | def decode_text(s):
"""Decodes a PDFDocEncoding string to Unicode."""
if s.startswith(b'\xfe\xff'):
return unicode(s[2:], 'utf-16be', 'ignore')
else:
return ''.join(PDFDocEncoding[ord(c)] for c in s) | [
"def",
"decode_text",
"(",
"s",
")",
":",
"if",
"s",
".",
"startswith",
"(",
"b'\\xfe\\xff'",
")",
":",
"return",
"unicode",
"(",
"s",
"[",
"2",
":",
"]",
",",
"'utf-16be'",
",",
"'ignore'",
")",
"else",
":",
"return",
"''",
".",
"join",
"(",
"PDFD... | Decodes a PDFDocEncoding string to Unicode. | [
"Decodes",
"a",
"PDFDocEncoding",
"string",
"to",
"Unicode",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L223-L228 | train |
euske/pdfminer | pdfminer/pdfparser.py | PDFParser.do_keyword | def do_keyword(self, pos, token):
"""Handles PDF-related keywords."""
if token in (self.KEYWORD_XREF, self.KEYWORD_STARTXREF):
self.add_results(*self.pop(1))
elif token is self.KEYWORD_ENDOBJ:
self.add_results(*self.pop(4))
elif token is self.KEYWORD_NULL:
... | python | def do_keyword(self, pos, token):
"""Handles PDF-related keywords."""
if token in (self.KEYWORD_XREF, self.KEYWORD_STARTXREF):
self.add_results(*self.pop(1))
elif token is self.KEYWORD_ENDOBJ:
self.add_results(*self.pop(4))
elif token is self.KEYWORD_NULL:
... | [
"def",
"do_keyword",
"(",
"self",
",",
"pos",
",",
"token",
")",
":",
"if",
"token",
"in",
"(",
"self",
".",
"KEYWORD_XREF",
",",
"self",
".",
"KEYWORD_STARTXREF",
")",
":",
"self",
".",
"add_results",
"(",
"*",
"self",
".",
"pop",
"(",
"1",
")",
"... | Handles PDF-related keywords. | [
"Handles",
"PDF",
"-",
"related",
"keywords",
"."
] | 8150458718e9024c80b00e74965510b20206e588 | https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/pdfparser.py#L60-L133 | train |
eliangcs/http-prompt | http_prompt/execution.py | generate_help_text | def generate_help_text():
"""Return a formatted string listing commands, HTTPie options, and HTTP
actions.
"""
def generate_cmds_with_explanations(summary, cmds):
text = '{0}:\n'.format(summary)
for cmd, explanation in cmds:
text += '\t{0:<10}\t{1:<20}\n'.format(cmd, explanat... | python | def generate_help_text():
"""Return a formatted string listing commands, HTTPie options, and HTTP
actions.
"""
def generate_cmds_with_explanations(summary, cmds):
text = '{0}:\n'.format(summary)
for cmd, explanation in cmds:
text += '\t{0:<10}\t{1:<20}\n'.format(cmd, explanat... | [
"def",
"generate_help_text",
"(",
")",
":",
"def",
"generate_cmds_with_explanations",
"(",
"summary",
",",
"cmds",
")",
":",
"text",
"=",
"'{0}:\\n'",
".",
"format",
"(",
"summary",
")",
"for",
"cmd",
",",
"explanation",
"in",
"cmds",
":",
"text",
"+=",
"'... | Return a formatted string listing commands, HTTPie options, and HTTP
actions. | [
"Return",
"a",
"formatted",
"string",
"listing",
"commands",
"HTTPie",
"options",
"and",
"HTTP",
"actions",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/execution.py#L154-L168 | train |
eliangcs/http-prompt | http_prompt/utils.py | colformat | def colformat(strings, num_sep_spaces=1, terminal_width=None):
"""Format a list of strings like ls does multi-column output."""
if terminal_width is None:
terminal_width = get_terminal_size().columns
if not strings:
return
num_items = len(strings)
max_len = max([len(strip_ansi_esca... | python | def colformat(strings, num_sep_spaces=1, terminal_width=None):
"""Format a list of strings like ls does multi-column output."""
if terminal_width is None:
terminal_width = get_terminal_size().columns
if not strings:
return
num_items = len(strings)
max_len = max([len(strip_ansi_esca... | [
"def",
"colformat",
"(",
"strings",
",",
"num_sep_spaces",
"=",
"1",
",",
"terminal_width",
"=",
"None",
")",
":",
"if",
"terminal_width",
"is",
"None",
":",
"terminal_width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
"if",
"not",
"strings",
":",
... | Format a list of strings like ls does multi-column output. | [
"Format",
"a",
"list",
"of",
"strings",
"like",
"ls",
"does",
"multi",
"-",
"column",
"output",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/utils.py#L47-L89 | train |
eliangcs/http-prompt | http_prompt/contextio.py | load_context | def load_context(context, file_path=None):
"""Load a Context object in place from user data directory."""
if not file_path:
file_path = _get_context_filepath()
if os.path.exists(file_path):
with io.open(file_path, encoding='utf-8') as f:
for line in f:
execute(lin... | python | def load_context(context, file_path=None):
"""Load a Context object in place from user data directory."""
if not file_path:
file_path = _get_context_filepath()
if os.path.exists(file_path):
with io.open(file_path, encoding='utf-8') as f:
for line in f:
execute(lin... | [
"def",
"load_context",
"(",
"context",
",",
"file_path",
"=",
"None",
")",
":",
"if",
"not",
"file_path",
":",
"file_path",
"=",
"_get_context_filepath",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"with",
"io",
".",
"... | Load a Context object in place from user data directory. | [
"Load",
"a",
"Context",
"object",
"in",
"place",
"from",
"user",
"data",
"directory",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/contextio.py#L23-L30 | train |
eliangcs/http-prompt | http_prompt/contextio.py | save_context | def save_context(context):
"""Save a Context object to user data directory."""
file_path = _get_context_filepath()
content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS)
with io.open(file_path, 'w', encoding='utf-8') as f:
f.write(content) | python | def save_context(context):
"""Save a Context object to user data directory."""
file_path = _get_context_filepath()
content = format_to_http_prompt(context, excluded_options=EXCLUDED_OPTIONS)
with io.open(file_path, 'w', encoding='utf-8') as f:
f.write(content) | [
"def",
"save_context",
"(",
"context",
")",
":",
"file_path",
"=",
"_get_context_filepath",
"(",
")",
"content",
"=",
"format_to_http_prompt",
"(",
"context",
",",
"excluded_options",
"=",
"EXCLUDED_OPTIONS",
")",
"with",
"io",
".",
"open",
"(",
"file_path",
","... | Save a Context object to user data directory. | [
"Save",
"a",
"Context",
"object",
"to",
"user",
"data",
"directory",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/contextio.py#L33-L38 | train |
eliangcs/http-prompt | http_prompt/context/transform.py | extract_args_for_httpie_main | def extract_args_for_httpie_main(context, method=None):
"""Transform a Context object to a list of arguments that can be passed to
HTTPie main function.
"""
args = _extract_httpie_options(context)
if method:
args.append(method.upper())
args.append(context.url)
args += _extract_http... | python | def extract_args_for_httpie_main(context, method=None):
"""Transform a Context object to a list of arguments that can be passed to
HTTPie main function.
"""
args = _extract_httpie_options(context)
if method:
args.append(method.upper())
args.append(context.url)
args += _extract_http... | [
"def",
"extract_args_for_httpie_main",
"(",
"context",
",",
"method",
"=",
"None",
")",
":",
"args",
"=",
"_extract_httpie_options",
"(",
"context",
")",
"if",
"method",
":",
"args",
".",
"append",
"(",
"method",
".",
"upper",
"(",
")",
")",
"args",
".",
... | Transform a Context object to a list of arguments that can be passed to
HTTPie main function. | [
"Transform",
"a",
"Context",
"object",
"to",
"a",
"list",
"of",
"arguments",
"that",
"can",
"be",
"passed",
"to",
"HTTPie",
"main",
"function",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/context/transform.py#L73-L84 | train |
eliangcs/http-prompt | http_prompt/context/transform.py | format_to_httpie | def format_to_httpie(context, method=None):
"""Format a Context object to an HTTPie command."""
cmd = ['http'] + _extract_httpie_options(context, quote=True,
join_key_value=True)
if method:
cmd.append(method.upper())
cmd.append(context.url)
cmd +=... | python | def format_to_httpie(context, method=None):
"""Format a Context object to an HTTPie command."""
cmd = ['http'] + _extract_httpie_options(context, quote=True,
join_key_value=True)
if method:
cmd.append(method.upper())
cmd.append(context.url)
cmd +=... | [
"def",
"format_to_httpie",
"(",
"context",
",",
"method",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'http'",
"]",
"+",
"_extract_httpie_options",
"(",
"context",
",",
"quote",
"=",
"True",
",",
"join_key_value",
"=",
"True",
")",
"if",
"method",
":",
"cmd... | Format a Context object to an HTTPie command. | [
"Format",
"a",
"Context",
"object",
"to",
"an",
"HTTPie",
"command",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/context/transform.py#L97-L105 | train |
eliangcs/http-prompt | http_prompt/context/transform.py | format_to_http_prompt | def format_to_http_prompt(context, excluded_options=None):
"""Format a Context object to HTTP Prompt commands."""
cmds = _extract_httpie_options(context, quote=True, join_key_value=True,
excluded_keys=excluded_options)
cmds.append('cd ' + smart_quote(context.url))
cmds... | python | def format_to_http_prompt(context, excluded_options=None):
"""Format a Context object to HTTP Prompt commands."""
cmds = _extract_httpie_options(context, quote=True, join_key_value=True,
excluded_keys=excluded_options)
cmds.append('cd ' + smart_quote(context.url))
cmds... | [
"def",
"format_to_http_prompt",
"(",
"context",
",",
"excluded_options",
"=",
"None",
")",
":",
"cmds",
"=",
"_extract_httpie_options",
"(",
"context",
",",
"quote",
"=",
"True",
",",
"join_key_value",
"=",
"True",
",",
"excluded_keys",
"=",
"excluded_options",
... | Format a Context object to HTTP Prompt commands. | [
"Format",
"a",
"Context",
"object",
"to",
"HTTP",
"Prompt",
"commands",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/context/transform.py#L108-L114 | train |
eliangcs/http-prompt | http_prompt/config.py | initialize | def initialize():
"""Initialize a default config file if it doesn't exist yet.
Returns:
tuple: A tuple of (copied, dst_path). `copied` is a bool indicating if
this function created the default config file. `dst_path` is the
path of the user config file.
"""
dst_path = ge... | python | def initialize():
"""Initialize a default config file if it doesn't exist yet.
Returns:
tuple: A tuple of (copied, dst_path). `copied` is a bool indicating if
this function created the default config file. `dst_path` is the
path of the user config file.
"""
dst_path = ge... | [
"def",
"initialize",
"(",
")",
":",
"dst_path",
"=",
"get_user_config_path",
"(",
")",
"copied",
"=",
"False",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst_path",
")",
":",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
... | Initialize a default config file if it doesn't exist yet.
Returns:
tuple: A tuple of (copied, dst_path). `copied` is a bool indicating if
this function created the default config file. `dst_path` is the
path of the user config file. | [
"Initialize",
"a",
"default",
"config",
"file",
"if",
"it",
"doesn",
"t",
"exist",
"yet",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/config.py#L17-L31 | train |
eliangcs/http-prompt | http_prompt/config.py | load_user | def load_user():
"""Read user config file and return it as a dict."""
config_path = get_user_config_path()
config = {}
# TODO: This may be overkill and too slow just for reading a config file
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec(code, config)
... | python | def load_user():
"""Read user config file and return it as a dict."""
config_path = get_user_config_path()
config = {}
# TODO: This may be overkill and too slow just for reading a config file
with open(config_path) as f:
code = compile(f.read(), config_path, 'exec')
exec(code, config)
... | [
"def",
"load_user",
"(",
")",
":",
"config_path",
"=",
"get_user_config_path",
"(",
")",
"config",
"=",
"{",
"}",
"# TODO: This may be overkill and too slow just for reading a config file",
"with",
"open",
"(",
"config_path",
")",
"as",
"f",
":",
"code",
"=",
"compi... | Read user config file and return it as a dict. | [
"Read",
"user",
"config",
"file",
"and",
"return",
"it",
"as",
"a",
"dict",
"."
] | 189321f25e3526fa1b79a9dc38c317892c478986 | https://github.com/eliangcs/http-prompt/blob/189321f25e3526fa1b79a9dc38c317892c478986/http_prompt/config.py#L48-L63 | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | filter_single_reads_by_length | def filter_single_reads_by_length(in_file, quality_format, min_length=20,
out_file=None):
"""
removes reads from a fastq file which are shorter than a minimum
length
"""
logger.info("Removing reads in %s thare are less than %d bases."
% (in_file, mi... | python | def filter_single_reads_by_length(in_file, quality_format, min_length=20,
out_file=None):
"""
removes reads from a fastq file which are shorter than a minimum
length
"""
logger.info("Removing reads in %s thare are less than %d bases."
% (in_file, mi... | [
"def",
"filter_single_reads_by_length",
"(",
"in_file",
",",
"quality_format",
",",
"min_length",
"=",
"20",
",",
"out_file",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing reads in %s thare are less than %d bases.\"",
"%",
"(",
"in_file",
",",
"min_... | removes reads from a fastq file which are shorter than a minimum
length | [
"removes",
"reads",
"from",
"a",
"fastq",
"file",
"which",
"are",
"shorter",
"than",
"a",
"minimum",
"length"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L40-L55 | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | filter_reads_by_length | def filter_reads_by_length(fq1, fq2, quality_format, min_length=20):
"""
removes reads from a pair of fastq files that are shorter than
a minimum length. removes both ends of a read if one end falls
below the threshold while maintaining the order of the reads
"""
logger.info("Removing reads in... | python | def filter_reads_by_length(fq1, fq2, quality_format, min_length=20):
"""
removes reads from a pair of fastq files that are shorter than
a minimum length. removes both ends of a read if one end falls
below the threshold while maintaining the order of the reads
"""
logger.info("Removing reads in... | [
"def",
"filter_reads_by_length",
"(",
"fq1",
",",
"fq2",
",",
"quality_format",
",",
"min_length",
"=",
"20",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing reads in %s and %s that \"",
"\"are less than %d bases.\"",
"%",
"(",
"fq1",
",",
"fq2",
",",
"min_lengt... | removes reads from a pair of fastq files that are shorter than
a minimum length. removes both ends of a read if one end falls
below the threshold while maintaining the order of the reads | [
"removes",
"reads",
"from",
"a",
"pair",
"of",
"fastq",
"files",
"that",
"are",
"shorter",
"than",
"a",
"minimum",
"length",
".",
"removes",
"both",
"ends",
"of",
"a",
"read",
"if",
"one",
"end",
"falls",
"below",
"the",
"threshold",
"while",
"maintaining"... | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L57-L99 | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | rstrip_extra | def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", ".R", "-R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)... | python | def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", ".R", "-R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)... | [
"def",
"rstrip_extra",
"(",
"fname",
")",
":",
"to_strip",
"=",
"(",
"\"_R\"",
",",
"\".R\"",
",",
"\"-R\"",
",",
"\"_\"",
",",
"\"fastq\"",
",",
"\".\"",
",",
"\"-\"",
")",
"while",
"fname",
".",
"endswith",
"(",
"to_strip",
")",
":",
"for",
"x",
"i... | Strip extraneous, non-discriminative filename info from the end of a file. | [
"Strip",
"extraneous",
"non",
"-",
"discriminative",
"filename",
"info",
"from",
"the",
"end",
"of",
"a",
"file",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L101-L110 | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | fast_combine_pairs | def fast_combine_pairs(files, force_single, full_name, separators):
"""
assume files that need to be paired are within 10 entries of each other, once the list is sorted
"""
files = sort_filenames(files)
chunks = tz.sliding_window(10, files)
pairs = [combine_pairs(chunk, force_single, full_name, ... | python | def fast_combine_pairs(files, force_single, full_name, separators):
"""
assume files that need to be paired are within 10 entries of each other, once the list is sorted
"""
files = sort_filenames(files)
chunks = tz.sliding_window(10, files)
pairs = [combine_pairs(chunk, force_single, full_name, ... | [
"def",
"fast_combine_pairs",
"(",
"files",
",",
"force_single",
",",
"full_name",
",",
"separators",
")",
":",
"files",
"=",
"sort_filenames",
"(",
"files",
")",
"chunks",
"=",
"tz",
".",
"sliding_window",
"(",
"10",
",",
"files",
")",
"pairs",
"=",
"[",
... | assume files that need to be paired are within 10 entries of each other, once the list is sorted | [
"assume",
"files",
"that",
"need",
"to",
"be",
"paired",
"are",
"within",
"10",
"entries",
"of",
"each",
"other",
"once",
"the",
"list",
"is",
"sorted"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L187-L204 | train |
bcbio/bcbio-nextgen | bcbio/bam/fastq.py | open_fastq | def open_fastq(in_file):
""" open a fastq file, using gzip if it is gzipped
"""
if objectstore.is_remote(in_file):
return objectstore.open_file(in_file)
else:
return utils.open_gzipsafe(in_file) | python | def open_fastq(in_file):
""" open a fastq file, using gzip if it is gzipped
"""
if objectstore.is_remote(in_file):
return objectstore.open_file(in_file)
else:
return utils.open_gzipsafe(in_file) | [
"def",
"open_fastq",
"(",
"in_file",
")",
":",
"if",
"objectstore",
".",
"is_remote",
"(",
"in_file",
")",
":",
"return",
"objectstore",
".",
"open_file",
"(",
"in_file",
")",
"else",
":",
"return",
"utils",
".",
"open_gzipsafe",
"(",
"in_file",
")"
] | open a fastq file, using gzip if it is gzipped | [
"open",
"a",
"fastq",
"file",
"using",
"gzip",
"if",
"it",
"is",
"gzipped"
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/fastq.py#L309-L315 | train |
bcbio/bcbio-nextgen | bcbio/variation/strelka2.py | get_region_bed | def get_region_bed(region, items, out_file, want_gzip=True):
"""Retrieve BED file of regions to analyze, either single or multi-region.
"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if no... | python | def get_region_bed(region, items, out_file, want_gzip=True):
"""Retrieve BED file of regions to analyze, either single or multi-region.
"""
variant_regions = bedutils.population_variant_regions(items, merged=True)
target = shared.subset_variant_regions(variant_regions, region, out_file, items)
if no... | [
"def",
"get_region_bed",
"(",
"region",
",",
"items",
",",
"out_file",
",",
"want_gzip",
"=",
"True",
")",
":",
"variant_regions",
"=",
"bedutils",
".",
"population_variant_regions",
"(",
"items",
",",
"merged",
"=",
"True",
")",
"target",
"=",
"shared",
"."... | Retrieve BED file of regions to analyze, either single or multi-region. | [
"Retrieve",
"BED",
"file",
"of",
"regions",
"to",
"analyze",
"either",
"single",
"or",
"multi",
"-",
"region",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/strelka2.py#L36-L52 | train |
bcbio/bcbio-nextgen | bcbio/variation/strelka2.py | coverage_interval_from_bed | def coverage_interval_from_bed(bed_file, per_chrom=True):
"""Calculate a coverage interval for the current region BED.
This helps correctly work with cases of uneven coverage across an analysis
genome. strelka2 and other model based callers have flags for targeted and non
which depend on the local cont... | python | def coverage_interval_from_bed(bed_file, per_chrom=True):
"""Calculate a coverage interval for the current region BED.
This helps correctly work with cases of uneven coverage across an analysis
genome. strelka2 and other model based callers have flags for targeted and non
which depend on the local cont... | [
"def",
"coverage_interval_from_bed",
"(",
"bed_file",
",",
"per_chrom",
"=",
"True",
")",
":",
"total_starts",
"=",
"{",
"}",
"total_ends",
"=",
"{",
"}",
"bed_bases",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"with",
"utils",
".",
"open_gzips... | Calculate a coverage interval for the current region BED.
This helps correctly work with cases of uneven coverage across an analysis
genome. strelka2 and other model based callers have flags for targeted and non
which depend on the local context.
Checks coverage per chromosome, avoiding non-standard c... | [
"Calculate",
"a",
"coverage",
"interval",
"for",
"the",
"current",
"region",
"BED",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/strelka2.py#L54-L93 | train |
bcbio/bcbio-nextgen | bcbio/variation/strelka2.py | _is_targeted_region | def _is_targeted_region(cur_bed, data):
"""Calculate if we should process region as a targeted or WGS.
Currently always based on total coverage interval, as that validates best and
is consistent between CWL (larger blocks) and non-CWL runs (smaller blocks).
We can check core usage and provide a consist... | python | def _is_targeted_region(cur_bed, data):
"""Calculate if we should process region as a targeted or WGS.
Currently always based on total coverage interval, as that validates best and
is consistent between CWL (larger blocks) and non-CWL runs (smaller blocks).
We can check core usage and provide a consist... | [
"def",
"_is_targeted_region",
"(",
"cur_bed",
",",
"data",
")",
":",
"cores",
"=",
"dd",
".",
"get_num_cores",
"(",
"data",
")",
"if",
"cores",
">",
"0",
":",
"# Apply to all core setups now for consistency",
"return",
"dd",
".",
"get_coverage_interval",
"(",
"d... | Calculate if we should process region as a targeted or WGS.
Currently always based on total coverage interval, as that validates best and
is consistent between CWL (larger blocks) and non-CWL runs (smaller blocks).
We can check core usage and provide a consistent report when moving to CWL
exclusively. | [
"Calculate",
"if",
"we",
"should",
"process",
"region",
"as",
"a",
"targeted",
"or",
"WGS",
"."
] | 6a9348c0054ccd5baffd22f1bb7d0422f6978b20 | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/strelka2.py#L95-L107 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.