id int64 20 338k | vocab_size int64 2 671 | ast_levels int64 4 32 | nloc int64 1 451 | n_ast_nodes int64 12 5.6k | n_identifiers int64 1 186 | n_ast_errors int64 0 10 | n_words int64 2 2.17k | n_whitespaces int64 2 13.8k | fun_name stringlengths 2 73 | commit_message stringlengths 51 15.3k | url stringlengths 31 59 | code stringlengths 51 31k | ast_errors stringlengths 0 1.46k | token_counts int64 6 3.32k | file_name stringlengths 5 56 | language stringclasses 1
value | path stringlengths 7 134 | commit_id stringlengths 40 40 | repo stringlengths 3 28 | complexity int64 1 153 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
143,848 | 14 | 11 | 5 | 63 | 11 | 0 | 14 | 53 | _extra_input_signature_def | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | https://github.com/ray-project/ray.git | def _extra_input_signature_def(self):
feed_dict = self.extra_compute_action_feed_dict()
return {
k.name: tf1.saved_model.utils.build_tensor_info(k) for k in feed_dict.keys()
}
| 38 | tf_policy.py | Python | rllib/policy/tf_policy.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 2 | |
310,124 | 53 | 14 | 39 | 310 | 28 | 0 | 83 | 316 | test_summary_correctly_updated | fix: 17track package summary status is not updated when there are no more packages in that summary (#64421)
* 17track package status is not updated when there are no packages
* 17track package status is not updated when there are no packages
* 17track package status is not updated when there are no packages | https://github.com/home-assistant/core.git | async def test_summary_correctly_updated(hass):
package = Package(
tracking_number="456",
destination_country=206,
friendly_name="friendly name 1",
info_text="info text 1",
location="location 1",
timestamp="2020-08-10 10:32",
origin_country=206,
p... | 186 | test_sensor.py | Python | tests/components/seventeentrack/test_sensor.py | 6176bb954c4aa68b33c9db487dbb5712059f4b38 | core | 4 | |
323,214 | 55 | 17 | 18 | 194 | 21 | 0 | 64 | 386 | acquire | Add model parallel for FasterGPT. (#1755)
* Add model parallel for FasterGPT.
* Make GPT model parallel runable
* Make FT model parallel optional.
* Fix _write_setup_file when kwargs is not empty.
* Fix ext_utils.load
* Add file lock for model parallel.
* Fix model_parallel.flag in CMakeLists.txt.
... | https://github.com/PaddlePaddle/PaddleNLP.git | def acquire(self):
start_time = time.time()
while True:
try:
self.fd = os.open(self.lock_file_path, os.O_CREAT | os.O_EXCL |
os.O_RDWR)
self.is_locked = True # moved to ensure tag only when locked
bre... | 116 | file_lock.py | Python | paddlenlp/utils/file_lock.py | c541f4ba1fcab8304c7ac4efdce3d63a2e478176 | PaddleNLP | 7 | |
171,627 | 20 | 14 | 13 | 163 | 4 | 0 | 36 | 142 | render_pep440 | BLD: use nonvendor versioneer (#49924)
* BLD: remove vendored versioneer
* run vis
* move config to pyproject.toml
* add versioneer to deps
* run pyupgrade
* fix isort and pylint
* fix ci
* fix env | https://github.com/pandas-dev/pandas.git | def render_pep440(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += f"{pieces['distance']}.g{pieces['short']}"
if pieces["dirty"]:
rendered... | 65 | _version.py | Python | pandas/_version.py | e2df99823758210fb2b7c4aba39e23f3445f7cd3 | pandas | 6 | |
139,165 | 23 | 11 | 27 | 104 | 13 | 0 | 27 | 86 | workflow_logging_context | [Workflow]Make workflow logs publish to the correct driver. (#24089)
All workflow tasks are executed as remote functions that submitted from WorkflowManagmentActor. WorkflowManagmentActor is a detached long-running actor whose owner is the first driver in the cluster that runs the very first workflow execution. Theref... | https://github.com/ray-project/ray.git | def workflow_logging_context(job_id) -> None:
node = ray.worker._global_node
original_out_file, original_err_file = node.get_log_file_handles(
get_worker_log_file_name("WORKER")
)
out_file, err_file = node.get_log_file_handles(
get_worker_log_file_name("WORKER", job_id)
)
tr... | 60 | workflow_context.py | Python | python/ray/workflow/workflow_context.py | e8fc66af348f2afd2b578fe1c6776cc88ea82499 | ray | 2 | |
271,851 | 45 | 12 | 15 | 134 | 16 | 0 | 58 | 150 | verify_dataset_shuffled | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def verify_dataset_shuffled(x):
assert isinstance(x, tf.data.Dataset)
graph_def = get_dataset_graph_def(x)
for node in graph_def.node:
if node.op.startswith("ShuffleDataset"):
return True
# Also check graph_def.library.function for ds.interleave or ds.flat_map
for function i... | 79 | training_utils_v1.py | Python | keras/engine/training_utils_v1.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 6 | |
264,296 | 123 | 17 | 40 | 565 | 47 | 0 | 192 | 698 | get | Refactor generic views; add plugins dev documentation | https://github.com/netbox-community/netbox.git | def get(self, request):
model = self.queryset.model
content_type = ContentType.objects.get_for_model(model)
if self.filterset:
self.queryset = self.filterset(request.GET, self.queryset).qs
# Compile a dictionary indicating which permissions are available to the cur... | 342 | bulk_views.py | Python | netbox/netbox/views/generic/bulk_views.py | 54834c47f8870e7faabcd847c3270da0bd3d2884 | netbox | 10 | |
286,002 | 11 | 8 | 9 | 48 | 8 | 1 | 11 | 16 | get_project_ids | Add 3 Token Terminal commands (#2447)
* add crypto/ov/fun
* add tokenterminal to dependencies
* update website content
* add to main.yml
* fix tests
* add tests
* Update _index.md
* Update _index.md
* fix tests
* fix test
* List hint added
* improve code based on Jose input
* fix te... | https://github.com/OpenBB-finance/OpenBBTerminal.git | def get_project_ids() -> List[str]:
return [project["project_id"] for project in PROJECTS_DATA]
@log_start_end(log=logger) | @log_start_end(log=logger) | 21 | tokenterminal_model.py | Python | openbb_terminal/cryptocurrency/due_diligence/tokenterminal_model.py | 7979b1fc071a1c3e7463044bea617d7305b4a17e | OpenBBTerminal | 2 |
85,425 | 28 | 11 | 9 | 191 | 27 | 0 | 32 | 102 | test_delete_performance_issue | feat(perf issues): Prevent deleting and merging (#38479)
* Prevent deleting, discarding, and merging in single and bulk operations
for performance issues. | https://github.com/getsentry/sentry.git | def test_delete_performance_issue(self):
self.login_as(user=self.user)
group = self.create_group(type=GroupType.PERFORMANCE_SLOW_SPAN.value)
GroupHash.objects.create(project=group.project, hash="x" * 32, group=group)
url = f"/api/0/issues/{group.id}/"
response = self.... | 114 | test_group_details.py | Python | tests/sentry/api/endpoints/test_group_details.py | dfe1d3442af1535cc2d4f8a511ee5733b3887572 | sentry | 1 | |
275,037 | 4 | 6 | 2 | 16 | 3 | 0 | 4 | 18 | dynamic_counter | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def dynamic_counter(self):
raise NotImplementedError
| 8 | loss_scale_optimizer.py | Python | keras/mixed_precision/loss_scale_optimizer.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 1 | |
295,912 | 17 | 12 | 5 | 84 | 10 | 0 | 18 | 37 | test_missing_tones_dict | Add EntityFeature enum to Siren (#69585)
Co-authored-by: Franck Nijhof <frenck@frenck.nl> | https://github.com/home-assistant/core.git | async def test_missing_tones_dict(hass):
siren = MockSirenEntity(SirenEntityFeature.TONES, {1: "a", 2: "b"})
siren.hass = hass
with pytest.raises(ValueError):
process_turn_on_params(siren, {"tone": 3})
| 47 | test_init.py | Python | tests/components/siren/test_init.py | a61ac3ddc6d65522dfa1eb599adf73420a9267dc | core | 1 | |
85,913 | 40 | 14 | 15 | 166 | 19 | 0 | 68 | 247 | get_matching_frame_actions | fix(grouping): Exception matcher with no frames (#38994)
We used to pass `-1` as a frame index for exception matchers, which
worked by accident because `-1` is a valid list index in Python, except
when the list of frames was empty.
Replace `-1` by `None` and make sure we do not attempt to access the
list of fram... | https://github.com/getsentry/sentry.git | def get_matching_frame_actions(self, frames, platform, exception_data=None, cache=None):
if not self.matchers:
return []
# 1 - Check if exception matchers match
for m in self._exception_matchers:
if not m.matches_frame(frames, None, platform, exception_data, cac... | 112 | __init__.py | Python | src/sentry/grouping/enhancer/__init__.py | 686675f81bf9402bc9b671e61ea0481b0c5c3468 | sentry | 8 | |
160,327 | 73 | 12 | 16 | 239 | 17 | 0 | 104 | 183 | eye | BUG: lib: Allow type uint64 for eye() arguments.
Closes gh-9982.
(Plus a few small PEP 8 fixes.) | https://github.com/numpy/numpy.git | def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):
if like is not None:
return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)
if M is None:
M = N
m = zeros((N, M), dtype=dtype, order=order)
if k >= M:
return m
# Ensure M and k are integers, ... | 146 | twodim_base.py | Python | numpy/lib/twodim_base.py | f9355942f6ef7c5d27691c4571096234efb67a2b | numpy | 5 | |
271,557 | 95 | 13 | 12 | 84 | 5 | 0 | 148 | 337 | _validate_target_and_loss | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def _validate_target_and_loss(self, y, loss):
# `self.loss` references the loss added via `compile` call. If users have
# provided such, the target must be provided; otherwise it's a user error.
# Note that `self.loss` does not include losses added via `add_loss`, and it
# is a... | 38 | training.py | Python | keras/engine/training.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 4 | |
276,843 | 22 | 12 | 18 | 78 | 8 | 0 | 24 | 56 | func_load | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def func_load(code, defaults=None, closure=None, globs=None):
if isinstance(code, (tuple, list)): # unpack previous dump
code, defaults, closure = code
if isinstance(defaults, list):
defaults = tuple(defaults)
| 147 | generic_utils.py | Python | keras/utils/generic_utils.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 7 | |
181,893 | 20 | 13 | 8 | 95 | 7 | 0 | 28 | 64 | float_range | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | https://github.com/EpistasisLab/tpot.git | def float_range(value):
try:
value = float(value)
except Exception:
raise argparse.ArgumentTypeError('Invalid float value: \'{}\''.format(value))
if value < 0.0 or value > 1.0:
raise argparse.ArgumentTypeError('Invalid float value: \'{}\''.format(value))
return value
| 56 | driver.py | Python | tpot/driver.py | 388616b6247ca4ea8de4e2f340d6206aee523541 | tpot | 4 | |
268,980 | 14 | 10 | 6 | 61 | 8 | 0 | 15 | 23 | config_for_enable_caching_device | Reorganize RNN layers, cells and wrappers into smaller logically organized files hosted under an `rnn` directory.
PiperOrigin-RevId: 428841673 | https://github.com/keras-team/keras.git | def config_for_enable_caching_device(rnn_cell):
default_enable_caching_device = tf.compat.v1.executing_eagerly_outside_functions(
)
if rnn_cell._enable_caching_device != default_enable_caching_device:
return {'enable_caching_device': rnn_cell._enable_caching_device}
return {}
| 35 | rnn_utils.py | Python | keras/layers/rnn/rnn_utils.py | 01c906c4178db5ae03b7eb2d298a052c952a0667 | keras | 2 | |
298,605 | 33 | 9 | 7 | 134 | 25 | 1 | 38 | 63 | test_update_hvac_mode | Use climate enums in gree (#70655)
* Use climate enums in gree
* Adjust tests | https://github.com/home-assistant/core.git | async def test_update_hvac_mode(hass, discovery, device, mock_now, hvac_mode):
device().power = hvac_mode != HVACMode.OFF
device().mode = HVAC_MODES_REVERSE.get(hvac_mode)
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == hvac_m... | @pytest.mark.parametrize(
"fan_mode",
(FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),
) | 63 | test_climate.py | Python | tests/components/gree/test_climate.py | 23c5bd97793af4eed9806a237593b482f8e1b932 | core | 1 |
267,080 | 22 | 16 | 9 | 104 | 14 | 0 | 24 | 95 | retry | ansible-test - Fix subprocess management. (#77638)
* Run code-smell sanity tests in UTF-8 Mode.
* Update subprocess use in sanity test programs.
* Use raw_command instead of run_command with always=True set.
* Add more capture=True usage.
* Don't expose stdin to subprocesses.
* Capture more output. Warn on retry.... | https://github.com/ansible/ansible.git | def retry(func, ex_type=SubprocessError, sleep=10, attempts=10, warn=True):
for dummy in range(1, attempts):
try:
return func()
except ex_type as ex:
if warn:
display.warning(str(ex))
time.sleep(sleep)
return func()
| 65 | util.py | Python | test/lib/ansible_test/_internal/util.py | 62d03c8e752ee35057031a91d7028e0a2e5d43e4 | ansible | 4 | |
81,378 | 34 | 10 | 9 | 69 | 9 | 0 | 38 | 108 | event_processing_finished | Split TaskManager into
- DependencyManager spawns dependencies if necessary
- WorkflowManager processes running workflows to see if a new job is
ready to spawn
- TaskManager starts tasks if unblocked and has execution capacity | https://github.com/ansible/awx.git | def event_processing_finished(self):
if self.status in ACTIVE_STATES:
return False # tally of events is only available at end of run
try:
event_qs = self.get_event_queryset()
except NotImplementedError:
return True # Model without events, such as WF... | 45 | unified_jobs.py | Python | awx/main/models/unified_jobs.py | 431b9370dfbbbcb64dee0b4ebc8af7df12740d08 | awx | 3 | |
20,916 | 15 | 9 | 2 | 52 | 7 | 2 | 15 | 27 | TypeAlias | check point progress on only bringing in pip==22.0.4 (#4966)
* vendor in pip==22.0.4
* updating vendor packaging version
* update pipdeptree to fix pipenv graph with new version of pip.
* Vendoring of pip-shims 0.7.0
* Vendoring of requirementslib 1.6.3
* Update pip index safety restrictions patch for p... | https://github.com/pypa/pipenv.git | def TypeAlias(self, parameters):
raise TypeError(f"{self} is not subscriptable")
# 3.7-3.8
elif sys.version_info[:2] >= (3, 7): | elif sys.version_info[:2] >= (3, 7):sys | 14 | typing_extensions.py | Python | pipenv/patched/notpip/_vendor/typing_extensions.py | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | pipenv | 1 |
224,055 | 75 | 17 | 27 | 303 | 28 | 0 | 106 | 411 | _load_theme_config | Remove spaces at the ends of docstrings, normalize quotes | https://github.com/mkdocs/mkdocs.git | def _load_theme_config(self, name):
theme_dir = utils.get_theme_dir(name)
self.dirs.append(theme_dir)
try:
file_path = os.path.join(theme_dir, 'mkdocs_theme.yml')
with open(file_path, 'rb') as f:
theme_config = utils.yaml_load(f)
... | 155 | theme.py | Python | mkdocs/theme.py | e7f07cc82ab2be920ab426ba07456d8b2592714d | mkdocs | 5 | |
47,693 | 32 | 16 | 16 | 195 | 15 | 0 | 42 | 166 | test_default_args | Replace usage of `DummyOperator` with `EmptyOperator` (#22974)
* Replace usage of `DummyOperator` with `EmptyOperator` | https://github.com/apache/airflow.git | def test_default_args():
execution_date = pendulum.parse("20201109")
with DAG(
dag_id='example_task_group_default_args',
start_date=execution_date,
default_args={
"owner": "dag",
},
):
with TaskGroup("group1", default_args={"owner": "group"}):
... | 103 | test_task_group.py | Python | tests/utils/test_task_group.py | 49e336ae0302b386a2f47269a6d13988382d975f | airflow | 1 | |
275,981 | 12 | 9 | 6 | 68 | 9 | 0 | 14 | 60 | trackable_children | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def trackable_children(self, serialization_cache):
if not utils.should_save_traces():
return {}
children = self.objects_to_serialize(serialization_cache)
children.update(self.functions_to_serialize(serialization_cache))
return children
| 40 | base_serialization.py | Python | keras/saving/saved_model/base_serialization.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 2 | |
35,104 | 19 | 10 | 4 | 35 | 5 | 0 | 19 | 51 | copy | Constrained Beam Search [without disjunctive decoding] (#15416)
* added classes to get started with constrained beam search
* in progress, think i can directly force tokens now but not yet with the round robin
* think now i have total control, now need to code the bank selection
* technically works as desired... | https://github.com/huggingface/transformers.git | def copy(self, stateful=False):
raise NotImplementedError(
f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
)
| 16 | generation_beam_constraints.py | Python | src/transformers/generation_beam_constraints.py | 2b5603f6ac58f0cd3b2116c01d6b9f62575248b2 | transformers | 1 | |
78,341 | 28 | 10 | 5 | 61 | 8 | 0 | 32 | 85 | test_settings_no_request_no_use_default | Add generic settings to compliment site-specific settings (#8327) | https://github.com/wagtail/wagtail.git | def test_settings_no_request_no_use_default(self):
context = {}
# Without a request in the context, and without use_default_site, this
# should bail with an error
template = '{{ settings("tests.testsitesetting").title }}'
with self.assertRaises(RuntimeError):
... | 33 | test_templates.py | Python | wagtail/contrib/settings/tests/site_specific/test_templates.py | d967eccef28ce47f60d26be1c28f2d83a25f40b0 | wagtail | 1 | |
97,856 | 11 | 9 | 3 | 45 | 6 | 0 | 11 | 32 | render_warning | ref(py): Split up large file (#32862)
Co-authored-by: getsantry[bot] <66042841+getsantry[bot]@users.noreply.github.com> | https://github.com/getsentry/sentry.git | def render_warning(self, message):
context = {"error": message}
return render_to_response("sentry/pipeline-provider-error.html", context, self.request)
| 26 | base.py | Python | src/sentry/pipeline/base.py | d246d2b6d3e014270941209e54f2f12e09ad9a81 | sentry | 1 | |
82,608 | 92 | 15 | 36 | 379 | 39 | 0 | 152 | 404 | get_page_from_request | fix: Prefer titles matching request language (#7144)
* prefer titles matching request language
* add comments on use of annotate
* fix wayward imports
* Add changelog entry
Co-authored-by: Vinit Kumar <mail@vinitkumar.me>
Co-authored-by: Mark Walker <theshow@gmail.com> | https://github.com/django-cms/django-cms.git | def get_page_from_request(request, use_path=None, clean_path=None):
from cms.utils.page_permissions import user_can_view_page_draft
if not bool(use_path) and hasattr(request, '_current_page_cache'):
# The following is set by CurrentPageMiddleware
return request._current_page_cache
if ... | 235 | page.py | Python | cms/utils/page.py | 06c9a85df486581f152dbf11bbf40a1c6c5e6cd3 | django-cms | 14 | |
132,826 | 63 | 15 | 15 | 162 | 25 | 0 | 79 | 312 | __call__ | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | https://github.com/ray-project/ray.git | def __call__(self, checkpoint):
if not self.runner:
return
if checkpoint.storage == Checkpoint.PERSISTENT and checkpoint.value:
checkpoint_path = checkpoint.value
logger.debug(
"Trial %s: Deleting checkpoint %s", self.trial_id, checkpoint_pa... | 95 | trial.py | Python | python/ray/tune/trial.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 6 | |
320,678 | 40 | 10 | 5 | 205 | 18 | 1 | 70 | 190 | test_filename_rubout | Add :rl-rubout and :rl-filename-rubout
Closes #4561 | https://github.com/qutebrowser/qutebrowser.git | def test_filename_rubout(os_sep, monkeypatch, lineedit, text, deleted, rest):
monkeypatch.setattr(os, "sep", os_sep)
_validate_deletion(lineedit,
readlinecommands.rl_filename_rubout, [],
text, deleted, rest)
@pytest.mark.parametrize('text, deleted, rest', [
... | @pytest.mark.parametrize('text, deleted, rest', [
pytest.param('test foobar| delete', ' delete', 'test foobar|',
marks=fixme),
('test foobar| delete', ' ', 'test foobar|delete'), # wrong
pytest.param('test foo|delete bar', 'delete', 'test foo| bar',
marks=fixme),
('tes... | 43 | test_readlinecommands.py | Python | tests/unit/components/test_readlinecommands.py | ab65c542a0551abf105eeb58803cd08bd040753b | qutebrowser | 1 |
41,878 | 47 | 13 | 18 | 198 | 16 | 0 | 72 | 249 | _map_attributes | Downgrade exception on mapping list length mismatch to warning (#2856)
* Downgrade exception on mapping list length mismatch to warning
* Lint
* Fix pairplot test
* Set stacklevel to report warning in user code | https://github.com/mwaskom/seaborn.git | def _map_attributes(self, arg, levels, defaults, attr):
if arg is True:
lookup_table = dict(zip(levels, defaults))
elif isinstance(arg, dict):
missing = set(levels) - set(arg)
if missing:
err = f"These `{attr}` levels are missing values: {miss... | 115 | _oldcore.py | Python | seaborn/_oldcore.py | 563e96d3be1eaee8db8dfbccf7eed1f1c66dfd31 | seaborn | 6 | |
300,836 | 42 | 11 | 9 | 119 | 17 | 0 | 48 | 133 | process_new_events | Clean up accessing dispatcher helpers via hass (#72014)
Clean up accessing ditpatcher helpers via hass | https://github.com/home-assistant/core.git | def process_new_events(self, new_values_dict) -> None:
self.async_set_available_state(True)
# Process any stateless events (via device_triggers)
async_fire_triggers(self, new_values_dict)
for (aid, cid), value in new_values_dict.items():
accessory = self.current_st... | 74 | connection.py | Python | homeassistant/components/homekit_controller/connection.py | c8f700c80319cef81a9a817c1b9111887ea98b1a | core | 2 | |
22,222 | 59 | 16 | 20 | 240 | 24 | 0 | 75 | 202 | get_dependencies | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | https://github.com/pypa/pipenv.git | def get_dependencies(ireq, sources=None, parent=None):
# type: (Union[InstallRequirement, InstallationCandidate], Optional[List[Dict[S, Union[S, bool]]]], Optional[AbstractDependency]) -> Set[S, ...]
if not isinstance(ireq, shims.InstallRequirement):
name = getattr(ireq, "project_name", getattr(ire... | 150 | dependencies.py | Python | pipenv/vendor/requirementslib/models/dependencies.py | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | pipenv | 5 | |
119,312 | 54 | 15 | 16 | 252 | 16 | 0 | 83 | 184 | odd_ext | Add some functions for spectral analysis.
This commit adds "stft", "csd", and "welch" functions in scipy.signal. | https://github.com/google/jax.git | def odd_ext(x, n, axis=-1):
if n < 1:
return x
if n > x.shape[axis] - 1:
raise ValueError(
f"The extension length n ({n}) is too big. "
f"It must not exceed x.shape[axis]-1, which is {x.shape[axis] - 1}.")
left_end = lax.slice_in_dim(x, 0, 1, axis=axis)
left_ext = jnp.flip(lax.slice_i... | 159 | signal.py | Python | jax/_src/scipy/signal.py | e085370ec4137cf0f73c5163cb664bc4e1c46082 | jax | 3 | |
34,604 | 38 | 14 | 4 | 90 | 13 | 0 | 44 | 58 | create_position_ids_from_input_ids | Add XGLM models (#14876)
* add xglm
* update vocab size
* fix model name
* style and tokenizer
* typo
* no mask token
* fix pos embed compute
* fix args
* fix tokenizer
* fix positions
* fix tokenization
* style and dic fixes
* fix imports
* add fast tokenizer
* update names
... | https://github.com/huggingface/transformers.git | def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
mask = input_ids.ne(padding_idx).int()
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) +... | 55 | modeling_xglm.py | Python | src/transformers/models/xglm/modeling_xglm.py | d25e25ee2b63ebfcd099deb689a5a7272574a10f | transformers | 1 | |
101,448 | 20 | 15 | 7 | 110 | 15 | 0 | 21 | 75 | _build_tabs | Bugfix: convert - Gif Writer
- Fix non-launch error on Gif Writer
- convert plugins - linting
- convert/fs_media/preview/queue_manager - typing
- Change convert items from dict to Dataclass | https://github.com/deepfakes/faceswap.git | def _build_tabs(self) -> None:
logger.debug("Build Tabs")
for section in self.config_tools.sections:
tab = ttk.Notebook(self)
self._tabs[section] = {"tab": tab}
self.add(tab, text=section.replace("_", " ").title())
| 64 | preview.py | Python | tools/preview/preview.py | 1022651eb8a7741014f5d2ec7cbfe882120dfa5f | faceswap | 2 | |
295,982 | 9 | 9 | 3 | 46 | 7 | 1 | 9 | 14 | token_expiry | Refresh google calendar tokens with invalid expiration times (#69679)
* Refresh google calendar tokens with invalid expiration times
* Update tests/components/google/conftest.py
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
* Remove unnecessary async methods in functions being touched already
Co-aut... | https://github.com/home-assistant/core.git | def token_expiry() -> datetime.datetime:
return utcnow() + datetime.timedelta(days=7)
@pytest.fixture | @pytest.fixture | 22 | conftest.py | Python | tests/components/google/conftest.py | 06d2aeec6b153a104b275c73068cf05a7b5c0c6b | core | 1 |
148,501 | 131 | 18 | 44 | 672 | 40 | 0 | 181 | 675 | start | Implement previous backtest result reuse when config and strategy did not change. | https://github.com/freqtrade/freqtrade.git | def start(self) -> None:
data: Dict[str, Any] = {}
data, timerange = self.load_bt_data()
self.load_bt_data_detail()
logger.info("Dataload complete. Calculating indicators")
run_ids = {
strategy.get_strategy_name(): get_strategy_run_id(strategy)
... | 391 | backtesting.py | Python | freqtrade/optimize/backtesting.py | 16861db653ec8166f73fc8480894f186a137e7bd | freqtrade | 13 | |
158,185 | 25 | 13 | 5 | 82 | 11 | 0 | 26 | 46 | evaluate_accuracy | [PaddlePaddle] Merge master into Paddle branch (#1186)
* change 15.2 title in chinese version (#1109)
change title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘
* 修改部分语义表述 (#1105)
* Update r0.17.5 (#1120)
* Bump versions in installation
* 94行typo: (“bert.mall”)->(“bert.small”) (#1129)
* line 313: "b... | https://github.com/d2l-ai/d2l-zh.git | def evaluate_accuracy(net, data_iter):
metric = Accumulator(2) # No. of correct predictions, no. of predictions
for X, y in data_iter:
metric.add(accuracy(net(X), y), d2l.size(y))
return metric[0] / metric[1]
| 52 | mxnet.py | Python | d2l/mxnet.py | b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2 | d2l-zh | 2 | |
287,724 | 7 | 9 | 3 | 31 | 4 | 0 | 7 | 21 | async_terminate_apps | Add Button platform to Bravia TV (#78093)
* Add Button platform to Bravia TV
* Add button.py to coveragerc
* improve callable type | https://github.com/home-assistant/core.git | async def async_terminate_apps(self) -> None:
await self.client.terminate_apps()
| 16 | coordinator.py | Python | homeassistant/components/braviatv/coordinator.py | ab4c1ebfd6ab79abfc4e214853f71afba2380099 | core | 1 | |
139,515 | 14 | 8 | 8 | 34 | 6 | 0 | 14 | 29 | extra_compute_grad_fetches | [RLlib] Introduce new policy base classes. (#24742) | https://github.com/ray-project/ray.git | def extra_compute_grad_fetches(self) -> Dict[str, Any]:
return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc.
| 20 | torch_policy_v2.py | Python | rllib/policy/torch_policy_v2.py | bc3a1d35cf6e9a5fd7eef908a8e76aefb80ce6a9 | ray | 1 | |
248,550 | 68 | 12 | 54 | 488 | 17 | 0 | 145 | 717 | test_join_rules_public | EventAuthTestCase: build events for the right room version
In practice, when we run the auth rules, all of the events have the right room
version. Let's stop building Room V1 events for these tests and use the right
version. | https://github.com/matrix-org/synapse.git | def test_join_rules_public(self):
creator = "@creator:example.com"
pleb = "@joiner:example.com"
auth_events = {
("m.room.create", ""): _create_event(RoomVersions.V6, creator),
("m.room.member", creator): _join_event(RoomVersions.V6, creator),
("m.roo... | 309 | test_event_auth.py | Python | tests/test_event_auth.py | 2959184a42398277ff916206235b844a8f7be5d7 | synapse | 1 | |
178,014 | 35 | 15 | 17 | 179 | 21 | 0 | 51 | 182 | check_toname_in_config_by_regex | fix: DEV-1462: Fix changing label config for repeater tag (#2725)
* fix: DEV-1462: Fix changing label config for repeater tag with created annotations | https://github.com/heartexlabs/label-studio.git | def check_toname_in_config_by_regex(config_string, to_name, control_type=None):
c = parse_config(config_string)
if control_type:
check_list = [control_type]
else:
check_list = list(c.keys())
for control in check_list:
item = c[control].get('regex', {})
for to_name_it... | 112 | label_config.py | Python | label_studio/core/label_config.py | 583b3cb3b03a36a30b3ce9fe96eb4fb28548a070 | label-studio | 6 | |
100,928 | 18 | 12 | 6 | 85 | 12 | 0 | 19 | 73 | ask_multi_load | Core updates
- Change loss loading mechanism
- Autosize tooltips based on content size
- Random linting + code modernisation | https://github.com/deepfakes/faceswap.git | def ask_multi_load(filepath, filetypes):
filenames = FileHandler("filename_multi", filetypes).return_file
if filenames:
final_names = " ".join(f"\"{fname}\"" for fname in filenames)
logger.debug(final_names)
filepath.set(final_names)
| 46 | control_helper.py | Python | lib/gui/control_helper.py | bad5025aea1adb9126580e14e064e6c99089243d | faceswap | 3 | |
38,106 | 64 | 18 | 33 | 349 | 24 | 0 | 105 | 564 | tokenize | Black preview (#17217)
* Black preview
* Fixup too!
* Fix check copies
* Use the same version as the CI
* Bump black | https://github.com/huggingface/transformers.git | def tokenize(self, x):
if isinstance(x, list) and all([isinstance(_x, list) for _x in x]):
d = None
for l in x:
t = self.tokenizer(
l,
padding="max_length",
max_length=384,
truncatio... | 219 | tokenizer_utils.py | Python | examples/research_projects/fsner/src/fsner/tokenizer_utils.py | afe5d42d8d1d80af911ed980c2936bfe887078f6 | transformers | 10 | |
266,410 | 331 | 24 | 134 | 1,651 | 111 | 0 | 624 | 3,924 | run | end_play: end the current play only (#76674)
Fixes #76672 | https://github.com/ansible/ansible.git | def run(self):
result = 0
entrylist = []
entry = {}
try:
# preload become/connection/shell to set config defs cached
list(connection_loader.all(class_only=True))
list(shell_loader.all(class_only=True))
list(become_loader.all(class... | 1,002 | playbook_executor.py | Python | lib/ansible/executor/playbook_executor.py | f78deccec2d4b5447f32d4fc67eaa549f479ccaa | ansible | 34 | |
119,595 | 13 | 8 | 2 | 63 | 10 | 1 | 16 | 17 | _coo_matmat | [sparse] change call signature of coo primitive wrappers | https://github.com/google/jax.git | def _coo_matmat(data, row, col, B, *, spinfo, transpose=False):
return coo_matmat_p.bind(data, row, col, B, spinfo=spinfo, transpose=transpose)
@coo_matmat_p.def_impl | @coo_matmat_p.def_impl | 41 | coo.py | Python | jax/experimental/sparse/coo.py | 424536dcf421a8dd4b6dfd7ddffc066fec7661c7 | jax | 1 |
215,816 | 22 | 12 | 5 | 91 | 14 | 0 | 24 | 55 | test_symlink_exists_file | Add some funtional tests
Add functional tests for the following:
- file.readlink
- file.replace
- file.symlink
Remove unit tests for file.replace as they are duplicated in the added
functional test | https://github.com/saltstack/salt.git | def test_symlink_exists_file(file, source):
with pytest.helpers.temp_file("symlink.txt", contents="Source content") as target:
with pytest.raises(CommandExecutionError) as exc:
file.symlink(source, target)
assert "Existing path is not a symlink:" in exc.value.message
| 50 | test_symlink.py | Python | tests/pytests/functional/modules/file/test_symlink.py | a35b29b2651bf33c5d5b45e64bc7765ffde4aff4 | salt | 1 | |
110,159 | 15 | 10 | 3 | 43 | 5 | 0 | 15 | 41 | nargs_error | Factor out error generation for function calls with wrong nargs.
... matching the wording for standard functions.
Note that nargs_error returns the exception without raising it itself to
make the control flow clearer on the caller side. | https://github.com/matplotlib/matplotlib.git | def nargs_error(name, takes, given):
return TypeError(f"{name}() takes {takes} positional arguments but "
f"{given} were given")
| 18 | __init__.py | Python | lib/matplotlib/_api/__init__.py | 973e475ef85524c5e9cef0638c90ca9a159935e4 | matplotlib | 1 | |
121,221 | 78 | 14 | 20 | 338 | 30 | 0 | 102 | 199 | conv_shape_tuple | lax.conv_general_dilated: validate negative paddings | https://github.com/google/jax.git | def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):
if isinstance(pads, str):
pads = lax.padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = "Wrong number of explicit pads for convolution: expected {}, got {}."
raise TypeE... | 210 | convolution.py | Python | jax/_src/lax/convolution.py | 489596c0e268bf37a7f6c2cb86822f38d24eecc9 | jax | 5 | |
185,776 | 7 | 8 | 10 | 27 | 4 | 0 | 7 | 13 | test_widget_remove_order | Add a unit test for removal ordering via DOMQuery.remove | https://github.com/Textualize/textual.git | async def test_widget_remove_order():
removals: list[str] = []
| 87 | test_widget_removing.py | Python | tests/test_widget_removing.py | d3e7f5ad994a92ae1734caea8bb66cfb043fcfc4 | textual | 1 | |
37,528 | 50 | 14 | 22 | 337 | 29 | 0 | 80 | 186 | nested_simplify | Replace dict/BatchEncoding instance checks by Mapping (#17014)
* Replace dict/BatchEncoding instance checks by Mapping
* Typo | https://github.com/huggingface/transformers.git | def nested_simplify(obj, decimals=3):
import numpy as np
if isinstance(obj, list):
return [nested_simplify(item, decimals) for item in obj]
elif isinstance(obj, np.ndarray):
return nested_simplify(obj.tolist())
elif isinstance(obj, Mapping):
return {nested_simplify(k, decim... | 213 | testing_utils.py | Python | src/transformers/testing_utils.py | 18df440709f1b19d1c5617c0d987c5ff8fd0915d | transformers | 14 | |
20,451 | 46 | 13 | 26 | 248 | 23 | 0 | 75 | 244 | guess_lexer_for_filename | check point progress on only bringing in pip==22.0.4 (#4966)
* vendor in pip==22.0.4
* updating vendor packaging version
* update pipdeptree to fix pipenv graph with new version of pip.
* Vendoring of pip-shims 0.7.0
* Vendoring of requirementslib 1.6.3
* Update pip index safety restrictions patch for p... | https://github.com/pypa/pipenv.git | def guess_lexer_for_filename(_fn, _text, **options):
fn = basename(_fn)
primary = {}
matching_lexers = set()
for lexer in _iter_lexerclasses():
for filename in lexer.filenames:
if _fn_matches(fn, filename):
matching_lexers.add(lexer)
primary[lexer... | 179 | __init__.py | Python | pipenv/patched/notpip/_vendor/pygments/lexers/__init__.py | f3166e673fe8d40277b804d35d77dcdb760fc3b3 | pipenv | 10 | |
111,538 | 55 | 12 | 21 | 269 | 30 | 1 | 68 | 197 | test_issue4674 | Refactor KB for easier customization (#11268)
* Add implementation of batching + backwards compatibility fixes. Tests indicate issue with batch disambiguation for custom singular entity lookups.
* Fix tests. Add distinction w.r.t. batch size.
* Remove redundant and add new comments.
* Adjust comments. Fix var... | https://github.com/explosion/spaCy.git | def test_issue4674():
nlp = English()
kb = InMemoryLookupKB(nlp.vocab, entity_vector_length=3)
vector1 = [0.9, 1.1, 1.01]
vector2 = [1.8, 2.25, 2.01]
with pytest.warns(UserWarning):
kb.set_entities(
entity_list=["Q1", "Q1"],
freq_list=[32, 111],
vecto... | @pytest.mark.issue(6730) | 166 | test_entity_linker.py | Python | spacy/tests/pipeline/test_entity_linker.py | 1f23c615d7a7326ca5a38a7d768b8b70caaa0e17 | spaCy | 2 |
50,918 | 107 | 19 | 50 | 611 | 48 | 0 | 172 | 610 | postprocess | update yolov3_darknet53_vehicles (#1957)
* update yolov3_darknet53_vehicles
* update gpu config
* update
* add clean func
* update save inference model | https://github.com/PaddlePaddle/PaddleHub.git | def postprocess(paths, images, data_out, score_thresh, label_names, output_dir, handle_id, visualization=True):
results = data_out.copy_to_cpu()
lod = data_out.lod()[0]
check_dir(output_dir)
if paths:
assert type(paths) is list, "type(paths) is not list."
if handle_id < len(paths)... | 380 | processor.py | Python | modules/image/object_detection/yolov3_darknet53_vehicles/processor.py | 7a847a39b1da6e6867031f52f713d92391b9729d | PaddleHub | 13 | |
255,400 | 43 | 13 | 15 | 229 | 23 | 0 | 54 | 209 | test_error_opset_import_mismatch | Use Python type annotations rather than comments (#3962)
* These have been supported since Python 3.5.
ONNX doesn't support Python < 3.6, so we can use the annotations.
Diffs generated by https://pypi.org/project/com2ann/.
Signed-off-by: Gary Miguel <garymiguel@microsoft.com>
* Remove MYPY conditional logi... | https://github.com/onnx/onnx.git | def test_error_opset_import_mismatch(self) -> None:
m1, m2 = _load_model(m1_def), _load_model(m2_def)
m1 = helper.make_model(m1.graph, producer_name='test',
opset_imports=[helper.make_opsetid("", 10)])
m2 = helper.make_model(m2.graph, producer_name='test',... | 142 | compose_test.py | Python | onnx/test/compose_test.py | 83fa57c74edfd13ddac9548b8a12f9e3e2ed05bd | onnx | 1 | |
319,856 | 17 | 10 | 4 | 63 | 11 | 0 | 17 | 56 | test_load_corrupt_file | Updates the classifier to catch warnings from scikit-learn and rebuild the model file when this happens | https://github.com/paperless-ngx/paperless-ngx.git | def test_load_corrupt_file(self, patched_pickle_load):
# First load is the schema version
patched_pickle_load.side_effect = [DocumentClassifier.FORMAT_VERSION, OSError()]
with self.assertRaises(ClassifierModelCorruptError):
self.classifier.load()
| 36 | test_classifier.py | Python | src/documents/tests/test_classifier.py | 77fbbe95ffb965525136982846f50e3ad8244de9 | paperless-ngx | 1 | |
186,604 | 14 | 9 | 9 | 55 | 6 | 0 | 20 | 85 | ipv4_enabled | Fully type certbot-nginx module (#9124)
* Work in progress
* Fix type
* Work in progress
* Work in progress
* Work in progress
* Work in progress
* Work in progress
* Oups.
* Fix typing in UnspacedList
* Fix logic
* Finish typing
* List certbot-nginx as fully typed in tox
* Fix lint... | https://github.com/certbot/certbot.git | def ipv4_enabled(self) -> bool:
if not self.addrs:
return True
for a in self.addrs:
if not a.ipv6:
return True
return False
| 33 | obj.py | Python | certbot-nginx/certbot_nginx/_internal/obj.py | 16aad35d31a887dab157f9d4f5e0fe9218d06064 | certbot | 4 | |
176,485 | 22 | 12 | 5 | 99 | 11 | 0 | 25 | 60 | test_basic | Update black (#5438)
* CI: sync up black dev requirements version with precommit
* Run black
Co-authored-by: Jarrod Millman <jarrod.millman@gmail.com> | https://github.com/networkx/networkx.git | def test_basic(self):
trees = [(nx.full_rary_tree(2, 2**2 - 1), 0) for i in range(2)]
actual = nx.join(trees)
expected = nx.full_rary_tree(2, 2**3 - 1)
assert nx.is_isomorphic(actual, expected)
| 64 | test_operations.py | Python | networkx/algorithms/tree/tests/test_operations.py | f6755ffa00211b523c6c0bec5398bc6c3c43c8b1 | networkx | 2 | |
296,688 | 5 | 15 | 2 | 53 | 6 | 0 | 5 | 11 | format_target_temperature | Fix #69952: Daikin AC Temperature jumps after being set (#70326) | https://github.com/home-assistant/core.git | def format_target_temperature(target_temperature):
return str(round(float(target_temperature), 1)).rstrip("0").rstrip(".")
| 29 | climate.py | Python | homeassistant/components/daikin/climate.py | b0ed42a5a58976ebe82b5bbbb60c499648a1718b | core | 1 | |
70,730 | 21 | 11 | 4 | 70 | 8 | 0 | 23 | 58 | test_not_collapsed_with_legacy | Update Wagtail test cases to match slim sidebar capabilities and implementation details | https://github.com/wagtail/wagtail.git | def test_not_collapsed_with_legacy(self):
# Sidebar should not be collapsed because the feature flag is not enabled
self.client.cookies['wagtail_sidebar_collapsed'] = '1'
response = self.client.get(reverse('wagtailadmin_home'))
self.assertNotContains(response, 'sidebar-collapsed... | 37 | test_menu.py | Python | wagtail/admin/tests/test_menu.py | 18c4d7c81356dbd5c4503db2ea24b21492512317 | wagtail | 1 | |
47,623 | 21 | 12 | 9 | 83 | 14 | 0 | 21 | 128 | test_pool_slots_property | Replace usage of `DummyOperator` with `EmptyOperator` (#22974)
* Replace usage of `DummyOperator` with `EmptyOperator` | https://github.com/apache/airflow.git | def test_pool_slots_property(self):
with pytest.raises(ValueError, match="pool slots .* cannot be less than 1"):
dag = models.DAG(dag_id='test_run_pooling_task')
EmptyOperator(
task_id='test_run_pooling_task_op',
dag=dag,
pool='te... | 47 | test_taskinstance.py | Python | tests/models/test_taskinstance.py | 49e336ae0302b386a2f47269a6d13988382d975f | airflow | 1 | |
163,655 | 127 | 16 | 47 | 435 | 46 | 0 | 191 | 651 | putmask | BUG: setting pd.NA into Series casts to object (#45431) | https://github.com/pandas-dev/pandas.git | def putmask(self, mask, new) -> list[Block]:
orig_mask = mask
values = cast(np.ndarray, self.values)
mask, noop = validate_putmask(values.T, mask)
assert not isinstance(new, (ABCIndex, ABCSeries, ABCDataFrame))
if new is lib.no_default:
new = self.fill_value... | 275 | blocks.py | Python | pandas/core/internals/blocks.py | 3510b1fd2a9cf752638f4af751bdeb33496db766 | pandas | 11 | |
109,118 | 92 | 14 | 27 | 281 | 19 | 1 | 100 | 285 | xkcd | Simplify impl. of functions optionally used as context managers.
We can actually just put the "exit" logic into an ExitStack callback.
If the return value is never `__enter__`'d via a "with" statement, it is
never `__exit__`'d either. | https://github.com/matplotlib/matplotlib.git | def xkcd(scale=1, length=100, randomness=2):
# This cannot be implemented in terms of contextmanager() or rc_context()
# because this needs to work as a non-contextmanager too.
if rcParams['text.usetex']:
raise RuntimeError(
"xkcd mode is not compatible with text.usetex = True")
... | @_api.make_keyword_only("3.6", "facecolor") | 158 | pyplot.py | Python | lib/matplotlib/pyplot.py | 2d918ba09155810194bb4ba136369082ad46c8c8 | matplotlib | 2 |
157,202 | 38 | 14 | 23 | 200 | 13 | 0 | 41 | 111 | test_use_nullable_dtypes | Add support for `use_nullable_dtypes` to `dd.read_parquet` (#9617) | https://github.com/dask/dask.git | def test_use_nullable_dtypes(tmp_path, engine):
df = pd.DataFrame(
{
"a": pd.Series([1, 2, pd.NA, 3, 4], dtype="Int64"),
"b": pd.Series([True, pd.NA, False, True, False], dtype="boolean"),
"c": pd.Series([0.1, 0.2, 0.3, pd.NA, 0.4], dtype="Float64"),
"d":... | 257 | test_parquet.py | Python | dask/dataframe/io/tests/test_parquet.py | b1e468e8645baee30992fbfa84250d816ac1098a | dask | 3 | |
107,623 | 113 | 14 | 26 | 418 | 49 | 0 | 169 | 501 | update_positions | Cleanup AnnotationBbox.
Inline _update_position_xybox into update_positions. Avoid unpacking
x,y pairs where unnecessary. Don't bother copying arrowprops, as we
don't actually modify it. Reuse mutation scale for both patch and
arrow. Clarify the doc for frameon. Various small extra cleanups. | https://github.com/matplotlib/matplotlib.git | def update_positions(self, renderer):
x, y = self.xybox
if isinstance(self.boxcoords, tuple):
xcoord, ycoord = self.boxcoords
x1, y1 = self._get_xy(renderer, x, y, xcoord)
x2, y2 = self._get_xy(renderer, x, y, ycoord)
ox0, oy0 = x1, y2
el... | 264 | offsetbox.py | Python | lib/matplotlib/offsetbox.py | 924d7c7f9900d8839e66616791121237101e7b57 | matplotlib | 4 | |
180,449 | 63 | 12 | 31 | 419 | 27 | 0 | 83 | 412 | test_component_functions | detect all types of null default value (#1685)
* detect all types of null default value
* fix test
* address review comments | https://github.com/gradio-app/gradio.git | def test_component_functions(self):
radio_input = gr.Radio(["a", "b", "c"])
self.assertEqual(radio_input.preprocess("c"), "c")
self.assertEqual(radio_input.preprocess_example("a"), "a")
self.assertEqual(radio_input.serialize("a", True), "a")
with tempfile.TemporaryDirect... | 235 | test_components.py | Python | test/test_components.py | a2b84199d88f84fd2dc515e092e79380ed7cef50 | gradio | 1 | |
189,528 | 10 | 8 | 11 | 40 | 5 | 0 | 10 | 38 | stop_submobject_movement | Upgraded typehints (#2429)
* Future Annotations
* Delete template_twitter_post.py
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Apply sugge... | https://github.com/ManimCommunity/manim.git | def stop_submobject_movement(self) -> VectorField:
self.remove_updater(self.submob_movement_updater)
self.submob_movement_updater = None
return self
| 23 | vector_field.py | Python | manim/mobject/vector_field.py | daf23c9d1031b12d9c119b8f6b7e60727d7f9242 | manim | 1 | |
107,875 | 14 | 11 | 3 | 57 | 6 | 0 | 14 | 35 | _extend_upper | FIX: Handle inverted colorbar axes with extensions
This fixes the colorbar extensions to use the proper color when the
long axis is inverted. | https://github.com/matplotlib/matplotlib.git | def _extend_upper(self):
minmax = "min" if self._long_axis().get_inverted() else "max"
return self.extend in ('both', minmax)
| 31 | colorbar.py | Python | lib/matplotlib/colorbar.py | ec374f5148631e4d392ed7e6d4c454d163a62f21 | matplotlib | 2 | |
260,354 | 24 | 10 | 11 | 135 | 14 | 0 | 34 | 119 | fit | MAINT Use _validate_params in SparsePCA and MiniBatchSparsePCA (#23710)
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
Co-authored-by: jeremiedbb <jeremiedbb@yahoo.fr> | https://github.com/scikit-learn/scikit-learn.git | def fit(self, X, y=None):
self._validate_params()
random_state = check_random_state(self.random_state)
X = self._validate_data(X)
self.mean_ = X.mean(axis=0)
X = X - self.mean_
if self.n_components is None:
n_components = X.shape[1]
else:
... | 85 | _sparse_pca.py | Python | sklearn/decomposition/_sparse_pca.py | db6123fe40400828918037f3fae949bfcc4d9d05 | scikit-learn | 2 | |
86,890 | 32 | 14 | 17 | 168 | 24 | 0 | 39 | 206 | get_repo | feat(github): Log Github integration errors (#39993)
We are flying blind without this. This helps the debugging of issues. | https://github.com/getsentry/sentry.git | def get_repo(self, integration, organization, event):
try:
project_id = event["project"]["id"]
except KeyError:
logger.info(
"gitlab.webhook.missing-projectid", extra={"integration_id": integration.id}
)
logger.exception("Missing p... | 100 | webhooks.py | Python | src/sentry/integrations/gitlab/webhooks.py | 746c20250f419a227bed0d174791e9c9b75daa13 | sentry | 3 | |
93,332 | 60 | 16 | 19 | 186 | 27 | 1 | 62 | 293 | handle_subscription_metrics_logger | refs(metric_alerts): Consolidate `QueryDatasets` and `Dataset` (#36894)
This refactor pr removes `QueryDatasets` and just uses `Dataset` everywhere. `QueryDatasets` existed
before `Dataset`, but `Dataset` is now more widely used and is more up to date. The values here are
the same, `Dataset` just supports a few more... | https://github.com/getsentry/sentry.git | def handle_subscription_metrics_logger(subscription_update, subscription):
from sentry.incidents.subscription_processor import SubscriptionProcessor
try:
if subscription.snuba_query.dataset == Dataset.Metrics.value:
processor = SubscriptionProcessor(subscription)
# XXX: Tem... | @register_subscriber(INCIDENTS_SNUBA_SUBSCRIPTION_TYPE) | 106 | tasks.py | Python | src/sentry/incidents/tasks.py | e1482001662b446c7c2be7c9daa19cba562c615c | sentry | 3 |
186,683 | 26 | 9 | 16 | 130 | 14 | 0 | 36 | 122 | _set_locations | Add typing to certbot.apache (#9071)
* Add typing to certbot.apache
Co-authored-by: Adrien Ferrand <ferrand.ad@gmail.com> | https://github.com/certbot/certbot.git | def _set_locations(self) -> Dict[str, str]:
default: str = self.loc["root"]
temp: str = os.path.join(self.root, "ports.conf")
if os.path.isfile(temp):
listen = temp
name = temp
else:
listen = default
name = default
return... | 77 | parser.py | Python | certbot-apache/certbot_apache/_internal/parser.py | 7d9e9a49005de7961e84d2a7c608db57dbab3046 | certbot | 2 | |
127,552 | 19 | 11 | 20 | 77 | 12 | 0 | 22 | 37 | test_placement_group_parent | Migrate the deprecated placement_group option to PlacementGroupSchedulingStrategy (#28437)
placement_group option is deprecated, use PlacementGroupSchedulingStrategy instead. | https://github.com/ray-project/ray.git | def test_placement_group_parent(ray_4_node_4_cpu, placement_group_capture_child_tasks):
num_workers = 2
bundle = {"CPU": 1}
bundles = [bundle.copy() for _ in range(num_workers + 1)]
placement_group = ray.util.placement_group(bundles)
| 109 | test_backend.py | Python | python/ray/train/tests/test_backend.py | 57cdbb1769a9c32972ba0ec9e7e857eeea961869 | ray | 4 | |
314,093 | 10 | 10 | 5 | 47 | 4 | 0 | 10 | 38 | async_will_remove_from_hass | Fix cover, light, select, sensor, switch type hints in zha (#73770)
* Fix zha sensor type hints
* Fix zha entity type hints
* Fix switch type hints
* Fix light type hints
* Fix cover type hints
* Fix select type hints | https://github.com/home-assistant/core.git | async def async_will_remove_from_hass(self) -> None:
assert self._cancel_refresh_handle
self._cancel_refresh_handle()
await super().async_will_remove_from_hass()
| 25 | light.py | Python | homeassistant/components/zha/light.py | 243905ae3e10f21c9bc8cbde565532e1b7b9112f | core | 1 | |
48,202 | 49 | 12 | 22 | 330 | 42 | 0 | 65 | 227 | test_find_executable_task_instances_negative_open_pool_slots | Pools with negative open slots should not block other pools (#23143) | https://github.com/apache/airflow.git | def test_find_executable_task_instances_negative_open_pool_slots(self, dag_maker):
set_default_pool_slots(0)
self.scheduler_job = SchedulerJob(subdir=os.devnull)
session = settings.Session()
pool1 = Pool(pool='pool1', slots=1)
pool2 = Pool(pool='pool2', slots=1)
... | 200 | test_scheduler_job.py | Python | tests/jobs/test_scheduler_job.py | 7132be2f11db24161940f57613874b4af86369c7 | airflow | 1 | |
258,549 | 9 | 11 | 3 | 45 | 7 | 0 | 9 | 34 | staged_predict_proba | DOC Fix incorrect heading underline length in docstrings (#22278) | https://github.com/scikit-learn/scikit-learn.git | def staged_predict_proba(self, X):
for raw_predictions in self._staged_raw_predict(X):
yield self._loss.predict_proba(raw_predictions)
| 27 | gradient_boosting.py | Python | sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py | 24106c2149683efeb642c8c1317152d7fe5be162 | scikit-learn | 2 | |
42,746 | 65 | 17 | 28 | 235 | 19 | 0 | 84 | 334 | provide_gcp_credential_file_as_context | Ensure @contextmanager decorates generator func (#23103) | https://github.com/apache/airflow.git | def provide_gcp_credential_file_as_context(self) -> Generator[Optional[str], None, None]:
key_path: Optional[str] = self._get_field('key_path', None)
keyfile_dict: Optional[str] = self._get_field('keyfile_dict', None)
if key_path and keyfile_dict:
raise AirflowException(
... | 133 | base_google.py | Python | airflow/providers/google/common/hooks/base_google.py | e58985598f202395098e15b686aec33645a906ff | airflow | 6 | |
287,994 | 94 | 16 | 114 | 985 | 22 | 1 | 246 | 1,907 | test_migration_1_1_to_1_4 | Add serial_number to device registry entries (#77713) | https://github.com/home-assistant/core.git | async def test_migration_1_1_to_1_4(hass, hass_storage):
hass_storage[device_registry.STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"data": {
"devices": [
{
"config_entries": ["1234"],
"connections": [["Zigbee", "0... | @pytest.mark.parametrize("load_registries", [False]) | 519 | test_device_registry.py | Python | tests/helpers/test_device_registry.py | cba3b6ad944408b9ffd906f4da5e5f5fd615b174 | core | 1 |
248,057 | 67 | 12 | 21 | 250 | 18 | 0 | 97 | 293 | test_thread_edit_latest_event | Misc. clean-ups to the relations code (#12519)
* Corrects some typos / copy & paste errors in tests.
* Clarifies docstrings.
* Removes an unnecessary method. | https://github.com/matrix-org/synapse.git | def test_thread_edit_latest_event(self) -> None:
# Create a thread and edit the last event.
channel = self._send_relation(
RelationTypes.THREAD,
"m.room.message",
content={"msgtype": "m.text", "body": "A threaded reply!"},
)
threaded_event_id... | 138 | test_relations.py | Python | tests/rest/client/test_relations.py | 185da8f0f2db8e4d502a904942cbd8a6840e27c8 | synapse | 1 | |
8,573 | 51 | 14 | 11 | 217 | 23 | 0 | 57 | 117 | _split | Add H&M fashion recommendation dataset (#2708)
* allow individual file downloads from kaggle
* pipe download_filenames to kaggle download fn
* add dataset config for H&M Fashion Recommendations
* add custom loader
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://p... | https://github.com/ludwig-ai/ludwig.git | def _split(df):
splitter = get_splitter("datetime", column="year_month", probabilities=(0.7, 0.2, 0.1))
if not isinstance(df, pd.DataFrame):
df = df.compute()
train_dfs, val_dfs, test_dfs = [], [], []
for customer_id in df["customer_id"].unique():
# Split per customer_id to ensure... | 141 | hm_fashion_recommendations.py | Python | ludwig/datasets/loaders/hm_fashion_recommendations.py | abfdc05018cc4dec5a2fed20ad09e94f1749fca9 | ludwig | 3 | |
132,860 | 40 | 14 | 18 | 185 | 20 | 0 | 67 | 256 | _get_next_trial | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | https://github.com/ray-project/ray.git | def _get_next_trial(self):
no_trials_unfinished = True
no_trials_pending = True
for trial in self._live_trials:
if not trial.is_finished():
no_trials_unfinished = False
if trial.status == Trial.PENDING:
no_trials_pending = False
... | 107 | trial_runner.py | Python | python/ray/tune/trial_runner.py | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | ray | 10 | |
43,207 | 31 | 13 | 15 | 152 | 24 | 0 | 35 | 192 | test__build_query | Don't rely on current ORM structure for db clean command (#23574)
For command DB clean, by not relying on the ORM models, we will be able to use the command even when the metadatabase is not yet upgraded to the version of Airflow you have installed.
Additionally we archive all rows before deletion. | https://github.com/apache/airflow.git | def test__build_query(self, table_name, date_add_kwargs, expected_to_delete, external_trigger):
base_date = pendulum.DateTime(2022, 1, 1, tzinfo=pendulum.timezone('UTC'))
create_tis(
base_date=base_date,
num_tis=10,
external_trigger=external_trigger,
... | 98 | test_db_cleanup.py | Python | tests/utils/test_db_cleanup.py | 95bd6b71cc9f5da377e272707f7b68000d980939 | airflow | 1 | |
160,128 | 32 | 11 | 10 | 131 | 18 | 0 | 35 | 97 | test_build_dir | TST: Initialize f2py2e tests of the F2PY CLI (#20668)
Increases F2PY coverage by around 15 percent. For the CLI itself it covers the major features (around 70 percent), with the exception of mostly numpy.distutils stuff.
More importantly, sets the groundwork for #20056, in that passing the same testsuite should ind... | https://github.com/numpy/numpy.git | def test_build_dir(capfd, hello_world_f90, monkeypatch):
ipath = Path(hello_world_f90)
mname = "blah"
odir = "tttmp"
monkeypatch.setattr(sys, "argv",
f'f2py -m {mname} {ipath} --build-dir {odir}'.split())
with util.switchdir(ipath.parent):
f2pycli()
out,... | 64 | test_f2py2e.py | Python | numpy/f2py/tests/test_f2py2e.py | 729ad4f92420231e2a7009b3223c6c7620b8b808 | numpy | 1 | |
298,212 | 29 | 11 | 14 | 127 | 19 | 0 | 32 | 115 | help_test_reload_with_config | Do not depend MQTT CI tests on debug logs (#84783)
* Do not depend MQTT CI tests on debug logs
* Leave Clean up expire as debug message | https://github.com/home-assistant/core.git | async def help_test_reload_with_config(hass, caplog, tmp_path, config):
new_yaml_config_file = tmp_path / "configuration.yaml"
new_yaml_config = yaml.dump(config)
new_yaml_config_file.write_text(new_yaml_config)
assert new_yaml_config_file.read_text() == new_yaml_config
with patch.object(hass_... | 82 | test_common.py | Python | tests/components/mqtt/test_common.py | ee66ffc8deaa6d383becc60c0418f63a7cfa4dc9 | core | 1 | |
171,851 | 4 | 7 | 46 | 25 | 4 | 0 | 4 | 18 | get_loc | DEPR: Remove method and tolerance in Index.get_loc, bump xarray (#49630)
* DEPR: Remove method and tolerance in Index.get_loc
* note xarray bump
* Fix tests
* Fix refactor in period
* Lighter parameterization
* xfail xarray test
* Just use get_indexer | https://github.com/pandas-dev/pandas.git | def get_loc(self, key):
self._check_indexing_error(key)
| 308 | multi.py | Python | pandas/core/indexes/multi.py | bc987e708b9856f5d5c8cf3096e1e2bcf23e1121 | pandas | 14 | |
192,296 | 13 | 10 | 4 | 63 | 14 | 0 | 14 | 42 | test_probe_video_from_memory | Improve test_video_reader (#5498)
* Improve test_video_reader
* Fix linter error | https://github.com/pytorch/vision.git | def test_probe_video_from_memory(self, test_video, config):
_, video_tensor = _get_video_tensor(VIDEO_DIR, test_video)
probe_result = torch.ops.video_reader.probe_video_from_memory(video_tensor)
self.check_probe_result(probe_result, config)
| 40 | test_video_reader.py | Python | test/test_video_reader.py | c50d48845f7b1ca86d6a3b7f37a59be0ae11e36b | vision | 1 | |
42,510 | 51 | 11 | 15 | 154 | 15 | 0 | 73 | 224 | __lazymodule_import | Prevent LazyLoader from modifying nltk.__dict__
Allows pytest --doctest-modules nltk to be executed | https://github.com/nltk/nltk.git | def __lazymodule_import(self):
# Load and register module
local_name = self.__lazymodule_name # e.g. "toolbox"
full_name = self.__name__ # e.g. "nltk.toolbox"
if self.__lazymodule_loaded:
return self.__lazymodule_locals[local_name]
if _debug:
p... | 89 | lazyimport.py | Python | nltk/lazyimport.py | 0fbbff998ed4b91b2f640a5193161642d98898cd | nltk | 4 | |
60,450 | 41 | 16 | 13 | 193 | 19 | 0 | 67 | 163 | print_table | Balanced joint maximum mean discrepancy for deep transfer learning | https://github.com/jindongwang/transferlearning.git | def print_table(table, max_width):
max_widths = [max_width] * len(table[0])
column_widths = [max(printed_len(row[j]) + 1 for row in table)
for j in range(len(table[0]))]
column_widths = [min(w, max_w) for w, max_w in zip(column_widths, max_widths)]
for row in table:
r... | 123 | summarize.py | Python | code/deep/BJMMD/caffe/tools/extra/summarize.py | cc4d0564756ca067516f71718a3d135996525909 | transferlearning | 6 | |
303,393 | 12 | 8 | 6 | 59 | 5 | 0 | 17 | 67 | vehicle_name | Refactor volvooncall to (mostly) use DataUpdateCoordinator (#75885)
Co-authored-by: Martin Hjelmare <marhje52@gmail.com> | https://github.com/home-assistant/core.git | def vehicle_name(self, vehicle):
if vehicle.registration_number and vehicle.registration_number != "UNKNOWN":
return vehicle.registration_number
if vehicle.vin:
return vehicle.vin
return "Volvo"
| 34 | __init__.py | Python | homeassistant/components/volvooncall/__init__.py | b5a6ee3c567aa50633ef47d342af685fb75e5219 | core | 4 | |
149,759 | 18 | 12 | 7 | 126 | 12 | 0 | 22 | 79 | fill_predictions | add freqao backend machinery, user interface, documentation | https://github.com/freqtrade/freqtrade.git | def fill_predictions(self, len_dataframe):
filler = np.zeros(len_dataframe -len(self.predictions)) # startup_candle_count
self.predictions = np.append(filler,self.predictions)
self.do_predict = np.append(filler,self.do_predict)
self.target_mean = np.append(filler,self.target_me... | 80 | data_handler.py | Python | freqtrade/freqai/data_handler.py | fc837c4daa27a18ff0e86128f4d52089b88fa5fb | freqtrade | 1 | |
89,350 | 20 | 12 | 10 | 84 | 12 | 0 | 20 | 126 | test_get_dynamic_sampling_default_biases | fix(dyn-sampling): Backend code clean up (#42001)
We are consolidating server-side-sampling and dynamic-sampling flags
into only dynamic-sampling. The flag is being controlled by plan | https://github.com/getsentry/sentry.git | def test_get_dynamic_sampling_default_biases(self):
with Feature(
{
self.new_ds_flag: True,
}
):
response = self.get_success_response(
self.organization.slug, self.project.slug, method="get"
)
assert res... | 50 | test_project_details.py | Python | tests/sentry/api/endpoints/test_project_details.py | 6fc6106b6a57149a5bae3c0f4677349cfbae1155 | sentry | 1 | |
280,789 | 5 | 7 | 2 | 27 | 5 | 0 | 5 | 19 | save | Add serialization support to FeatureSpace.
PiperOrigin-RevId: 496914744 | https://github.com/keras-team/keras.git | def save(self, filepath):
saving_lib.save_model(self, filepath)
| 16 | feature_space.py | Python | keras/utils/feature_space.py | 799f70761eeb8155dc25c6afce8c1d22b38367b0 | keras | 1 | |
100,441 | 56 | 15 | 24 | 294 | 30 | 0 | 77 | 360 | detect_rnet | Update all Keras Imports to be conditional (#1214)
* Remove custom keras importer
* first round keras imports fix
* launcher.py: Remove KerasFinder references
* 2nd round keras imports update (lib and extract)
* 3rd round keras imports update (train)
* remove KerasFinder from tests
* 4th round keras ... | https://github.com/deepfakes/faceswap.git | def detect_rnet(self, images, rectangle_batch, height, width):
ret = []
# TODO: batching
for idx, rectangles in enumerate(rectangle_batch):
if not rectangles:
ret.append([])
continue
image = images[idx]
crop_number = 0
... | 193 | mtcnn.py | Python | plugins/extract/detect/mtcnn.py | aa39234538a8f83e6aa2b60b8275a570e8876ac2 | faceswap | 4 | |
81,964 | 50 | 16 | 11 | 137 | 13 | 0 | 60 | 186 | extract_data | Register pages for the Instance peers and install bundle endpoints
This includes exposing a new interface for Page objects, Page.bytes,
to return the full bytestring contents of the response. | https://github.com/ansible/awx.git | def extract_data(self, response):
try:
data = response.json()
except ValueError as e: # If there was no json to parse
data = {}
if response.text or response.status_code not in (200, 202, 204):
text = response.text
if len(text)... | 83 | page.py | Python | awxkit/awxkit/api/pages/page.py | 68a44529b6b77d2d43d7099b654560bfd8bbf518 | awx | 5 | |
106,933 | 18 | 12 | 7 | 73 | 11 | 0 | 18 | 37 | _isolated_tk_test | TST: Remove numpy cpu disabling from some subprocess tests
This removes the NPY_DISABLE_CPU_FEATURES flag from the sphinx and tk tests
as they emit warnings on CI which leads to failure from the subprocess.
These don't need to be disabled on these tests, so remove them from
the environment variables that are passed in... | https://github.com/matplotlib/matplotlib.git | def _isolated_tk_test(success_count, func=None):
if func is None:
return functools.partial(_isolated_tk_test, success_count)
# Remove decorators.
source = re.search(r"(?ms)^def .*", inspect.getsource(func)).group(0)
| 56 | test_backend_tk.py | Python | lib/matplotlib/tests/test_backend_tk.py | d6f68757c234d33f341adc9e3bd65053094cf748 | matplotlib | 2 | |
70,901 | 21 | 9 | 7 | 103 | 11 | 0 | 28 | 91 | test_is_html_renderer | Improve asserts in wagtail.
These improvements were based on flake8-assertive, which compiled an extensive
list of patterns to replace with more precise assertions. This should make
the error messages better in case of failures. | https://github.com/wagtail/wagtail.git | def test_is_html_renderer(self):
# TableBlock with default table_options
block1 = TableBlock()
self.assertIs(block1.is_html_renderer(), False)
# TableBlock with altered table_options
new_options = self.default_table_options.copy()
new_options['renderer'] = 'html... | 58 | tests.py | Python | wagtail/contrib/table_block/tests.py | a0ef2477a68f2deb83cdc9a0bb709cb644be028b | wagtail | 1 | |
268,996 | 11 | 10 | 3 | 58 | 9 | 0 | 12 | 15 | top_k_categorical_matches | making util methods for all the categorical accuracies | https://github.com/keras-team/keras.git | def top_k_categorical_matches(y_true, y_pred, k=5):
y_true = tf.math.argmax(y_true, axis=-1)
return sparse_top_k_categorical_matches(y_true, y_pred, k=k)
| 38 | metrics_utils.py | Python | keras/utils/metrics_utils.py | 33f395aeceaad95910ce6f0931621bb82d3e967c | keras | 1 | |
276,480 | 18 | 13 | 8 | 98 | 9 | 0 | 19 | 67 | basic_sequential | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | https://github.com/keras-team/keras.git | def basic_sequential():
model = keras.Sequential(
[
keras.layers.Dense(3, activation="relu", input_shape=(3,)),
keras.layers.Dense(2, activation="softmax"),
]
)
return ModelFn(model, (None, 3), (None, 2))
| 64 | model_architectures.py | Python | keras/tests/model_architectures.py | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | keras | 1 | |
267,989 | 15 | 12 | 3 | 74 | 10 | 0 | 17 | 31 | env_dict | ansible-test - Use more native type hints. (#78435)
* ansible-test - Use more native type hints.
Simple search and replace to switch from comments to native type hints for return types of functions with no arguments.
* ansible-test - Use more native type hints.
Conversion of simple single-line function annota... | https://github.com/ansible/ansible.git | def env_dict(self) -> t.Dict[str, str]:
return dict((item[0], item[1]) for item in [e.split('=', 1) for e in self.env])
| 49 | docker_util.py | Python | test/lib/ansible_test/_internal/docker_util.py | 3eb0485dd92c88cc92152d3656d94492db44b183 | ansible | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.