bug_id stringlengths 6 14 | project stringclasses 17
values | bug_num int64 1 166 | file_path stringlengths 8 58 | buggy_commit stringlengths 7 40 | fixed_commit stringlengths 40 40 | test_command stringlengths 14 136 | function_name stringlengths 1 33 | func_start_line int64 1 9.85k | func_end_line int64 2 9.87k | num_hunks int64 1 3 | num_removed int64 1 31 | input stringlengths 113 3.7k | output stringlengths 0 1.49k | buggy_function stringlengths 87 3.66k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PySnooper/3 | PySnooper | 3 | pysnooper/pysnooper.py | 6e3d797be3fa0a746fb5b1b7c7fea78eb926c208 | 15555ed760000b049aff8fecc79d29339c1224c3 | tests/test_pysnooper.py | write | 25 | 27 | 1 | 1 | def write(s):
# Buggy code:
# with open(output_path, 'a') as output_file:
<FILL_ME>
output_file.write(s)
| with open(output, 'a') as output_file:
| def write(s):
with open(output_path, 'a') as output_file:
output_file.write(s)
|
ansible/3 | ansible | 3 | lib/ansible/module_utils/facts/system/distribution.py | 70219df9056ffb1e2766f572fbe71f7a1800c9f5 | 9d48884e36fb4fd9551f000b87d264383de74e75 | test/units/module_utils/test_distribution_version.py | parse_distribution_file_Debian | 301 | 357 | 1 | 1 | def parse_distribution_file_Debian(self, name, data, path, collected_facts):
debian_facts = {}
if 'Debian' in data or 'Raspbian' in data:
debian_facts['distribution'] = 'Debian'
release = re.search(r"PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data)
if release:
... | elif path in ('/etc/lsb-release', '/etc/os-release') and 'Kali' in data:
# Kali does not provide /etc/lsb-release anymore
| def parse_distribution_file_Debian(self, name, data, path, collected_facts):
debian_facts = {}
if 'Debian' in data or 'Raspbian' in data:
debian_facts['distribution'] = 'Debian'
release = re.search(r"PRETTY_NAME=[^(]+ \(?([^)]+?)\)", data)
if release:
... |
ansible/7 | ansible | 7 | lib/ansible/module_utils/network/eos/config/vlans/vlans.py | cd146b836e032df785ecd9eb711c6ef23c2228b8 | 4ec1437212b2fb3c313e44ed5a76b105f2151622 | test/units/modules/network/eos/test_eos_vlans.py | generate_commands | 206 | 223 | 1 | 4 | def generate_commands(vlan_id, to_set, to_remove):
commands = []
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
# Buggy cod... | if commands:
commands.insert(0, "vlan {0}".format(vlan_id))
| def generate_commands(vlan_id, to_set, to_remove):
commands = []
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
for key... |
ansible/15 | ansible | 15 | lib/ansible/modules/network/eos/eos_eapi.py | b1e8a6c1cbd2a668b462995487b819ef7dd8ba4b | 68de182555b185737353e780882159a3d213908c | test/units/modules/network/eos/test_eos_eapi.py | map_obj_to_commands | 219 | 282 | 1 | 1 | def map_obj_to_commands(updates, module, warnings):
commands = list()
want, have = updates
def needs_update(x):
return want.get(x) is not None and (want.get(x) != have.get(x))
def add(cmd):
if 'management api http-commands' not in commands:
commands.insert(0, 'management ap... | if needs_update('state'):
| def map_obj_to_commands(updates, module, warnings):
commands = list()
want, have = updates
def needs_update(x):
return want.get(x) is not None and (want.get(x) != have.get(x))
def add(cmd):
if 'management api http-commands' not in commands:
commands.insert(0, 'management ap... |
black/2 | black | 2 | black.py | c8ca6b2b9ff3510bee12129824cebfc2fc51e5b2 | 892eddacd215d685e136686b7f629ade70adca83 | tests/test_black.py | generate_ignored_nodes | 3,112 | 3,130 | 1 | 9 | def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.type != token.ENDMARKER:
# Buggy code:
#... | if fmt_on(container):
return
# fix for fmt: on in children
if contains_fmt_on_at_column(container, leaf.column):
for child in container.children:
if contains_fmt_on_at_column(child, leaf.column):
return
yield child
... | def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
while container is not None and container.type != token.ENDMARKER:
is_fmt_... |
black/4 | black | 4 | black.py | 65ea568e3301951f26e0e3b98f6d5dc80132e917 | c7495b9aa098ef7a358fc74556359d21c6a4ba11 | tests/test_black.py;tests/data/beginning_backslash.py | maybe_empty_lines | 1,476 | 1,486 | 1 | 1 | def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
"""Return the number of extra empty lines before and after the `current_line`.
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._ma... | before = (
# Black should not insert empty lines at the beginning
# of the file
0
if self.previous_line is None
else before - self.previous_after
)
| def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
"""Return the number of extra empty lines before and after the `current_line`.
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._ma... |
black/7 | black | 7 | black.py | 18119d38466652ae818436cb497f601294ed4558 | de806405d2934b629d67e2a6317ad7e826765a20 | tests/data/tupleassign.py;tests/test_black.py | normalize_invisible_parens | 2,713 | 2,762 | 2 | 1 | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
"""Make existing optional parentheses invisible or create new ones.
`parens_after` is a set of string leaf values immeditely after which parens
should be put.
Standardizes on visible parentheses for single-element tuples, and ... | prefix = child.prefix
child.prefix = ""
new_child = Node(syms.atom, [lpar, child, rpar])
new_child.prefix = prefix
node.insert_child(index, new_child)
| def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
"""Make existing optional parentheses invisible or create new ones.
`parens_after` is a set of string leaf values immeditely after which parens
should be put.
Standardizes on visible parentheses for single-element tuples, and ... |
black/8 | black | 8 | black.py | e6ddb68c786256e1cb0c76b42d10c212ef34cb2a | 6b994fdb8ab70ce4c2eafb8f2f0ff2648f3ff1ef | tests/data/comments7.py;tests/test_black.py | bracket_split_build_line | 2,393 | 2,419 | 1 | 3 | def bracket_split_build_line(
leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
) -> Line:
"""Return a new line with given `leaves` and respective comments from `original`.
If `is_body` is True, the result line is one-indented inside brackets and as such
has its first ... | # Ensure a trailing comma for imports, but be careful not to add one after
# any comments.
if original.is_import:
for i in range(len(leaves) - 1, -1, -1):
if leaves[i].type == STANDALONE_COMMENT:
continue
... | def bracket_split_build_line(
leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
) -> Line:
"""Return a new line with given `leaves` and respective comments from `original`.
If `is_body` is True, the result line is one-indented inside brackets and as such
has its first ... |
black/9 | black | 9 | black.py | 026c81b83454f176a9f9253cbfb70be2c159d822 | d6db1c12a8e14833fe22da377cddc2bd1f43dc14 | tests/data/python2_print_function.py;tests/test_black.py | get_grammars | 725 | 735 | 1 | 2 | def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
return GRAMMARS
elif all(not version.is_python2() for version in target_versions):
# Buggy code:
# # Python 2-compatible code, so don't try Python 3 grammar.
# return [
# pygram.py... | # Python 3-compatible code, so don't try Python 2 grammar
return [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
]
else:
return [pygram.python_grammar_no_print_statement, pygram.python_grammar]
| def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
return GRAMMARS
elif all(not version.is_python2() for version in target_versions):
# Python 2-compatible code, so don't try Python 3 grammar.
return [
pygram.python_grammar_no_prin... |
black/10 | black | 10 | blib2to3/pgen2/driver.py | f6643c4f0cfbae1f2493fdfce46cfbae3d26f46b | 66aa676278948368dff251dffd58c850cb8b889e | tests/test_black.py | _partially_consume_prefix | 117 | 144 | 1 | 3 | def _partially_consume_prefix(self, prefix, column):
lines = []
current_line = ""
current_column = 0
wait_for_nl = False
for char in prefix:
current_line += char
if wait_for_nl:
if char == '\n':
if current_line.strip... | elif char in ' \t':
current_column += 1
| def _partially_consume_prefix(self, prefix, column):
lines = []
current_line = ""
current_column = 0
wait_for_nl = False
for char in prefix:
current_line += char
if wait_for_nl:
if char == '\n':
if current_line.strip... |
black/16 | black | 16 | black.py | fb34c9e19589d05f92084a28940837151251ebd6 | 42a3fe53319a8c02858c2a96989ed1339f84515a | tests/test_black.py | gen_python_files_in_dir | 2,934 | 2,962 | 1 | 1 | def gen_python_files_in_dir(
path: Path,
root: Path,
include: Pattern[str],
exclude: Pattern[str],
report: "Report",
) -> Iterator[Path]:
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
`report` is where ou... | try:
normalized_path = "/" + child.resolve().relative_to(root).as_posix()
except ValueError:
if child.is_symlink():
report.path_ignored(
child,
"is a symbolic link that points outside of the root directory",
... | def gen_python_files_in_dir(
path: Path,
root: Path,
include: Pattern[str],
exclude: Pattern[str],
report: "Report",
) -> Iterator[Path]:
"""Generate all files under `path` whose paths are not excluded by the
`exclude` regex, but are included by the `include` regex.
`report` is where ou... |
black/20 | black | 20 | black.py | 2e52a2b3ecc0fe025439c3db05a4457ab14f167b | 06e95b1e9bcd43c4574840f8174ba4b2c5d281bd | tests/test_black.py | format_file_in_place | 318 | 354 | 1 | 2 | def format_file_in_place(
src: Path,
line_length: int,
fast: bool,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
"""Format file under `src` path. Return True if changed.
If `write_back` is True, write reformatted c... | src_name = f"{src} (original)"
dst_name = f"{src} (formatted)"
| def format_file_in_place(
src: Path,
line_length: int,
fast: bool,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
"""Format file under `src` path. Return True if changed.
If `write_back` is True, write reformatted c... |
black/21 | black | 21 | black.py | c071af761e1550c6e4ebab8e5af747d2d8fdd48e | 8e7848c63efe36f09e4651bece8c0efc34a1c3e1 | tests/test_black.py | dump_to_file | 2,323 | 2,334 | 1 | 1 | def dump_to_file(*output: str) -> str:
"""Dump `output` to a temporary file. Return path to the file."""
import tempfile
with tempfile.NamedTemporaryFile(
# Buggy code:
# mode="w", prefix="blk_", suffix=".log", delete=False
<FILL_ME>
) as f:
for lines in output:
f.write(line... | mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
| def dump_to_file(*output: str) -> str:
"""Dump `output` to a temporary file. Return path to the file."""
import tempfile
with tempfile.NamedTemporaryFile(
mode="w", prefix="blk_", suffix=".log", delete=False
) as f:
for lines in output:
f.write(lines)
if lines an... |
cookiecutter/1 | cookiecutter | 1 | cookiecutter/generate.py | c15633745df6abdb24e02746b82aadb20b8cdf8c | 7f6804c4953a18386809f11faf4d86898570debc | tests/test_generate_context.py | generate_context | 70 | 111 | 1 | 1 | def generate_context(
context_file='cookiecutter.json', default_context=None, extra_context=None
):
"""Generate the context for a Cookiecutter project template.
Loads the JSON file as a Python object, with key being the JSON filename.
:param context_file: JSON file containing key/value pairs for popul... | with open(context_file, encoding='utf-8') as file_handle:
| def generate_context(
context_file='cookiecutter.json', default_context=None, extra_context=None
):
"""Generate the context for a Cookiecutter project template.
Loads the JSON file as a Python object, with key being the JSON filename.
:param context_file: JSON file containing key/value pairs for popul... |
cookiecutter/3 | cookiecutter | 3 | cookiecutter/prompt.py | 5c282f020a8db7e5e7c4e7b51b010556ca31fb7f | 7129d474206761a6156925db78eee4b62a0e3944 | tests/test_read_user_choice.py | read_user_choice | 61 | 93 | 1 | 1 | def read_user_choice(var_name, options):
"""Prompt the user to choose from several options for the given variable.
The first item will be returned if no input happens.
:param str var_name: Variable as specified in the context
:param list options: Sequence of options that are available to select from
... | prompt, type=click.Choice(choices), default=default, show_choices=False
| def read_user_choice(var_name, options):
"""Prompt the user to choose from several options for the given variable.
The first item will be returned if no input happens.
:param str var_name: Variable as specified in the context
:param list options: Sequence of options that are available to select from
... |
fastapi/2 | fastapi | 2 | fastapi/routing.py | 210af1fd3dc0f612a08fa02a0cb3f5adb81e5bfb | 02441ff0313d5b471b662293244c53e712f1243f | tests/test_ws_router.py | add_api_websocket_route | 498 | 502 | 1 | 1 | def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
# Buggy code:
# route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
<FILL_ME>
self.routes.append(route)
| route = APIWebSocketRoute(
path,
endpoint=endpoint,
name=name,
dependency_overrides_provider=self.dependency_overrides_provider,
)
| def add_api_websocket_route(
self, path: str, endpoint: Callable, name: str = None
) -> None:
route = APIWebSocketRoute(path, endpoint=endpoint, name=name)
self.routes.append(route)
|
fastapi/3 | fastapi | 3 | fastapi/routing.py | 869c7389e22dc9ad659940fa271da76c4f3ba3b1 | aea04ee32ee1942e6e1a904527bb8da6ba76abd9 | tests/test_serialize_response_model.py | serialize_response | 51 | 90 | 2 | 7 | async def serialize_response(
*,
field: ModelField = None,
response_content: Any,
include: Union[SetIntStr, DictIntStrAny] = None,
exclude: Union[SetIntStr, DictIntStrAny] = set(),
by_alias: bool = True,
exclude_unset: bool = False,
is_coroutine: bool = True,
) -> Any:
if field:
... | response_content = _prepare_response_content(
response_content, by_alias=by_alias, exclude_unset=exclude_unset
)
| async def serialize_response(
*,
field: ModelField = None,
response_content: Any,
include: Union[SetIntStr, DictIntStrAny] = None,
exclude: Union[SetIntStr, DictIntStrAny] = set(),
by_alias: bool = True,
exclude_unset: bool = False,
is_coroutine: bool = True,
) -> Any:
if field:
... |
fastapi/5 | fastapi | 5 | fastapi/utils.py | 7cea84b74ca3106a7f861b774e9d215e5228728f | 75a07f24bf01a31225ee687f3e2b3fc1981b67ab | tests/test_filter_pydantic_sub_model.py | create_cloned_field | 89 | 154 | 1 | 1 | def create_cloned_field(field: ModelField) -> ModelField:
original_type = field.type_
if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
original_type = original_type.__pydantic_model__ # type: ignore
use_type = original_type
if lenient_issubclass(original_type, Ba... | use_type.__fields__[f.name] = create_cloned_field(f)
| def create_cloned_field(field: ModelField) -> ModelField:
original_type = field.type_
if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
original_type = original_type.__pydantic_model__ # type: ignore
use_type = original_type
if lenient_issubclass(original_type, Ba... |
fastapi/6 | fastapi | 6 | fastapi/dependencies/utils.py | 5db99a27cf640864b4793807811848698c5ff4a2 | 874d24181e779ebc6e1c52afb7d6598f863fd6a8 | tests/test_forms_from_non_typing_sequences.py | request_body_to_args | 617 | 685 | 1 | 3 | async def request_body_to_args(
required_params: List[ModelField],
received_body: Optional[Union[Dict[str, Any], FormData]],
) -> Tuple[Dict[str, Any], List[ErrorWrapper]]:
values = {}
errors = []
if required_params:
field = required_params[0]
field_info = get_field_info(field)
... | if (
field.shape in sequence_shapes or field.type_ in sequence_types
) and isinstance(received_body, FormData):
| async def request_body_to_args(
required_params: List[ModelField],
received_body: Optional[Union[Dict[str, Any], FormData]],
) -> Tuple[Dict[str, Any], List[ErrorWrapper]]:
values = {}
errors = []
if required_params:
field = required_params[0]
field_info = get_field_info(field)
... |
fastapi/9 | fastapi | 9 | fastapi/dependencies/utils.py | a7a92bc63768ccee3f3afc2b73b2c581928dfe75 | c5817912d2be25bb310bf9da517882f57bbe7bb5 | tests/test_request_body_parameters_media_type.py | get_body_field | 549 | 579 | 3 | 1 | def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
flat_dependant = get_flat_dependant(dependant)
if not flat_dependant.body_params:
return None
first_param = flat_dependant.body_params[0]
embed = getattr(first_param.schema, "embed", None)
if len(flat_dependant.body_p... | schema=BodySchema(**BodySchema_kwargs),
| def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]:
flat_dependant = get_flat_dependant(dependant)
if not flat_dependant.body_params:
return None
first_param = flat_dependant.body_params[0]
embed = getattr(first_param.schema, "embed", None)
if len(flat_dependant.body_p... |
fastapi/11 | fastapi | 11 | fastapi/dependencies/utils.py | bf229ad5d830eb5320f966d51a55e590e8d57008 | 06eb4219345a77d23484528c9d164eb8d2097fec | tests/test_union_body.py;tests/test_union_inherited_body.py | is_scalar_field | 133 | 139 | 1 | 2 | def is_scalar_field(field: Field) -> bool:
# Buggy code:
# return (
# field.shape == Shape.SINGLETON
# and not lenient_issubclass(field.type_, BaseModel)
# and not lenient_issubclass(field.type_, sequence_types + (dict,))
# and not isinstance(field.schema, params.Body)
# )
<FILL_... | if not (
field.shape == Shape.SINGLETON
and not lenient_issubclass(field.type_, BaseModel)
and not lenient_issubclass(field.type_, sequence_types + (dict,))
and not isinstance(field.schema, params.Body)
):
return False
if field.sub_fields:
if not all(is_scalar... | def is_scalar_field(field: Field) -> bool:
return (
field.shape == Shape.SINGLETON
and not lenient_issubclass(field.type_, BaseModel)
and not lenient_issubclass(field.type_, sequence_types + (dict,))
and not isinstance(field.schema, params.Body)
)
|
fastapi/12 | fastapi | 12 | fastapi/security/http.py | d61f5e4b555b123bf222503fc0e076cbae6a7ebc | d262f6e9296993e528e2327f0a73f7bf5514e7c6 | tests/test_security_http_bearer_optional.py | __call__ | 102 | 119 | 1 | 4 | async def __call__(
self, request: Request
) -> Optional[HTTPAuthorizationCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
if ... | if self.auto_error:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid authentication credentials",
)
else:
return None
| async def __call__(
self, request: Request
) -> Optional[HTTPAuthorizationCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
if ... |
fastapi/13 | fastapi | 13 | fastapi/routing.py | 6f7f9268f6b03f42831dcfeaa5c15ba9813333ec | c8df3ae57c57e119d115dd3c1f44efa78de1022a | tests/test_additional_responses_router.py | include_router | 275 | 321 | 2 | 4 | def include_router(
self,
router: "APIRouter",
*,
prefix: str = "",
tags: List[str] = None,
responses: Dict[Union[int, str], Dict[str, Any]] = None,
) -> None:
if prefix:
assert prefix.startswith("/"), "A path prefix must start with '/'"
... | combined_responses = {**responses, **route.responses}
self.add_api_route(
prefix + route.path,
route.endpoint,
summary=route.summary,
description=route.description,
response_description=ro... | def include_router(
self,
router: "APIRouter",
*,
prefix: str = "",
tags: List[str] = None,
responses: Dict[Union[int, str], Dict[str, Any]] = None,
) -> None:
if prefix:
assert prefix.startswith("/"), "A path prefix must start with '/'"
... |
fastapi/16 | fastapi | 16 | fastapi/encoders.py | 92c825be6a7362099400c9c3fe8b01ea13add3dc | 9745a5d1ae86a7fefacf79bdde8e5dd2d59fa2f4 | tests/test_datetime_custom_encoder.py;tests/test_jsonable_encoder.py | jsonable_encoder | 9 | 79 | 1 | 11 | def jsonable_encoder(
obj: Any,
include: Set[str] = None,
exclude: Set[str] = set(),
by_alias: bool = False,
include_none: bool = True,
custom_encoder: dict = {},
) -> Any:
if isinstance(obj, BaseModel):
# Buggy code:
# if not obj.Config.json_encoders:
# return jsonable_e... | encoder = getattr(obj.Config, "json_encoders", custom_encoder)
return jsonable_encoder(
obj.dict(include=include, exclude=exclude, by_alias=by_alias),
include_none=include_none,
custom_encoder=encoder,
)
| def jsonable_encoder(
obj: Any,
include: Set[str] = None,
exclude: Set[str] = set(),
by_alias: bool = False,
include_none: bool = True,
custom_encoder: dict = {},
) -> Any:
if isinstance(obj, BaseModel):
if not obj.Config.json_encoders:
return jsonable_encoder(
... |
httpie/4 | httpie | 4 | httpie/models.py | 8c892edd4fe700a7ca5cc733dcb4817831d253e2 | 040d981f00c3f6830b2d0db3daf3c64c080e96e3 | tests/test_regressions.py | headers | 95 | 118 | 1 | 2 | def headers(self):
url = urlsplit(self._orig.url)
request_line = '{method} {path}{query} HTTP/1.1'.format(
method=self._orig.method,
path=url.path or '/',
query='?' + url.query if url.query else ''
)
headers = dict(self._orig.headers)
# Buggy cod... | if 'Host' not in self._orig.headers:
| def headers(self):
url = urlsplit(self._orig.url)
request_line = '{method} {path}{query} HTTP/1.1'.format(
method=self._orig.method,
path=url.path or '/',
query='?' + url.query if url.query else ''
)
headers = dict(self._orig.headers)
if... |
httpie/5 | httpie | 5 | httpie/cli.py | 16df8848e81eefac830f407e4b985f42b52970da | 90af1f742230831792d74d303d1e7ce56c96d4bd | tests/tests.py | __call__ | 40 | 63 | 1 | 4 | def __call__(self, string):
found = {}
for sep in self.separators:
# Buggy code:
# regex = '[^\\\\]' + sep
# match = re.search(regex, string)
# if match:
# found[match.start() + 1] = sep
<FILL_ME>
if not found:
#noinspection Py... | matches = re.finditer(sep, string)
for match in matches:
start, end = match.span()
inside_escape = False
for estart, eend in found_escapes:
if start >= estart and end <= eend:
inside_escape = True
... | def __call__(self, string):
found = {}
for sep in self.separators:
regex = '[^\\\\]' + sep
match = re.search(regex, string)
if match:
found[match.start() + 1] = sep
if not found:
#noinspection PyExceptionInherit
rai... |
keras/4 | keras | 4 | keras/optimizers.py | b0bfd5201da2bfced84028bcc5bda05bdfd75af7 | 4185cbb50bfcae9cc30b0fc7b67e81d67a50a8ac | tests/keras/optimizers_test.py | get_updates | 705 | 711 | 1 | 1 | def get_updates(self, loss, params):
# Buggy code:
# grads = self.optimizer.compute_gradients(loss, params)
<FILL_ME>
self.updates = [K.update_add(self.iterations, 1)]
opt_update = self.optimizer.apply_gradients(
grads, global_step=self.iterations)
self.updates.append(opt... | grads = self.optimizer.compute_gradients(loss, var_list=params)
| def get_updates(self, loss, params):
grads = self.optimizer.compute_gradients(loss, params)
self.updates = [K.update_add(self.iterations, 1)]
opt_update = self.optimizer.apply_gradients(
grads, global_step=self.iterations)
self.updates.append(opt_update)
return se... |
keras/6 | keras | 6 | keras/engine/training_utils.py | 88af7d0c97497b5c3a198ee9416b2accfbc72c36 | 4b54657ab4806b0aaef8f8eeb973edb83c3d3483 | tests/test_loss_masking.py | weighted | 392 | 424 | 1 | 1 | def weighted(y_true, y_pred, weights, mask=None):
"""Wrapper function.
# Arguments
y_true: `y_true` argument of `fn`.
y_pred: `y_pred` argument of `fn`.
weights: Weights tensor.
mask: Mask tensor.
# Returns
Scalar tensor.
... | score_array /= K.mean(mask) + K.epsilon()
| def weighted(y_true, y_pred, weights, mask=None):
"""Wrapper function.
# Arguments
y_true: `y_true` argument of `fn`.
y_pred: `y_pred` argument of `fn`.
weights: Weights tensor.
mask: Mask tensor.
# Returns
Scalar tensor.
... |
keras/7 | keras | 7 | keras/wrappers/scikit_learn.py | 26b620fb37c885d60183f83abc744f43775ce75a | c05ef1fd95a6024155ab59656fef8dac5a45c335 | tests/keras/wrappers/scikit_learn_test.py | predict | 308 | 323 | 1 | 1 | def predict(self, x, **kwargs):
"""Returns predictions for the given test data.
# Arguments
x: array-like, shape `(n_samples, n_features)`
Test samples where `n_samples` is the number of samples
and `n_features` is the number of features.
**kw... | return np.squeeze(self.model.predict(x, **kwargs), axis=-1)
| def predict(self, x, **kwargs):
"""Returns predictions for the given test data.
# Arguments
x: array-like, shape `(n_samples, n_features)`
Test samples where `n_samples` is the number of samples
and `n_features` is the number of features.
**kw... |
keras/9 | keras | 9 | docs/autogen.py | 0cd3b07eb5de1aaaad84d1ff7f7c2ed7dab4b23c | 0505393746d56ddacc34bb1c016dba79429c9ac9 | tests/test_doc_auto_generation.py | process_list_block | 117 | 158 | 1 | 2 | def process_list_block(docstring, starting_point, section_end,
leading_spaces, marker):
ending_point = docstring.find('\n\n', starting_point)
# Buggy code:
# block = docstring[starting_point:(None if ending_point == -1 else
# ending_point - 1)]
<FILL_... | block = docstring[starting_point:(ending_point - 1 if ending_point > -1 else
section_end)]
| def process_list_block(docstring, starting_point, section_end,
leading_spaces, marker):
ending_point = docstring.find('\n\n', starting_point)
block = docstring[starting_point:(None if ending_point == -1 else
ending_point - 1)]
# Place marker for l... |
keras/14 | keras | 14 | keras/metrics.py | 98465b85d020f1326bcef7632f1261a9a7a84e92 | 02bc5010a04bb11c8e91835cc9775c8149dec754 | tests/keras/metrics_test.py | sparse_top_k_categorical_accuracy | 47 | 49 | 1 | 1 | def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
# Buggy code:
# return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k),
<FILL_ME>
axis=-1)
| # If the shape of y_true is (num_samples, 1), flatten to (num_samples,)
return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k),
| def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k),
axis=-1)
|
keras/17 | keras | 17 | keras/metrics.py | c913b6da92f6ab9a3f4c897caa4085e782a14680 | 5a6af4bc6d44e9adbc2a21804bfcd18c4ce849ef | tests/keras/metrics_test.py | sparse_categorical_accuracy | 36 | 39 | 1 | 1 | def sparse_categorical_accuracy(y_true, y_pred):
# Buggy code:
# return K.cast(K.equal(K.max(y_true, axis=-1),
<FILL_ME>
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.floatx())
| # flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,)
return K.cast(K.equal(K.flatten(y_true),
| def sparse_categorical_accuracy(y_true, y_pred):
return K.cast(K.equal(K.max(y_true, axis=-1),
K.cast(K.argmax(y_pred, axis=-1), K.floatx())),
K.floatx())
|
keras/26 | keras | 26 | keras/backend/tensorflow_backend.py | 87417470c8168772559be0531e297120c569a422 | 97d5fa920e4f8248128f7c1b460fd9bb20d3478f | tests/keras/backend/backend_test.py | _step | 2,850 | 2,876 | 1 | 1 | def _step(time, output_ta_t, *states):
"""RNN step function.
# Arguments
time: Current timestep value.
output_ta_t: TensorArray.
*states: List of states.
# Returns
Tuple: `(time ... | new_states = [
tf.where(tf.tile(mask_t, tf.stack([1, tf.shape(new_states[i])[1]])),
new_states[i], states[i]) for i in range(len(states))
]
| def _step(time, output_ta_t, *states):
"""RNN step function.
# Arguments
time: Current timestep value.
output_ta_t: TensorArray.
*states: List of states.
# Returns
Tuple: `(time ... |
keras/31 | keras | 31 | keras/backend/tensorflow_backend.py | ced81968b0e9d8b1389e6580721ac60d9cf3ca60 | e2a10a5e6e156a45e946c4d08db7133f997c1f9a | tests/keras/backend/backend_test.py | ctc_batch_cost | 3,928 | 3,953 | 1 | 2 | def ctc_batch_cost(y_true, y_pred, input_length, label_length):
"""Runs CTC loss algorithm on each batch element.
# Arguments
y_true: tensor `(samples, max_string_length)`
containing the truth labels.
y_pred: tensor `(samples, time_steps, num_categories)`
containing the ... | label_length = tf.to_int32(tf.squeeze(label_length, axis=-1))
input_length = tf.to_int32(tf.squeeze(input_length, axis=-1))
| def ctc_batch_cost(y_true, y_pred, input_length, label_length):
"""Runs CTC loss algorithm on each batch element.
# Arguments
y_true: tensor `(samples, max_string_length)`
containing the truth labels.
y_pred: tensor `(samples, time_steps, num_categories)`
containing the ... |
keras/33 | keras | 33 | keras/preprocessing/text.py | 1c9a49781da2101507db23e2014e4e5d16bd2e52 | 70ad0d6e4a569701ef106058397ad0540ec08340 | tests/keras/preprocessing/text_test.py | text_to_word_sequence | 24 | 48 | 1 | 4 | def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
"""Converts a text to a sequence of words (or tokens).
# Arguments
text: Input text (string).
filters: Sequence of characters to filter out... | if sys.version_info < (3,):
if isinstance(text, unicode):
translate_map = dict((ord(c), unicode(split)) for c in filters)
text = text.translate(translate_map)
elif len(split) == 1:
translate_map = maketrans(filters, split * len(filters))
text = text.tr... | def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
"""Converts a text to a sequence of words (or tokens).
# Arguments
text: Input text (string).
filters: Sequence of characters to filter out... |
keras/36 | keras | 36 | keras/backend/tensorflow_backend.py | 85f011df5a5c0fcf1f01b39eca338eb6b7e58401 | fb1887d132a8ce8548ff53d868a6ba531cd63b34 | tests/keras/layers/convolutional_test.py | separable_conv1d | 3,391 | 3,439 | 1 | 2 | def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding='valid', data_format=None, dilation_rate=1):
"""1D convolution with separable filters.
# Arguments
x: input tensor
depthwise_kernel: convolution kernel for the depthwise convolution.
poin... | strides = (1,) + strides * 2 + (1,)
else:
spatial_start_dim = 2
strides = (1, 1) + strides * 2
| def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding='valid', data_format=None, dilation_rate=1):
"""1D convolution with separable filters.
# Arguments
x: input tensor
depthwise_kernel: convolution kernel for the depthwise convolution.
poin... |
keras/38 | keras | 38 | keras/layers/recurrent.py | 53ec990d54130dd0a457dd235c93d39de32d571d | 64f80d6077edd5f277a1181df94bf4510ea0517a | tests/keras/layers/recurrent_test.py | build | 101 | 110 | 1 | 1 | def build(self, input_shape):
for cell in self.cells:
if isinstance(cell, Layer):
cell.build(input_shape)
if hasattr(cell.state_size, '__len__'):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
# Buggy cod... | input_shape = (input_shape[0], output_dim)
| def build(self, input_shape):
for cell in self.cells:
if isinstance(cell, Layer):
cell.build(input_shape)
if hasattr(cell.state_size, '__len__'):
output_dim = cell.state_size[0]
else:
output_dim = cell.state_size
... |
keras/40 | keras | 40 | keras/layers/recurrent.py | 871007dbb0e6211459b9d16244cc3c9683459df7 | 4cad455ef4da600c96ddc69800bab39d0e52b677 | tests/keras/layers/recurrent_test.py | compute_output_shape | 393 | 411 | 2 | 3 | def compute_output_shape(self, input_shape):
if isinstance(input_shape, list):
input_shape = input_shape[0]
if hasattr(self.cell.state_size, '__len__'):
# Buggy code:
# output_dim = self.cell.state_size[0]
# else:
# output_dim = self.cell.state_size
#
# ... | state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (input_shape[0], input_shape[1], output_dim)
output_shape = (input_shape[0], output_dim)
if se... | def compute_output_shape(self, input_shape):
if isinstance(input_shape, list):
input_shape = input_shape[0]
if hasattr(self.cell.state_size, '__len__'):
output_dim = self.cell.state_size[0]
else:
output_dim = self.cell.state_size
if self.return_s... |
keras/45 | keras | 45 | keras/layers/recurrent.py | d368dc870bfd8fdd4ca0ff82bd5b61aa549291c5 | 159bb1aac17a8de0f96997d35703b8f26926a848 | tests/keras/layers/recurrent_test.py | call | 1,786 | 1,853 | 1 | 4 | def call(self, inputs, states, training=None):
# dropout matrices for input units
dp_mask = self._dropout_mask
# dropout matrices for recurrent units
rec_dp_mask = self._recurrent_dropout_mask
h_tm1 = states[0] # previous memory state
c_tm1 = states[1] # previous c... | x_i = K.dot(inputs_i, self.kernel_i)
x_f = K.dot(inputs_f, self.kernel_f)
x_c = K.dot(inputs_c, self.kernel_c)
x_o = K.dot(inputs_o, self.kernel_o)
if self.use_bias:
x_i = K.bias_add(x_i, self.bias_i)
x_f = K.bias_add(x_f, self.... | def call(self, inputs, states, training=None):
# dropout matrices for input units
dp_mask = self._dropout_mask
# dropout matrices for recurrent units
rec_dp_mask = self._recurrent_dropout_mask
h_tm1 = states[0] # previous memory state
c_tm1 = states[1] # previous c... |
luigi/1 | luigi | 1 | luigi/server.py | 1164eb6b85b8a70f596dbb99452bec513e72c12e | aec5dc2ed8db53fc282a0bd24aabe59031b6d1ba | test/server_test.py | get | 281 | 285 | 1 | 2 | def get(self):
# Buggy code:
# metrics = self._scheduler._state._metrics_collector.generate_latest()
# if metrics:
# metrics.configure_http_handler(self)
<FILL_ME>
self.write(metrics)
| metrics_collector = self._scheduler._state._metrics_collector
metrics = metrics_collector.generate_latest()
if metrics:
metrics_collector.configure_http_handler(self)
| def get(self):
metrics = self._scheduler._state._metrics_collector.generate_latest()
if metrics:
metrics.configure_http_handler(self)
self.write(metrics)
|
luigi/3 | luigi | 3 | luigi/parameter.py | a0f1db01ddab5b4b2bda3fbe58bad09a6d94a7b4 | 3a0bfbff69addfb3be1107adab3d4914bcae3e4b | test/parameter_test.py | parse | 1,095 | 1,118 | 1 | 2 | def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.
# A tuple string may come from ... | except (ValueError, TypeError):
return tuple(literal_eval(x)) # if this causes an error, let that error be raised.
| def parse(self, x):
"""
Parse an individual value from the input.
:param str x: the value to parse.
:return: the parsed value.
"""
# Since the result of json.dumps(tuple) differs from a tuple string, we must handle either case.
# A tuple string may come from ... |
luigi/4 | luigi | 4 | luigi/contrib/redshift.py | ffa51b50103a3adaf3c4d0569fdb037a7ba01e8e | 8501e5dbb8d3040453a89bb0d3562526086d51e5 | test/contrib/redshift_test.py | copy | 348 | 370 | 1 | 1 | def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
# Buggy code:
# if len(self.columns) > 0:
<FILL_ME... | if self.columns and len(self.columns) > 0:
| def copy(self, cursor, f):
"""
Defines copying from s3 into redshift.
If both key-based and role-based credentials are provided, role-based will be used.
"""
logger.info("Inserting file: %s", f)
colnames = ''
if len(self.columns) > 0:
colnames = "... |
luigi/8 | luigi | 8 | luigi/contrib/redshift.py | 61ee32e9968978c32be12a6af0affa3a5750e87e | 8874b93165953c4f6bbe7b747804654d13290018 | test/contrib/redshift_test.py | does_table_exist | 327 | 346 | 1 | 2 | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
# Buggy code:
# "where table_schema = %s and... | "where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_exists "
"from pg_table_def "
"where tablename = lower(%s) limit 1")
| def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = %s and table_name = %s... |
luigi/10 | luigi | 10 | luigi/scheduler.py | f538d1b3d473d542a19d508e5f7e0809b1dfe5ef | 3c55acd2cd5cf9c6c760bec5bb3159e0bc48a614 | test/scheduler_test.py | get_pending_tasks | 295 | 305 | 1 | 1 | def get_pending_tasks(self, state):
"""
Get PENDING (and RUNNING) tasks for this worker.
You have to pass in the state for optimization reasons.
"""
if len(self.tasks) < state.num_pending_tasks():
return six.moves.filter(lambda task: task.status in [PENDING, RUNN... | return six.moves.filter(lambda task: self.id in task.workers, state.get_pending_tasks())
| def get_pending_tasks(self, state):
"""
Get PENDING (and RUNNING) tasks for this worker.
You have to pass in the state for optimization reasons.
"""
if len(self.tasks) < state.num_pending_tasks():
return six.moves.filter(lambda task: task.status in [PENDING, RUNN... |
luigi/13 | luigi | 13 | luigi/file.py | 3c90bcdac63d978dbdaeae408420e22b963c9863 | a8e64fe7f83d69702166a44c7e8cb9470ff31040 | test/file_test.py | move | 86 | 92 | 1 | 1 | def move(self, old_path, new_path, raise_if_exists=False):
if raise_if_exists and os.path.exists(new_path):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
# Buggy code:
# self.fs.mkdir(d)
<FILL_ME>... | self.mkdir(d)
| def move(self, old_path, new_path, raise_if_exists=False):
if raise_if_exists and os.path.exists(new_path):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.fs.mkdir(d)
os.rename(old_pat... |
luigi/15 | luigi | 15 | luigi/scheduler.py | a822f55d4d7c5adf5b9e3b64f23189d8305e9bf9 | 736c0f1352463c20ece84f2f651bcd37fd2b88ae | test/central_planner_test.py | get_necessary_tasks | 482 | 489 | 1 | 2 | def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
# Buggy code:
# if task.status not in (DONE, DISABLED) or \
# getattr(task, 'scheduler_disable_time', None) is not None:
<FILL_ME>
necessary_tasks.update(task.d... | if task.status not in (DONE, DISABLED, UNKNOWN) or \
task.scheduler_disable_time is not None:
| def get_necessary_tasks(self):
necessary_tasks = set()
for task in self.get_active_tasks():
if task.status not in (DONE, DISABLED) or \
getattr(task, 'scheduler_disable_time', None) is not None:
necessary_tasks.update(task.deps)
necessa... |
luigi/16 | luigi | 16 | luigi/scheduler.py | e38392a1381dd8daee0f180f0ac7f651edb88e0c | 96f2b5a97c2cc5f63bea0f422c57f93dcec0ebac | test/central_planner_test.py | prune | 550 | 575 | 1 | 1 | def prune(self):
logger.info("Starting pruning of task graph")
remove_workers = []
for worker in self._state.get_active_workers():
if worker.prune(self._config):
logger.info("Worker %s timed out (no contact for >=%ss)", worker, self._config.worker_disconnect_delay... | removed = self._state.prune(task, self._config)
if removed and task.id not in necessary_tasks:
| def prune(self):
logger.info("Starting pruning of task graph")
remove_workers = []
for worker in self._state.get_active_workers():
if worker.prune(self._config):
logger.info("Worker %s timed out (no contact for >=%ss)", worker, self._config.worker_disconnect_delay... |
luigi/17 | luigi | 17 | luigi/interface.py | c39922350cba3a93c96c2ed223283bf8cf315a7d | e38392a1381dd8daee0f180f0ac7f651edb88e0c | test/scheduler_test.py | create_local_scheduler | 133 | 134 | 1 | 1 | def create_local_scheduler(self):
# Buggy code:
# return scheduler.CentralPlannerScheduler(prune_on_get_work=True)
<FILL_ME>
| return scheduler.CentralPlannerScheduler(prune_on_get_work=True, record_task_history=False)
| def create_local_scheduler(self):
return scheduler.CentralPlannerScheduler(prune_on_get_work=True)
|
luigi/18 | luigi | 18 | luigi/scheduler.py | 6cffbf438d023441f7f42c2019a51c62eecd9018 | c521d59c5eacf6c19ce3c17a62f73e042fa0556e | test/central_planner_test.py | set_status | 393 | 427 | 1 | 1 | def set_status(self, task, new_status, config=None):
if new_status == FAILED:
assert config is not None
if new_status == DISABLED and task.status == RUNNING:
return
if task.status == DISABLED:
if new_status == DONE:
self.re_enable(task)
... | elif task.scheduler_disable_time is not None and new_status != DISABLED:
| def set_status(self, task, new_status, config=None):
if new_status == FAILED:
assert config is not None
if new_status == DISABLED and task.status == RUNNING:
return
if task.status == DISABLED:
if new_status == DONE:
self.re_enable(task)
... |
luigi/19 | luigi | 19 | luigi/scheduler.py | 3d2f75224c7649402927a5ef57558d8c3717cd94 | 6cffbf438d023441f7f42c2019a51c62eecd9018 | test/central_planner_test.py | set_status | 393 | 427 | 1 | 1 | def set_status(self, task, new_status, config=None):
if new_status == FAILED:
assert config is not None
if new_status == DISABLED and task.status == RUNNING:
return
if task.status == DISABLED:
if new_status == DONE:
self.re_enable(task)
... | if new_status == FAILED and task.can_disable() and task.status != DISABLED:
| def set_status(self, task, new_status, config=None):
if new_status == FAILED:
assert config is not None
if new_status == DISABLED and task.status == RUNNING:
return
if task.status == DISABLED:
if new_status == DONE:
self.re_enable(task)
... |
luigi/20 | luigi | 20 | luigi/task.py | b958140c2ec838e590a5be02dbac7414d5d0bf17 | c3d685e2b03369aab6f4d86ed1c95169c1c2c217 | test/task_test.py | to_str_params | 302 | 312 | 1 | 2 | def to_str_params(self):
"""
Convert all parameters to a str->str hash.
"""
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
# Buggy code:
# if params[param_name].significant:
# ... | params_str[param_name] = params[param_name].serialize(param_value)
| def to_str_params(self):
"""
Convert all parameters to a str->str hash.
"""
params_str = {}
params = dict(self.get_params())
for param_name, param_value in six.iteritems(self.param_kwargs):
if params[param_name].significant:
params_str[para... |
luigi/24 | luigi | 24 | luigi/contrib/spark.py | 572fce617a3b8133983cdee2b2cc336a65af5abe | 8a4f73296f237fcf8182c342e62c2cb201c717df | test/contrib/spark_test.py | _dict_arg | 268 | 273 | 1 | 1 | def _dict_arg(self, name, value):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
# Buggy code:
# command += [name, '"{0}={1}"'.format(prop, value)]
<FILL_ME>
return command
| command += [name, '{0}={1}'.format(prop, value)]
| def _dict_arg(self, name, value):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '"{0}={1}"'.format(prop, value)]
return command
|
luigi/25 | luigi | 25 | luigi/contrib/redshift.py | d7ec31609c88503391d12d65b6037f397feff816 | 040bbc9ef8d1703b64d13c60f271fded63e13601 | test/contrib/redshift_test.py | run | 158 | 185 | 1 | 1 | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
# Buggy code:
# path = self.s3_load_path()
<FILL_ME>
conn... | path = self.s3_load_path
| def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
connection = self.output().con... |
luigi/26 | luigi | 26 | luigi/contrib/hadoop_jar.py | ed351ca3c3baf3657de584db08dfe0414fa000a3 | 13673fd488c25325db633b1d49e664fb937fabc2 | test/contrib/hadoop_jar_test.py | run_job | 70 | 109 | 1 | 1 | def run_job(self, job):
ssh_config = job.ssh()
if ssh_config:
host = ssh_config.get("host", None)
key_file = ssh_config.get("key_file", None)
username = ssh_config.get("username", None)
if not host or not key_file or not username or not job.jar():
... | if not job.jar():
raise HadoopJarJobError("Jar not defined")
if not os.path.exists(job.jar()):
| def run_job(self, job):
ssh_config = job.ssh()
if ssh_config:
host = ssh_config.get("host", None)
key_file = ssh_config.get("key_file", None)
username = ssh_config.get("username", None)
if not host or not key_file or not username or not job.jar():
... |
luigi/28 | luigi | 28 | luigi/contrib/hive.py | e37cb0ea1d97e6340840128a68c8d59bd05c28c3 | e2be971226c34a193d7029c51206e488b6a037cd | test/contrib/hive_test.py | table_exists | 137 | 149 | 1 | 1 | def table_exists(self, table, database='default', partition=None):
if partition is None:
stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table))
# Buggy code:
# return stdout and table in stdout
<FILL_ME>
else:
stdout = run_hive_cmd("""u... | return stdout and table.lower() in stdout
| def table_exists(self, table, database='default', partition=None):
if partition is None:
stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table))
return stdout and table in stdout
else:
stdout = run_hive_cmd("""use %s; show partitions %s ... |
luigi/30 | luigi | 30 | luigi/worker.py | 97fa4afea3748f0d714482d2c97990bb467bc9d1 | f1e3fb48fe9877e511a2d079636fd75eaaba4573 | test/test_event_callbacks.py | run | 168 | 219 | 1 | 19 | def run(self):
logger.info('[pid %s] Worker %s running %s', os.getpid(), self.worker_id, self.task.task_id)
if self.random_seed:
# Need to have different random seeds if running in separate processes
random.seed((os.getpid(), time.time()))
status = FAILED
... |
new_deps = self._run_get_new_deps()
if new_deps is None:
status = DONE
self.task.trigger_event(
Event.PROCESSING_TIME, self.task, time.time() - t0)
error_message = json.dumps(self.task.on_success())
logger.info... | def run(self):
logger.info('[pid %s] Worker %s running %s', os.getpid(), self.worker_id, self.task.task_id)
if self.random_seed:
# Need to have different random seeds if running in separate processes
random.seed((os.getpid(), time.time()))
status = FAILED
... |
luigi/33 | luigi | 33 | luigi/task.py | a7c0662eab78fd226fd7ef6b4461d7199336cbb1 | fccb631a14e1d52138d39f06004be14ca8f3337d | test/parameter_test.py | get_param_values | 314 | 363 | 1 | 1 | def get_param_values(cls, params, args, kwargs):
"""
Get the values of the parameters from the args and kwargs.
:param params: list of (param_name, Parameter).
:param args: positional arguments
:param kwargs: keyword arguments.
:returns: list of `(name, value)` tuple... | positional_params = [(n, p) for n, p in params if not p.is_global]
| def get_param_values(cls, params, args, kwargs):
"""
Get the values of the parameters from the args and kwargs.
:param params: list of (param_name, Parameter).
:param args: positional arguments
:param kwargs: keyword arguments.
:returns: list of `(name, value)` tuple... |
matplotlib/3 | matplotlib | 3 | lib/matplotlib/markers.py | 5e046f72ae82788788c7e9b9354b87b131891cd8 | 2a3707d9c3472b1a010492322b6946388d4989ae | lib/matplotlib/tests/test_marker.py | _recache | 225 | 236 | 1 | 1 | def _recache(self):
if self._marker_function is None:
return
self._path = _empty_path
self._transform = IdentityTransform()
self._alt_path = None
self._alt_transform = None
self._snap_threshold = None
self._joinstyle = 'round'
self._capstyl... | # Initial guess: Assume the marker is filled unless the fillstyle is
# set to 'none'. The marker function will override this for unfilled
# markers.
self._filled = self._fillstyle != 'none'
| def _recache(self):
if self._marker_function is None:
return
self._path = _empty_path
self._transform = IdentityTransform()
self._alt_path = None
self._alt_transform = None
self._snap_threshold = None
self._joinstyle = 'round'
self._capstyl... |
matplotlib/7 | matplotlib | 7 | lib/matplotlib/colors.py | 969513e2a5227331a2eb9e4bc4ba8448a0f9831d | ac400b51bb31b91920ee9aae02a0606a67983a8f | lib/matplotlib/tests/test_colors.py | shade_rgb | 1,873 | 1,944 | 1 | 1 | def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
vert_exag=1, dx=1, dy=1, **kwargs):
"""
Use this light source to adjust the colors of the *rgb* input array to
give the impression of a shaded relief map with the given *elevation*.
Parameters
... | if np.ma.is_masked(intensity):
| def shade_rgb(self, rgb, elevation, fraction=1., blend_mode='hsv',
vert_exag=1, dx=1, dy=1, **kwargs):
"""
Use this light source to adjust the colors of the *rgb* input array to
give the impression of a shaded relief map with the given *elevation*.
Parameters
... |
matplotlib/10 | matplotlib | 10 | lib/matplotlib/axis.py | b31d64ce3910e8d297d8300690e459587f77181f | 1986da3968ee76c6bce8f4c04aed80e23bd4ecfa | lib/matplotlib/tests/test_axes.py | set_tick_params | 798 | 831 | 1 | 1 | def set_tick_params(self, which='major', reset=False, **kw):
"""
Set appearance parameters for ticks, ticklabels, and gridlines.
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
cbook._check_in_list(['major', 'minor', 'both'],... | # labelOn and labelcolor also apply to the offset text.
if 'label1On' in kwtrans or 'label2On' in kwtrans:
self.offsetText.set_visible(
self._major_tick_kw.get('label1On', False)
or self._major_tick_kw.get('label2On', False))
| def set_tick_params(self, which='major', reset=False, **kw):
"""
Set appearance parameters for ticks, ticklabels, and gridlines.
For documentation of keyword arguments, see
:meth:`matplotlib.axes.Axes.tick_params`.
"""
cbook._check_in_list(['major', 'minor', 'both'],... |
matplotlib/11 | matplotlib | 11 | lib/matplotlib/text.py | f8459a513c3f67447ceb1a07c29760d504517ff2 | af745264376a10782bd0d8b96d255f958c2950f3 | lib/matplotlib/tests/test_text.py | get_window_extent | 870 | 914 | 2 | 12 | def get_window_extent(self, renderer=None, dpi=None):
"""
Return the `.Bbox` bounding the text, in display units.
In addition to being used internally, this is useful for specifying
clickable regions in a png file on a web page.
Parameters
----------
rendere... | if dpi is None:
dpi = self.figure.dpi
if self.get_text() == '':
with cbook._setattr_cm(self.figure, dpi=dpi):
tx, ty = self._get_xy_display()
return Bbox.from_bounds(tx, ty, 0, 0)
if renderer is not None:
self._renderer = rende... | def get_window_extent(self, renderer=None, dpi=None):
"""
Return the `.Bbox` bounding the text, in display units.
In addition to being used internally, this is useful for specifying
clickable regions in a png file on a web page.
Parameters
----------
rendere... |
matplotlib/24 | matplotlib | 24 | lib/matplotlib/axis.py | 9a5473dbac05f3d6773b42c8e16d58a7dc3159b8 | 407a9fe71a4c0a8ba4914b8f54f21d32d6dd2d74 | lib/matplotlib/tests/test_axes.py | setter | 1,885 | 1,897 | 1 | 1 | def setter(self, vmin, vmax, ignore=False):
# docstring inherited.
if ignore:
setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
else:
oldmin, oldmax = getter(self)
if oldmin < oldmax:
setter(self, min(vmin, vmax, oldmin), max(v... | setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
| def setter(self, vmin, vmax, ignore=False):
# docstring inherited.
if ignore:
setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
else:
oldmin, oldmax = getter(self)
if oldmin < oldmax:
setter(self, min(vmin, vmax, oldmin), max(v... |
matplotlib/25 | matplotlib | 25 | lib/matplotlib/collections.py | 9a5473dbac05f3d6773b42c8e16d58a7dc3159b8 | 184225bc5639fbd2f29c1253602806a8b6462d9f | lib/matplotlib/tests/test_collections.py | __init__ | 1,415 | 1,505 | 1 | 3 | def __init__(self,
positions, # Cannot be None.
orientation=None,
lineoffset=0,
linelength=1,
linewidth=None,
color=None,
linestyle='solid',
antialiased=None,
... | if positions is None:
raise ValueError('positions must be an array-like object')
# Force a copy of positions
positions = np.array(positions, copy=True)
segment = (lineoffset + linelength / 2.,
lineoffset - linelength / 2.)
if positions.size == 0:
... | def __init__(self,
positions, # Cannot be None.
orientation=None,
lineoffset=0,
linelength=1,
linewidth=None,
color=None,
linestyle='solid',
antialiased=None,
... |
matplotlib/26 | matplotlib | 26 | lib/matplotlib/axis.py | 04d9d28b820af0b4df230a3c67314ed5b0af8fdd | 557375ff91f64c1b827f6014da2d369513a69316 | lib/matplotlib/tests/test_axes.py | setter | 1,899 | 1,911 | 1 | 1 | def setter(self, vmin, vmax, ignore=False):
# docstring inherited.
if ignore:
setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
else:
oldmin, oldmax = getter(self)
if oldmin < oldmax:
setter(self, min(vmin, vmax, oldmin), max(v... | setter(self, max(vmin, vmax, oldmin), min(vmin, vmax, oldmax),
| def setter(self, vmin, vmax, ignore=False):
# docstring inherited.
if ignore:
setattr(getattr(self.axes, lim_name), attr_name, (vmin, vmax))
else:
oldmin, oldmax = getter(self)
if oldmin < oldmax:
setter(self, min(vmin, vmax, oldmin), max(v... |
matplotlib/27 | matplotlib | 27 | lib/matplotlib/colorbar.py | 11269123d516cda369764a081ddfb8c1a10ddc53 | 02f25d60139b160fd9b321802b4a2f6c6f3f8672 | lib/matplotlib/tests/test_colorbar.py | set_label | 725 | 729 | 1 | 1 | def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
# Buggy code:
# self._label = str(label)
<FILL_ME>
self._labelkw = kw
self._set_label()
| self._label = label
| def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = str(label)
self._labelkw = kw
self._set_label()
|
matplotlib/30 | matplotlib | 30 | lib/matplotlib/colors.py | 3b26ee6f6b31bc0cca4be0407dbb40f44756030d | d4de838fe7b38abb02f061540fd93962cc063fc4 | lib/matplotlib/tests/test_colors.py | makeMappingArray | 336 | 391 | 1 | 10 | def makeMappingArray(N, data, gamma=1.0):
"""Create an *N* -element 1-d lookup table
*data* represented by a list of x,y0,y1 mapping correspondences.
Each element in this list represents how a value between 0 and 1
(inclusive) represented by x is mapped to a corresponding value
between 0 and 1 (inc... | if N == 1:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut = np.array(y0[-1])
else:
x = x * (N - 1)
xind = (N - 1) * np.linspace(0, 1, N) ** gamma
ind = np.searchsorted(x, xind)[1:-1]
distance = (xind[1:-1] - x[ind - 1]) / (x[ind] - x[ind ... | def makeMappingArray(N, data, gamma=1.0):
"""Create an *N* -element 1-d lookup table
*data* represented by a list of x,y0,y1 mapping correspondences.
Each element in this list represents how a value between 0 and 1
(inclusive) represented by x is mapped to a corresponding value
between 0 and 1 (inc... |
pandas/1 | pandas | 1 | pandas/core/dtypes/common.py | 3fd150c | e41ee47a90bb1d8a1fa28fcefcd45ed8ef5cb946 | pandas/tests/dtypes/test_dtypes.py | is_excluded_dtype | 598 | 603 | 1 | 1 | def is_excluded_dtype(dtype) -> bool:
"""
These have kind = "O" but aren't string dtypes so need to be explicitly excluded
"""
# Buggy code:
# is_excluded_checks = (is_period_dtype, is_interval_dtype)
<FILL_ME>
return any(is_excluded(dtype) for is_excluded in is_excluded_chec... | is_excluded_checks = (is_period_dtype, is_interval_dtype, is_categorical_dtype)
| def is_excluded_dtype(dtype) -> bool:
"""
These have kind = "O" but aren't string dtypes so need to be explicitly excluded
"""
is_excluded_checks = (is_period_dtype, is_interval_dtype)
return any(is_excluded(dtype) for is_excluded in is_excluded_checks)
|
pandas/4 | pandas | 4 | pandas/core/indexes/base.py | cca710b | 2250ddfaff92abaff20a5bcd78315f5d4bd44981 | pandas/tests/indexes/multi/test_join.py | _join_multi | 3,479 | 3,552 | 1 | 1 | def _join_multi(self, other, how, return_indexers=True):
from pandas.core.indexes.multi import MultiIndex
from pandas.core.reshape.merge import _restore_dropped_levels_multijoin
# figure out join names
self_names = set(com.not_none(*self.names))
other_names = set(com.not_non... | if return_indexers:
return multi_join_idx, lidx, ridx
else:
return multi_join_idx
| def _join_multi(self, other, how, return_indexers=True):
from pandas.core.indexes.multi import MultiIndex
from pandas.core.reshape.merge import _restore_dropped_levels_multijoin
# figure out join names
self_names = set(com.not_none(*self.names))
other_names = set(com.not_non... |
pandas/6 | pandas | 6 | pandas/core/groupby/grouper.py | 21a10d1 | 8cd8ed3657e52ad9f67e17b7f5c20f7340ab6a2c | pandas/tests/groupby/test_size.py | is_in_obj | 752 | 758 | 1 | 1 | def is_in_obj(gpr) -> bool:
if not hasattr(gpr, "name"):
return False
try:
return gpr is obj[gpr.name]
# Buggy code:
# except (KeyError, IndexError):
<FILL_ME>
return False
| except (KeyError, IndexError, ValueError):
# TODO: ValueError: Given date string not likely a datetime.
# should be KeyError?
| def is_in_obj(gpr) -> bool:
if not hasattr(gpr, "name"):
return False
try:
return gpr is obj[gpr.name]
except (KeyError, IndexError):
return False
|
pandas/7 | pandas | 7 | pandas/core/indexes/base.py | 27f365d | 64336ff8414f8977ff94adb9a5bc000a3a4ef454 | pandas/tests/frame/indexing/test_indexing.py | _get_nearest_indexer | 3,067 | 3,088 | 1 | 3 | def _get_nearest_indexer(self, target: "Index", limit, tolerance) -> np.ndarray:
"""
Get the indexer for the nearest index labels; requires an index with
values that can be subtracted from each other (e.g., not strings or
tuples).
"""
left_indexer = self.get_indexer(t... | left_distances = np.abs(self[left_indexer] - target)
right_distances = np.abs(self[right_indexer] - target)
| def _get_nearest_indexer(self, target: "Index", limit, tolerance) -> np.ndarray:
"""
Get the indexer for the nearest index labels; requires an index with
values that can be subtracted from each other (e.g., not strings or
tuples).
"""
left_indexer = self.get_indexer(t... |
pandas/8 | pandas | 8 | pandas/core/internals/blocks.py | ddbeca6 | d09f20e29bdfa82f5efc071986e2633001d552f6 | pandas/tests/frame/methods/test_replace.py | replace | 668 | 763 | 1 | 5 | def replace(
self,
to_replace,
value,
inplace: bool = False,
regex: bool = False,
convert: bool = True,
):
"""
replace the to_replace value with value, possible to create new
blocks here this is just a call to putmask. regex is not used her... | def replace(
self,
to_replace,
value,
inplace: bool = False,
regex: bool = False,
convert: bool = True,
):
"""
replace the to_replace value with value, possible to create new
blocks here this is just a call to putmask. regex is not used her... | |
pandas/10 | pandas | 10 | pandas/core/internals/blocks.py | de8ca78 | e1ee2b0679e5999c993a787606d30e75faaba7a2 | pandas/tests/series/methods/test_update.py | putmask | 1,590 | 1,608 | 1 | 1 | def putmask(
self, mask, new, inplace: bool = False, axis: int = 0, transpose: bool = False,
) -> List["Block"]:
"""
See Block.putmask.__doc__
"""
inplace = validate_bool_kwarg(inplace, "inplace")
mask = _extract_bool_array(mask)
new_values = self.values... | if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask):
| def putmask(
self, mask, new, inplace: bool = False, axis: int = 0, transpose: bool = False,
) -> List["Block"]:
"""
See Block.putmask.__doc__
"""
inplace = validate_bool_kwarg(inplace, "inplace")
mask = _extract_bool_array(mask)
new_values = self.values... |
pandas/11 | pandas | 11 | pandas/core/reshape/concat.py | 1c88e6a | b7f061c3d24df943e16918ad3932e767f5639a38 | pandas/tests/reshape/test_concat.py | _make_concat_multiindex | 590 | 692 | 1 | 4 | def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiIndex:
if (levels is None and isinstance(keys[0], tuple)) or (
levels is not None and len(levels) > 1
):
zipped = list(zip(*keys))
if names is None:
names = [None] * len(zipped)
if levels is... | mask = level == key
if not mask.any():
raise ValueError(f"Key {key} not in level {level}")
i = np.nonzero(level == key)[0][0]
| def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiIndex:
if (levels is None and isinstance(keys[0], tuple)) or (
levels is not None and len(levels) > 1
):
zipped = list(zip(*keys))
if names is None:
names = [None] * len(zipped)
if levels is... |
pandas/19 | pandas | 19 | pandas/core/indexing.py | 17dc6b0 | c6a1638bcd99df677a8f76f036c0b30027eb243c | pandas/tests/indexing/multiindex/test_loc.py;pandas/tests/indexing/multiindex/test_slice.py;pandas/tests/series/indexing/test_getitem.py | _getitem_axis | 1,070 | 1,133 | 1 | 31 | def _getitem_axis(self, key, axis: int):
key = item_from_zerodim(key)
if is_iterator(key):
key = list(key)
labels = self.obj._get_axis(axis)
key = labels._get_partial_string_timestamp_match_key(key)
if isinstance(key, slice):
self._validate_key(key, ... | def _getitem_axis(self, key, axis: int):
key = item_from_zerodim(key)
if is_iterator(key):
key = list(key)
labels = self.obj._get_axis(axis)
key = labels._get_partial_string_timestamp_match_key(key)
if isinstance(key, slice):
self._validate_key(key, ... | |
pandas/21 | pandas | 21 | pandas/core/series.py | 4071c3b | 56d0934092b8296c90f940c56fce3b731e0de81b | pandas/tests/series/indexing/test_boolean.py;pandas/tests/series/indexing/test_getitem.py | _get_with | 915 | 956 | 1 | 5 | def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
# _convert_slice_indexer to determin if this slice is positional
# or label based, and if the latter, convert to positional
slobj = self.index._convert_slice_indexer(key, kin... | # handle the dup indexing case GH#4246
return self.loc[key]
| def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
# _convert_slice_indexer to determin if this slice is positional
# or label based, and if the latter, convert to positional
slobj = self.index._convert_slice_indexer(key, kin... |
pandas/25 | pandas | 25 | pandas/core/arrays/datetimes.py | ecc3b2e | 73d614403759831814ef7ab83ef1e4aaa645b33a | pandas/tests/indexes/datetimes/test_misc.py | isocalendar | 1,245 | 1,286 | 1 | 1 | def isocalendar(self):
"""
Returns a DataFrame with the year, week, and day calculated according to
the ISO 8601 standard.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
with columns year, week and day
See Also
--------
... | if self.tz is not None and not timezones.is_utc(self.tz):
values = self._local_timestamps()
else:
values = self.asi8
sarray = fields.build_isocalendar_sarray(values)
| def isocalendar(self):
"""
Returns a DataFrame with the year, week, and day calculated according to
the ISO 8601 standard.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
with columns year, week and day
See Also
--------
... |
pandas/28 | pandas | 28 | pandas/core/strings.py | 40fd73a | ef9b9387c88cf12b20dd8656dfedfc236e0f3352 | pandas/tests/test_strings.py | _get_series_list | 2,273 | 2,328 | 1 | 1 | def _get_series_list(self, others):
"""
Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index).
Parameters
----------
others : Series, DataFrame,... | return [Series(others._values, index=idx)]
| def _get_series_list(self, others):
"""
Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index).
Parameters
----------
others : Series, DataFrame,... |
pandas/29 | pandas | 29 | pandas/core/arrays/interval.py | 6e3537d | 4334482c348c3adc69683c8332295e22092c1b57 | pandas/tests/arrays/interval/test_interval.py;pandas/tests/series/methods/test_convert_dtypes.py | __setitem__ | 515 | 558 | 1 | 6 | def __setitem__(self, key, value):
# na value: need special casing to set directly on numpy arrays
needs_float_conversion = False
if is_scalar(value) and isna(value):
if is_integer_dtype(self.dtype.subtype):
# can't set NaN on a numpy integer array
... | left._values[key] = value_left
self._left = left
right = self.right.copy(deep=True)
right._values[key] = value_right
| def __setitem__(self, key, value):
# na value: need special casing to set directly on numpy arrays
needs_float_conversion = False
if is_scalar(value) and isna(value):
if is_integer_dtype(self.dtype.subtype):
# can't set NaN on a numpy integer array
... |
pandas/30 | pandas | 30 | pandas/io/json/_json.py | 60d6f28 | d857cd12b3ae11be788ba96015383a5b7464ecc9 | pandas/tests/io/json/test_pandas.py | _try_convert_to_date | 953 | 988 | 1 | 1 | def _try_convert_to_date(self, data):
"""
Try to parse a ndarray like into a date column.
Try to coerce object in epoch/iso formats and integer/float in epoch
formats. Return a boolean if parsing was successful.
"""
# no conversion on empty
if not len(data):
... | except (ValueError, OverflowError, TypeError):
| def _try_convert_to_date(self, data):
"""
Try to parse a ndarray like into a date column.
Try to coerce object in epoch/iso formats and integer/float in epoch
formats. Return a boolean if parsing was successful.
"""
# no conversion on empty
if not len(data):
... |
pandas/33 | pandas | 33 | pandas/core/arrays/integer.py | 03dacc1 | 89d8aba76a2bb930e520590d145e3d67b2046e39 | pandas/tests/arrays/integer/test_function.py | _values_for_argsort | 487 | 503 | 1 | 1 | def _values_for_argsort(self) -> np.ndarray:
"""
Return values for sorting.
Returns
-------
ndarray
The transformed values should maintain the ordering between values
within the array.
See Also
--------
ExtensionArray.argsort
... | if self._mask.any():
data[self._mask] = data.min() - 1
| def _values_for_argsort(self) -> np.ndarray:
"""
Return values for sorting.
Returns
-------
ndarray
The transformed values should maintain the ordering between values
within the array.
See Also
--------
ExtensionArray.argsort
... |
pandas/34 | pandas | 34 | pandas/core/resample.py | 02a134b | cf9ec7854ecb80709804178e769425f02ddf8c64 | pandas/tests/resample/test_datetime_index.py | _get_time_bins | 1,406 | 1,460 | 1 | 1 | def _get_time_bins(self, ax):
if not isinstance(ax, DatetimeIndex):
raise TypeError(
"axis must be a DatetimeIndex, but got "
f"an instance of {type(ax).__name__}"
)
if len(ax) == 0:
binner = labels = DatetimeIndex(data=[], freq=se... | ambiguous=True,
| def _get_time_bins(self, ax):
if not isinstance(ax, DatetimeIndex):
raise TypeError(
"axis must be a DatetimeIndex, but got "
f"an instance of {type(ax).__name__}"
)
if len(ax) == 0:
binner = labels = DatetimeIndex(data=[], freq=se... |
pandas/38 | pandas | 38 | pandas/core/reshape/reshape.py | c81d90f | e7ee418fa7a519225203fef23481c5fa35834dc3 | pandas/tests/frame/test_reshape.py | _unstack_multiple | 312 | 395 | 2 | 2 | def _unstack_multiple(data, clocs, fill_value=None):
if len(clocs) == 0:
return data
# NOTE: This doesn't deal with hierarchical columns yet
index = data.index
# GH 19966 Make sure if MultiIndexed index has tuple name, they will be
# recognised as a whole
if clocs in index.names:
... | if not rlocs:
# Everything is in clocs, so the dummy df has a regular index
dummy_index = Index(obs_ids, name="__placeholder__")
else:
for i in range(len(clocs)):
val = clocs[i]
result = result.unstack(val, fill_value=fill_value)
clocs ... | def _unstack_multiple(data, clocs, fill_value=None):
if len(clocs) == 0:
return data
# NOTE: This doesn't deal with hierarchical columns yet
index = data.index
# GH 19966 Make sure if MultiIndexed index has tuple name, they will be
# recognised as a whole
if clocs in index.names:
... |
pandas/39 | pandas | 39 | pandas/core/ops/methods.py | 8a5f291 | a3097b5bd172e76dd3524eb5dbe18b6b4c22df50 | pandas/tests/frame//test_axis_select_reindex.py | f | 94 | 103 | 1 | 1 | def f(self, other):
result = method(self, other)
# Buggy code:
#
<FILL_ME>
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace(
result.reindex_like(self, copy=False)._dat... | # Delete cacher
self._reset_cacher()
| def f(self, other):
result = method(self, other)
# this makes sure that we are aligned like the input
# we are updating inplace so we want to ignore is_copy
self._update_inplace(
result.reindex_like(self, copy=False)._data, verify_is_copy=False
... |
pandas/50 | pandas | 50 | pandas/core/arrays/categorical.py | ebf9668 | 821aa25c9039e72da9a7b236cf2f9e7d549cbb7b | pandas/tests/extension/test_categorical.py | func | 69 | 140 | 1 | 1 | def func(self, other):
if is_list_like(other) and len(other) != len(self):
# TODO: Could this fail if the categories are listlike objects?
raise ValueError("Lengths must match.")
if not self.ordered:
if opname in ["__lt__", "__gt__", "__le__", "__ge__"]:
... | if opname == "__ne__":
ret[(self._codes == -1) & (other_codes == -1)] = True
else:
ret[mask] = False
| def func(self, other):
if is_list_like(other) and len(other) != len(self):
# TODO: Could this fail if the categories are listlike objects?
raise ValueError("Lengths must match.")
if not self.ordered:
if opname in ["__lt__", "__gt__", "__le__", "__ge__"]:
... |
pandas/52 | pandas | 52 | pandas/core/groupby/generic.py | 20a84a5 | 7017599821e02ba95282848c12f7d3b5f2ce670a | pandas/tests/groupby/test_function.py | nunique | 581 | 644 | 1 | 18 | def nunique(self, dropna: bool = True) -> Series:
"""
Return number of unique elements in the group.
Returns
-------
Series
Number of unique values within each group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj._internal_get_va... | codes, _ = algorithms.factorize(val, sort=False)
sorter = np.lexsort((codes, ids))
codes = codes[sorter]
ids = ids[sorter]
# group boundaries are where group ids change
# unique observations are where sorted values change
idx = np.r_[0, 1 + np.nonzero(ids[1:] != ... | def nunique(self, dropna: bool = True) -> Series:
"""
Return number of unique elements in the group.
Returns
-------
Series
Number of unique values within each group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj._internal_get_va... |
pandas/56 | pandas | 56 | pandas/core/frame.py | 9e69040 | dafec63f2e138d0451dae5b37edea2e83f9adc8a | pandas/tests/indexing/test_scalar.py | _get_value | 2,610 | 2,644 | 1 | 2 | def _get_value(self, index, col, takeable: bool = False):
"""
Quickly retrieve single value at passed column and index.
Parameters
----------
index : row label
col : column label
takeable : interpret the index/col as indexers, default False
Returns
... | series = self._ixs(col, axis=1)
return series._values[index]
| def _get_value(self, index, col, takeable: bool = False):
"""
Quickly retrieve single value at passed column and index.
Parameters
----------
index : row label
col : column label
takeable : interpret the index/col as indexers, default False
Returns
... |
pandas/58 | pandas | 58 | pandas/core/arrays/categorical.py | 634a41f | 16684f2affaf901b42a12e50f9c29e7c034ad7ea | pandas/tests/arrays/categorical/test_constructors.py | from_codes | 593 | 654 | 1 | 1 | def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
"""
Make a Categorical type from codes and categories or dtype.
This constructor is useful if you already have codes and
categories/dtype and so do not need the (computation intensive)
factorization step,... | if is_extension_array_dtype(codes) and is_integer_dtype(codes):
# Avoid the implicit conversion of Int to object
if isna(codes).any():
raise ValueError("codes cannot contain NA values")
codes = codes.to_numpy(dtype=np.int64)
else:
codes = n... | def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
"""
Make a Categorical type from codes and categories or dtype.
This constructor is useful if you already have codes and
categories/dtype and so do not need the (computation intensive)
factorization step,... |
pandas/59 | pandas | 59 | pandas/core/window/rolling.py | 292a993 | 8dd9fabd2ad9104e747084437b9ad436d5be087a | pandas/tests/window/test_pairwise.py | corr | 1,779 | 1,799 | 1 | 1 | def corr(self, other=None, pairwise=None, **kwargs):
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
# Buggy code:
# window = self._get_window(other)
<FIL... | window = self._get_window(other) if not self.is_freq_type else self.win_freq
| def corr(self, other=None, pairwise=None, **kwargs):
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
window = self._get_window(other)
def _get_co... |
pandas/60 | pandas | 60 | pandas/core/window/rolling.py | 6bc2dca | fcf7258c19b0a6a712f33fb0bcefdae426be7e7f | pandas/tests/window/test_grouper.py | apply | 1,259 | 1,306 | 1 | 1 | def apply(
self,
func,
raw: bool = False,
engine: str = "cython",
engine_kwargs: Optional[Dict] = None,
args: Optional[Tuple] = None,
kwargs: Optional[Dict] = None,
):
if args is None:
args = ()
if kwargs is None:
kw... | # name=func & raw=raw for WindowGroupByMixin._apply
| def apply(
self,
func,
raw: bool = False,
engine: str = "cython",
engine_kwargs: Optional[Dict] = None,
args: Optional[Tuple] = None,
kwargs: Optional[Dict] = None,
):
if args is None:
args = ()
if kwargs is None:
kw... |
pandas/61 | pandas | 61 | pandas/core/series.py | 74dad82 | f7e2b74f1bcc1d1cbebbc42481e33f0abb2843dc | pandas/tests/indexing/test_indexing.py | _get_with | 884 | 935 | 1 | 1 | def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
return self._slice(key)
elif isinstance(key, ABCDataFrame):
raise TypeError(
"Indexing a Series with DataFrame is not "
"supported, use the appropr... | return self.iloc[key]
| def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
return self._slice(key)
elif isinstance(key, ABCDataFrame):
raise TypeError(
"Indexing a Series with DataFrame is not "
"supported, use the appropr... |
pandas/63 | pandas | 63 | pandas/core/indexing.py | e5c65bf | e1ca66bae38b8026079dfcbe0edad5f278546608 | pandas/tests/indexing/test_scalar.py | _convert_key | 2,081 | 2,104 | 1 | 15 | def _convert_key(self, key, is_setter: bool = False):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key)
# Buggy code:
# for ax, i in zip(self.obj.axes, key):... | lkey = list(key)
for n, (ax, i) in enumerate(zip(self.obj.axes, key)):
lkey[n] = ax._convert_scalar_indexer(i, kind="loc")
return tuple(lkey)
| def _convert_key(self, key, is_setter: bool = False):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ... |
pandas/64 | pandas | 64 | pandas/io/formats/excel.py | 31c1856 | d0c84ce57d23a409169daf7232ec7681e42363fe | pandas/tests/io/excel/test_writers.py | __init__ | 372 | 414 | 1 | 1 | def __init__(
self,
df,
na_rep: str = "",
float_format: Optional[str] = None,
cols: Optional[Sequence[Label]] = None,
header: Union[Sequence[Label], bool] = True,
index: bool = True,
index_label: Optional[Union[Label, Sequence[Label]]] = None,
... | self.df = df.reindex(columns=cols)
| def __init__(
self,
df,
na_rep: str = "",
float_format: Optional[str] = None,
cols: Optional[Sequence[Label]] = None,
header: Union[Sequence[Label], bool] = True,
index: bool = True,
index_label: Optional[Union[Label, Sequence[Label]]] = None,
... |
pandas/69 | pandas | 69 | pandas/core/indexing.py | 426d445 | 948f95756c79543bb089a94a85e73011a3730b2d | pandas/tests/indexes/test_numeric.py | _convert_key | 2,110 | 2,133 | 1 | 1 | def _convert_key(self, key, is_setter: bool = False):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ... | if is_integer(i) and not (ax.holds_integer() or ax.is_floating()):
| def _convert_key(self, key, is_setter: bool = False):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# allow arbitrary setting
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ... |
pandas/72 | pandas | 72 | pandas/core/internals/blocks.py | a9b61a9 | 0c50950f2a7e32887eff6be5979f09772091e1de | pandas/tests/frame/indexing/test_categorical.py | setitem | 808 | 909 | 2 | 6 | def setitem(self, indexer, value):
"""
Set the value inplace, returning a a maybe different typed block.
Parameters
----------
indexer : tuple, list-like, array-like, slice
The subset of self.values to set
value : object
The value being set
... | exact_match = (
len(arr_value.shape)
and arr_value.shape[0] == values.shape[0]
and arr_value.size == values.size
)
if is_empty_indexer(indexer, arr_value):
# GH#8669 empty indexers
pass
# be e.g. a list; see GH#6043
... | def setitem(self, indexer, value):
"""
Set the value inplace, returning a a maybe different typed block.
Parameters
----------
indexer : tuple, list-like, array-like, slice
The subset of self.values to set
value : object
The value being set
... |
pandas/74 | pandas | 74 | pandas/core/indexes/timedeltas.py | 9a211aa | 839e7f1416148caff518a5b75327a2480a2bbbb4 | pandas/tests/indexes/timedeltas/test_constructors.py | __new__ | 142 | 182 | 1 | 1 | def __new__(
cls,
data=None,
unit=None,
freq=None,
closed=None,
dtype=_TD_DTYPE,
copy=False,
name=None,
):
name = maybe_extract_name(name, data, cls)
if is_scalar(data):
raise TypeError(
f"{cls.__name__}... | if isinstance(data, TimedeltaArray) and freq is None:
| def __new__(
cls,
data=None,
unit=None,
freq=None,
closed=None,
dtype=_TD_DTYPE,
copy=False,
name=None,
):
name = maybe_extract_name(name, data, cls)
if is_scalar(data):
raise TypeError(
f"{cls.__name__}... |
pandas/76 | pandas | 76 | pandas/io/json/_json.py | 4da554f | 47922d3b00edfc264f73b1484589734bbd077c11 | pandas/tests/io/json/test_pandas.py | _try_convert_data | 886 | 958 | 1 | 1 | def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):
"""
Try to parse a ndarray like into a column by inferring dtype.
"""
# don't try to coerce, unless a force conversion
if use_dtypes:
if not self.dtype:
return data, Fal... | except (TypeError, ValueError, OverflowError):
| def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True):
"""
Try to parse a ndarray like into a column by inferring dtype.
"""
# don't try to coerce, unless a force conversion
if use_dtypes:
if not self.dtype:
return data, Fal... |
pandas/77 | pandas | 77 | pandas/core/ops/array_ops.py | 667bb37 | daef69c1366e31c3c49aea6f2e55f577d0c832fd | pandas/tests/arithmetic/test_array_ops.py | na_logical_op | 263 | 301 | 2 | 2 | def na_logical_op(x: np.ndarray, y, op):
try:
# For exposition, write:
# yarr = isinstance(y, np.ndarray)
# yint = is_integer(y) or (yarr and y.dtype.kind == "i")
# ybool = is_bool(y) or (yarr and y.dtype.kind == "b")
# xint = x.dtype.kind == "i"
# xbool = x.dtyp... | result = libops.vec_binop(x.ravel(), y.ravel(), op)
else:
# let null fall thru
assert lib.is_scalar(y)
f"and scalar of type [{typ}]"
)
return result.reshape(x.shape)
| def na_logical_op(x: np.ndarray, y, op):
try:
# For exposition, write:
# yarr = isinstance(y, np.ndarray)
# yint = is_integer(y) or (yarr and y.dtype.kind == "i")
# ybool = is_bool(y) or (yarr and y.dtype.kind == "b")
# xint = x.dtype.kind == "i"
# xbool = x.dtyp... |
pandas/82 | pandas | 82 | pandas/core/internals/concat.py | 6f395ad | e83a6bddac8c89b144dfe0783594dd332c5b3030 | pandas/tests/reshape/merge/test_merge.py | _get_empty_dtype_and_na | 268 | 372 | 1 | 1 | def _get_empty_dtype_and_na(join_units):
"""
Return dtype and N/A values to use when concatenating specified units.
Returned N/A value may be None which means there was no casting involved.
Returns
-------
dtype
na
"""
if len(join_units) == 1:
blk = join_units[0].block
... | return np.dtype("M8[ns]"), np.datetime64("NaT", "ns")
| def _get_empty_dtype_and_na(join_units):
"""
Return dtype and N/A values to use when concatenating specified units.
Returned N/A value may be None which means there was no casting involved.
Returns
-------
dtype
na
"""
if len(join_units) == 1:
blk = join_units[0].block
... |
pandas/89 | pandas | 89 | pandas/core/reshape/reshape.py | 0dc317f | feaa5033b7810f7775fd4806c27b2f9f1e9b5051 | pandas/tests/frame/test_reshape.py | _unstack_multiple | 312 | 390 | 1 | 1 | def _unstack_multiple(data, clocs, fill_value=None):
if len(clocs) == 0:
return data
# NOTE: This doesn't deal with hierarchical columns yet
index = data.index
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in range(index.nlevels) if i not in clocs]
clevels = [... | result = result.unstack(val, fill_value=fill_value)
| def _unstack_multiple(data, clocs, fill_value=None):
if len(clocs) == 0:
return data
# NOTE: This doesn't deal with hierarchical columns yet
index = data.index
clocs = [index._get_level_number(i) for i in clocs]
rlocs = [i for i in range(index.nlevels) if i not in clocs]
clevels = [... |
pandas/91 | pandas | 91 | pandas/core/indexes/timedeltas.py | 5c12d4f | cb9a1c7d0319c34a97247973ca96af53ead8033a | pandas/tests/arrays/test_timedeltas.py | searchsorted | 358 | 364 | 1 | 4 | def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
# Buggy code:
# value = np.array(value, dtype=_TD_DTYPE, copy=False)
# else:
# value = Timedelta(value).asm8.view(_TD_DTYPE)
#
# return self.values.searchsorted(value,... | if not type(self._data)._is_recognized_dtype(value):
raise TypeError(
"searchsorted requires compatible dtype or scalar, "
f"not {type(value).__name__}"
)
value = type(self._data)(value)
self._data._check_compati... | def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
value = np.array(value, dtype=_TD_DTYPE, copy=False)
else:
value = Timedelta(value).asm8.view(_TD_DTYPE)
return self.values.searchsorted(value, side=side, sorter=sorte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.