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
276,774
94
15
99
961
49
0
188
1,125
test_get_file_and_validate_it
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def test_get_file_and_validate_it(self): dest_dir = self.get_temp_dir() orig_dir = self.get_temp_dir() text_file_path = os.path.join(orig_dir, "test.txt") zip_file_path = os.path.join(orig_dir, "test.zip") tar_file_path = os.path.join(orig_dir, "test.tar.gz") w...
608
data_utils_test.py
Python
keras/utils/data_utils_test.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
2
211,402
171
17
62
961
58
0
292
1,144
get_pred
add flag skipping postprocess to support edgeboard hardware (#6719) * add flag skipping postprocess to support edgeboard hardware * add flag skipping postprocess to support edgeboard hardware * add flag skipping postprocess to support edgeboard hardware * add comment for the flag export_eb
https://github.com/PaddlePaddle/PaddleDetection.git
def get_pred(self, bboxes, bbox_num, im_shape, scale_factor): if self.export_eb: # enable rcnn models for edgeboard hw to skip the following postprocess. return bboxes, bboxes, bbox_num if not self.export_onnx: bboxes_list = [] bbox_num_list = []...
651
post_process.py
Python
ppdet/modeling/post_process.py
b41194eaed10a01409451e4d3ea7f8b4812cdd23
PaddleDetection
7
130,291
15
8
5
61
9
0
19
58
is_file
[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 is_file(self, follow_links=None): if follow_links is None: follow_links = True node_stat = self._stat if follow_links else self._lstat return stat.S_ISREG(node_stat.st_mode)
38
util.py
Python
python/ray/_private/thirdparty/pathspec/util.py
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
3
178,342
170
18
99
725
65
0
273
1,045
executePostProcessing
Windows: Fix, cmd files created for accelerated mode didn't forward arguments
https://github.com/Nuitka/Nuitka.git
def executePostProcessing(): result_filename = OutputDirectories.getResultFullpath(onefile=False) if not os.path.exists(result_filename): postprocessing_logger.sysexit( "Error, scons failed to create the expected file %r. " % result_filename ) if isWin32Windows(): ...
431
PostProcessing.py
Python
nuitka/PostProcessing.py
ccc9b2f5a305c76d05eaaf29f94c74e7b4ece7ff
Nuitka
20
305,503
139
26
105
798
55
0
213
1,944
test_sync_in_area
Remove area_id from entity_registry.async_get_or_create (#77700) * Remove area_id from entity_registry.async_get_or_create * Adjust tests * Fix lying comment in test
https://github.com/home-assistant/core.git
async def test_sync_in_area(area_on_device, hass, registries): area = registries.area.async_create("Living Room") device = registries.device.async_get_or_create( config_entry_id="1234", manufacturer="Someone", model="Some model", sw_version="Some Version", connectio...
466
test_smart_home.py
Python
tests/components/google_assistant/test_smart_home.py
1bc8770b51658f0dc1bd076b392d70be5a7433bc
core
3
266,492
8
11
4
42
6
0
8
33
check_layout
ansible-test - Improve help for unsupported cwd. (#76866) * ansible-test - Improve help for unsupported cwd. * The `--help` option is now available when an unsupported cwd is in use. * The `--help` output now shows the same instructions about cwd as would be shown in error messages if the cwd is unsupported. * Ad...
https://github.com/ansible/ansible.git
def check_layout(self) -> None: if self.content.unsupported: raise ApplicationError(self.explain_working_directory())
24
data.py
Python
test/lib/ansible_test/_internal/data.py
de5f60e374524de13fe079b52282cd7a9eeabd5f
ansible
2
21,982
115
20
42
457
48
0
159
1,081
_yield_distributions
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
https://github.com/pypa/pipenv.git
def _yield_distributions(self): # We need to check if we've seen some resources already, because on # some Linux systems (e.g. some Debian/Ubuntu variants) there are # symlinks which alias other files in the environment. seen = set() for path in self.path: fi...
277
database.py
Python
pipenv/patched/pip/_vendor/distlib/database.py
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
15
20,199
12
11
9
55
8
0
15
54
user_log_dir
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 user_log_dir(self) -> str: path = self.user_cache_dir if self.opinion: path = os.path.join(path, "log") return path
32
android.py
Python
pipenv/patched/notpip/_vendor/platformdirs/android.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
2
176,457
25
10
5
54
7
0
35
72
dict_to_numpy_array
Deprecate dict to numpy helpers (#5427) * Convert to private fns and add deprecated public wrappers. * Modify existing tests to use private fns. * Add test that dep warnings are raised. * Add dep note. * Add release note. * Add importorskip(numpy).
https://github.com/networkx/networkx.git
def dict_to_numpy_array(d, mapping=None): try: return _dict_to_numpy_array2(d, mapping) except (AttributeError, TypeError): # AttributeError is when no mapping was provided and v.keys() fails. # TypeError is when a mapping was provided and d[k1][k2] fails. return _dict_to_nu...
33
misc.py
Python
networkx/utils/misc.py
72b1dca7d7d4d8bab519d55541d981d2f4f61365
networkx
2
279,606
45
11
10
167
18
1
52
105
save_img
Add f-string format and lint with flynt on the whole codebase
https://github.com/keras-team/keras.git
def save_img(path, x, data_format=None, file_format=None, scale=True, **kwargs): if data_format is None: data_format = backend.image_data_format() img = array_to_img(x, data_format=data_format, scale=scale) if img.mode == "RGBA" and (file_format == "jpg" or file_format == "jpeg"): warni...
@keras_export("keras.utils.load_img", "keras.preprocessing.image.load_img")
93
image_utils.py
Python
keras/utils/image_utils.py
be73ac1a1e25d9abd4d793cba9707098d7adf231
keras
5
83,030
26
11
9
63
6
0
29
64
test_subscriptions_exist_invalid_name
string_validation: Give a more specific message for empty stream names. Co-authored-by: Shlok Patel <shlokcpatel2001@gmail.com>
https://github.com/zulip/zulip.git
def test_subscriptions_exist_invalid_name(self) -> None: # currently, the only invalid stream name is the empty string invalid_stream_name = "" result = self.client_post("/json/subscriptions/exists", {"stream": invalid_stream_name}) self.assert_json_error(result, "Stream name ca...
33
test_subs.py
Python
zerver/tests/test_subs.py
94dbb540b149251068698ceca4591ad74b494686
zulip
1
111,253
57
11
31
294
12
0
82
315
test_displacy_parse_spans_with_kb_id_options
Add displacy support for overlapping Spans (#10332) * Fix docstring for EntityRenderer * Add warning in displacy if doc.spans are empty * Implement parse_spans converter One notable change here is that the default spans_key is sc, and it's set by the user through the options. * Implement SpanRenderer H...
https://github.com/explosion/spaCy.git
def test_displacy_parse_spans_with_kb_id_options(en_vocab): doc = Doc(en_vocab, words=["Welcome", "to", "the", "Bank", "of", "China"]) doc.spans["sc"] = [ Span(doc, 3, 6, "ORG", kb_id="Q790068"), Span(doc, 5, 6, "GPE", kb_id="Q148"), ] spans = displacy.parse_spans( doc, {"k...
165
test_displacy.py
Python
spacy/tests/test_displacy.py
a79cd3542b3dd667d8a97293462e22ed26a04ee5
spaCy
1
80,113
31
13
11
106
11
0
34
114
map_list_block_value
Add StreamField migration helpers from https://github.com/sandilsranasinghe/wagtail-streamfield-migration-toolkit/
https://github.com/wagtail/wagtail.git
def map_list_block_value(list_block_value, block_def, block_path, **kwargs): mapped_value = [] # In case data is in old list format for child_block in formatted_list_child_generator(list_block_value): mapped_child_value = map_block_value( child_block["value"], block_de...
67
utils.py
Python
wagtail/blocks/migrations/utils.py
ec6229c23600ebae8ec0d5db6846b095a9468151
wagtail
2
209,490
23
12
4
70
8
0
25
53
get_if_addr6
Answering machines improvements (NBNS/DNS/LLMNR) (#3699) * Minor NBNS improvements * Improve Netbios/LLMNR/DNS answering machines * DNS_am: support IPv6 * More customization of some answering machines
https://github.com/secdev/scapy.git
def get_if_addr6(niff): # type: (NetworkInterface) -> Optional[str] iff = network_name(niff) return next((x[0] for x in in6_getifaddr() if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL), None)
44
__init__.py
Python
scapy/arch/__init__.py
dd7a5c97d68c00d1d03ecf8ac27c6c7038525065
scapy
4
176,095
11
10
7
44
3
0
11
46
test_edgeql_select_subqueries_09
Add a `bag` type that tells assert_query_result to ignore order (#3314) assert_query_result currently supports using sets to ignore order, but that doesn't work for objects, which can't be hashed or sorted. There is a system for specifying a sort key for internal data, but it is way clunkier than just saying we d...
https://github.com/edgedb/edgedb.git
async def test_edgeql_select_subqueries_09(self): await self.assert_query_result( r, {'11', '22', '33', '44'}, )
24
test_edgeql_select.py
Python
tests/test_edgeql_select.py
26be7d28bdb4eb96c888e373e08f46e6b85711e3
edgedb
1
111,250
23
11
7
146
7
0
31
52
test_doc_to_json_span
Add spans to doc.to_json (#10073) * Add spans to to_json * adjustments to_json * Change docstring * change doc key naming * Update spacy/tokens/doc.pyx Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
https://github.com/explosion/spaCy.git
def test_doc_to_json_span(doc): doc.spans["test"] = [Span(doc, 0, 2, "test"), Span(doc, 0, 1, "test")] json_doc = doc.to_json() assert "spans" in json_doc assert len(json_doc["spans"]) == 1 assert len(json_doc["spans"]["test"]) == 2 assert json_doc["spans"]["test"][0]["start"] == 0
86
test_to_json.py
Python
spacy/tests/doc/test_to_json.py
b68bf43f5bf07b78c062777f35240f031374fe00
spaCy
1
286,657
78
13
32
286
26
0
109
267
functions_df
Audit SDK and View/Model functions (#3384) * Initial commit * Finalized functionality * update script * Allow using it without forecasting * Update gitignore * Update `sdk_audit.py` * Fixed issues, found more * Added fix for helper functions, and column for SDK type * Checked one more thing ...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def functions_df() -> pd.DataFrame: modules = all_view_models() all_formatted = [] for module in modules: if not FORECASTING and "forecast" in str(module): continue loaded = load_modules(module) # Gets all of a module's functions, but ignores imported functions ...
169
sdk_audit.py
Python
openbb_terminal/core/scripts/sdk_audit.py
963ca9b2b924d0514e0e65243dc8d9d7af023ad1
OpenBBTerminal
10
266,729
20
7
2
23
3
0
21
29
format_line
ansible-test - Code cleanup and refactoring. (#77169) * Remove unnecessary PyCharm ignores. * Ignore intentional undefined attribute usage. * Add missing type hints. Fix existing type hints. * Fix docstrings and comments. * Use function to register completion handler. * Pass strings to display functions. * Fix C...
https://github.com/ansible/ansible.git
def format_line(value): # type: (int) -> str return str(value) # putting this in a function keeps both pylint and mypy happy
11
__init__.py
Python
test/lib/ansible_test/_internal/commands/coverage/analyze/targets/__init__.py
a06fa496d3f837cca3c437ab6e9858525633d147
ansible
1
301,457
17
9
7
69
9
0
20
42
_get_full_name
Fix memory leak when firing state_changed events (#72571)
https://github.com/home-assistant/core.git
def _get_full_name(obj) -> str: objtype = type(obj) name = objtype.__name__ if module := getattr(objtype, "__module__", None): return f"{module}.{name}" return name
36
test_core.py
Python
tests/test_core.py
049c06061ce92834b0c82b0e8b06ae7520322e54
core
2
249,078
26
12
18
160
12
0
38
185
test_update_display_name
Use literals in place of `HTTPStatus` constants in tests (#13469)
https://github.com/matrix-org/synapse.git
def test_update_display_name(self) -> None: # Set new display_name channel = self.make_request( "PUT", self.url, access_token=self.admin_user_tok, content={"display_name": "new displayname"}, ) self.assertEqual(200, channel.code, ...
99
test_device.py
Python
tests/rest/admin/test_device.py
c97042f7eef3748e17c90e48a4122389a89c4735
synapse
1
32,882
27
15
9
123
18
0
34
82
test_correct_head_class
`bitsandbytes` - `Linear8bitLt` integration into `transformers` models (#17901) * first commit * correct replace function * add final changes - works like charm! - cannot implement tests yet - tested * clean up a bit * add bitsandbytes dependencies * working version - added import function - ad...
https://github.com/huggingface/transformers.git
def test_correct_head_class(self): r from bitsandbytes.nn import Int8Params # last param of a base model should be a linear8bit module self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Int8Params) # Other heads should be nn.Parameter self.asser...
77
test_mixed_int8.py
Python
tests/mixed_int8/test_mixed_int8.py
4a51075a96d2049f368b5f3dd6c0e9f08f599b62
transformers
1
246,261
11
8
16
42
7
0
13
41
test_overlapping_spans
Fixes for opentracing scopes (#11869) `start_active_span` was inconsistent as to whether it would activate the span immediately, or wait for `scope.__enter__` to happen (it depended on whether the current logcontext already had an associated scope). The inconsistency was rather confusing if you were hoping to set...
https://github.com/matrix-org/synapse.git
def test_overlapping_spans(self) -> None: reactor = MemoryReactorClock() clock = Clock(reactor) scopes = []
108
test_opentracing.py
Python
tests/logging/test_opentracing.py
31b554c2976612ce5fd983517615906261c39cea
synapse
1
287,950
39
11
17
180
21
1
51
146
mock_smile_anna
Bump plugwise to v0.21.3, add related new features (#76610) Co-authored-by: Franck Nijhof <frenck@frenck.nl>
https://github.com/home-assistant/core.git
def mock_smile_anna() -> Generator[None, MagicMock, None]: chosen_env = "anna_heatpump_heating" with patch( "homeassistant.components.plugwise.gateway.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "015ae9ea3f964e668e490fa39da3870b" ...
@pytest.fixture
95
conftest.py
Python
tests/components/plugwise/conftest.py
2667f0b792b1f936aeb5958cc40d5dee26350bf6
core
1
266,728
49
16
11
266
24
0
76
127
make_report
ansible-test - Code cleanup and refactoring. (#77169) * Remove unnecessary PyCharm ignores. * Ignore intentional undefined attribute usage. * Add missing type hints. Fix existing type hints. * Fix docstrings and comments. * Use function to register completion handler. * Pass strings to display functions. * Fix C...
https://github.com/ansible/ansible.git
def make_report(target_indexes, arcs, lines): # type: (TargetIndexes, Arcs, Lines) -> t.Dict[str, t.Any] set_indexes = {} # type: TargetSetIndexes arc_refs = dict((path, dict((format_arc(arc), get_target_set_index(indexes, set_indexes)) for arc, indexes in data.items())) for path, data in arcs.items()) ...
177
__init__.py
Python
test/lib/ansible_test/_internal/commands/coverage/analyze/targets/__init__.py
a06fa496d3f837cca3c437ab6e9858525633d147
ansible
7
271,043
39
12
6
62
10
0
48
101
_maybe_broadcast_to_outputs
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def _maybe_broadcast_to_outputs(self, outputs, objects): if not self._should_broadcast(objects): return objects # When there is more than one Model output, this is needed to keep # each Metric / Loss separate. When there is only one Model output, # the user-supplied...
54
compile_utils.py
Python
keras/engine/compile_utils.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
2
20,010
37
14
11
101
16
0
41
93
_get_pyvenv_cfg_lines
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_pyvenv_cfg_lines() -> Optional[List[str]]: pyvenv_cfg_file = os.path.join(sys.prefix, "pyvenv.cfg") try: # Although PEP 405 does not specify, the built-in venv module always # writes with UTF-8. (pypa/pip#8717) with open(pyvenv_cfg_file, encoding="utf-8") as f: ...
56
virtualenv.py
Python
pipenv/patched/notpip/_internal/utils/virtualenv.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
2
260,757
10
9
4
53
7
0
11
39
fit
MAINT Parameters validation for `ClassifierChain` and `RegressorChain` (#24112) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr>
https://github.com/scikit-learn/scikit-learn.git
def fit(self, X, Y, **fit_params): self._validate_params() super().fit(X, Y, **fit_params) return self
33
multioutput.py
Python
sklearn/multioutput.py
01944223c81617c24b9ce741356505fcfc0d6b44
scikit-learn
1
9,864
40
12
23
204
23
0
55
142
update_runtime_cls
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 update_runtime_cls(args, copy=False) -> 'Namespace': _args = deepcopy(args) if copy else args gateway_runtime_dict = { GatewayProtocolType.GRPC: 'GRPCGatewayRuntime', GatewayProtocolType.WEBSOCKET: 'WebSocketGatewayRuntime', GatewayProtocolType.HTTP: 'HTTPGatewayRuntime', } ...
122
helper.py
Python
jina/peapods/peas/helper.py
933415bfa1f9eb89f935037014dfed816eb9815d
jina
6
262,743
160
16
54
650
40
0
283
840
findLibrary
Bindepend: Add Termux-specific libraries search path. According to termux/termux-app#1595, this is all we need to change to faclitate using PyInstaller on Termux.
https://github.com/pyinstaller/pyinstaller.git
def findLibrary(name): assert compat.is_unix, "Current implementation for Unix only (Linux, Solaris, AIX, FreeBSD)" # Look in the LD_LIBRARY_PATH according to platform. if compat.is_aix: lp = compat.getenv('LIBPATH', '') elif compat.is_darwin: lp = compat.getenv('DYLD_LIBRARY_PATH'...
360
bindepend.py
Python
PyInstaller/depend/bindepend.py
57c520132b4d0ab7bfd5653383ec2602e40088af
pyinstaller
21
249,827
7
8
5
28
4
0
7
21
test_gen_next_while_still_waiting_for_persistence
Reintroduce #14376, with bugfix for monoliths (#14468) * Add tests for StreamIdGenerator * Drive-by: annotate all defs * Revert "Revert "Remove slaved id tracker (#14376)" (#14463)" This reverts commit d63814fd736fed5d3d45ff3af5e6d3bfae50c439, which in turn reverted 36097e88c4da51fce6556a58c49bd675f4cf20ab. This re...
https://github.com/matrix-org/synapse.git
def test_gen_next_while_still_waiting_for_persistence(self) -> None: id_gen = self._create_id_generator()
26
test_id_generators.py
Python
tests/storage/test_id_generators.py
115f0eb2334b13665e5c112bd87f95ea393c9047
synapse
1
297,971
50
13
22
124
14
0
61
315
connection_is_valid
String formatting and max line length - Part 5 (#84501) Co-authored-by: jjlawren <jjlawren@users.noreply.github.com>
https://github.com/home-assistant/core.git
def connection_is_valid(self): server = None try: server = self.connect() except (smtplib.socket.gaierror, ConnectionRefusedError): _LOGGER.exception( ( "SMTP server not found or refused connection (%s:%s). Please check" ...
72
notify.py
Python
homeassistant/components/smtp/notify.py
f39f3b612a8c1a12504f2f1d54fb1c9872216d12
core
5
138,092
36
15
17
183
19
0
42
141
test_multi_trial_reuse_with_failing
[air/tune] Internal resource management 2 - Ray Tune to use new Ray AIR resource manager (#30016) Includes/depends on #30777 TLDR: This PR refactors Ray Tune's resource management to use a central AIR resource management package instead of the tightly coupled PlacementGroupManager. Ray Tune's resource management...
https://github.com/ray-project/ray.git
def test_multi_trial_reuse_with_failing(ray_start_4_cpus_extra): os.environ["TUNE_MAX_PENDING_TRIALS_PG"] = "2" register_trainable("foo2", MyResettableClass) [trial1, trial2, trial3, trial4] = tune.run( "foo2", config={ "fail": tune.grid_search([False, True, False, False])...
113
test_actor_reuse.py
Python
python/ray/tune/tests/test_actor_reuse.py
1510fb2cd631b2776092fb45ee4082e5e65f16f8
ray
1
270,862
19
13
112
102
15
1
21
70
check_graph_consistency
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def check_graph_consistency(tensor=None, method="add_loss", force_raise=False): if force_raise or ( tf.compat.v1.executing_eagerly_outside_functions() and hasattr(tensor, "graph") and tensor.graph.is_control_flow_graph ): if method == "activity_regularizer": bad_...
bad_example = """
142
base_layer_utils.py
Python
keras/engine/base_layer_utils.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
8
268,859
5
9
2
32
4
0
5
7
multiply
Refactor `merge.py` into smaller logically organized files hosted under a `merging` directory. PiperOrigin-RevId: 424162837
https://github.com/keras-team/keras.git
def multiply(inputs, **kwargs): return Multiply(**kwargs)(inputs)
18
multiply.py
Python
keras/layers/merging/multiply.py
85ccb4e108551b7444213276ffb4c4c09f22f886
keras
1
100,503
60
15
23
361
39
0
88
377
_add_actions
bugfix: Preview Tool, ensure all config items are written
https://github.com/deepfakes/faceswap.git
def _add_actions(self, parent, config_key): logger.debug("Adding util buttons") title = config_key.split(".")[1].replace("_", " ").title() btn_frame = ttk.Frame(self._action_frame) btn_frame.pack(padx=5, side=tk.BOTTOM, fill=tk.X) for utl in ("save", "clear", "reload"):...
210
preview.py
Python
tools/preview/preview.py
71c20252c2e747f692289cdefe80ad0d5a456ea6
faceswap
5
336,635
44
12
27
199
22
0
60
100
downsample_2d
Rename variables from single letter to meaningful name fix (#395) Co-authored-by: Rashmi S <rashmis@Rashmis-MacBook-Pro.local>
https://github.com/huggingface/diffusers.git
def downsample_2d(x, kernel=None, factor=2, gain=1): r assert isinstance(factor, int) and factor >= 1 if kernel is None: kernel = [1] * factor kernel = np.asarray(kernel, dtype=np.float32) if kernel.ndim == 1: kernel = np.outer(kernel, kernel) kernel /= np.sum(kernel) kern...
128
resnet.py
Python
src/diffusers/models/resnet.py
1a431ae886b516d13f49c1f8a1e1e68d3159eab4
diffusers
4
135,744
30
11
13
123
16
1
37
147
test_cuda_visible_devices
[Jobs] Allow resource requests for driver (entrypoint command) (#28654) Allows num_cpus, num_gpus and resources to be reserved for the job entrypoint command. This is achieved by passing them in as .options() to the JobSupervisor actor. Adds a friendly error message if the JobSupervisor cannot be scheduled Update...
https://github.com/ray-project/ray.git
async def test_cuda_visible_devices(self, job_manager, resource_kwarg, env_vars): run_cmd = f"python {_driver_script_path('check_cuda_devices.py')}" runtime_env = {"env_vars": env_vars} if resource_kwarg: run_cmd = "RAY_TEST_RESOURCES_SPECIFIED=1 " + run_cmd job_id =...
@pytest.mark.asyncio
63
test_job_manager.py
Python
dashboard/modules/job/tests/test_job_manager.py
e4b211a921698b79452f8c2f4d3e6a34ff58b26b
ray
2
154,492
36
14
9
192
19
0
61
100
deploy_dask_func
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_dask_func(deployer, axis, f_to_deploy, f_args, f_kwargs, *args, **kwargs): result = deployer(axis, f_to_deploy, f_args, f_kwargs, *args, **kwargs) ip = get_ip() if isinstance(result, pandas.DataFrame): return result, len(result), len(result.columns), ip elif all(isinstance(r, pan...
136
virtual_partition.py
Python
modin/core/execution/dask/implementations/pandas_on_dask/partitioning/virtual_partition.py
d6d503ac7c3028d871c34d9e99e925ddb0746df6
modin
8
309,915
53
18
37
290
34
0
74
593
async_step_client_control
Orphaned MAC addresses breaks UniFi options flow (#64327)
https://github.com/home-assistant/core.git
async def async_step_client_control(self, user_input=None): errors = {} if user_input is not None: self.options.update(user_input) return await self.async_step_statistics_sensors() clients_to_block = {} for client in self.controller.api.clients.values(...
178
config_flow.py
Python
homeassistant/components/unifi/config_flow.py
d4e509422a2d93764586dc9de0789f1deed4cfaa
core
5
81,815
13
12
6
71
9
0
18
84
test_non_job_config_complete
Add WorkflowJob.instance_groups and distinguish from char_prompts This removes a loop that ran on import the loop was giving the wrong behavior and it initialized too many fields as char_prompts fields With this, we will now enumerate the char_prompts type fields manually
https://github.com/ansible/awx.git
def test_non_job_config_complete(self): for field_name in JobTemplate.get_ask_mapping().keys(): if field_name in LaunchTimeConfigBase.SUBCLASS_FIELDS: assert not hasattr(LaunchTimeConfigBase, field_name) else: assert hasattr(LaunchTimeConfigBase, ...
43
test_job_launch_config.py
Python
awx/main/tests/functional/models/test_job_launch_config.py
68e11d2b81ccb9aa4189cdbc37739fbd1207b65f
awx
3
282,475
47
16
21
296
22
1
62
224
get_quote
Refactored terminal.py (#1312) * Seperated run_scripts function from main * Added scripts ability * Converted to endswith * Count success and failure * Fixed commands without -h * Handled edge case * Replaced prints with console.print * Fixed main function issue * Tried more things for output ...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def get_quote(ticker) -> pd.DataFrame: try: df_fa = fa.quote(ticker, cfg.API_KEY_FINANCIALMODELINGPREP) except ValueError: df_fa = pd.DataFrame() if not df_fa.empty: clean_df_index(df_fa) df_fa.loc["Market cap"][0] = long_number_format(df_fa.loc["Market cap"][0]) ...
@log_start_end(log=logger)
158
fmp_model.py
Python
gamestonk_terminal/stocks/fundamental_analysis/financial_modeling_prep/fmp_model.py
e22c48ac9fd518f28527e9f82e5b89741b750b8c
OpenBBTerminal
4
289,733
8
9
4
38
5
0
8
33
async_mqtt_connect
Add typing hints for MQTT mixins (#80702) * Add typing hints for MQTT mixins * Follow up comments * config_entry is always set * typing discovery_data - substate None assignment * Rename `config[CONF_DEVICE]` -> specifications
https://github.com/home-assistant/core.git
def async_mqtt_connect(self) -> None: if not self.hass.is_stopping: self.async_write_ha_state()
21
mixins.py
Python
homeassistant/components/mqtt/mixins.py
2f1138562720cd50343d2fedd4981913a9ef6bd9
core
2
20,054
10
7
2
23
2
0
10
19
distro_release_info
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 distro_release_info(): # type: () -> Dict[str, str] return _distro.distro_release_info()
11
distro.py
Python
pipenv/patched/notpip/_vendor/distro.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
1
266,103
21
14
13
246
21
0
39
166
apply
Closes #10851: New staging mechanism (#10890) * WIP * Convert checkout() context manager to a class * Misc cleanup * Drop unique constraint from Change model * Extend staging tests * Misc cleanup * Incorporate M2M changes * Don't cancel wipe out creation records when an object is deleted * Rena...
https://github.com/netbox-community/netbox.git
def apply(self): if self.action == ChangeActionChoices.ACTION_CREATE: instance = deserialize_object(self.model, self.data, pk=self.object_id) logger.info(f'Creating {self.model._meta.verbose_name} {instance}') instance.save() if self.action == ChangeActionCh...
121
staging.py
Python
netbox/extras/models/staging.py
a5308ea28e851a4ddb65a4e7ca2297b641e5891f
netbox
4
267,150
14
9
3
75
9
0
14
80
find_plugin
expand ansible-doc coverage (#74963) * Expand ansible-doc to tests/filters and fix existing issues enable filter/test docs if in single file or companion yaml add docs for several filters/tests plugins allow .yml companion for docs for other plugins, must be colocated verify plugins are valid (not module...
https://github.com/ansible/ansible.git
def find_plugin(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None): return super(Jinja2Loader, self).find_plugin(name, mod_type=mod_type, ignore_deprecated=ignore_deprecated, check_aliases=check_aliases, col...
52
loader.py
Python
lib/ansible/plugins/loader.py
b439e41a915ccec0ccbabecc966919ea406db74e
ansible
1
285,679
10
10
13
36
6
0
11
30
get_anchor_yield_reserve
Next release : reports on steroids (#2349) * fix gov tests * refactor insider * new virtual path extraction * removed some symbol default params as they're considered critical * little adjustments * portfolio refactor * merge API factory * add helpers, stocks, crypto, forex * minor forex change...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def get_anchor_yield_reserve() -> pd.DataFrame: df = get_history_asset_from_terra_address( address="terra1tmnqgvg567ypvsvk6rwsga3srp7e3lg6u0elp8" ) return df
19
terraengineer_model.py
Python
openbb_terminal/cryptocurrency/defi/terraengineer_model.py
72b0a9f1ee8b91ad9fd9e76d80d2ccab51ee6d21
OpenBBTerminal
1
267,385
22
11
2
59
7
0
24
31
get_type_associations
ansible-test - Code cleanup. This helps prepare for a future pylint upgrade.
https://github.com/ansible/ansible.git
def get_type_associations(base_type, generic_base_type): # type: (t.Type[TBase], t.Type[TValue]) -> t.List[t.Tuple[t.Type[TValue], t.Type[TBase]]] return [item for item in [(get_generic_type(sc_type, generic_base_type), sc_type) for sc_type in get_subclasses(base_type)] if item[1]]
39
util.py
Python
test/lib/ansible_test/_internal/util.py
86779cc90376ea70bafa7044b12ce5132409fd63
ansible
4
20,335
5
9
2
37
6
0
5
19
_translate_parts
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 _translate_parts(self, value): return value.translate(_escape_html_table).split('\n')
20
html.py
Python
pipenv/patched/notpip/_vendor/pygments/formatters/html.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
1
290,569
20
9
14
114
10
0
49
107
test_cover_positions
Implemented RestoreEntity for Dynalite (#73911) * Implemented RestoreEntity Merged commit conflict * removed accidental change * Update homeassistant/components/dynalite/dynalitebase.py Co-authored-by: Erik Montnemery <erik@montnemery.com> * added tests for the state * added tests for switch state *...
https://github.com/home-assistant/core.git
async def test_cover_positions(hass, mock_device): update_func = await create_entity_from_device(hass, mock_device) await check_cover_position( hass, update_func, mock_device, True, False, False, STATE_CLOSING ) await check_cover_position( hass, update_func, mock_device, False, True...
85
test_cover.py
Python
tests/components/dynalite/test_cover.py
b6c27585c74294fd4cc4d3a2640cf98ef6b4c343
core
1
48,376
21
10
11
84
10
0
24
81
_get_multiprocessing_start_method
Add typing for airflow/configuration.py (#23716) * Add typing for airflow/configuration.py The configuraiton.py did not have typing information and it made it rather difficult to reason about it-especially that it went a few changes in the past that made it rather complex to understand. This PR adds typing in...
https://github.com/apache/airflow.git
def _get_multiprocessing_start_method(self) -> str: if conf.has_option('core', 'mp_start_method'): return conf.get_mandatory_value('core', 'mp_start_method') method = multiprocessing.get_start_method() if not method: raise ValueError("Failed to determine start m...
45
mixins.py
Python
airflow/utils/mixins.py
71e4deb1b093b7ad9320eb5eb34eca8ea440a238
airflow
3
34,981
17
12
4
50
6
0
18
50
get_subsampled_output_lengths
Add TFSpeech2Text (#15113) * Add wrapper classes * convert inner layers to tf * Add TF Encoder and Decoder layers * TFSpeech2Text models * Loadable model * TF model with same outputs as PT model * test skeleton * correct tests and run the fixup * correct attention expansion * TFSpeech2Text p...
https://github.com/huggingface/transformers.git
def get_subsampled_output_lengths(self, input_lengths): for _ in range(self.num_conv_layers): input_lengths = (input_lengths - 1) // 2 + 1 return input_lengths
28
test_modeling_tf_speech_to_text.py
Python
tests/test_modeling_tf_speech_to_text.py
8406fa6dd538c6e1b5a218b119e8efd771023112
transformers
2
286,052
58
15
39
304
25
1
72
259
us_indices
Enhances error handling in economy menu (#2819) * Lots of bug fixes * Fixed issue
https://github.com/OpenBB-finance/OpenBBTerminal.git
def us_indices() -> pd.DataFrame: url = ( "https://www.wsj.com/market-data/stocks?id=%7B%22application%22%3A%22WSJ%22%2C%22instruments%22%3A%5B%7B" "%22symbol%22%3A%22INDEX%2FUS%2F%2FDJIA%22%2C%22name%22%3A%22DJIA%22%7D%2C%7B%22symbol%22%3A%22INDEX%2FUS%2F" "%2FCOMP%22%2C%22name%22%3A%2...
@log_start_end(log=logger)
162
wsj_model.py
Python
openbb_terminal/economy/wsj_model.py
4304a5c664700cf083f1432fa7523f051492754c
OpenBBTerminal
3
176,384
32
11
9
182
19
0
37
76
test_to_numpy_array_structured_dtype_nonedge_ary
Add structured dtypes to `to_numpy_array` (#5324) * Add basic test for supporting multi-attr adjacency. * WIP: sloppy implementation of multiattr adjacency in to_numpy_array. Conditionals could be improved. * Reorg conditionals. * Test to_numpy_array raises with structured dtype for multigraphs. * Fix d...
https://github.com/networkx/networkx.git
def test_to_numpy_array_structured_dtype_nonedge_ary(G): G.add_edge(0, 1, weight=10) dtype = np.dtype([("weight", float), ("cost", float)]) nonedges = np.array([(0, np.inf)], dtype=dtype) A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=nonedges) for attr in dtype.names: noned...
122
test_convert_numpy.py
Python
networkx/tests/test_convert_numpy.py
d2278b4c3402c735a31e266adde75ecc2eeb98eb
networkx
2
323,154
5
7
2
21
3
0
5
19
_new_epoch
[Trainer] Add init version of paddlenlp trainer and apply finetune for ernie-1.0 pretraining. (#1761) * add some datasets for finetune. * support fine tune for all tastks. * add trainer prototype. * init verison for paddlenlp trainer. * refine trainer. * update for some details. * support multi-card...
https://github.com/PaddlePaddle/PaddleNLP.git
def _new_epoch(self): self.should_epoch_stop = False
11
trainer_callback.py
Python
paddlenlp/trainer/trainer_callback.py
44a290e94d1becd1f09fddc3d873f9e19c9d6919
PaddleNLP
1
100,333
18
13
9
119
23
0
18
139
add_option_save
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 add_option_save(self): logger.debug("Adding save option") btnsave = ttk.Button(self.optsframe, image=get_images().icons["save"], command=self.save_items) btnsave.pack(padx=2, side=tk.RIGHT) Tooltip(btnsave, ...
69
display_page.py
Python
lib/gui/display_page.py
c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf
faceswap
1
290,947
8
9
4
49
7
0
9
30
async_press
AVM Fritz!Box SmartHome: Integrate Templates (#81885)
https://github.com/home-assistant/core.git
async def async_press(self) -> None: await self.hass.async_add_executor_job(self.apply_template) await self.coordinator.async_refresh()
27
button.py
Python
homeassistant/components/fritzbox/button.py
3b783a85c30001d7a8cf60c54932cb2b6616de4d
core
1
261,025
40
12
13
199
17
0
55
120
softmax
ENH Adds Array API support to LinearDiscriminantAnalysis (#22554) Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org> Co-authored-by: Julien Jerphanion <git@jjerphan.xyz>
https://github.com/scikit-learn/scikit-learn.git
def softmax(X, copy=True): xp, is_array_api = get_namespace(X) if copy: X = xp.asarray(X, copy=True) max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1)) X -= max_prob if xp.__name__ in {"numpy", "numpy.array_api"}: # optimization for NumPy arrays np.exp(X, out=np.asarray(...
126
extmath.py
Python
sklearn/utils/extmath.py
2710a9e7eefd2088ce35fd2fb6651d5f97e5ef8b
scikit-learn
3
64,677
39
15
17
186
23
1
47
29
get_delivered_serial_nos
fix(pos): remove returned sr. nos. from pos reserved sr. nos. list
https://github.com/frappe/erpnext.git
def get_delivered_serial_nos(serial_nos): from frappe.query_builder.functions import Coalesce SerialNo = frappe.qb.DocType("Serial No") serial_nos = get_serial_nos(serial_nos) query = ( frappe.qb .from_(SerialNo) .select(SerialNo.name) .where( (SerialNo.name.isin(serial_nos)) & (Coalesce(Seria...
@frappe.whitelist()
107
serial_no.py
Python
erpnext/stock/doctype/serial_no/serial_no.py
f2ae63cbfdc0262f45ccae5991927e49e5c38c4c
erpnext
4
42,246
12
9
3
45
7
0
12
21
crayon_palette
Convert color palette docstrings to notebooks (#3034) * Convert color palette docstrings to notebooks and rerun all with py310 kernel * Add v0.12.1 release notes to index * Improve failure mode when ipywidgets is not involved * Update palettes docstrings * Remove all other doctest-style examples * Remov...
https://github.com/mwaskom/seaborn.git
def crayon_palette(colors): palette = [crayons[name] for name in colors] return color_palette(palette, len(palette))
28
palettes.py
Python
seaborn/palettes.py
e644793f0ac2b1be178425f20f529121f37f29de
seaborn
2
294,627
24
13
10
134
15
1
27
80
test_form_stream_invalidimage
Generic IP Camera configflow 2 (#52360) Co-authored-by: J. Nick Koston <nick@koston.org>
https://github.com/home-assistant/core.git
async def test_form_stream_invalidimage(hass, mock_av_open, user_flow): respx.get("http://127.0.0.1/testurl/1").respond(stream=b"invalid") with mock_av_open: result2 = await hass.config_entries.flow.async_configure( user_flow["flow_id"], TESTDATA, ) await hass.as...
@respx.mock
70
test_config_flow.py
Python
tests/components/generic/test_config_flow.py
c1a2be72fc8b76b55cfde1823c5688100e397369
core
1
42,167
59
10
5
537
46
0
65
206
plot
Cleanup and merge #2909 (#2955) * Sorting boxenplot * Boxenplot separate kws Removed `kwargs` which were used to draw the median lines and scatter plot of outliers previously. Added separate kwargs - `box_kws`, `line_kws` (drawing the median lines) and `flier_kws` (for the scatter of outliers). Updated the...
https://github.com/mwaskom/seaborn.git
def plot(self, ax, box_kws, flier_kws, line_kws): self.draw_letter_value_plot(ax, box_kws, flier_kws, line_kws) self.annotate_axes(ax) if self.orient == "h": ax.invert_yaxis() _categorical_docs = dict( # Shared narrative docs categorical_narrative=dedent(), n...
44
categorical.py
Python
seaborn/categorical.py
b1db0f72627e9fae8fda261514392d53906384cf
seaborn
2
263,869
81
12
7
110
17
0
111
266
exec_module
loader: remove pyimod01_os_path and replace its use with os.path Add os (and its dependencies) to compat.PY3_BASE_MODULES so that they are collected into base_library.zip. As this archive is available during the bootstrap, we can now use full functionality of os.path in our bootstrap scripts/modules instead of having ...
https://github.com/pyinstaller/pyinstaller.git
def exec_module(self, module): spec = module.__spec__ bytecode = self.get_code(spec.loader_state) # Set by the import machinery assert hasattr(module, '__file__') # If `submodule_search_locations` is not None, this is a package; set __path__. if spec.submodule_...
62
pyimod02_importers.py
Python
PyInstaller/loader/pyimod02_importers.py
c115bce4dd1eb43c3e1ad52ca6743ed6fd3f0a70
pyinstaller
2
200,399
29
11
7
95
13
0
34
94
perpendicular_segment
Fix various typos Found via `codespell -q 3 -L aboves,aline,ans,aother,arithmetics,assum,atleast,braket,clen,declar,declars,dorder,dum,enew,fo,fro,inout,iself,ist,ket,lamda,lightyear,lightyears,nd,numer,numers,orderd,ot,pring,rcall,rever,ro,ser,siz,splitted,sring,supercedes,te,tht,unequality,upto,vas,versin,whet`
https://github.com/sympy/sympy.git
def perpendicular_segment(self, p): p = Point(p, dim=self.ambient_dimension) if p in self: return p l = self.perpendicular_line(p) # The intersection should be unique, so unpack the singleton p2, = Intersection(Line(self.p1, self.p2), l) return Segme...
60
line.py
Python
sympy/geometry/line.py
24f1e7730119fe958cc8e28411f790c9a5ec04eb
sympy
2
85,851
124
16
39
442
33
0
208
743
get_autoassign_owners
feat(codeowners): Add codeowners type to group owners (#38813)
https://github.com/getsentry/sentry.git
def get_autoassign_owners(cls, project_id, data, limit=2): from sentry.models import ProjectCodeOwners from sentry.models.groupowner import OwnerRuleType with metrics.timer("projectownership.get_autoassign_owners"): ownership = cls.get_ownership_cached(project_id) ...
291
projectownership.py
Python
src/sentry/models/projectownership.py
56a4e17eb1a20773ef60d62a364daad4980bd643
sentry
11
337,589
20
13
11
130
18
0
24
76
test_load_states_by_steps
Refactor tests to use accelerate launch (#373) Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>
https://github.com/huggingface/accelerate.git
def test_load_states_by_steps(self): testargs = f.split() output = subprocess.run( self._launch_args + testargs, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).stdout self.assertNotIn("epoch 0:", output) self.assertIn("epoch 1:", output) ...
67
test_examples.py
Python
tests/test_examples.py
23c0341262bd396a3ba9265614b3818d6e08a6c1
accelerate
1
118,546
37
10
18
153
26
0
40
217
_maybe_create_scriptrunner
Rename and refactor `Report` machinery (#4141) This refactor renames (almost) everything related to the outdated "report" concept with more precise concepts that we use throughout our code, primarily "script run", "session", and "app".
https://github.com/streamlit/streamlit.git
def _maybe_create_scriptrunner(self): if ( self._state == AppSessionState.SHUTDOWN_REQUESTED or self._scriptrunner is not None or not self._script_request_queue.has_request ): return # Create the ScriptRunner, attach event handlers, and s...
100
app_session.py
Python
lib/streamlit/app_session.py
704eab3478cf69847825b23dabf15813a8ac9fa2
streamlit
4
133,741
32
15
15
217
20
0
41
150
multi_log_probs_from_logits_and_actions
[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 multi_log_probs_from_logits_and_actions(policy_logits, actions, dist_class, model): log_probs = [] for i in range(len(policy_logits)): p_shape = tf.shape(policy_logits[i]) a_shape = tf.shape(actions[i]) policy_logits_flat = tf.reshape( policy_logits[i], tf.concat([[-...
144
vtrace_tf.py
Python
rllib/agents/impala/vtrace_tf.py
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
2
95,536
8
9
6
83
8
0
9
51
capture_screenshots
test(dashboard-layout): Add missing acceptance tests (#31099)
https://github.com/getsentry/sentry.git
def capture_screenshots(self, screenshot_name): self.page.wait_until_loaded() self.browser.snapshot(screenshot_name) self.browser.refresh() self.page.wait_until_loaded() self.browser.snapshot(f"{screenshot_name} (refresh)")
46
test_organization_dashboards.py
Python
tests/acceptance/test_organization_dashboards.py
cc156785c3f63b942597d84fe458c37bdcf92ec2
sentry
1
294,028
22
12
10
109
12
0
29
104
offset
Support multiple Plex servers in media browser (#68321)
https://github.com/home-assistant/core.git
def offset(self) -> int: if offset := self._params.get("offset", 0): return offset * 1000 resume = self._params.get("resume", False) if isinstance(resume, str): resume = bool(strtobool(resume)) if resume: return self.media.viewOffset r...
66
models.py
Python
homeassistant/components/plex/models.py
653305b998dd033365576db303b32dd5df3a6c54
core
4
87,081
64
16
27
311
28
0
76
373
test_cannot_update_dynamic_sampling_config_on_am2_plan
feat(ds): Handle GET and PUT in project details for v2 dynamic sampling [TET-475] (#40181) Ensures that when new AM2 plan flag is enabled GET request does not return `dynamicSampling` data in response, and for PUT request guards against storing `dynamicSampling` data. Also, handles popping `dynamicSampling` data fr...
https://github.com/getsentry/sentry.git
def test_cannot_update_dynamic_sampling_config_on_am2_plan(self): dynamic_sampling = _dyn_sampling_data() project = self.project # force creation # Update project adding three rules project.update_option("sentry:dynamic_sampling", dynamic_sampling) self.login_as(self.u...
180
test_project_details.py
Python
tests/sentry/api/endpoints/test_project_details.py
8c51b98545d71ed7ef0b3b924db13461e924023a
sentry
1
267,952
19
11
11
119
13
0
21
107
to_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 to_dict(self) -> t.Dict[str, t.Any]: value: t.Dict[str, t.Any] = dict( host_ip=self.host_ip, names=self.names, ) if self.ports: value.update(ports=self.ports) if self.forwards: value.update(forwards=self.forwards) re...
77
containers.py
Python
test/lib/ansible_test/_internal/containers.py
3eb0485dd92c88cc92152d3656d94492db44b183
ansible
3
270,139
20
11
11
83
10
0
22
75
get_word_index
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def get_word_index(path="reuters_word_index.json"): origin_folder = ( "https://storage.googleapis.com/tensorflow/tf-keras-datasets/" ) path = get_file( path, origin=origin_folder + "reuters_word_index.json", file_hash="4d44cc38712099c9e383dc6e5f11a921", ) with op...
45
reuters.py
Python
keras/datasets/reuters.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
1
20,414
120
24
53
468
29
0
195
1,392
get_tokens_unprocessed
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_tokens_unprocessed(self, text, stack=('root',)): pos = 0 tokendefs = self._tokens statestack = list(stack) statetokens = tokendefs[statestack[-1]] while 1: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) ...
279
lexer.py
Python
pipenv/patched/notpip/_vendor/pygments/lexer.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
17
20,061
77
14
26
284
15
0
116
461
version
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 version(self, pretty=False, best=False): # type: (bool, bool) -> str versions = [ self.os_release_attr("version_id"), self.lsb_release_attr("release"), self.distro_release_attr("version_id"), self._parse_distro_release_content(self.os_release_...
160
distro.py
Python
pipenv/patched/notpip/_vendor/distro.py
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
10
168,206
63
12
27
152
24
0
73
219
to_perioddelta
PERF cache find_stack_level (#48023) cache stacklevel
https://github.com/pandas-dev/pandas.git
def to_perioddelta(self, freq) -> TimedeltaArray: # Deprecaation GH#34853 warnings.warn( "to_perioddelta is deprecated and will be removed in a " "future version. " "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.", FutureWarning, ...
87
datetimes.py
Python
pandas/core/arrays/datetimes.py
2f8d0a36703e81e4dca52ca9fe4f58c910c1b304
pandas
2
159,520
38
12
26
250
17
0
56
291
_validate_configuration
Enable `union-attr` mypy check and fix issues (#10942) * first batch of mypy fixes * fix for failing tests * fix errors in channels and shared packages * add docstring, fix error in brokers and lock module * more fixes * fix more union-attr errors * add more fixes * fix errors in action module, un...
https://github.com/RasaHQ/rasa.git
def _validate_configuration(self) -> None: if self.assistant_voice not in self.SUPPORTED_VOICES: self._raise_invalid_voice_exception() try: int(self.speech_timeout) except ValueError: if self.speech_timeout.lower() != "auto": self._ra...
143
twilio_voice.py
Python
rasa/core/channels/twilio_voice.py
ec8de9bc19c20880bf681a686f776523b612cc27
rasa
10
1,493
23
14
5
123
11
0
34
69
forward
Moved all code from notebook to codebase Took 19 minutes
https://github.com/OpenMined/PySyft.git
def forward(self, outputs, targets): outputs = outputs.clip(self.epsilon, 1 - self.epsilon) log_loss = targets * dp_log(outputs) + ((targets * -1) + 1) * dp_log((outputs * -1) + 1) log_loss = log_loss.sum(axis=1) * -1 return log_loss.mean()
76
loss.py
Python
packages/syft/src/syft/core/tensor/nn/loss.py
f3b8f6f1196e6f8a92620b4efc190715273fecab
PySyft
1
138,500
38
10
16
105
13
0
53
135
meta_count
[Datasets] [Out-of-Band Serialization: 2/3] Refactor `ExecutionPlan` to maintain complete lineage and eagerly unlink block references. (#23931) This PR refactors ExecutionPlan to maintain complete stage lineage, even for eagerly computed datasets, while ensuring that block references are unlinked as early as possible ...
https://github.com/ray-project/ray.git
def meta_count(self) -> Optional[int]: if self._stages_after_snapshot: return None # Snapshot is now guaranteed to be the output of the final stage or None. blocks = self._snapshot_blocks metadata = blocks.get_metadata() if blocks else None if metadata and al...
66
plan.py
Python
python/ray/data/impl/plan.py
9ee24530abf1b5e3239869b5257dd7b678337b90
ray
7
43,335
7
9
3
38
6
0
7
21
hook
Amazon appflow (#24057) * Add Amazon AppFlow hook. * Add Amazon AppFlow operators. * Add Amazon AppFlow examples. * Add Amazon Appflow docs. * Apply comments/docs patterns. * Removing the "private" attribute signal and more. * Fix task_ids for example_appflow. * Move datetime_to_epoch() to utils a...
https://github.com/apache/airflow.git
def hook(self) -> AppflowHook: return AppflowHook(aws_conn_id=self.aws_conn_id, region_name=self.region)
23
appflow.py
Python
airflow/providers/amazon/aws/operators/appflow.py
e477f4ba6cd15fabbfe5210c99947bcb70ddac4f
airflow
1
306,789
13
8
5
43
8
0
13
32
test_convert_from_gallons
Refactor distance, speed and volume utils (#77952) * Refactor distance util * Fix bmw connected drive tests * Adjust here travel time tests * Adjust waze travel time tests * Adjust test_distance * Adjust rounding values * Adjust more tests * Adjust volume conversions * Add tests
https://github.com/home-assistant/core.git
def test_convert_from_gallons(): gallons = 5 assert volume_util.convert(gallons, VOLUME_GALLONS, VOLUME_LITERS) == pytest.approx( 18.92706 )
28
test_volume.py
Python
tests/util/test_volume.py
9490771a8737892a7a86afd866a3520b836779fd
core
1
269,529
17
11
43
77
11
0
21
47
switch
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def switch(condition, then_expression, else_expression): if condition.dtype != tf.bool: condition = tf.cast(condition, "bool") cond_ndim = ndim(condition) if not cond_ndim: if not callable(then_expression):
239
backend.py
Python
keras/backend.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
9
180,699
10
10
7
47
5
0
11
43
gather_data_and_broadcast_estimations
Release new queue beta (#1969) * queue-refactor-backend (#1489) * queue-refactor-backend - create a template for the new design * queue-refactor-backend - clean after the old queue * queue-refactor-backend - add basic test to websocket endpoint * queue-refactor-backend - small fix * queue-re...
https://github.com/gradio-app/gradio.git
async def gather_data_and_broadcast_estimations(cls) -> None: await cls.gather_data_for_first_ranks() if cls.LIVE_UPDATES: await cls.broadcast_estimations()
25
event_queue.py
Python
gradio/event_queue.py
b1dfc9a172440e9c9736566f326ba339ff559604
gradio
2
100,667
34
12
14
161
15
0
48
163
_check_folder
Alignments tool - Replace 'extract-large' with 'min-size'
https://github.com/deepfakes/faceswap.git
def _check_folder(self) -> None: err = None if not self._faces_dir: err = "ERROR: Output faces folder not provided." elif not os.path.isdir(self._faces_dir): logger.debug("Creating folder: '%s'", self._faces_dir) os.makedirs(self._faces_dir) e...
90
jobs.py
Python
tools/alignments/jobs.py
a9908b46f77dc66ac7efe7100ea0eed4b1f2b460
faceswap
5
265,888
10
10
5
66
8
0
13
28
register_search
Closes #10560: New global search (#10676) * Initial work on new search backend * Clean up search backends * Return only the most relevant result per object * Clear any pre-existing cached entries on cache() * #6003: Implement global search functionality for custom field values * Tweak field weights & do...
https://github.com/netbox-community/netbox.git
def register_search(cls): model = cls.model label = f'{model._meta.app_label}.{model._meta.model_name}' registry['search'][label] = cls return cls
26
__init__.py
Python
netbox/netbox/search/__init__.py
9628dead07ccef9608b32906aa8194bc948e5a09
netbox
1
271,874
66
12
25
250
20
0
108
284
get_metric_function
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
https://github.com/keras-team/keras.git
def get_metric_function(metric, output_shape=None, loss_fn=None): if metric not in ["accuracy", "acc", "crossentropy", "ce"]: return metrics_module.get(metric) is_sparse_categorical_crossentropy = isinstance( loss_fn, losses.SparseCategoricalCrossentropy ) or ( isinstance(loss_...
156
training_utils_v1.py
Python
keras/engine/training_utils_v1.py
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
13
141,975
29
11
18
153
21
0
39
145
test_multi_sync_different_node
[tune] Refactor Syncer / deprecate Sync client (#25655) This PR includes / depends on #25709 The two concepts of Syncer and SyncClient are confusing, as is the current API for passing custom sync functions. This PR refactors Tune's syncing behavior. The Sync client concept is hard deprecated. Instead, we offer a...
https://github.com/ray-project/ray.git
def test_multi_sync_different_node(ray_start_2_cpus, temp_data_dirs, num_workers): tmp_source, tmp_target = temp_data_dirs assert_file(True, tmp_source, "level0.txt") assert_file(True, tmp_source, "subdir/level1.txt") node_ip = ray.util.get_node_ip_address() futures = [ _sync_dir_betw...
99
test_util_file_transfer.py
Python
python/ray/tune/tests/test_util_file_transfer.py
6313ddc47cf9df4df8c8907997df559850a1b874
ray
2
128,724
4
6
43
17
4
0
4
7
test_recover_from_latest
[tune] Try to recover from latest available checkpoint (#29099) Tune tracks the latest available checkpoint per trial in the trial metadata, which is stored on the driver. This data is periodically synced to cloud storage, but can get out of sync if e.g. the node where the driver was on is terminated. When experime...
https://github.com/ray-project/ray.git
def test_recover_from_latest(tmpdir, upload_uri, fetch_from_cloud):
230
test_trainable.py
Python
python/ray/tune/tests/test_trainable.py
d7b2b49a962bf33dae7a50376f159ab15d80800f
ray
6
44,879
43
14
18
233
27
0
53
159
dag_bag_multiple
Fix test_clear_multiple_external_task_marker timing out (#21343) closes: #11443
https://github.com/apache/airflow.git
def dag_bag_multiple(): dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False) daily_dag = DAG("daily_dag", start_date=DEFAULT_DATE, schedule_interval="@daily") agg_dag = DAG("agg_dag", start_date=DEFAULT_DATE, schedule_interval="@daily") dag_bag.bag_dag(dag=daily_dag, root_dag=daily_dag) ...
139
test_external_task_sensor.py
Python
tests/sensors/test_external_task_sensor.py
0873ee7e847e67cf045d9fcc3da6f6422b1b7701
airflow
2
120,111
13
10
9
66
7
0
19
31
explicit_device_get_scope
Bump minimum jaxlib version to 0.3.2 and remove transfer guard compatibility code
https://github.com/google/jax.git
def explicit_device_get_scope() -> Iterator[None]: state = transfer_guard_lib.thread_local_state() prev = state.explicit_device_get state.explicit_device_get = True try: yield finally: state.explicit_device_get = prev
37
config.py
Python
jax/_src/config.py
36df8619d74672b0072e7880bcdd257c4a83e9f1
jax
2
102,400
38
12
10
195
14
0
46
92
no_batch_dim_reference_mha
[rnn/gru] no batch dim (#70442) Summary: Fixes https://github.com/pytorch/pytorch/issues/60585 TODO: * [x] Doc updates Pull Request resolved: https://github.com/pytorch/pytorch/pull/70442 Reviewed By: zou3519 Differential Revision: D33460427 Pulled By: jbschlosser fbshipit-source-id: c64d9624c305d90570c79d11a285...
https://github.com/pytorch/pytorch.git
def no_batch_dim_reference_mha(m, p, *args, **kwargs): batch_dim = 0 if kwargs.get('batch_first', True) else 1 if 'batch_first' in kwargs: kwargs.pop('batch_first') if 'key_padding_mask' in kwargs and kwargs['key_padding_mask'] is not None: kwargs['key_padding_mask'] = kwargs['key_paddi...
117
common_modules.py
Python
torch/testing/_internal/common_modules.py
6eba936082a641be8ece156f70c0f5c435f7a7aa
pytorch
6
9,836
42
10
29
143
9
0
56
156
set_ping_parser
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 set_ping_parser(parser=None): if not parser: parser = set_base_parser() parser.add_argument( 'host', type=str, help='The host address of the target Pea, e.g. 0.0.0.0' ) parser.add_argument('port', type=int, help='The control port of the target pod/pea') parser.add_argument(...
104
ping.py
Python
jina/parsers/ping.py
933415bfa1f9eb89f935037014dfed816eb9815d
jina
2
155,204
25
13
12
95
11
0
26
91
to_pickle_distributed
FEAT-#5053: Add pandas on unidist execution with MPI backend (#5059) Signed-off-by: Igoshev, Iaroslav <iaroslav.igoshev@intel.com>
https://github.com/modin-project/modin.git
def to_pickle_distributed(cls, qc, **kwargs): if not ( isinstance(kwargs["filepath_or_buffer"], str) and "*" in kwargs["filepath_or_buffer"] ) or not isinstance(qc, PandasQueryCompiler): warnings.warn("Defaulting to Modin core implementation") ret...
93
io.py
Python
modin/experimental/core/execution/unidist/implementations/pandas_on_unidist/io/io.py
193505fdf0c984743397ba3df56262f30aee13a8
modin
4
250,109
35
11
35
186
8
0
57
374
test_expiry_logic
Require types in tests.storage. (#14646) Adds missing type hints to `tests.storage` package and does not allow untyped definitions.
https://github.com/matrix-org/synapse.git
def test_expiry_logic(self) -> None: self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[ "1" ] = 100000 self.event_creator_handler._rooms_to_exclude_from_dummy_event_insertion[ "2" ] = 200000 self.event_creator_handler._rooms_...
114
test_cleanup_extrems.py
Python
tests/storage/test_cleanup_extrems.py
3ac412b4e2f8c5ba11dc962b8a9d871c1efdce9b
synapse
1
7,174
20
12
9
93
12
0
23
98
get_metrics
feat: Added model type GBM (LightGBM tree learner), as an alternative to ECD (#2027)
https://github.com/ludwig-ai/ludwig.git
def get_metrics(self): all_of_metrics = {} for of_name, of_obj in self.output_features.items(): all_of_metrics[of_name] = of_obj.get_metrics() all_of_metrics[COMBINED] = { LOSS: get_scalar_from_ludwig_metric(self.eval_loss_metric) + get_scalar_from_lu...
57
base.py
Python
ludwig/models/base.py
aa0c63bf2ed825eb3ca8eff8a002d5ccbe395173
ludwig
2
283,270
19
13
16
105
13
0
20
67
get_user_timezone
Updating some names (#1575) * quick econ fix * black * keys and feature flags * terminal name :eyes: * some more replacements * some more replacements * edit pyproject * gst -> openbb * add example portfolios back to git * Update api from gst * sorry. skipping some tests * another rou...
https://github.com/OpenBB-finance/OpenBBTerminal.git
def get_user_timezone() -> str: filename = os.path.join( os.path.dirname(os.path.abspath(__file__)), "timezone.openbb", ) if os.path.isfile(filename): with open(filename) as f: return f.read() return ""
60
helper_funcs.py
Python
openbb_terminal/helper_funcs.py
b71abcfbf4d7e8ac1855522aff0378e13c8b5362
OpenBBTerminal
2
297,814
33
17
20
247
9
0
46
278
extra_state_attributes
String formatting and max line length - Part 1 (#84390) Co-authored-by: Erik Montnemery <erik@montnemery.com>
https://github.com/home-assistant/core.git
def extra_state_attributes(self): if self._attr_native_value is None or self._attrs is None: return None if ( self.entity_description.key == SENSOR_RANDOM_RECORD_TYPE and self._attr_native_value is not None ): return { "ca...
118
sensor.py
Python
homeassistant/components/discogs/sensor.py
b0cee0bc46cbd7efe0e6421da18d91595c7a25ad
core
5
46,884
26
10
13
77
11
0
30
110
parse_time_mapped_ti_count
Expand mapped tasks at DagRun.Veriy_integrity (#22679) Create the necessary task instances for a mapped task at dagrun.verify_integrity Co-authored-by: Ash Berlin-Taylor <ash@apache.org>
https://github.com/apache/airflow.git
def parse_time_mapped_ti_count(self) -> Optional[int]: total = 0 for value in self._get_expansion_kwargs().values(): if not isinstance(value, MAPPABLE_LITERAL_TYPES): # None literal type encountered, so give up return None total += len(va...
46
mappedoperator.py
Python
airflow/models/mappedoperator.py
91832a42d8124b040073481fd93c54e9e64c2609
airflow
3
312,477
23
13
11
102
11
0
25
139
_async_cancel_websocket_loop
Remove unnecessary `TYPE_CHECKING` declarations in SimpliSafe (#65750)
https://github.com/home-assistant/core.git
async def _async_cancel_websocket_loop(self) -> None: if self._websocket_reconnect_task: self._websocket_reconnect_task.cancel() try: await self._websocket_reconnect_task except asyncio.CancelledError: LOGGER.debug("Websocket reconnect...
58
__init__.py
Python
homeassistant/components/simplisafe/__init__.py
fbe4d4272912a2ac5e2783b90eb75c90a6d7e6f5
core
3
120,940
34
16
8
206
25
0
48
56
_complex_truncated_normal
[x64] make nn_test pass with strict dtype promotion
https://github.com/google/jax.git
def _complex_truncated_normal(key, upper, shape, dtype): key_r, key_theta = random.split(key) real_dtype = np.array(0, dtype).real.dtype dtype = dtypes._to_complex_dtype(real_dtype) t = (1 - jnp.exp(jnp.array(-(upper ** 2), dtype))) * random.uniform(key_r, shape, real_dtype).astype(dtype) r = jnp.sqrt(-jnp...
134
initializers.py
Python
jax/_src/nn/initializers.py
80d814ab8933a29a82e5645490128e1412e01891
jax
1
298,130
33
15
16
149
19
0
42
215
_update_data
Improve DataUpdateCoordinator typing in integrations (2) (#84656)
https://github.com/home-assistant/core.git
def _update_data(self) -> CanaryData: locations_by_id: dict[str, Location] = {} readings_by_device_id: dict[str, ValuesView[Reading]] = {} for location in self.canary.get_locations(): location_id = location.location_id locations_by_id[location_id] = location ...
95
coordinator.py
Python
homeassistant/components/canary/coordinator.py
06db5476e4e687f1034196eb04c5cad3cf6861ad
core
4