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
160,530
42
14
16
215
22
0
58
157
openhook
ENH: Support character string arrays TST: added test for issue #18684 ENH: f2py opens files with correct encoding, fixes #635 TST: added test for issue #6308 TST: added test for issue #4519 TST: added test for issue #3425 ENH: Implement user-defined hooks support for post-processing f2py data structure. Implement...
https://github.com/numpy/numpy.git
def openhook(filename, mode): bytes = min(32, os.path.getsize(filename)) with open(filename, 'rb') as f: raw = f.read(bytes) if raw.startswith(codecs.BOM_UTF8): encoding = 'UTF-8-SIG' elif raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)): encoding = 'UTF-32' el...
127
crackfortran.py
Python
numpy/f2py/crackfortran.py
d4e11c7a2eb64861275facb076d47ccd135fa28c
numpy
5
303,750
9
9
5
47
6
0
9
41
async_state_changed
Improve type hints in yeelight lights (#76018) Co-authored-by: Franck Nijhof <frenck@frenck.nl>
https://github.com/home-assistant/core.git
def async_state_changed(self) -> None: if not self._device.available: self._async_cancel_pending_state_check() self.async_write_ha_state()
26
light.py
Python
homeassistant/components/yeelight/light.py
66b742f110025013e60ca8cac7aeb3247bac8f47
core
2
243,137
39
12
7
158
18
1
48
138
test_sanity_ati2
Add support for ATI1/2(BC4/BC5) DDS files This commit adds support for loading DDS with ATI1 and ATI2 fourcc pixel format
https://github.com/python-pillow/Pillow.git
def test_sanity_ati2(): with Image.open(TEST_FILE_ATI2) as im: im.load() assert im.format == "DDS" assert im.mode == "RGB" assert im.size == (128, 128) assert_image_equal_tofile(im, TEST_FILE_ATI2.replace(".dds", ".png")) @pytest.mark.parametrize( ("image_path",...
@pytest.mark.parametrize( ("image_path", "expected_path"), ( # hexeditted to be typeless (TEST_FILE_DX10_BC5_TYPELESS, TEST_FILE_DX10_BC5_UNORM), (TEST_FILE_DX10_BC5_UNORM, TEST_FILE_DX10_BC5_UNORM), # hexeditted to use DX10 FourCC (TEST_FILE_DX10_BC5_SNORM, TEST_FILE_BC5...
55
test_file_dds.py
Python
Tests/test_file_dds.py
ad2c6a20fe874958d8d9adecbbfeb81856155f05
Pillow
1
60,238
26
11
5
92
9
0
28
44
crop_params
Balanced joint maximum mean discrepancy for deep transfer learning
https://github.com/jindongwang/transferlearning.git
def crop_params(fn): params = fn.params.get('crop_param', fn.params) axis = params.get('axis', 2) # default to spatial crop for N, C, H, W offset = np.array(params.get('offset', 0), ndmin=1) return (axis, offset)
55
coord_map.py
Python
code/deep/BJMMD/caffe/python/caffe/coord_map.py
cc4d0564756ca067516f71718a3d135996525909
transferlearning
1
290,734
30
13
17
161
20
0
45
189
_async_create_radio_entry
Minor refactor of zha config flow (#82200) * Minor refactor of zha config flow * Move ZhaRadioManager to a separate module
https://github.com/home-assistant/core.git
async def _async_create_radio_entry(self) -> FlowResult: assert self._title is not None assert self._radio_mgr.radio_type is not None assert self._radio_mgr.device_path is not None assert self._radio_mgr.device_settings is not None device_settings = self._radio_mgr.devi...
106
config_flow.py
Python
homeassistant/components/zha/config_flow.py
bb64b39d0e6d41f531af9c63b69d1ce243a2751b
core
1
135,991
41
13
20
200
26
0
57
247
test_foreach_worker
[RLlib] Refactor `WorkerSet` on top of `FaultTolerantActorManager`. (#29938) Signed-off-by: Jun Gong <jungong@anyscale.com>
https://github.com/ray-project/ray.git
def test_foreach_worker(self): ws = WorkerSet( env_creator=lambda _: gym.make("CartPole-v1"), default_policy_class=RandomPolicy, config=AlgorithmConfig().rollouts(num_rollout_workers=2), num_workers=2, ) policies = ws.foreach_worker( ...
126
test_worker_set.py
Python
rllib/evaluation/tests/test_worker_set.py
e707ce4fb3717e3c05118c57f503dfbd03552ca9
ray
2
280,144
46
11
39
219
40
4
61
253
get_config
Make default `Layer.get_config()` automatically work for a wide range of layers that do not override it. PiperOrigin-RevId: 480781082
https://github.com/keras-team/keras.git
def get_config(self): config = { "name": self.name, "trainable": self.trainable, } config["dtype"] = policy.serialize(self._dtype_policy) if hasattr(self, "_batch_input_shape"): config["batch_input_shape"] = self._batch_input_shape if...
raise NotImplementedError( textwrap.dedent( f""" Layer {self.__class__.__name__} was created by passingargument valuesand therefore the layer must override `get_config()` in order to be serializable. Please implement `get_config()`. Example:order to be serial...
99
base_layer.py
Python
keras/engine/base_layer.py
af1408d3255e3db9067522762e22a6c454c56654
keras
4
127,668
37
12
16
77
10
0
42
143
to_object_ref
[AIR] Deprecate `Checkpoint.to_object_ref` and `Checkpoint.from_object_ref` (#28318) Before object_ref = checkpoint.to_object_ref() checkpoint.from_object_ref(object_ref) After (this is already possible) object_ref = ray.put(checkpoint) ray.get(checkpoint) Why are these changes needed? We need to effi...
https://github.com/ray-project/ray.git
def to_object_ref(self) -> ray.ObjectRef: warnings.warn( "`to_object_ref` is deprecated and will be removed in a future Ray " "version. To store the checkpoint in the Ray object store, call " "`ray.put(ckpt)` instead of `ckpt.to_object_ref()`.", Deprecati...
43
checkpoint.py
Python
python/ray/air/checkpoint.py
c2bdee9fea6f354330545009d5e6caec3dd7eb26
ray
2
260,762
18
13
15
99
14
0
22
40
test_toy_example_collapse_points
MAINT Parameters validation for NeighborhoodComponentsAnalysis (#24195) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr>
https://github.com/scikit-learn/scikit-learn.git
def test_toy_example_collapse_points(): rng = np.random.RandomState(42) input_dim = 5 two_points = rng.randn(2, input_dim) X = np.vstack([two_points, two_points.mean(axis=0)[np.newaxis, :]]) y = [0, 0, 1]
132
test_nca.py
Python
sklearn/neighbors/tests/test_nca.py
d7c978b764c6aafb65cc28757baf3f64da2cae34
scikit-learn
1
154,497
22
10
6
90
11
0
30
76
deploy
FIX-#4597: Refactor Partition handling of func, args, kwargs (#4715) Co-authored-by: Iaroslav Igoshev <Poolliver868@mail.ru> Signed-off-by: Jonathan Shi <jhshi@ponder.io>
https://github.com/modin-project/modin.git
def deploy(cls, func, f_args=None, f_kwargs=None, num_returns=1): args = [] if f_args is None else f_args kwargs = {} if f_kwargs is None else f_kwargs return _deploy_ray_func.options(num_returns=num_returns).remote( func, *args, **kwargs )
60
engine_wrapper.py
Python
modin/core/execution/ray/common/engine_wrapper.py
d6d503ac7c3028d871c34d9e99e925ddb0746df6
modin
3
320,112
2
6
10
13
2
0
2
9
test_scan_file_for_separating_barcodes_pillow_transcode_error
In case pikepdf fails to convert an image to a PIL image, fall back to converting pages to PIL images
https://github.com/paperless-ngx/paperless-ngx.git
def test_scan_file_for_separating_barcodes_pillow_transcode_error(self):
69
test_barcodes.py
Python
src/documents/tests/test_barcodes.py
caf4b54bc7bf828ba170fcc329aa82a0c45da382
paperless-ngx
1
40,304
120
17
44
472
29
0
195
586
plotting_context
Use f-strings for string formatting (#2800) Reformats all the text from the old "%-formatted" and .format(...) format to the newer f-string format, as defined in PEP 498. This requires Python 3.6+. Flynt 0.76 was used to reformat the strings. 45 f-strings were created in 13 files. F-strings are in general more r...
https://github.com/mwaskom/seaborn.git
def plotting_context(context=None, font_scale=1, rc=None): if context is None: context_dict = {k: mpl.rcParams[k] for k in _context_keys} elif isinstance(context, dict): context_dict = context else: contexts = ["paper", "notebook", "talk", "poster"] if context not in ...
290
rcmod.py
Python
seaborn/rcmod.py
f7e25e18983f2f36a1529cd9e4bda6fa008cbd6d
seaborn
10
47,420
29
13
8
194
22
0
41
81
create_test_pipeline
Replace usage of `DummyOperator` with `EmptyOperator` (#22974) * Replace usage of `DummyOperator` with `EmptyOperator`
https://github.com/apache/airflow.git
def create_test_pipeline(suffix, trigger_rule): skip_operator = EmptySkipOperator(task_id=f'skip_operator_{suffix}') always_true = EmptyOperator(task_id=f'always_true_{suffix}') join = EmptyOperator(task_id=trigger_rule, trigger_rule=trigger_rule) final = EmptyOperator(task_id=f'final_{suffix}') ...
59
example_skip_dag.py
Python
airflow/example_dags/example_skip_dag.py
49e336ae0302b386a2f47269a6d13988382d975f
airflow
1
287,839
15
11
7
66
9
0
16
74
async_will_remove_from_hass
Netatmo refactor to use pyatmo 7.0.1 (#73482) (#78523) Co-authored-by: Robert Svensson <Kane610@users.noreply.github.com>
https://github.com/home-assistant/core.git
async def async_will_remove_from_hass(self) -> None: await super().async_will_remove_from_hass() for publisher in self._publishers: await self.data_handler.unsubscribe( publisher[SIGNAL_NAME], self.async_update_callback )
39
netatmo_entity_base.py
Python
homeassistant/components/netatmo/netatmo_entity_base.py
81abeac83ed85c5753cb8f2ac317caf079cf1868
core
2
53,074
27
11
14
49
5
0
29
105
import_distributed
Delay import of `distributed` This improves `prefect` module import times which can be really slow with all of the distributed extras and allows configuration of a `DaskTaskRunner` on a machine without `distributed` installed
https://github.com/PrefectHQ/prefect.git
def import_distributed() -> "distributed": try: import distributed except ImportError as exc: raise RuntimeError( "Using the Dask task runner requires Dask `distributed` to be installed." ) from exc return distributed
25
task_runners.py
Python
src/prefect/task_runners.py
9de7f04816f1ef884d98ed817e869e73a9523ca1
prefect
2
115,994
72
14
20
295
26
0
126
403
get_columns
implemented the connection_args and connection_args_example dicts
https://github.com/mindsdb/mindsdb.git
def get_columns(self) -> StatusResponse: query = "SELECT * FROM S3Object LIMIT 5" df = self.native_query(query) response = Response( RESPONSE_TYPE.TABLE, data_frame=pd.DataFrame( { 'column_name': df.columns, ...
50
s3_handler.py
Python
mindsdb/integrations/handlers/s3_handler/s3_handler.py
4c20820d35782ed27f41e964ad2a429420b0eb67
mindsdb
1
216,271
30
15
11
124
10
0
36
164
_get_job_completion_ipc_path
Enable minion's IPC channel to aggregate results from spawned jobber processes. Use a long-running request channel in the minion parent process to communicate job results back to the master via broker-based or broker-less transport. This is a necessary optimization for transports that prefer a sustained long-running c...
https://github.com/saltstack/salt.git
def _get_job_completion_ipc_path(self): if self.opts["ipc_mode"] == "tcp": # try to find the port and fallback to something if not configured uxd_path_or_tcp_port = int( self.opts.get("tcp_job_completion_port", self.opts["tcp_pub_port"] + 1) ) ...
70
minion.py
Python
salt/minion.py
171926cc57618b51bf3fdc042b62212e681180fc
salt
2
22,117
10
8
10
48
6
0
11
24
patch
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
https://github.com/pypa/pipenv.git
def patch(self, url, data=None, **kwargs): r return self.request("PATCH", url, data=data, **kwargs)
32
sessions.py
Python
pipenv/patched/pip/_vendor/requests/sessions.py
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
1
248,583
36
10
12
177
15
0
48
154
test_guest_access_token
Move the "email unsubscribe" resource, refactor the macaroon generator & simplify the access token verification logic. (#12986) This simplifies the access token verification logic by removing the `rights` parameter which was only ever used for the unsubscribe link in email notifications. The latter has been moved un...
https://github.com/matrix-org/synapse.git
def test_guest_access_token(self): token = self.macaroon_generator.generate_guest_access_token("@user:tesths") user_id = self.macaroon_generator.verify_guest_token(token) self.assertEqual(user_id, "@user:tesths") # Raises with another secret key with self.assertRaises(M...
96
test_macaroons.py
Python
tests/util/test_macaroons.py
fe1daad67237c2154a3d8d8cdf6c603f0d33682e
synapse
1
160,733
31
10
6
48
5
0
34
73
no_nep50_warning
WIP: Add warning context manager and fix min_scalar for new promotion Even the new promotion has to use the min-scalar logic to avoid picking up a float16 loop for `np.int8(3) * 3.`.
https://github.com/numpy/numpy.git
def no_nep50_warning(): # TODO: We could skip the manager entirely if NumPy as a whole is not # in the warning mode. (Which is NOT thread/context safe.) token = NO_NEP50_WARNING.set(True) try: yield finally: NO_NEP50_WARNING.reset(token)
24
_ufunc_config.py
Python
numpy/core/_ufunc_config.py
baaeb9a16c9c28683db97c4fc3d047e86d32a0c5
numpy
2
224,136
19
15
17
130
19
0
20
136
test_invalid_config
Some manual changes ahead of formatting code with Black
https://github.com/mkdocs/mkdocs.git
def test_invalid_config(self): file_contents = dedent( ) config_file = tempfile.NamedTemporaryFile('w', delete=False) try: config_file.write(file_contents) config_file.flush() config_file.close() with self.assertRaises(Configu...
74
config_tests.py
Python
mkdocs/tests/config/config_tests.py
372384d8102ddb4be6360f44d1bfddb8b45435a4
mkdocs
2
203,227
13
12
9
72
8
0
13
82
_get_default_collation
Refs #33476 -- Refactored problematic code before reformatting by Black. In these cases Black produces unexpected results, e.g. def make_random_password( self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789', ): or cursor.execute(""" SELECT ... """, ...
https://github.com/django/django.git
def _get_default_collation(self, table_name): with self.connection.cursor() as cursor: cursor.execute( , [self.normalize_name(table_name)], ) return cursor.fetchone()[0]
43
schema.py
Python
django/db/backends/oracle/schema.py
c5cd8783825b5f6384417dac5f3889b4210b7d08
django
1
272,375
44
16
15
153
17
0
60
184
_apply_scores
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def _apply_scores(self, scores, value, scores_mask=None, training=None): if scores_mask is not None: padding_mask = tf.logical_not(scores_mask) # Bias so padding positions do not contribute to attention distribution. # Note 65504. is the max float16 value. ...
133
base_dense_attention.py
Python
keras/layers/attention/base_dense_attention.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
4
133,351
12
11
4
52
9
0
12
44
update_scheduler
[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 update_scheduler(self, metric): self.worker_group.apply_all_operators( lambda op: [sched.step(metric) for sched in op._schedulers] )
32
torch_trainer.py
Python
python/ray/util/sgd/torch/torch_trainer.py
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
2
288,502
6
9
3
33
7
0
6
20
auto_update
Supervisor update entity auto update from api (#79611) * Supervisor update entity auto update from api * Update api mocks in tests
https://github.com/home-assistant/core.git
def auto_update(self) -> bool: return self.coordinator.data[DATA_KEY_SUPERVISOR][ATTR_AUTO_UPDATE]
20
update.py
Python
homeassistant/components/hassio/update.py
416c10a793a982fb8c17259d36b99be458131cd0
core
1
272,119
64
15
38
329
29
0
114
680
test_shared_embedding_column_with_non_sequence_categorical
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def test_shared_embedding_column_with_non_sequence_categorical(self): with tf.Graph().as_default(): vocabulary_size = 3 sparse_input_a = tf.compat.v1.SparseTensorValue( # example 0, ids [2] # example 1, ids [0, 1] indices=((0, 0), ...
216
sequence_feature_column_test.py
Python
keras/feature_column/sequence_feature_column_test.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
1
268,177
164
21
57
556
39
0
348
1,100
package_status
apt: include apt preferences (e.g. pinning) when selecting packages (#78327) Fixes #77969
https://github.com/ansible/ansible.git
def package_status(m, pkgname, version_cmp, version, default_release, cache, state): try: # get the package from the cache, as well as the # low-level apt_pkg.Package object which contains # state fields not directly accessible from the # higher-level apt.package.Package object....
350
apt.py
Python
lib/ansible/modules/apt.py
04e892757941bf77198692bbe37041d7a8cbf999
ansible
24
265,648
17
10
9
88
11
0
18
97
test_interface_label_count_valid
Fixes #10247: Allow changing selected device/VM when creating a new component (#10312) * Initial work on #10247 * Continued work on #10247 * Clean up component creation tests * Move valdiation of replicated field to form * Clean up ordering of fields in component creation forms * Omit fieldset header if...
https://github.com/netbox-community/netbox.git
def test_interface_label_count_valid(self): interface_data = { 'device': self.device.pk, 'name': 'eth[0-9]', 'label': 'Interface[0-9]', 'type': InterfaceTypeChoices.TYPE_1GE_GBIC, } form = InterfaceCreateForm(interface_data) self....
48
test_forms.py
Python
netbox/dcim/tests/test_forms.py
c4b7ab067a914349abd88398dd9bfef9f6c2f806
netbox
1
154,556
113
16
57
498
44
0
171
912
_join_by_index
FEAT-#4946: Replace OmniSci with HDK (#4947) Co-authored-by: Iaroslav Igoshev <Poolliver868@mail.ru> Signed-off-by: Andrey Pavlenko <andrey.a.pavlenko@gmail.com>
https://github.com/modin-project/modin.git
def _join_by_index(self, other_modin_frames, how, sort, ignore_index): if how == "outer": raise NotImplementedError("outer join is not supported in HDK engine") lhs = self._maybe_materialize_rowid() reset_index_names = False for rhs in other_modin_frames: ...
315
dataframe.py
Python
modin/experimental/core/execution/native/implementations/hdk_on_native/dataframe/dataframe.py
e5b1888cd932909e49194d58035da34b210b91c4
modin
11
282,373
35
15
17
232
18
0
48
243
get_crypto_yfinance
Portfolio class (#1280) * remerge into main ? * tests again * change the example csv * squash all the bugs * Improve `add` interface * Add warning on loading portfolio with no cash * left a rogue print * oopsie. hugo * oopsie. hugo * Add back a new `al` function + port name * test Co...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def get_crypto_yfinance(self): if self._crypto_tickers: list_of_coins = [f"{coin}-USD" for coin in self._crypto_tickers] self._historical_crypto = yf.download( list_of_coins, start=self._start_date, progress=False )["Close"] if len(list_o...
142
portfolio_model.py
Python
gamestonk_terminal/portfolio/portfolio_model.py
2a998a5a417ba81b6ee3c4de90d2ffaca52b46fa
OpenBBTerminal
5
102,005
6
9
2
35
5
0
6
20
active
Update Face Filter - Remove old face filter - plugins.extract.pipeline: Expose plugins directly - Change `is_aligned` from plugin level to ExtractMedia level - Allow extract pipeline to take faceswap aligned images - Add ability for recognition plugins to accept aligned faces as input - Add face filter to r...
https://github.com/deepfakes/faceswap.git
def active(self): return bool(self._filter_files) or bool(self._nfilter_files)
20
extract.py
Python
scripts/extract.py
1d1face00d9476896e7857d3976afce383585d1b
faceswap
2
276,023
18
13
6
93
9
0
20
72
_set_network_attributes_from_metadata
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def _set_network_attributes_from_metadata(revived_obj): with utils.no_automatic_dependency_tracking_scope(revived_obj): # pylint:disable=protected-access metadata = revived_obj._serialized_attributes["metadata"] if metadata.get("dtype") is not None: revived_obj._set_dtype_po...
50
load.py
Python
keras/saving/saved_model/load.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
2
283,220
9
11
4
51
9
0
11
39
_words_and_emoticons
Create a packaged app bundle with Pyinstaller (#1525) * Add dashboard widget assets * Add ipywidgets and ipyflex to project * Add currencies dashboard notebook * Update docs and docstrings * Add pyinstaller to project deps * Add pyinstaller artifacts to gitignore * Fix linter errors in terminal.py ...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def _words_and_emoticons(self): wes = self.text.split() stripped = list(map(self._strip_punc_if_word, wes)) return stripped
30
vaderSentiment.py
Python
build/pyinstaller/vaderSentiment/vaderSentiment.py
ab4de1dd70fba866930150e440a03e461a6ca6a8
OpenBBTerminal
1
126,370
8
11
4
59
11
0
9
37
_reset_replica_iterator
[Serve] ServeHandle detects ActorError and drop replicas from target group (#26685)
https://github.com/ray-project/ray.git
def _reset_replica_iterator(self): replicas = list(self.in_flight_queries.keys()) random.shuffle(replicas) self.replica_iterator = itertools.cycle(replicas)
34
router.py
Python
python/ray/serve/_private/router.py
545c51609f0f55b41cf99cec95a9c21bee6846de
ray
1
176,368
47
13
18
219
17
1
79
203
is_perfect_matching
Update matching functions for error validation and speed (#4897) * First steps to update matching functions for #4644 Expand tests Change API to raise NetworkXError when matching involves nodes not in G Update is_*_matching to 100+ times faster. * improve matching_dict_to_set and docs for min_weight_matching ...
https://github.com/networkx/networkx.git
def is_perfect_matching(G, matching): if isinstance(matching, dict): matching = matching_dict_to_set(matching) nodes = set() for edge in matching: if len(edge) != 2: raise nx.NetworkXError(f"matching has non-2-tuple edge {edge}") u, v = edge if u not in G or...
@not_implemented_for("multigraph") @not_implemented_for("directed")
119
matching.py
Python
networkx/algorithms/matching.py
28b3014d68d2b4e40d3e02219770296a827bd55c
networkx
10
314,030
7
7
8
24
4
0
7
21
assumed_state
Enable polling for hardwired powerview devices (#73659) * Enable polling for hardwired powerview devices * Update homeassistant/components/hunterdouglas_powerview/cover.py * Update homeassistant/components/hunterdouglas_powerview/cover.py * docs were wrong * Update homeassistant/components/hunterdouglas_po...
https://github.com/home-assistant/core.git
def assumed_state(self) -> bool: return not self._is_hard_wired
13
cover.py
Python
homeassistant/components/hunterdouglas_powerview/cover.py
120479acef9a8e9e52fa356f036e55465e441d31
core
1
293,838
60
11
20
281
23
1
76
170
test_matching_filter
Simplify time zone setting in tests (#68330) * Simplify timezone setting in tests * Fix typo * Adjust caldav tests * Adjust input_datetime tests * Adjust time_date tests * Adjust tod tests * Adjust helper tests * Adjust recorder tests * Adjust risco tests * Adjust aemet tests * Adjust flu...
https://github.com/home-assistant/core.git
async def test_matching_filter(mock_now, hass, calendar, set_tz): config = dict(CALDAV_CONFIG) config["custom_calendars"] = [ {"name": "Private", "calendar": "Private", "search": "This is a normal event"} ] assert await async_setup_component(hass, "calendar", {"calendar": config}) awai...
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00))
124
test_calendar.py
Python
tests/components/caldav/test_calendar.py
cf4033b1bc853fc70828c6128ac91cdfb1d5bdaf
core
1
43,466
11
11
4
71
14
0
11
43
test_send_message_exception
Implement Azure Service Bus Queue Operators (#24038) Implemented Azure Service Bus Queue based Operator's to create queue, send message to the queue and receive message(list of message or batch message) and delete queue in azure service - Added `AzureServiceBusCreateQueueOperator` - Added `AzureServiceBusSendMessag...
https://github.com/apache/airflow.git
def test_send_message_exception(self, mock_sb_client): hook = MessageHook(azure_service_bus_conn_id=self.conn_id) with pytest.raises(TypeError): hook.send_message(queue_name=None, messages="", batch_message_flag=False)
42
test_asb.py
Python
tests/providers/microsoft/azure/hooks/test_asb.py
09f38ad3f6872bae5059a1de226362eb358c4a7a
airflow
1
175,300
22
11
5
80
9
0
22
61
__setattr__
bpo-40066: [Enum] update str() and format() output (GH-30582) Undo rejected PEP-663 changes: - restore `repr()` to its 3.10 status - restore `str()` to its 3.10 status New changes: - `IntEnum` and `IntFlag` now leave `__str__` as the original `int.__str__` so that str() and format() return the same result ...
https://github.com/python/cpython.git
def __setattr__(cls, name, value): member_map = cls.__dict__.get('_member_map_', {}) if name in member_map: raise AttributeError('cannot reassign member %r' % (name, )) super().__setattr__(name, value)
48
enum.py
Python
Lib/enum.py
acf7403f9baea3ae1119fc6b4a3298522188bf96
cpython
2
22,039
12
10
7
50
6
0
13
46
unicode_is_ascii
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
https://github.com/pypa/pipenv.git
def unicode_is_ascii(u_string): assert isinstance(u_string, str) try: u_string.encode("ascii") return True except UnicodeEncodeError: return False
28
_internal_utils.py
Python
pipenv/patched/pip/_vendor/requests/_internal_utils.py
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
2
303,773
11
9
5
45
3
0
13
49
_clean_up_listener
Add schedule helper (#76566) Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
https://github.com/home-assistant/core.git
def _clean_up_listener(self) -> None: if self._unsub_update is not None: self._unsub_update() self._unsub_update = None
26
__init__.py
Python
homeassistant/components/schedule/__init__.py
f0827a20c3c0014de7e28dbeba76fc3f2e74fc70
core
2
245,544
35
12
14
118
10
0
46
113
update_data_root
[Fix] replace mmcv's function and modules imported with mmengine's (#8594) * use mmengine's load_state_dict and load_checkpoint * from mmengine import dump * from mmengine import FileClient dump list_from_file * remove redundant registry * update * update * update * replace _load_checkpoint with C...
https://github.com/open-mmlab/mmdetection.git
def update_data_root(cfg, logger=None): assert isinstance(cfg, Config), \ f'cfg got wrong type: {type(cfg)}, expected mmengine.Config' if 'MMDET_DATASETS' in os.environ: dst_root = os.environ['MMDET_DATASETS'] print_log(f'MMDET_DATASETS has been set to be {dst_root}.' ...
76
misc.py
Python
mmdet/utils/misc.py
d0695e68654ca242be54e655491aef8c959ac345
mmdetection
2
287,795
76
22
131
795
31
0
184
2,873
test_ryse_smart_bridge_four_shades_setup
Handle battery services that only report low battery in HomeKit Controller (#79072)
https://github.com/home-assistant/core.git
async def test_ryse_smart_bridge_four_shades_setup(hass): accessories = await setup_accessories_from_file( hass, "ryse_smart_bridge_four_shades.json" ) await setup_test_accessories(hass, accessories) await assert_devices_and_entities_created( hass, DeviceTestInfo( ...
490
test_ryse_smart_bridge.py
Python
tests/components/homekit_controller/specific_devices/test_ryse_smart_bridge.py
917cf674de2db2216681dfec3ef9d63df573ace8
core
1
293,754
54
13
14
127
18
0
70
311
to_native
Separate attrs into another table (reduces database size) (#68224)
https://github.com/home-assistant/core.git
def to_native(self, validate_entity_id=True): try: return State( self.entity_id, self.state, # Join the state_attributes table on attributes_id to get the attributes # for newer states json.loads(self.attributes...
80
models.py
Python
homeassistant/components/recorder/models.py
9215702388eef03c7c3ed9f756ea0db533d5beec
core
3
224,316
17
13
10
120
17
0
17
115
test_load_missing_required
Format code with `black -l100 --skip-string-normalization`
https://github.com/mkdocs/mkdocs.git
def test_load_missing_required(self): config_file = tempfile.NamedTemporaryFile('w', delete=False) try: config_file.write("site_dir: output\nsite_uri: https://www.mkdocs.org\n") config_file.flush() config_file.close() with self.assertRaises(exce...
66
base_tests.py
Python
mkdocs/tests/config/base_tests.py
dca7cbb43fcd6ea7c677c98ba585395b070d387b
mkdocs
2
127,791
21
10
8
105
15
0
21
92
_create_default_prometheus_configs
Export default configurations for grafana and prometheus (#28286)
https://github.com/ray-project/ray.git
def _create_default_prometheus_configs(self): prometheus_config_output_path = os.path.join( self.metrics_root, "prometheus", "prometheus.yml" ) # Copy default prometheus configurations if os.path.exists(prometheus_config_output_path): os.remove(prometheu...
63
metrics_head.py
Python
dashboard/modules/metrics/metrics_head.py
42da4445e7a3cb358a1a02ae433a004e9fa836b5
ray
2
259,014
58
14
19
246
24
0
81
166
calinski_harabasz_score
FIX Calinski and Harabasz score description (#22605)
https://github.com/scikit-learn/scikit-learn.git
def calinski_harabasz_score(X, labels): X, labels = check_X_y(X, labels) le = LabelEncoder() labels = le.fit_transform(labels) n_samples, _ = X.shape n_labels = len(le.classes_) check_number_of_labels(n_labels, n_samples) extra_disp, intra_disp = 0.0, 0.0 mean = np.mean(X, axis=0...
168
_unsupervised.py
Python
sklearn/metrics/cluster/_unsupervised.py
d548c77980c4a633780cee3671e54ecd2f8cecb4
scikit-learn
3
139,696
36
12
30
154
3
0
56
408
get_valid_runtime_envs
[Serve] Add deployment graph `import_path` and `runtime_env` to `ServeApplicationSchema` (#24814) A newly planned version of the Serve schema (used in the REST API and CLI) requires the user to pass in their deployment graph's`import_path` and optionally a runtime_env containing that graph. This new schema can then pi...
https://github.com/ray-project/ray.git
def get_valid_runtime_envs() -> List[Dict]: return [ # Empty runtime_env {}, # Runtime_env with remote_URIs { "working_dir": ( "https://github.com/shrekris-anyscale/test_module/archive/HEAD.zip" ), "py_modules": [ ...
78
test_schema.py
Python
python/ray/serve/tests/test_schema.py
3a2bd16ecae15d6e26585c32c113dcfe7469ccd7
ray
1
42,732
17
10
15
192
13
0
27
60
create_directories_and_files
Replace generation of docker volumes to be done from python (#23985) The pre-commit to generate docker volumes in docker compose file is now written in Python and it also uses the newer "volume:" syntax to define the volumes mounted in the docker-compose.
https://github.com/apache/airflow.git
def create_directories_and_files() -> None: BUILD_CACHE_DIR.mkdir(parents=True, exist_ok=True) FILES_DIR.mkdir(parents=True, exist_ok=True) MSSQL_DATA_VOLUME.mkdir(parents=True, exist_ok=True) KUBE_DIR.mkdir(parents=True, exist_ok=True) LOGS_DIR.mkdir(parents=True, exist_ok=True) DIST_DIR.m...
118
path_utils.py
Python
dev/breeze/src/airflow_breeze/utils/path_utils.py
882535a8a2699af7d1d079ecebd8c31aa7fbaba9
airflow
1
109,545
22
10
11
108
4
0
45
139
_equal_aspect_axis_indices
Provide `adjustable='box'` to 3D axes aspect ratio setting (#23552) * Provided `adjustable='box'` option to set 3D aspect ratio. * "What's New": `adjustable` argument of 3D plots aspect ratio.
https://github.com/matplotlib/matplotlib.git
def _equal_aspect_axis_indices(self, aspect): ax_indices = [] # aspect == 'auto' if aspect == 'equal': ax_indices = [0, 1, 2] elif aspect == 'equalxy': ax_indices = [0, 1] elif aspect == 'equalxz': ax_indices = [0, 2] elif aspect == '...
64
axes3d.py
Python
lib/mpl_toolkits/mplot3d/axes3d.py
7c6a74c47accdfb8d66e526cbd0b63c29ffede12
matplotlib
5
45,599
133
17
54
595
49
0
185
744
clear_not_launched_queued_tasks
Add map_index to pods launched by KubernetesExecutor (#21871) I also did a slight drive-by-refactor (sorry!) to rename `queued_tasks and `task` inside `clear_not_launched_queued_tasks` to `queued_tis` and `ti` to reflect what they are.
https://github.com/apache/airflow.git
def clear_not_launched_queued_tasks(self, session=None) -> None: self.log.debug("Clearing tasks that have not been launched") if not self.kube_client: raise AirflowException(NOT_STARTED_MESSAGE) queued_tis: List[TaskInstance] = ( session.query(TaskInstance).filte...
318
kubernetes_executor.py
Python
airflow/executors/kubernetes_executor.py
ac77c89018604a96ea4f5fba938f2fbd7c582793
airflow
10
133,790
168
12
34
306
7
0
264
743
validate_config
[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 validate_config(self, config): # Call (base) PPO's config validation function first. # Note that this will not touch or check on the train_batch_size=-1 # setting. super().validate_config(config) # Error if run on Win. if sys.platform in ["win32", "cygwin"]:...
152
ddppo.py
Python
rllib/agents/ppo/ddppo.py
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
9
331,644
11
10
4
43
5
0
12
28
get_pretrained_cfg_value
Transitioning default_cfg -> pretrained_cfg. Improving handling of pretrained_cfg source (HF-Hub, files, timm config, etc). Checkpoint handling tweaks.
https://github.com/huggingface/pytorch-image-models.git
def get_pretrained_cfg_value(model_name, cfg_key): if model_name in _model_pretrained_cfgs: return _model_pretrained_cfgs[model_name].get(cfg_key, None) return None
27
registry.py
Python
timm/models/registry.py
abc9ba254430ef971ea3dbd12f2b4f1969da55be
pytorch-image-models
2
158,113
18
15
4
86
11
0
19
35
split_batch_multi_inputs
[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 split_batch_multi_inputs(X, y, devices): X = list(zip(*[gluon.utils.split_and_load( feature, devices, even_split=False) for feature in X])) return (X, gluon.utils.split_and_load(y, devices, even_split=False))
58
mxnet.py
Python
d2l/mxnet.py
b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2
d2l-zh
2
84,208
45
13
30
178
23
0
52
114
clean_archived_data
retention: Add docstring info on how archive cleaning works. In particular, it's important to record the special treatment around ArchivedAttachment rows not being deleted in this step.
https://github.com/zulip/zulip.git
def clean_archived_data() -> None: logger.info("Cleaning old archive data.") check_date = timezone_now() - timedelta(days=settings.ARCHIVED_DATA_VACUUMING_DELAY_DAYS) # Associated archived objects will get deleted through the on_delete=CASCADE property: count = 0 transaction_ids = list( ...
105
retention.py
Python
zerver/lib/retention.py
acfa55138ee2e5f43a0a96614aa0581b115fc714
zulip
2
250,533
33
9
44
162
20
0
47
211
test_get_multiple_keys_from_perspectives
Add missing type hints to tests. (#14687) Adds type hints to tests.metrics and tests.crypto.
https://github.com/matrix-org/synapse.git
def test_get_multiple_keys_from_perspectives(self) -> None: fetcher = PerspectivesKeyFetcher(self.hs) SERVER_NAME = "server2" testkey1 = signedjson.key.generate_signing_key("ver1") testverifykey1 = signedjson.key.get_verify_key(testkey1) testverifykey1_id = "ed25519:v...
292
test_keyring.py
Python
tests/crypto/test_keyring.py
a4ca770655a6b067468de3d507292ec133fdc5ca
synapse
1
156,160
6
8
2
31
4
0
6
12
sample
Bag: add implementation for reservoir sampling (#7068) (#7636) - Implement the [L algorithm](https://en.wikipedia.org/wiki/Reservoir_sampling#An_optimal_algorithm) for reservoir sampling without replacement. - Use the **k** reservoir of size 1 strategy for sampling with replacement (see [reference](http://uto...
https://github.com/dask/dask.git
def sample(population, k): return _sample(population=population, k=k)
19
random.py
Python
dask/bag/random.py
4e5dfe7463028a39a90e026c7fb9220969093ab3
dask
1
292,851
10
9
8
35
5
0
10
24
available
Fix powerwall data incompatibility with energy integration (#67245)
https://github.com/home-assistant/core.git
def available(self) -> bool: return super().available and self.native_value != 0
20
sensor.py
Python
homeassistant/components/powerwall/sensor.py
3f16c6d6efad20b60a4a8d2114a0905ecd252820
core
2
298,591
24
9
14
170
18
0
43
85
test_restore_state_uncoherence_case
Use climate enums in generic_thermostat (#70656) * Use climate enums in generic_thermostat * Adjust tests
https://github.com/home-assistant/core.git
async def test_restore_state_uncoherence_case(hass): _mock_restore_cache(hass, temperature=20) calls = _setup_switch(hass, False) _setup_sensor(hass, 15) await _setup_climate(hass) await hass.async_block_till_done() state = hass.states.get(ENTITY) assert state.attributes[ATTR_TEMPERAT...
105
test_climate.py
Python
tests/components/generic_thermostat/test_climate.py
b81f8e75eea3d1aaa8111f542519de1d58093200
core
1
269,571
17
14
8
84
10
1
21
67
int_shape
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def int_shape(x): try: shape = x.shape if not isinstance(shape, tuple): shape = tuple(shape.as_list()) return shape except ValueError: return None @keras_export("keras.backend.ndim") @doc_controls.do_not_generate_docs
@keras_export("keras.backend.ndim") @doc_controls.do_not_generate_docs
39
backend.py
Python
keras/backend.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
3
247,935
31
8
11
126
15
0
39
116
test_linearizer
Convert `Linearizer` tests from `inlineCallbacks` to async (#12353) Signed-off-by: Sean Quah <seanq@element.io>
https://github.com/matrix-org/synapse.git
def test_linearizer(self) -> None: linearizer = Linearizer() key = object() _, acquired_d1, unblock1 = self._start_task(linearizer, key) self.assertTrue(acquired_d1.called) _, acquired_d2, unblock2 = self._start_task(linearizer, key) self.assertFalse(acquired_...
76
test_linearizer.py
Python
tests/util/test_linearizer.py
41b5f72677ea9763f3cf920d4f6df507653222f2
synapse
1
8,639
17
12
5
89
15
0
19
54
test_window_autosizing_disabled
Enable dataset window autosizing (#2721) * set windowed shuffle for large datasets * documentation * update to automatic windowing flag * address reviews * address reviews * update logging info and add auto_window flag passthrough * update tests to use flag passthrough * more descriptive test cla...
https://github.com/ludwig-ai/ludwig.git
def test_window_autosizing_disabled(self, ray_cluster_small_object_store): ds = self.create_dataset(self.object_store_size * 8, auto_window=False) pipe = ds.pipeline() rep = next(iter(pipe._base_iterable))() assert rep.num_blocks() == self.num_partitions
54
test_ray.py
Python
tests/integration_tests/test_ray.py
0d19a48cff0958ed77926a0712cbdb6485d4034a
ludwig
1
186,362
47
10
7
111
10
0
54
125
pick_apache_config
Various clean-ups in certbot-apache. Use f-strings. (#9132) * Various clean-ups in certbot-apache. Use f-strings. * Smaller tweaks
https://github.com/certbot/certbot.git
def pick_apache_config(self, warn_on_no_mod_ssl=True): # Disabling TLS session tickets is supported by Apache 2.4.11+ and OpenSSL 1.0.2l+. # So for old versions of Apache we pick a configuration without this option. min_openssl_version = util.parse_loose_version('1.0.2l') openss...
66
configurator.py
Python
certbot-apache/certbot_apache/_internal/configurator.py
eeca208c8f57304590ac1af80b496e61021aaa45
certbot
4
9,880
5
6
8
20
2
0
5
19
start
feat: star routing (#3900) * feat(proto): adjust proto for star routing (#3844) * feat(proto): adjust proto for star routing * feat(proto): generate proto files * feat(grpc): refactor grpclet interface (#3846) * feat: refactor connection pool for star routing (#3872) * feat(k8s): add more labels to k8s ...
https://github.com/jina-ai/jina.git
def start(self) -> 'BasePod': ...
9
__init__.py
Python
jina/peapods/pods/__init__.py
933415bfa1f9eb89f935037014dfed816eb9815d
jina
1
104,813
12
13
6
89
12
0
13
39
xbasename
Add support for metadata files to `imagefolder` (#4069) * Add support for metadata files to `imagefolder` * Fix imagefolder drop_labels test * Replace csv with jsonl * Add test * Correct resolution for nested metadata files * Allow None as JSON Lines value * Add comments * Count path segments *...
https://github.com/huggingface/datasets.git
def xbasename(a): a, *b = str(a).split("::") if is_local_path(a): return os.path.basename(Path(a).as_posix()) else: return posixpath.basename(a)
51
streaming_download_manager.py
Python
src/datasets/utils/streaming_download_manager.py
7017b0965f0a0cae603e7143de242c3425ecef91
datasets
2
142,253
86
10
16
182
20
0
120
305
__call__
[air] Consolidate Tune and Train report (#25558) Consolidate tune/train report/checkpoint functionality by working with a unified Session interface. The goal of this PR is to establish a solid Session and Session.report path. In favor of having less merging conflict (as other folks are doing the whole package renam...
https://github.com/ray-project/ray.git
def __call__(self, _metric=None, **kwargs): assert self._last_report_time is not None, ( "_StatusReporter._start() must be called before the first " "report __call__ is made to ensure correct runtime metrics." ) if _metric: kwargs[DEFAULT_METRIC] = ...
107
function_runner.py
Python
python/ray/tune/function_runner.py
97f42425dacc914fc90059a010f5a02a5ab3b8c7
ray
4
100,318
52
16
15
217
23
0
76
302
get_loss_keys
Update code to support Tensorflow versions up to 2.8 (#1213) * Update maximum tf version in setup + requirements * - bump max version of tf version in launcher - standardise tf version check * update keras get_custom_objects for tf>2.6 * bugfix: force black text in GUI file dialogs (linux) * dssim loss -...
https://github.com/deepfakes/faceswap.git
def get_loss_keys(self, session_id): if get_backend() == "amd": # We can't log the graph in Tensorboard logs for AMD so need to obtain from state file loss_keys = {int(sess_id): [name for name in session["loss_names"] if name != "total"] for sess_id, ses...
126
stats.py
Python
lib/gui/analysis/stats.py
c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf
faceswap
9
249,541
21
11
10
95
12
0
25
103
test_get_insertion_event_backward_extremities_in_room
Only try to backfill event if we haven't tried before recently (#13635) Only try to backfill event if we haven't tried before recently (exponential backoff). No need to keep trying the same backfill point that fails over and over. Fix https://github.com/matrix-org/synapse/issues/13622 Fix https://github.com/matrix...
https://github.com/matrix-org/synapse.git
def test_get_insertion_event_backward_extremities_in_room(self): setup_info = self._setup_room_for_insertion_backfill_tests() room_id = setup_info.room_id backfill_points = self.get_success( self.store.get_insertion_event_backward_extremities_in_room(room_id) ) ...
57
test_event_federation.py
Python
tests/storage/test_event_federation.py
ac1a31740b6d0dfda4d57a25762aaddfde981caf
synapse
2
274,643
30
13
10
115
13
0
33
147
merge_state
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def merge_state(self, metrics): assign_add_ops = [] for metric in metrics: if len(self.weights) != len(metric.weights): raise ValueError( f"Metric {metric} is not compatible with {self}" ) for weight, weight_to_add in z...
67
base_metric.py
Python
keras/metrics/base_metric.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
4
258,495
61
13
20
298
23
0
79
216
manhattan_distances
DOC Ensures that manhattan_distances passes numpydoc validation (#22139) Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
https://github.com/scikit-learn/scikit-learn.git
def manhattan_distances(X, Y=None, *, sum_over_features=True): X, Y = check_pairwise_arrays(X, Y) if issparse(X) or issparse(Y): if not sum_over_features: raise TypeError( "sum_over_features=%r not supported for sparse matrices" % sum_over_features ...
194
pairwise.py
Python
sklearn/metrics/pairwise.py
ff09c8a579b116500deade618f93c4dc0d5750bd
scikit-learn
5
155,898
142
20
55
576
40
0
240
846
get_scheduler
Raise warning when using multiple types of schedulers where one is `distributed` (#8700) Raise a warning when `compute` or `persist` are called with a scheduler different from "dask.distributed" or "distributed" in Dask.distributed mode
https://github.com/dask/dask.git
def get_scheduler(get=None, scheduler=None, collections=None, cls=None): if get: raise TypeError(get_err_msg) if scheduler is not None: if callable(scheduler): return scheduler elif "Client" in type(scheduler).__name__ and hasattr(scheduler, "get"): return s...
346
base.py
Python
dask/base.py
277859ddfcc30a9070ca560c9e3e2720e5eed616
dask
23
101,370
79
14
37
262
25
0
112
531
_load_extractor
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 _load_extractor(self) -> Optional[Extractor]: if not self._alignments.have_alignments_file and not self._args.on_the_fly: logger.error("No alignments file found. Please provide an alignments file for your " "destination video (recommended) or enable on-the-fly c...
148
convert.py
Python
scripts/convert.py
1022651eb8a7741014f5d2ec7cbfe882120dfa5f
faceswap
5
107,814
7
8
2
29
5
0
7
13
test_strip_comment
Support quoted strings in matplotlibrc This enables using the comment character # within strings. Closes #19288. Superseeds #22565.
https://github.com/matplotlib/matplotlib.git
def test_strip_comment(line, result): assert cbook._strip_comment(line) == result
17
test_cbook.py
Python
lib/matplotlib/tests/test_cbook.py
7c378a8f3f30ce57c874a851f3af8af58f1ffdf6
matplotlib
1
153,666
50
15
19
112
9
0
71
245
_is_zero_copy_possible
FEAT-#4244: Implement dataframe exchange protocol for OmniSci (#4269) Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru> Co-authored-by: Vasily Litvinov <vasilij.n.litvinov@intel.com> Signed-off-by: Dmitry Chigarev <dmitry.chigarev@intel.com>
https://github.com/modin-project/modin.git
def _is_zero_copy_possible(self) -> bool: if self.__is_zero_copy_possible is None: if self._df._has_arrow_table(): # If PyArrow table is already materialized then we can # retrieve data zero-copy self.__is_zero_copy_possible = True ...
64
dataframe.py
Python
modin/experimental/core/execution/native/implementations/omnisci_on_native/exchange/dataframe_protocol/dataframe.py
0c1a2129df64cf45bf1ff49c8ed92c510fdb1c82
modin
4
126,252
46
12
19
166
26
0
59
162
test_syncer_callback_noop_on_trial_cloud_checkpointing
[air] Add annotation for Tune module. (#27060) Co-authored-by: Kai Fricke <kai@anyscale.com>
https://github.com/ray-project/ray.git
def test_syncer_callback_noop_on_trial_cloud_checkpointing(): callbacks = _create_default_callbacks(callbacks=[], sync_config=SyncConfig()) syncer_callback = None for cb in callbacks: if isinstance(cb, SyncerCallback): syncer_callback = cb trial1 = MockTrial(trial_id="a", logdi...
103
test_syncer_callback.py
Python
python/ray/tune/tests/test_syncer_callback.py
eb69c1ca286a2eec594f02ddaf546657a8127afd
ray
3
241,536
23
9
6
96
7
0
30
48
test_prefix_metric_keys
Group metrics generated by `DeviceStatsMonitor` for better visualization (#11254) Co-authored-by: Carlos Mocholí <carlossmocholi@gmail.com> Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com>
https://github.com/Lightning-AI/lightning.git
def test_prefix_metric_keys(tmpdir): metrics = {"1": 1.0, "2": 2.0, "3": 3.0} prefix = "foo" separator = "." converted_metrics = _prefix_metric_keys(metrics, prefix, separator) assert converted_metrics == {"foo.1": 1.0, "foo.2": 2.0, "foo.3": 3.0}
65
test_device_stats_monitor.py
Python
tests/callbacks/test_device_stats_monitor.py
05ed9a201c24e08c2b4d3df4735296758ddcd6a5
lightning
1
273,619
4
6
2
16
3
0
4
18
output_size
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def output_size(self): raise NotImplementedError
8
abstract_rnn_cell.py
Python
keras/layers/rnn/abstract_rnn_cell.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
1
269,586
136
14
31
405
40
1
189
444
categorical_crossentropy
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def categorical_crossentropy(target, output, from_logits=False, axis=-1): target = tf.convert_to_tensor(target) output = tf.convert_to_tensor(output) target.shape.assert_is_compatible_with(output.shape) # Use logits whenever they are available. `softmax` and `sigmoid` # activations cache logit...
@keras_export("keras.backend.sparse_categorical_crossentropy") @tf.__internal__.dispatch.add_dispatch_support @doc_controls.do_not_generate_docs
237
backend.py
Python
keras/backend.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
7
156,322
6
6
12
19
3
0
6
20
produces_keys
Use DataFrameIOLayer in DataFrame.from_delayed (#8852)
https://github.com/dask/dask.git
def produces_keys(self) -> bool: return False
10
blockwise.py
Python
dask/blockwise.py
1ccd1a4f96afa1fe89ea93dcfe66517319b0664d
dask
1
22,678
16
11
5
50
6
0
16
59
set
refactor: clean code Signed-off-by: slowy07 <slowy.arfy@gmail.com>
https://github.com/geekcomputers/Python.git
def set(self, components): if len(components) > 0: self.__components = components else: raise Exception("please give any vector")
28
lib.py
Python
linear-algebra-python/src/lib.py
f0af0c43340763724f139fa68aa1e5a9ffe458b4
Python
2
176,703
23
9
74
83
9
0
25
43
average_clustering
Remove redundant py2 numeric conversions (#5661) * Remove redundant float conversion * Remove redundant int conversion * Use integer division Co-authored-by: Miroslav Šedivý <6774676+eumiro@users.noreply.github.com>
https://github.com/networkx/networkx.git
def average_clustering(G, nodes=None, mode="dot"): r if nodes is None: nodes = G ccs = latapy_clustering(G, nodes=nodes, mode=mode) return sum(ccs[v] for v in nodes) / len(nodes)
54
cluster.py
Python
networkx/algorithms/bipartite/cluster.py
2a05ccdb07cff88e56661dee8a9271859354027f
networkx
3
89,862
70
18
45
339
23
0
88
887
test_first_event_with_minified_stack_trace_received
ref(onboarding): Add function to record first event per project with min stack trace -(#42208)
https://github.com/getsentry/sentry.git
def test_first_event_with_minified_stack_trace_received(self, record_analytics): now = timezone.now() project = self.create_project(first_event=now) project_created.send(project=project, user=self.user, sender=type(project)) url = "http://localhost:3000" data = load_data...
198
test_onboarding.py
Python
tests/sentry/receivers/test_onboarding.py
ce841204ef3b20d0f6ac812ebb06aebbc63547ac
sentry
1
260,279
9
9
4
49
7
0
9
37
fit
MAINT parameter validation for Normalizer (#23543) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr>
https://github.com/scikit-learn/scikit-learn.git
def fit(self, X, y=None): self._validate_params() self._validate_data(X, accept_sparse="csr") return self
29
_data.py
Python
sklearn/preprocessing/_data.py
40e055b362a337cef15645d4b1be046aa782c415
scikit-learn
1
86,878
15
14
14
69
10
0
18
59
get_region_to_control_producer
chore(hybrid-cloud): AuditLogEntry is a control silo model now (#39890) In the control silo, creating an audit log entry writes to the db directly, whilst in region silo mode creating an audit log entry will instead push to a new kafka producer that consumes into the control silo asynchronously.
https://github.com/getsentry/sentry.git
def get_region_to_control_producer() -> KafkaProducer: global _publisher if _publisher is None: config = settings.KAFKA_TOPICS.get(settings.KAFKA_REGION_TO_CONTROL) _publisher = KafkaProducer( kafka_config.get_kafka_producer_cluster_options(config["cluster"]) )
48
producer.py
Python
src/sentry/region_to_control/producer.py
941184cd24186324fd9f7f304b7f713041834726
sentry
2
181,702
19
9
6
60
8
0
23
41
test_source_decode_2
Revert "Deployed 7ccda9a with MkDocs version: 1.3.0" This reverts commit bd9629c40e01241766197119b581a99409b07068.
https://github.com/EpistasisLab/tpot.git
def test_source_decode_2(): import_str, op_str, op_obj = source_decode("sklearn.linear_model.LogisticReg") from sklearn.linear_model import LogisticRegression assert import_str == "sklearn.linear_model" assert op_str == "LogisticReg" assert op_obj is None
33
tpot_tests.py
Python
tests/tpot_tests.py
388616b6247ca4ea8de4e2f340d6206aee523541
tpot
1
20,964
47
14
16
171
18
0
58
157
get_allowed_args
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 get_allowed_args(fn_or_class): # type: (Union[Callable, Type]) -> Tuple[List[str], Dict[str, Any]] try: signature = inspect.signature(fn_or_class) except AttributeError: import funcsigs signature = funcsigs.signature(fn_or_class) args = [] kwargs = {} for arg, p...
106
utils.py
Python
pipenv/vendor/pip_shims/utils.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
6
211,029
31
15
12
233
9
0
69
146
convert_x_to_bbox
[MOT] Add OC_SORT tracker (#6272) * add ocsort tracker * add ocsort deploy * merge develop * fix ocsort tracker codes * fix doc, test=document_fix * fix doc, test=document_fix
https://github.com/PaddlePaddle/PaddleDetection.git
def convert_x_to_bbox(x, score=None): w = np.sqrt(x[2] * x[3]) h = x[2] / w if (score == None): return np.array( [x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2.]).reshape((1, 4)) else: score = np.array([score]) return np.array([ ...
167
ocsort_tracker.py
Python
deploy/pptracking/python/mot/tracker/ocsort_tracker.py
c84153a355d9855fe55cf51d203b8b24e7d884e5
PaddleDetection
2
107,206
7
8
3
40
7
0
7
44
get_current_underline_thickness
Factor out underline-thickness lookups in mathtext. Just adding a small helper function.
https://github.com/matplotlib/matplotlib.git
def get_current_underline_thickness(self): return self.font_output.get_underline_thickness( self.font, self.fontsize, self.dpi)
25
_mathtext.py
Python
lib/matplotlib/_mathtext.py
b71421e685733b1cade94113b588ca1a773ae558
matplotlib
1
86,136
23
14
8
112
13
0
23
95
get_form
fix(admin): Fix typo in admin user creation form (#38418) This fixes the error reported in https://github.com/getsentry/sentry/issues/38303, which appears to be due to a typo in the django module name.
https://github.com/getsentry/sentry.git
def get_form(self, request, obj=None, **kwargs): defaults = {} if obj is None: defaults.update( {"form": self.add_form, "fields": admin.utils.flatten_fieldsets(self.add_fieldsets)} ) defaults.update(kwargs) return super().get_form(request,...
69
admin.py
Python
src/sentry/admin.py
d522d620e5e6799000b918278c86cbaa0b1592a1
sentry
2
9,760
104
15
6
374
37
0
161
496
different
Check gallery up to date as part of CI (#3329) * Check gallery up to date as part of CI Fix #2916 * tweak check_gallery.py * update CI workflow * update stale doc cache * update stale docs
https://github.com/RaRe-Technologies/gensim.git
def different(path1, path2): with open(path1) as fin: f1 = fin.read() with open(path2) as fin: f2 = fin.read() return f1 != f2 curr_dir = os.path.dirname(__file__) stale = [] for root, dirs, files in os.walk(os.path.join(curr_dir, 'gallery')): for f in files: if f.endswith('.py...
41
check_gallery.py
Python
docs/src/check_gallery.py
9bbf12c330275351e777b553c145066b7c397f95
gensim
1
106,118
52
14
22
326
17
0
85
222
fast_slice
Clean up Table class docstrings (#5355) * clean table docstrings * apply review Co-authored-by: Quentin Lhoest <42851186+lhoestq@users.noreply.github.com> Co-authored-by: Quentin Lhoest <42851186+lhoestq@users.noreply.github.com>
https://github.com/huggingface/datasets.git
def fast_slice(self, offset=0, length=None) -> pa.Table: if offset < 0: raise IndexError("Offset must be non-negative") elif offset >= self._offsets[-1] or (length is not None and length <= 0): return pa.Table.from_batches([], schema=self._schema) i = _interpolat...
214
table.py
Python
src/datasets/table.py
c902456677116a081f762fa2b4aad13a0aa04d6e
datasets
7
133,814
41
11
10
198
18
0
55
93
_mac
[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 _mac(model, obs, h): B, n_agents = obs.size(0), obs.size(1) if not isinstance(obs, dict): obs = {"obs": obs} obs_agents_as_batches = {k: _drop_agent_dim(v) for k, v in obs.items()} h_flat = [s.reshape([B * n_agents, -1]) for s in h] q_flat, h_flat = model(obs_agents_as_batches, h_fl...
130
qmix_policy.py
Python
rllib/agents/qmix/qmix_policy.py
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
5
136,639
10
10
5
45
5
0
10
42
post_process
KubeRay node provider refactor (#30281) Implements KubeRay node provider as a "BatchingNodeProvider". Builds on #29933. Summary of design An autoscaler update now works like this: list pod data from k8s check if it's safe to proceed with update. Abort the update if not. do some internal calculation to determ...
https://github.com/ray-project/ray.git
def post_process(self) -> None: if self.scale_change_needed: self.submit_scale_request(self.scale_request) self.scale_change_needed = False
26
batching_node_provider.py
Python
python/ray/autoscaler/batching_node_provider.py
c976799dfd96806ec9972a287835f7a034ec3d2c
ray
2
309,333
6
7
22
27
4
0
8
29
test_circular_import
Use Platform enum in load_platform [tests] (#63904) * Use Platform enum in numato tests * Use Platform enum in discovery tests * Adjust load_platform argument Co-authored-by: epenet <epenet@users.noreply.github.com>
https://github.com/home-assistant/core.git
def test_circular_import(self): component_calls = [] platform_calls = []
131
test_discovery.py
Python
tests/helpers/test_discovery.py
b71a22557dc6ca87b6c1871a0e4d3c3a949759fc
core
1
126,889
24
8
3
46
7
0
27
62
__reduce__
Fix out-of-band deserialization of actor handle (#27700) When we deserialize actor handle via pickle, we will register it with an outer object ref equaling to itself which is wrong. For out-of-band deserialization, there should be no outer object ref. Signed-off-by: Jiajun Yao <jeromeyjj@gmail.com>
https://github.com/ray-project/ray.git
def __reduce__(self): (serialized, _) = self._serialization_helper() # There is no outer object ref when the actor handle is # deserialized out-of-band using pickle. return ActorHandle._deserialization_helper, (serialized, None)
27
actor.py
Python
python/ray/actor.py
f084546d41f0533c1e9e96a7249532d0eb4ff47d
ray
1
3,763
29
14
12
176
19
0
39
114
get_json_schema
🎉 🎉 Source FB Marketing: performance and reliability fixes (#9805) * Facebook Marketing performance improvement * add comments and little refactoring * fix integration tests with the new config * improve job status handling, limit concurrency to 10 * fix campaign jobs, refactor manager * big refactori...
https://github.com/airbytehq/airbyte.git
def get_json_schema(self) -> Mapping[str, Any]: loader = ResourceSchemaLoader(package_name_from_class(self.__class__)) schema = loader.get_schema("ads_insights") if self._fields: schema["properties"] = {k: v for k, v in schema["properties"].items() if k in self._fields} ...
106
base_insight_streams.py
Python
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/base_insight_streams.py
a3aae8017a0a40ff2006e2567f71dccb04c997a5
airbyte
6
247,670
14
9
6
71
12
0
15
50
test_exception_callback
Add tests for database transaction callbacks (#12198) Signed-off-by: Sean Quah <seanq@element.io>
https://github.com/matrix-org/synapse.git
def test_exception_callback(self) -> None: _test_txn = Mock(side_effect=ZeroDivisionError) after_callback, exception_callback = self._run_interaction(_test_txn) after_callback.assert_not_called() exception_callback.assert_called_once_with(987, 654, extra=321)
43
test_database.py
Python
tests/storage/test_database.py
dea577998f221297d3ff30bdf904f7147f3c3d8a
synapse
1
268,826
25
13
9
95
11
0
28
55
print_msg
Put absl logging control flag in a separate file. Open the APIs for control the logging in Keras. PiperOrigin-RevId: 419972643
https://github.com/keras-team/keras.git
def print_msg(message, line_break=True): # Use `getattr` in case `INTERACTIVE_LOGGING` # does not have the `enable` attribute. if INTERACTIVE_LOGGING.enable: if line_break: sys.stdout.write(message + '\n') else: sys.stdout.write(message) sys.stdout.flush() else: logging.info(messa...
53
io_utils.py
Python
keras/utils/io_utils.py
f427e16d9e4a440b5e7e839001255f7cd87127f5
keras
3
288,323
63
12
29
253
17
0
74
289
test_webhook_person_event
Fix Netatmo scope issue with HA cloud (#79437) Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
https://github.com/home-assistant/core.git
async def test_webhook_person_event(hass, config_entry, netatmo_auth): with selected_platforms(["camera"]): assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() test_netatmo_event = async_capture_events(hass, NETATMO_EVENT) assert not ...
133
test_camera.py
Python
tests/components/netatmo/test_camera.py
3e411935bbe07ebe0e7a9f5323734448486d75d7
core
1
291,525
26
13
10
137
13
0
40
119
_is_today
Fix Sonos alarm 'scheduled_today' attribute logic (#82816) fixes undefined
https://github.com/home-assistant/core.git
def _is_today(self) -> bool: recurrence = self.alarm.recurrence daynum = int(datetime.datetime.today().strftime("%w")) return ( recurrence in ("DAILY", "ONCE") or (recurrence == "WEEKENDS" and daynum in WEEKEND_DAYS) or (recurrence == "WEEKDAYS" and d...
79
switch.py
Python
homeassistant/components/sonos/switch.py
f887aeedfe057682f8d5a3abd44082d02fe42758
core
7