Dataset Viewer
Auto-converted to Parquet Duplicate
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, ...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
4