ast_errors
stringlengths
0
3.2k
d_id
int64
44
121k
id
int64
70
338k
n_whitespaces
int64
3
14k
path
stringlengths
8
134
n_words
int64
4
4.82k
n_identifiers
int64
1
131
random_cut
stringlengths
16
15.8k
commit_message
stringlengths
2
15.3k
fun_name
stringlengths
1
84
commit_id
stringlengths
40
40
repo
stringlengths
3
28
file_name
stringlengths
5
79
ast_levels
int64
6
31
nloc
int64
1
548
url
stringlengths
31
59
complexity
int64
1
66
token_counts
int64
6
2.13k
n_ast_errors
int64
0
28
vocab_size
int64
4
1.11k
n_ast_nodes
int64
15
19.2k
language
stringclasses
1 value
documentation
dict
code
stringlengths
101
62.2k
40,113
167,770
101
pandas/core/groupby/groupby.py
18
13
def rolling(self, *args, **kwargs) -> RollingGroupby: from pandas.core.window import RollingGroupby
TYP: more return annotations in core/ (#47618) * TYP: more return annotations in core/ * from __future__ import annotations * more __future__
rolling
f65417656ba8c59438d832b6e2a431f78d40c21c
pandas
groupby.py
9
12
https://github.com/pandas-dev/pandas.git
1
48
0
17
71
Python
{ "docstring": "\n Return a rolling grouper, providing rolling functionality per group.\n ", "language": "en", "n_whitespaces": 24, "n_words": 9, "vocab_size": 8 }
def rolling(self, *args, **kwargs) -> RollingGroupby: from pandas.core.window import RollingGroupby return RollingGroupby( self._selected_obj, *args, _grouper=self.grouper, _as_index=self.as_index, **kwargs, )
42,064
176,730
417
networkx/generators/degree_seq.py
179
35
def expected_degree_graph(w, seed=None, selfloops=True): r n = len(w) G = nx.empty_graph(n) # If there are no nodes are no edges in the graph, return the empty graph. if n == 0 or max(w) == 0: return G rho = 1 / sum(w) # Sort the weights in decreasing order. The original order of t...
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>
expected_degree_graph
2a05ccdb07cff88e56661dee8a9271859354027f
networkx
degree_seq.py
17
100
https://github.com/networkx/networkx.git
13
240
0
97
375
Python
{ "docstring": "Returns a random graph with given expected degrees.\n\n Given a sequence of expected degrees $W=(w_0,w_1,\\ldots,w_{n-1})$\n of length $n$ this algorithm assigns an edge between node $u$ and\n node $v$ with probability\n\n .. math::\n\n p_{uv} = \\frac{w_u w_v}{\\sum_k w_k} .\n\n ...
def expected_degree_graph(w, seed=None, selfloops=True): r n = len(w) G = nx.empty_graph(n) # If there are no nodes are no edges in the graph, return the empty graph. if n == 0 or max(w) == 0: return G rho = 1 / sum(w) # Sort the weights in decreasing order. The original order of t...
2,897
19,151
208
mlflow/models/evaluation/base.py
49
22
def save(self, path): os.makedirs(path,
Improve evaluation api (#5256) * init Signed-off-by: Weichen Xu <weichen.xu@databricks.com> * update Signed-off-by: Weichen Xu <weichen.xu@databricks.com> * update Signed-off-by: Weichen Xu <weichen.xu@databricks.com> * update doc Signed-off-by: Weichen Xu <weichen.xu@databricks.com> * update d...
save
4c58179509e6f6047789efb0a95c2b0e20cb6c8f
mlflow
base.py
13
17
https://github.com/mlflow/mlflow.git
3
153
0
36
253
Python
{ "docstring": "Write the evaluation results to the specified local filesystem path", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 9 }
def save(self, path): os.makedirs(path, exist_ok=True) with open(os.path.join(path, "metrics.json"), "w") as fp: json.dump(self.metrics, fp) artifacts_metadata = { artifact_name: { "uri": artifact.uri, "class_name": _get_fully_qua...
18,592
89,933
154
tests/sentry/integrations/slack/test_message_builder.py
51
25
def test_build_group_generic_issue_attachment(self): event = self.store_event( data={"message": "Hello world", "level": "error"}, project_id=self.project.id ) event = event.for_group(event.groups[0]) occurrence = self.build_occurrence(level="info") occurrence...
feat(integrations): Support generic issue type alerts (#42110) Add support for issue alerting integrations that use the message builder (Slack and MSTeams) for generic issue types. Preview text for Slack alert: <img width="350" alt="Screen Shot 2022-12-08 at 4 07 16 PM" src="https://user-images.githubuserconte...
test_build_group_generic_issue_attachment
3255fa4ebb9fbc1df6bb063c0eb77a0298ca8f72
sentry
test_message_builder.py
12
14
https://github.com/getsentry/sentry.git
1
137
0
38
249
Python
{ "docstring": "Test that a generic issue type's Slack alert contains the expected values", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 12 }
def test_build_group_generic_issue_attachment(self): event = self.store_event( data={"message": "Hello world", "level": "error"}, project_id=self.project.id ) event = event.for_group(event.groups[0]) occurrence = self.build_occurrence(level="info") occurrence...
42,906
179,114
127
xlib/image/ImageProcessor.py
45
14
def apply(self, func, mask=None) -> 'ImageProcessor': img = orig_img = self._img img = func(img).astype(orig_img.dtype) if img.ndim != 4: raise Exception('func used in ImageProcessor.apply changed format of image') if mask is not None:
ImageProcessor.py refactoring
apply
b3bc4e734528d3b186c3a38a6e73e106c3555cc7
DeepFaceLive
ImageProcessor.py
13
21
https://github.com/iperov/DeepFaceLive.git
3
82
0
34
137
Python
{ "docstring": "\n apply your own function on internal image\n\n image has NHWC format. Do not change format, but dims can be changed.\n\n func callable (img) -> img\n\n example:\n\n .apply( lambda img: img-[102,127,63] )\n ", "language": "en", "n_whitespaces": 79, ...
def apply(self, func, mask=None) -> 'ImageProcessor': img = orig_img = self._img img = func(img).astype(orig_img.dtype) if img.ndim != 4: raise Exception('func used in ImageProcessor.apply changed format of image') if mask is not None: mask = self._check...
7,073
39,007
110
recommenders/models/rbm/rbm.py
38
17
def predict(self, x): # start the timer self.timer.start() v_, _ = self
removed time from returning args
predict
843dba903757d592f7703a83ebd75eb3ffb46f6f
recommenders
rbm.py
12
7
https://github.com/microsoft/recommenders.git
1
65
0
30
111
Python
{ "docstring": "Returns the inferred ratings. This method is similar to recommend_k_items() with the\n exceptions that it returns all the inferred ratings\n\n Basic mechanics:\n\n The method samples new ratings from the learned joint distribution, together with\n their probabilities. The i...
def predict(self, x): # start the timer self.timer.start() v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities vp = self.sess.run(v_, feed_dict={self.vu: x}) # stop the timer self.timer.stop() log.info("Done infere...
55,394
218,569
74
python3.10.4/Lib/json/decoder.py
24
11
def raw_decode(self, s, idx=0): try: obj, end = self.scan_once(s, idx) except StopIteration as err: raise JSONDecodeError("Expecting value", s, err.val
add python 3.10.4 for windows
raw_decode
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
decoder.py
11
6
https://github.com/XX-net/XX-Net.git
2
48
0
21
76
Python
{ "docstring": "Decode a JSON document from ``s`` (a ``str`` beginning with\n a JSON document) and return a 2-tuple of the Python\n representation and the index in ``s`` where the document ended.\n\n This can be used to decode a JSON document from a string that may\n have extraneous data a...
def raw_decode(self, s, idx=0): try: obj, end = self.scan_once(s, idx) except StopIteration as err: raise JSONDecodeError("Expecting value", s, err.value) from None return obj, end
@not_implemented_for("multigraph") @not_implemented_for("directed")
41,965
176,561
45
networkx/algorithms/bridges.py
14
7
def has_bridges(G, root=None): try: next(bridges
Improve bridges documentation (#5519) * Fix bridges documentation * Revert source code modification * Revert raise errors for multigraphs
has_bridges
aa1f40a93a882db304e9a06c2a11d93b2532d80a
networkx
bridges.py
11
7
https://github.com/networkx/networkx.git
2
28
1
13
70
Python
{ "docstring": "Decide whether a graph has any bridges.\n\n A *bridge* in a graph is an edge whose removal causes the number of\n connected components of the graph to increase.\n\n Parameters\n ----------\n G : undirected graph\n\n root : node (optional)\n A node in the graph `G`. If specified...
def has_bridges(G, root=None): try: next(bridges(G)) except StopIteration: return False else: return True @not_implemented_for("multigraph") @not_implemented_for("directed")
12,520
61,338
112
.venv/lib/python3.8/site-packages/pip/_internal/utils/wheel.py
65
13
def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message path = f"{dist_info_dir}/WHEEL" # Zip file path separators must be / wheel_contents = read_wheel_metadata_file(source, path) try: wheel_text = wheel_contents.decode() except UnicodeDecodeError as e: ...
upd; format
wheel_metadata
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
wheel.py
12
8
https://github.com/jindongwang/transferlearning.git
2
49
0
57
103
Python
{ "docstring": "Return the WHEEL metadata of an extracted wheel, if possible.\n Otherwise, raise UnsupportedWheel.\n ", "language": "en", "n_whitespaces": 19, "n_words": 13, "vocab_size": 13 }
def wheel_metadata(source, dist_info_dir): # type: (ZipFile, str) -> Message path = f"{dist_info_dir}/WHEEL" # Zip file path separators must be / wheel_contents = read_wheel_metadata_file(source, path) try: wheel_text = wheel_contents.decode() except UnicodeDecodeError as e: ...
21,852
104,416
172
src/datasets/table.py
40
14
def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_colu
Update docs to new frontend/UI (#3690) * WIP: update docs to new UI * make style * Rm unused * inject_arrow_table_documentation __annotations__ * hasattr(arrow_table_method, "__annotations__") * Update task_template.rst * Codeblock PT-TF-SPLIT * Convert loading scripts * Convert docs to mdx ...
remove_column
e35be138148333078284b942ccc9ed7b1d826f97
datasets
table.py
16
12
https://github.com/huggingface/datasets.git
4
96
0
29
145
Python
{ "docstring": "\n Create new Table with the indicated column removed.\n\n Args:\n i (:obj:`int`):\n Index of column to remove.\n\n Returns:\n :class:`datasets.table.Table`:\n New table without the column.\n ", "language": "en", "n_wh...
def remove_column(self, i, *args, **kwargs): table = self.table.remove_column(i, *args, **kwargs) name = self.table.column_names[i] blocks = [] for tables in self.blocks: blocks.append( [ t.remove_column(t.column_names.index(name),...
77,897
264,886
53
netbox/dcim/tests/test_models.py
14
18
def test_cable_cannot_terminate_to_a_wireless_interface(self): wireless_interface = Interface(device=self.device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A) cable = Cable(a_terminations=[self.interface2], b_terminations=[wireless_interface]) with self.assertRaises(ValidationErro...
Update Cable instantiations to match new signature
test_cable_cannot_terminate_to_a_wireless_interface
3a461d02793e6f9d41c2b1a92647e691de1abaac
netbox
test_models.py
11
5
https://github.com/netbox-community/netbox.git
1
57
0
13
95
Python
{ "docstring": "\n A cable cannot terminate to a wireless interface\n ", "language": "en", "n_whitespaces": 23, "n_words": 8, "vocab_size": 8 }
def test_cable_cannot_terminate_to_a_wireless_interface(self): wireless_interface = Interface(device=self.device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A) cable = Cable(a_terminations=[self.interface2], b_terminations=[wireless_interface]) with self.assertRaises(ValidationErro...
50,917
204,838
114
django/db/backends/base/creation.py
43
7
def get_test_db_clone_settings(self, suffix): # When this function is called, the test database has been created # already and its name has been copied to
Refs #33476 -- Reformatted code with Black.
get_test_db_clone_settings
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
creation.py
11
6
https://github.com/django/django.git
1
35
0
38
63
Python
{ "docstring": "\n Return a modified connection settings dict for the n-th clone of a DB.\n ", "language": "en", "n_whitespaces": 28, "n_words": 13, "vocab_size": 12 }
def get_test_db_clone_settings(self, suffix): # When this function is called, the test database has been created # already and its name has been copied to settings_dict['NAME'] so # we don't need to call _get_test_db_name. orig_settings_dict = self.connection.settings_dict ...
55,005
217,907
52
python3.10.4/Lib/imaplib.py
17
10
def open(self, host='', port=IMAP4_PORT, timeout=None): self.host = host self.port = port self.sock = self._create_socket(timeout) self.file = self.sock.makefile('rb')
add python 3.10.4 for windows
open
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
imaplib.py
9
5
https://github.com/XX-net/XX-Net.git
1
50
0
14
83
Python
{ "docstring": "Setup connection to remote server on \"host:port\"\n (default: localhost:standard IMAP4 port).\n This connection will be used by the routines:\n read, readline, send, shutdown.\n ", "language": "en", "n_whitespaces": 59, "n_words": 23, "vocab_size": 22 }
def open(self, host='', port=IMAP4_PORT, timeout=None): self.host = host self.port = port self.sock = self._create_socket(timeout) self.file = self.sock.makefile('rb')
44,257
183,574
42
src/textual/_terminal_features.py
10
7
def synchronized_output_end_sequence(self) -> str: if self.synchronised_output: return
[terminal buffering] Address PR feedback
synchronized_output_end_sequence
7f27e70440c177b2a047b7f74a78ed5cd5b4b596
textual
_terminal_features.py
10
13
https://github.com/Textualize/textual.git
2
25
0
9
45
Python
{ "docstring": "\n Returns the ANSI sequence that we should send to the terminal to tell it that\n it should stop buffering the content we're about to send.\n If the terminal doesn't seem to support synchronised updates the string will be empty.\n\n Returns:\n str: the \"synchro...
def synchronized_output_end_sequence(self) -> str: if self.synchronised_output: return TERMINAL_MODES_ANSI_SEQUENCES[Mode.SynchronizedOutput]["end_sync"] return ""
39,253
162,681
98
frequency_response.py
42
23
def _band_penalty_coefficients(self, fc, q, gain, filter_frs): ref_frs = biquad.digital_coeffs(self.frequenc
Improved quality regularization to a point where it works well. 10 kHz to 20 kHz is RMSE is calculated from the average levels. Split neo PEQ notebook by band and Q.
_band_penalty_coefficients
f6021faf2a8e62f88a8d6979ce812dcb71133a8f
AutoEq
frequency_response.py
12
8
https://github.com/jaakkopasanen/AutoEq.git
1
121
0
34
176
Python
{ "docstring": "Calculates penalty coefficients for filters if their transition bands extend beyond Nyquist frequency\n\n The calculation is based on ratio of frequency response integrals between 44.1 kHz and 192 kHz\n\n Args:\n fc: Filter center frequencies, 1-D array\n q: Filter ...
def _band_penalty_coefficients(self, fc, q, gain, filter_frs): ref_frs = biquad.digital_coeffs(self.frequency, 192e3, *biquad.peaking(fc, q, gain, fs=192e3)) est_sums = np.sum(filter_frs, axis=1) ref_sums = np.sum(ref_frs, axis=1) penalties = np.zeros((len(fc),)) mask = ...
76,664
261,153
201
sklearn/ensemble/tests/test_voting.py
104
22
def test_predict_on_toy_problem(global_random_seed): clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array( [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4...
TST use global_random_seed in sklearn/ensemble/tests/test_voting.py (#24282) Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com>
test_predict_on_toy_problem
02b04cb3ecfc5fce1f627281c312753f3b4b8494
scikit-learn
test_voting.py
12
23
https://github.com/scikit-learn/scikit-learn.git
1
357
0
48
469
Python
{ "docstring": "Manually check predicted class labels for toy dataset.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def test_predict_on_toy_problem(global_random_seed): clf1 = LogisticRegression(random_state=global_random_seed) clf2 = RandomForestClassifier(n_estimators=10, random_state=global_random_seed) clf3 = GaussianNB() X = np.array( [[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4...
76,257
260,448
29
sklearn/feature_extraction/_dict_vectorizer.py
8
7
def fit_transform(self, X, y=None): self._validate_params() return self._tran
MAINT Param validation for Dictvectorizer (#23820)
fit_transform
5a850eb044ca07f1f3bcb1b284116d6f2d37df1b
scikit-learn
_dict_vectorizer.py
8
3
https://github.com/scikit-learn/scikit-learn.git
1
28
0
8
45
Python
{ "docstring": "Learn a list of feature name -> indices mappings and transform X.\n\n Like fit(X) followed by transform(X), but does not require\n materializing X in memory.\n\n Parameters\n ----------\n X : Mapping or iterable over Mappings\n Dict(s) or Mapping(s) from f...
def fit_transform(self, X, y=None): self._validate_params() return self._transform(X, fitting=True)
117,565
321,150
761
qutebrowser/browser/webengine/webenginetab.py
125
54
def _on_feature_permission_requested(self, url, feature): page = self._widget.page() grant_permission = functools.partial( page.setFeaturePermission, url, feature, QWebEnginePage.PermissionPolicy.PermissionGrantedByUser) deny_permission = functools.partial( ...
Run scripts/dev/rewrite_enums.py
_on_feature_permission_requested
0877fb0d78635692e481c8bde224fac5ad0dd430
qutebrowser
webenginetab.py
14
44
https://github.com/qutebrowser/qutebrowser.git
10
301
0
84
470
Python
{ "docstring": "Ask the user for approval for geolocation/media/etc..", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 6 }
def _on_feature_permission_requested(self, url, feature): page = self._widget.page() grant_permission = functools.partial( page.setFeaturePermission, url, feature, QWebEnginePage.PermissionPolicy.PermissionGrantedByUser) deny_permission = functools.partial( ...
56,684
222,643
784
python3.10.4/Lib/distutils/command/bdist_msi.py
167
20
def add_find_python(self): start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_reg = "python.machine." + ver user_reg = "python.user." + ver machine_prop = "PYTHON.MACHINE." + ver ...
add python 3.10.4 for windows
add_find_python
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
bdist_msi.py
14
42
https://github.com/XX-net/XX-Net.git
3
304
0
86
469
Python
{ "docstring": "Adds code to the installer to compute the location of Python.\n\n Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the\n registry for each version of Python.\n\n Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined,\n else from PYTHON.MACHIN...
def add_find_python(self): start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_reg = "python.machine." + ver user_reg = "python.user." + ver machine_prop = "PYTHON.MACHINE." + ver ...
12,781
61,961
45
.venv/lib/python3.8/site-packages/pip/_vendor/distlib/database.py
13
8
def write_exports(self, exports): rf = self
upd; format
write_exports
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
database.py
11
4
https://github.com/jindongwang/transferlearning.git
1
32
0
13
57
Python
{ "docstring": "\n Write a dictionary of exports to a file in .ini format.\n :param exports: A dictionary of exports, mapping an export category to\n a list of :class:`ExportEntry` instances describing the\n individual export entries.\n ", "language...
def write_exports(self, exports): rf = self.get_distinfo_file(EXPORTS_FILENAME) with open(rf, 'w') as f: write_exports(exports, f)
78,856
267,337
685
lib/ansible/executor/task_executor.py
191
41
def _get_action_handler_with_module_context(self, connection, templar): module_collection, separator, module_name = self._task.action.rpartition(".") module_prefix = module_name.split('_')[0] if module_collection: # For network modules, which look for one action plugin per p...
Add toggle to fix module_defaults with module-as-redirected-action on a per-module basis (#77265) * If there is a platform specific handler, prefer the resolved module over the resolved action when loading module_defaults Add a toggle for action plugins to prefer the resolved module when loading module_defaults ...
_get_action_handler_with_module_context
621e782ed0c119d2c84124d006fdf253c082449a
ansible
task_executor.py
15
38
https://github.com/ansible/ansible.git
8
264
0
117
420
Python
{ "docstring": "\n Returns the correct action plugin to handle the requestion task action and the module context\n ", "language": "en", "n_whitespaces": 30, "n_words": 15, "vocab_size": 12 }
def _get_action_handler_with_module_context(self, connection, templar): module_collection, separator, module_name = self._task.action.rpartition(".") module_prefix = module_name.split('_')[0] if module_collection: # For network modules, which look for one action plugin per p...
77,241
262,500
161
TTS/tts/layers/losses.py
61
18
def forward(self, y_hat, y, length): mask = sequence_mask(sequence_length=length, max_len=y.size(1)).unsqueeze(2) y_norm = sample_wise_min_max(y, mask) y_hat_norm = sample_wise_min_max(y_hat, mask) ssim_loss = self.loss_func((y_norm * mask).unsqueeze(1), (y_hat_norm * mask).unsq...
Fix SSIM loss
forward
c17ff17a18f21be60c6916714ac8afd87d4441df
TTS
losses.py
13
12
https://github.com/coqui-ai/TTS.git
3
122
0
40
203
Python
{ "docstring": "\n Args:\n y_hat (tensor): model prediction values.\n y (tensor): target values.\n length (tensor): length of each sample in a batch for masking.\n\n Shapes:\n y_hat: B x T X D\n y: B x T x D\n length: B\n\n Return...
def forward(self, y_hat, y, length): mask = sequence_mask(sequence_length=length, max_len=y.size(1)).unsqueeze(2) y_norm = sample_wise_min_max(y, mask) y_hat_norm = sample_wise_min_max(y_hat, mask) ssim_loss = self.loss_func((y_norm * mask).unsqueeze(1), (y_hat_norm * mask).unsq...
50,200
202,989
67
django/core/management/__init__.py
31
15
def get_commands(): commands = {name: 'django.core' for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(apps.get_app_configs()): path = os.path.join(app_config.path, 'management') commands.update({n
Refs #32355 -- Removed unnecessary list() calls before reversed() on dictviews. Dict and dictviews are iterable in reversed insertion order using reversed() in Python 3.8+.
get_commands
7346c288e307e1821e3ceb757d686c9bd879389c
django
__init__.py
13
8
https://github.com/django/django.git
5
77
0
22
126
Python
{ "docstring": "\n Return a dictionary mapping command names to their callback applications.\n\n Look for a management.commands package in django.core, and in each\n installed application -- if a commands package exists, register all\n commands in that package.\n\n Core commands are always included. If...
def get_commands(): commands = {name: 'django.core' for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(apps.get_app_configs()): path = os.path.join(app_config.path, 'management') commands.update({name: app_config.name...
57,004
223,611
193
python3.10.4/Lib/email/_parseaddr.py
35
13
def getphraselist(self): plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': ...
add python 3.10.4 for windows
getphraselist
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_parseaddr.py
15
14
https://github.com/XX-net/XX-Net.git
6
119
0
26
196
Python
{ "docstring": "Parse a sequence of RFC 2822 phrases.\n\n A phrase is a sequence of words, which are in turn either RFC 2822\n atoms or quoted-strings. Phrases are canonicalized by squeezing all\n runs of continuous whitespace into one space.\n ", "language": "en", "n_whitespaces": 66...
def getphraselist(self): plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': ...
23,720
109,724
363
lib/matplotlib/axes/_secondary_axes.py
142
19
def set_location(self, location): # This puts the rectangle
Clean up code in SecondaryAxis
set_location
8387676bc049d7b3e071846730c632e6ced137ed
matplotlib
_secondary_axes.py
15
17
https://github.com/matplotlib/matplotlib.git
5
130
0
97
230
Python
{ "docstring": "\n Set the vertical or horizontal location of the axes in\n parent-normalized coordinates.\n\n Parameters\n ----------\n location : {'top', 'bottom', 'left', 'right'} or float\n The position to put the secondary axis. Strings can be 'top' or\n ...
def set_location(self, location): # This puts the rectangle into figure-relative coordinates. if isinstance(location, str): _api.check_in_list(self._locstrings, location=location) self._pos = 1. if location in ('top', 'right') else 0. elif isinstance(location, n...
35,383
153,347
149
modin/core/execution/ray/implementations/pandas_on_ray/partitioning/partition.py
24
14
def length(self): if self._length_cache is None: if len(self.call_queue): self.drain_call_queue() else: self._length_cache, self._width_cache = _get_index_and_columns.remote( self.oid
REFACTOR-#4251: define public interfaces in `modin.core.execution.ray` module (#3868) Signed-off-by: Anatoly Myachev <anatoly.myachev@intel.com>
length
e7cb2e82f8b9c7a68f82abdd3b6011d661230b7e
modin
partition.py
14
11
https://github.com/modin-project/modin.git
4
70
0
19
115
Python
{ "docstring": "\n Get the length of the object wrapped by this partition.\n\n Returns\n -------\n int\n The length of the object.\n ", "language": "en", "n_whitespaces": 65, "n_words": 18, "vocab_size": 14 }
def length(self): if self._length_cache is None: if len(self.call_queue): self.drain_call_queue() else: self._length_cache, self._width_cache = _get_index_and_columns.remote( self.oid ) if isinstance(sel...
47,480
195,939
44
sympy/polys/densearith.py
25
8
def dmp_l2_norm_squared(f, u, K): if not u: return dup_l2_norm_squared(f, K) v = u - 1 return s
Add `l2_norm_squared` methods.
dmp_l2_norm_squared
0f6dde45a1c75b02c208323574bdb09b8536e3e4
sympy
densearith.py
10
5
https://github.com/sympy/sympy.git
3
44
0
23
67
Python
{ "docstring": "\n Returns squared l2 norm of a polynomial in ``K[X]``.\n\n Examples\n ========\n\n >>> from sympy.polys import ring, ZZ\n >>> R, x,y = ring(\"x,y\", ZZ)\n\n >>> R.dmp_l2_norm_squared(2*x*y - x - 3)\n 14\n\n ", "language": "en", "n_whitespaces": 55, "n_words": 30, "voca...
def dmp_l2_norm_squared(f, u, K): if not u: return dup_l2_norm_squared(f, K) v = u - 1 return sum([ dmp_l2_norm_squared(c, v, K) for c in f ])
78,551
266,740
72
test/lib/ansible_test/_internal/commands/integration/cloud/__init__.py
40
9
def cloud_filter(args, targets): # type: (IntegrationConfig, t.Tuple[IntegrationTarget, ...]) -> t.List[str] if args.metadata.cloud_config is not None: return [] # cloud filter already performed prior to delegation exclude = [] # type: t.List[str] for provider in get_cloud_providers(
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...
cloud_filter
a06fa496d3f837cca3c437ab6e9858525633d147
ansible
__init__.py
9
7
https://github.com/ansible/ansible.git
3
45
0
32
74
Python
{ "docstring": "Return a list of target names to exclude based on the given targets.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 13 }
def cloud_filter(args, targets): # type: (IntegrationConfig, t.Tuple[IntegrationTarget, ...]) -> t.List[str] if args.metadata.cloud_config is not None: return [] # cloud filter already performed prior to delegation exclude = [] # type: t.List[str] for provider in get_cloud_providers(args, ...
53,805
215,087
252
tests/pytests/unit/modules/test_aixpkg.py
64
19
def test_upgrade_available_none(): chk_upgrade_out = ( "Last metadata ex
Working tests for install
test_upgrade_available_none
f1c37893caf90738288e789c3233ab934630254f
salt
test_aixpkg.py
16
21
https://github.com/saltstack/salt.git
1
124
0
56
217
Python
{ "docstring": "\n test upgrade available where a valid upgrade is not available\n ", "language": "en", "n_whitespaces": 17, "n_words": 10, "vocab_size": 8 }
def test_upgrade_available_none(): chk_upgrade_out = ( "Last metadata expiration check: 22:5:48 ago on Mon Dec 6 19:26:36 EST 2021." ) dnf_call = MagicMock(return_value={"retcode": 100, "stdout": chk_upgrade_out}) version_mock = MagicMock(return_value="6.6-2") with patch("pathlib.Pat...
18,273
87,293
373
tests/sentry/event_manager/test_event_manager.py
56
27
def test_too_many_boosted_releases_do_not_boost_anymore(self): release_2 = Release.get_or_create(
feat(ds): Limit the amount of boosted releases to 10 (#40501) Limits amount of boosted releases to 10 releases otherwise do not add any more releases to hash set of listed releases
test_too_many_boosted_releases_do_not_boost_anymore
361b7f444a53cc34cad8ddc378d125b7027d96df
sentry
test_event_manager.py
14
27
https://github.com/getsentry/sentry.git
2
185
0
46
342
Python
{ "docstring": "\n This test tests the case when we have already too many boosted releases, in this case we want to skip the\n boosting of anymore releases\n ", "language": "en", "n_whitespaces": 47, "n_words": 25, "vocab_size": 22 }
def test_too_many_boosted_releases_do_not_boost_anymore(self): release_2 = Release.get_or_create(self.project, "2.0") release_3 = Release.get_or_create(self.project, "3.0") for release_id in (self.release.id, release_2.id): self.redis_client.set(f"ds::p:{self.project.id}:r:...
41,745
176,175
175
networkx/algorithms/link_analysis/hits_alg.py
90
39
def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): import numpy as np import scipy as sp imp
Use scipy.sparse array datastructure (#5139) * Step 1: use sparse arrays in nx.to_scipy_sparse_matrix. Seems like a reasonable place to start. nx.to_scipy_sparse_matrix is one of the primary interfaces to scipy.sparse from within NetworkX. * 1: Use np.outer instead of mult col/row vectors Fix two instances ...
hits
5dfd57af2a141a013ae3753e160180b82bec9469
networkx
hits_alg.py
15
20
https://github.com/networkx/networkx.git
4
226
0
56
339
Python
{ "docstring": "Returns HITS hubs and authorities values for nodes.\n\n The HITS algorithm computes two numbers for a node.\n Authorities estimates the node value based on the incoming links.\n Hubs estimates the node value based on outgoing links.\n\n Parameters\n ----------\n G : graph\n A Ne...
def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): import numpy as np import scipy as sp import scipy.sparse.linalg # call as sp.sparse.linalg if len(G) == 0: return {}, {} A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float) if nstart is None: u, s...
8,731
45,823
87
airflow/providers/ftp/hooks/ftp.py
22
10
def test_connection(self) -> Tuple[bool, str]: try: conn = se
Updates FTPHook provider to have test_connection (#21997) * Updates FTP provider to have test_connection Co-authored-by: eladkal <45845474+eladkal@users.noreply.github.com>
test_connection
26e8d6d7664bbaae717438bdb41766550ff57e4f
airflow
ftp.py
11
8
https://github.com/apache/airflow.git
2
41
0
21
71
Python
{ "docstring": "Test the FTP connection by calling path with directory", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_connection(self) -> Tuple[bool, str]: try: conn = self.get_conn() conn.pwd return True, "Connection successfully tested" except Exception as e: return False, str(e)
85,397
285,727
352
openbb_terminal/cryptocurrency/crypto_controller.py
74
28
def call_price(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="price", description=, ) parser.add_argument( "-s", "--symbol", ...
Integrate live feeds from Pyth (#2178) * added dependency * added pyth models * dependencies * docs * some improvements to this pyth command (#2433) * some improvements to this pyth command * minor improv * dependencies * tests Co-authored-by: DidierRLopes <dro.lopes@campus.fct.unl.pt>; COli...
call_price
1661ddd44044c637526e9a1e812e7c1863be35fc
OpenBBTerminal
crypto_controller.py
13
26
https://github.com/OpenBB-finance/OpenBBTerminal.git
5
131
0
64
221
Python
{ "docstring": "Process price commandDisplay price and interval of confidence in real-time. [Source: Pyth]", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 11 }
def call_price(self, other_args): parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="price", description=, ) parser.add_argument( "-s", "--symbol", ...
21,793
104,238
316
src/datasets/utils/py_utils.py
182
38
def _single_map_nested(args): function, data_struct, types, rank, disable_tqdm, desc = args # Singleton first to spare some computation if not isinstance(data_struct, dict) and not isinstance(data_struct, types): return function(data_struct) # Reduce logging to keep things readable in mul...
Better TQDM output (#3654) * Show progress bar when generating examples * Consistent utils.is_progress_bar_enabled calls * Fix tqdm in notebook * Add missing params to DatasetDict.map * Specify total in tqdm progress bar in map * Fix total computation * Small fix * Add desc to map_nested * Add ...
_single_map_nested
6ed6ac9448311930557810383d2cfd4fe6aae269
datasets
py_utils.py
13
21
https://github.com/huggingface/datasets.git
17
259
0
107
398
Python
{ "docstring": "Apply a function recursively to each element of a nested data struct.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 11 }
def _single_map_nested(args): function, data_struct, types, rank, disable_tqdm, desc = args # Singleton first to spare some computation if not isinstance(data_struct, dict) and not isinstance(data_struct, types): return function(data_struct) # Reduce logging to keep things readable in mul...
51,930
207,334
99
tests/admin_scripts/tests.py
35
11
def test_unified(self):
Refs #33476 -- Reformatted code with Black.
test_unified
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
11
9
https://github.com/django/django.git
1
77
0
26
140
Python
{ "docstring": "--output=unified emits settings diff in unified mode.", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 7 }
def test_unified(self): self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") ...
31,793
139,848
18
python/ray/runtime_context.py
4
5
def runtime_env(self):
[runtime env] runtime env inheritance refactor (#24538) * [runtime env] runtime env inheritance refactor (#22244) Runtime Environments is already GA in Ray 1.6.0. The latest doc is [here](https://docs.ray.io/en/master/ray-core/handling-dependencies.html#runtime-environments). And now, we already supported a [inheri...
runtime_env
eb2692cb32bb1747e312d5b20e976d7a879c9588
ray
runtime_context.py
9
2
https://github.com/ray-project/ray.git
1
17
0
4
31
Python
{ "docstring": "Get the runtime env of the current job/worker.\n\n If this API is called in driver or ray client, returns the job level runtime\n env.\n If this API is called in workers/actors, returns the worker level runtime env.\n\n Returns:\n A new ray.runtime_env.RuntimeEnv...
def runtime_env(self): return RuntimeEnv.deserialize(self._get_runtime_env_string())
45,770
187,407
65
src/streamlink/stream/dash.py
19
7
def sleeper(self, duration): s = time() yield time_to_sleep = duration - (time() - s) if time_to_sleep > 0: s
stream.dash: update DASHStreamWorker.iter_segments - Refactor DASHStreamWorker.iter_segments() - Replace dash_manifest.sleeper() with SegmentedStreamWorker.wait(), and make the worker thread shut down immediately on close(). - Prevent unnecessary wait times for static manifest types by calling close() after all se...
sleeper
d1a8d1597d4fe9f129a72fe94c1508304b7eae0f
streamlink
dash.py
11
6
https://github.com/streamlink/streamlink.git
2
36
0
16
63
Python
{ "docstring": "\n Do something and then wait for a given duration minus the time it took doing something\n ", "language": "en", "n_whitespaces": 31, "n_words": 16, "vocab_size": 15 }
def sleeper(self, duration): s = time() yield time_to_sleep = duration - (time() - s) if time_to_sleep > 0: self.wait(time_to_sleep)
23,566
109,399
1,100
lib/matplotlib/tests/test_colors.py
623
52
def test_BoundaryNorm(): boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # ncolors != len(boundaries)...
MNT: convert tests and internal usage way from using mpl.cm.get_cmap
test_BoundaryNorm
a17f4f3bd63e3ca3754f96d7db4ce5197720589b
matplotlib
test_colors.py
12
119
https://github.com/matplotlib/matplotlib.git
4
1,470
0
192
2,192
Python
{ "docstring": "\n GitHub issue #1258: interpolation was failing with numpy\n 1.7 pre-release.\n ", "language": "en", "n_whitespaces": 20, "n_words": 10, "vocab_size": 10 }
def test_BoundaryNorm(): boundaries = [0, 1.1, 2.2] vals = [-1, 0, 1, 2, 2.2, 4] # Without interpolation expected = [-1, 0, 0, 1, 2, 2] ncolors = len(boundaries) - 1 bn = mcolors.BoundaryNorm(boundaries, ncolors) assert_array_equal(bn(vals), expected) # ncolors != len(boundaries)...
36,066
154,556
912
modin/experimental/core/execution/native/implementations/hdk_on_native/dataframe/dataframe.py
171
44
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: ...
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>
_join_by_index
e5b1888cd932909e49194d58035da34b210b91c4
modin
dataframe.py
16
57
https://github.com/modin-project/modin.git
11
315
0
113
498
Python
{ "docstring": "\n Perform equi-join operation for multiple frames by index columns.\n\n Parameters\n ----------\n other_modin_frames : list of HdkOnNativeDataframe\n Frames to join with.\n how : str\n A type of join.\n sort : bool\n Sort the ...
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: ...
342
2,710
112
packages/syft/src/syft/core/node/common/action/function_or_constructor_action.py
25
16
def _object2proto(self) -> RunFunctionOrConstructorAction_PB: return RunFunctionOrConstructorAction_PB( path=self.path, args=[serialize(x, to_bytes=True) for x in self.args], kwargs={k: serialize(v, to_bytes=True) for k, v in self.kwargs.items()}, id_at_l...
[syft.core.node.common.action] Change syft import absolute -> relative
_object2proto
e272ed2fa4c58e0a89e273a3e85da7d13a85e04c
PySyft
function_or_constructor_action.py
13
23
https://github.com/OpenMined/PySyft.git
3
91
0
22
135
Python
{ "docstring": "Returns a protobuf serialization of self.\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms the current object into the corresponding\n Protobuf object so that it can be further serialized.\n\n :return: returns a protobuf object\n...
def _object2proto(self) -> RunFunctionOrConstructorAction_PB: return RunFunctionOrConstructorAction_PB( path=self.path, args=[serialize(x, to_bytes=True) for x in self.args], kwargs={k: serialize(v, to_bytes=True) for k, v in self.kwargs.items()}, id_at_l...
41,741
176,171
370
networkx/generators/small.py
56
5
def truncated_cube_graph(create_using=None): description = [ "adjacencylist", "Truncated Cube Graph", 24, [ [2, 3, 5], [12, 15], [4, 5], [7, 9], [6], [17, 19], [8, 9], [11, 13], ...
Docstrings for the small.py module (#5240) * added description for the first 5 small graphs * modified descriptions based on comment and added description for two more functions * added doctrings to all the functions * Minor touchups. Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
truncated_cube_graph
dec723f072eb997a497a159dbe8674cd39999ee9
networkx
small.py
9
34
https://github.com/networkx/networkx.git
1
152
0
46
197
Python
{ "docstring": "\n Returns the skeleton of the truncated cube.\n\n The truncated cube is an Archimedean solid with 14 regular\n faces (6 octagonal and 8 triangular), 36 edges and 24 nodes [1]_.\n The truncated cube is created by truncating (cutting off) the tips\n of the cube one third of the way into ...
def truncated_cube_graph(create_using=None): description = [ "adjacencylist", "Truncated Cube Graph", 24, [ [2, 3, 5], [12, 15], [4, 5], [7, 9], [6], [17, 19], [8, 9], [11, 13], ...
15,593
70,994
53
wagtail/contrib/modeladmin/options.py
14
5
def get_admin_urls_for_registration(self): urls = () for instance in self.modeladmin_instances: urls += instance.get_admin_urls_for_registration() return urls
Fix warnings from flake8-comprehensions.
get_admin_urls_for_registration
de3fcba9e95818e9634ab7de6bfcb1f4221f2775
wagtail
options.py
10
5
https://github.com/wagtail/wagtail.git
2
26
0
12
45
Python
{ "docstring": "\n Utilised by Wagtail's 'register_admin_urls' hook to register urls for\n used by any associated ModelAdmin instances\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 14 }
def get_admin_urls_for_registration(self): urls = () for instance in self.modeladmin_instances: urls += instance.get_admin_urls_for_registration() return urls
13,241
63,304
63
.venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py
17
7
def setName(self, name): self.name = name self.errmsg = "Expected " + self.name if __diag__.enable_debug_on_named_expressions: self.setDebug() return self
upd; format
setName
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
pyparsing.py
9
6
https://github.com/jindongwang/transferlearning.git
2
34
0
15
59
Python
{ "docstring": "\n Define name for this expression, makes debugging and exception messages clearer.\n\n Example::\n\n Word(nums).parseString(\"ABC\") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)\n Word(nums).setName(\"integer\").parseString(\"ABC\") # -> Exce...
def setName(self, name): self.name = name self.errmsg = "Expected " + self.name if __diag__.enable_debug_on_named_expressions: self.setDebug() return self
35,257
153,097
82
modin/core/dataframe/algebra/default2pandas/groupby.py
21
5
def get_func(cls, key, **kwargs): if "agg_func" in kwargs: return cls.inplace_applyier_builder(key, kwargs["agg_func"]) elif "func_dict" in kwargs: return cls.inplace_applyier_builder(key, kwargs["func_dict"]) else: return cls.inplace_applyier_builder...
FIX-#3197: do not pass lambdas to the backend in GroupBy (#3373) Signed-off-by: Dmitry Chigarev <dmitry.chigarev@intel.com>
get_func
1e65a4afd191cf61ba05b80545d23f9b88962f41
modin
groupby.py
12
7
https://github.com/modin-project/modin.git
3
54
0
16
92
Python
{ "docstring": "\n Extract aggregation function from groupby arguments.\n\n Parameters\n ----------\n key : callable or str\n Default aggregation function. If aggregation function is not specified\n via groupby arguments, then `key` function is used.\n **kwargs...
def get_func(cls, key, **kwargs): if "agg_func" in kwargs: return cls.inplace_applyier_builder(key, kwargs["agg_func"]) elif "func_dict" in kwargs: return cls.inplace_applyier_builder(key, kwargs["func_dict"]) else: return cls.inplace_applyier_builder...
29,983
133,351
44
python/ray/util/sgd/torch/torch_trainer.py
12
9
def update_scheduler(self, metric): self.worker_group.apply_all_operators( lambda op: [sched.step(m
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
update_scheduler
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
torch_trainer.py
11
4
https://github.com/ray-project/ray.git
2
32
0
12
52
Python
{ "docstring": "Calls ``scheduler.step(metric)`` on all registered schedulers.\n\n This is useful for lr_schedulers such as ``ReduceLROnPlateau``.\n ", "language": "en", "n_whitespaces": 28, "n_words": 14, "vocab_size": 14 }
def update_scheduler(self, metric): self.worker_group.apply_all_operators( lambda op: [sched.step(metric) for sched in op._schedulers] )
75,273
258,521
56
sklearn/metrics/pairwise.py
31
10
def paired_cosine_distances(X, Y): X, Y = c
DOC Ensures that sklearn.metrics.pairwise.paired_cosine_distances passes numpydoc validation (#22141) Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
paired_cosine_distances
a5b70b3132467b5e3616178d9ecca6cb7316c400
scikit-learn
pairwise.py
11
3
https://github.com/scikit-learn/scikit-learn.git
1
39
0
27
108
Python
{ "docstring": "\n Compute the paired cosine distances between X and Y.\n\n Read more in the :ref:`User Guide <metrics>`.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n An array where each row is a sample and each column is a feature.\n\n Y : array-like of sha...
def paired_cosine_distances(X, Y): X, Y = check_paired_arrays(X, Y) return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True) PAIRED_DISTANCES = { "cosine": paired_cosine_distances, "euclidean": paired_euclidean_distances, "l2": paired_euclidean_distances, "l1": paired_manhattan_d...
5,648
30,695
131
src/transformers/trainer.py
29
12
def torchdynamo_smart_context_manager(self): ctx_manager = contextlib.nullcontext() if is_torchdynamo_available(): import torchdynamo from torchdy
Support compilation via Torchdynamo, AOT Autograd, NVFuser (#17308) * Support compilation via Torchdynamo, AOT Autograd, NVFuser * Address comments * Lint * Stas comments - missing quality test * Lintere * Quality test * Doc lint * Reset CUDA peak mem * Add CustomTrainer * require a single g...
torchdynamo_smart_context_manager
897a8dd89f40817201bc4aebe532a096405bdeb1
transformers
trainer.py
13
10
https://github.com/huggingface/transformers.git
4
64
0
20
112
Python
{ "docstring": "\n A helper wrapper that creates an appropriate context manager for `torchdynamo`.\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 11 }
def torchdynamo_smart_context_manager(self): ctx_manager = contextlib.nullcontext() if is_torchdynamo_available(): import torchdynamo from torchdynamo.optimizations.training import aot_autograd_speedup_strategy if self.args.torchdynamo == "eager": ...
45,584
186,677
110
certbot-apache/certbot_apache/_internal/parser.py
20
9
def check_aug_version(self) -> bool: self.aug.set("/test/path/testing/arg", "aRgUMeNT") try: matches = self.aug.match( "/test//*[self::arg=~regexp('argument', 'i')]") except RuntimeError: self.aug.remove("/test/path") return False ...
Add typing to certbot.apache (#9071) * Add typing to certbot.apache Co-authored-by: Adrien Ferrand <ferrand.ad@gmail.com>
check_aug_version
7d9e9a49005de7961e84d2a7c608db57dbab3046
certbot
parser.py
11
13
https://github.com/certbot/certbot.git
2
53
0
17
98
Python
{ "docstring": " Checks that we have recent enough version of libaugeas.\n If augeas version is recent enough, it will support case insensitive\n regexp matching", "language": "en", "n_whitespaces": 36, "n_words": 22, "vocab_size": 20 }
def check_aug_version(self) -> bool: self.aug.set("/test/path/testing/arg", "aRgUMeNT") try: matches = self.aug.match( "/test//*[self::arg=~regexp('argument', 'i')]") except RuntimeError: self.aug.remove("/test/path") return False ...
37,003
157,635
42
ldm/modules/midas/utils.py
20
13
def resize_depth(depth, width, height): depth = torch.squeeze(depth[0, :, :, :]).to("cpu") depth_resized = cv2.resize( depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC ) return depth_resized
release more models
resize_depth
ca86da3a30c4e080d4db8c25fca73de843663cb4
stablediffusion
utils.py
12
6
https://github.com/Stability-AI/stablediffusion.git
1
58
0
17
91
Python
{ "docstring": "Resize depth map and bring to CPU (numpy).\n\n Args:\n depth (tensor): depth\n width (int): image width\n height (int): image height\n\n Returns:\n array: processed depth\n ", "language": "en", "n_whitespaces": 61, "n_words": 24, "vocab_size": 17 }
def resize_depth(depth, width, height): depth = torch.squeeze(depth[0, :, :, :]).to("cpu") depth_resized = cv2.resize( depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC ) return depth_resized
47,440
195,853
729
sympy/core/numbers.py
213
34
def comp(z1, z2, tol=None): r if type(z2) is str: if not
Improved documentation formatting
comp
cda8dfe6f45dc5ed394c2f5cda706cd6c729f713
sympy
numbers.py
24
105
https://github.com/sympy/sympy.git
26
381
0
107
605
Python
{ "docstring": "Return a bool indicating whether the error between z1 and z2\n is $\\le$ ``tol``.\n\n Examples\n ========\n\n If ``tol`` is ``None`` then ``True`` will be returned if\n :math:`|z1 - z2|\\times 10^p \\le 5` where $p$ is minimum value of the\n decimal precision of each value.\n\n >>...
def comp(z1, z2, tol=None): r if type(z2) is str: if not pure_complex(z1, or_real=True): raise ValueError('when z2 is a str z1 must be a Number') return str(z1) == z2 if not z1: z1, z2 = z2, z1 if not z1: return True if not tol: a, b = z1, z2 ...
70,677
245,152
491
mmdet/datasets/openimages.py
58
24
def _parse_img_level_ann(self, image_level_ann_file): item_lists = defaultdict(list) with self.file_client.get_local_path( image_level_ann_file) as local_path: with open(local_path, 'r') as f: reader = csv.reader(f) i = -1 ...
Refactor OpenImages.
_parse_img_level_ann
36c1f477b273cb2fb0dea3c921ec267db877c039
mmdetection
openimages.py
19
23
https://github.com/open-mmlab/mmdetection.git
3
122
0
45
201
Python
{ "docstring": "Parse image level annotations from csv style ann_file.\n\n Args:\n image_level_ann_file (str): CSV style image level annotation\n file path.\n\n Returns:\n defaultdict[list[dict]]: Annotations where item of the defaultdict\n indicates an im...
def _parse_img_level_ann(self, image_level_ann_file): item_lists = defaultdict(list) with self.file_client.get_local_path( image_level_ann_file) as local_path: with open(local_path, 'r') as f: reader = csv.reader(f) i = -1 ...
55,789
219,771
32
python3.10.4/Lib/_pydecimal.py
11
7
def logical_and(self, a, b): a = _convert
add python 3.10.4 for windows
logical_and
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_pydecimal.py
9
3
https://github.com/XX-net/XX-Net.git
1
31
0
11
48
Python
{ "docstring": "Applies the logical operation 'and' between each operand's digits.\n\n The operands must be both logical numbers.\n\n >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))\n Decimal('0')\n >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))\n Decimal('0...
def logical_and(self, a, b): a = _convert_other(a, raiseit=True) return a.logical_and(b, context=self)
48,514
197,371
587
sympy/utilities/enumerative.py
182
16
def decrement_part_small(self, part, ub): if self.lpart >= ub - 1: self.p1 += 1 # increment to keep track of usefulness of tests return False plen = len(part) for j in range(plen - 1, -1, -1): # Knuth's mod, (answer to problem 7.2.1.5.69) ...
Remove abbreviations in documentation
decrement_part_small
65be461082dda54c8748922f9c29a19af1279fe1
sympy
enumerative.py
18
21
https://github.com/sympy/sympy.git
13
214
0
114
333
Python
{ "docstring": "Decrements part (a subrange of pstack), if possible, returning\n True iff the part was successfully decremented.\n\n Parameters\n ==========\n\n part\n part to be decremented (topmost part on the stack)\n\n ub\n the maximum number of parts allow...
def decrement_part_small(self, part, ub): if self.lpart >= ub - 1: self.p1 += 1 # increment to keep track of usefulness of tests return False plen = len(part) for j in range(plen - 1, -1, -1): # Knuth's mod, (answer to problem 7.2.1.5.69) ...
27,935
125,638
40
python/ray/runtime_context.py
12
8
def get_node_id(self) -> str: node_id = self.worker.current_node_id assert not node_id.is_nil() return node_i
Ray 2.0 API deprecation (#26116) Ray 2.0 API deprecation for: ray.remote(): placement_group ray.remote(): placement_group_bundle_index ray.remote(): placement_group_capture_child_tasks ray.get_dashboard_url() ray.get_resource_ids() ray.disconnect() ray.connect() ray.util.ActorGroup ray.util.ActorPo...
get_node_id
90cea203befa8f2e86e9c1c18bb3972296358e7b
ray
runtime_context.py
8
12
https://github.com/ray-project/ray.git
1
28
0
12
49
Python
{ "docstring": "Get current node ID for this worker or driver.\n\n Node ID is the id of a node that your driver, task, or actor runs.\n The ID will be in hex format.\n\n Returns:\n A node id in hex format for this worker or driver.\n ", "language": "en", "n_whitespaces": 82,...
def get_node_id(self) -> str: node_id = self.worker.current_node_id assert not node_id.is_nil() return node_id.hex()
117,392
320,849
57
qutebrowser/completion/models/configmodel.py
16
10
def list_option(*, info): return _option( info, "List options", lambda opt: (isinstance(info.config.get_obj(op
pylint: Fix new unnecessary-lambda-assignment
list_option
6c4e2810285af0698538aed9d46a99de085eb310
qutebrowser
configmodel.py
15
7
https://github.com/qutebrowser/qutebrowser.git
2
41
0
16
67
Python
{ "docstring": "A CompletionModel filled with settings whose values are lists.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def list_option(*, info): return _option( info, "List options", lambda opt: (isinstance(info.config.get_obj(opt.name), list) and not opt.no_autoconfig) )
@pytest.mark.parametrize( "query, fields", [ ( """ SELecT campaign.id, campaign.name, campaign.status, metrics.impressions FROM campaign wheRe campaign.status = 'PAUSED' AND metrics.impressions > 100 order by campaign.status """, ["campaign.id", "campaign.name", "...
480
3,546
201
airbyte-integrations/connectors/source-google-ads/unit_tests/test_source.py
53
18
def get_instance_from_config_with_end_date(config, query): start_date = "2021-03-04" end_date = "2021-04-04" conversion_window_days = 14 google_api = GoogleAds(credentials=config["credentials"], customer_id=config["customer_id"]) instance = CustomQuery( api=google_api, conversion_wi...
Source GoogleAds: add end_date to config (#8669) * GoogleAds add end_date to config * Update script following review comments * Add unit test * Solve conflicts * Solve conflicts in MR * Update test_google_ads.py Instanciate IncrementalGoogleAdsStream in tests + add missing line between functions *...
get_instance_from_config_with_end_date
2e7ee756eb1d55080d707cef63454788a7abb6be
airbyte
test_source.py
12
14
https://github.com/airbytehq/airbyte.git
1
73
1
44
208
Python
{ "docstring": "\n SELecT\n campaign.id,\n campaign.name,\n campaign.status,\n metrics.impressions FROM campaign\nwheRe campaign.status = 'PAUSED'\nAND metrics.impressions > 100\norder by campaign.status\n \n SELECT\n campaign.accessible_bidding_strategy,\n segments.ad_destinati...
def get_instance_from_config_with_end_date(config, query): start_date = "2021-03-04" end_date = "2021-04-04" conversion_window_days = 14 google_api = GoogleAds(credentials=config["credentials"], customer_id=config["customer_id"]) instance = CustomQuery( api=google_api, conversion_wi...
41,838
176,324
144
networkx/algorithms/assortativity/pairs.py
69
21
def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): nodes = set(G) if nodes is None else set(nodes) if G.is_directed(): direction = {"out": G.out_degree, "in": G.in_degree} xdeg = direction[x] ydeg = direction[y] else: xdeg = ydeg = G.degree for u, degu...
MAINT: Cleanup assortativity module, remove unused variables (#5301) Remove unused variables, sort imports, raise errors instead of accepting invalid arguments silently Co-authored-by: Dan Schult <dschult@colgate.edu>
node_degree_xy
34d9d630bb02426d297d3e20fedb7da8c3ced03a
networkx
pairs.py
12
12
https://github.com/networkx/networkx.git
7
132
0
49
209
Python
{ "docstring": "Generate node degree-degree pairs for edges in G.\n\n Parameters\n ----------\n G: NetworkX graph\n\n x: string ('in','out')\n The degree type for source node (directed graphs only).\n\n y: string ('in','out')\n The degree type for target node (directed graphs only).\n\n ...
def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): nodes = set(G) if nodes is None else set(nodes) if G.is_directed(): direction = {"out": G.out_degree, "in": G.in_degree} xdeg = direction[x] ydeg = direction[y] else: xdeg = ydeg = G.degree for u, degu...
29,985
133,353
88
python/ray/util/sgd/torch/torch_trainer.py
20
9
def validate(self, num_steps=None, profile=False, reduce_results=True, info=None): worker_stats = self.worker_group.validate(
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
validate
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
torch_trainer.py
9
8
https://github.com/ray-project/ray.git
2
56
0
18
85
Python
{ "docstring": "Evaluates the model on the validation data set.\n\n Args:\n num_steps (int): Number of batches to compute update steps on\n per worker. This corresponds also to the number of times\n ``TrainingOperator.validate_batch`` is called per worker.\n ...
def validate(self, num_steps=None, profile=False, reduce_results=True, info=None): worker_stats = self.worker_group.validate( num_steps=num_steps, profile=profile, info=info ) if reduce_results: return self._process_stats(worker_stats) else: ...
12,047
60,255
29
code/deep/BJMMD/caffe/python/caffe/io.py
8
6
def set_raw_scale(self, in_, scale): self.__check_input(in_) self.raw_scale[in_] = scale
Balanced joint maximum mean discrepancy for deep transfer learning
set_raw_scale
cc4d0564756ca067516f71718a3d135996525909
transferlearning
io.py
8
3
https://github.com/jindongwang/transferlearning.git
1
24
0
8
39
Python
{ "docstring": "\n Set the scale of raw features s.t. the input blob = input * scale.\n While Python represents images in [0, 1], certain Caffe models\n like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale\n of these models must be 255.\n\n Parameters\n ---...
def set_raw_scale(self, in_, scale): self.__check_input(in_) self.raw_scale[in_] = scale
30,178
134,046
238
ci/run/bazel_sharding/tests/test_bazel_sharding.py
151
16
def test_add_rule_to_best_shard(): # If we start with an empty list, then add to first shard shards: List[List[bazel_sharding.BazelRule]] = [list() for _ in range(4)] optimum = 600 rule = bazel_sharding.BazelRule("mock", "medium") bazel_sharding.add_rule_to_best_shard(rule, shards, optimum) ...
[CI] Make bazel sharding for parallel buildkite more intelligent (#29221) This PR implements two changes to our `bazel-sharding.py` script, used for determining which bazel tests to run on each instance when buildkite parallelism is used: * An ability to filter tests before they are sharded, using the same logic as `...
test_add_rule_to_best_shard
d1aa5608979891e3dd859c07fa919fa01cfead5f
ray
test_bazel_sharding.py
10
25
https://github.com/ray-project/ray.git
7
291
0
61
460
Python
{ "docstring": "Test that the best shard in optimal strategy is chosen correctly.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def test_add_rule_to_best_shard(): # If we start with an empty list, then add to first shard shards: List[List[bazel_sharding.BazelRule]] = [list() for _ in range(4)] optimum = 600 rule = bazel_sharding.BazelRule("mock", "medium") bazel_sharding.add_rule_to_best_shard(rule, shards, optimum) ...
110,798
312,146
37
homeassistant/components/isy994/binary_sensor.py
9
5
def async_heartbeat(self) -> None: self._computed_state = False self._restart_timer() self.async_write_ha_stat
Enable strict typing for isy994 (#65439) Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
async_heartbeat
6c38a6b5697bcf4587e00101771001bf596974f9
core
binary_sensor.py
7
11
https://github.com/home-assistant/core.git
1
23
0
9
42
Python
{ "docstring": "Mark the device as online, and restart the 25 hour timer.\n\n This gets called when the heartbeat node beats, but also when the\n parent sensor sends any events, as we can trust that to mean the device\n is online. This mitigates the risk of false positives due to a single\n ...
def async_heartbeat(self) -> None: self._computed_state = False self._restart_timer() self.async_write_ha_state()
39,861
166,848
49
pandas/tests/util/test_assert_series_equal.py
24
17
def test_assert_series_equal_interval_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/32747 left = Series([pd.Interval(0, 1, "right")], dtype="interval") right = left.astype(object) msg = tm.assert_series_equal(left, right, check_dtype=False) with pytest.raises(AssertionError...
ENH: consistency of input args for boundaries - Interval (#46522)
test_assert_series_equal_interval_dtype_mismatch
7e23a37e1c5bda81234801a6584563e2880769eb
pandas
test_assert_series_equal.py
12
11
https://github.com/pandas-dev/pandas.git
1
72
0
20
123
Python
{ "docstring": "Attributes of Series are different\n\nAttribute \"dtype\" are different\n\\\\[left\\\\]: interval\\\\[int64, right\\\\]\n\\\\[right\\\\]: object", "language": "en", "n_whitespaces": 11, "n_words": 14, "vocab_size": 12 }
def test_assert_series_equal_interval_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/32747 left = Series([pd.Interval(0, 1, "right")], dtype="interval") right = left.astype(object) msg = tm.assert_series_equal(left, right, check_dtype=False) with pytest.raises(AssertionError...
23,106
108,225
85
lib/matplotlib/__init__.py
35
10
def rc_file_defaults(): #
Fix removed cross-references
rc_file_defaults
7c6c5f6215b40a27cfefb7bf21246299fd9b3a1e
matplotlib
__init__.py
12
5
https://github.com/matplotlib/matplotlib.git
3
41
0
32
72
Python
{ "docstring": "\n Restore the `.rcParams` from the original rc file loaded by Matplotlib.\n\n Style-blacklisted `.rcParams` (defined in\n ``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.\n ", "language": "en", "n_whitespaces": 32, "n_words": 19, "vocab_size": 17 }
def rc_file_defaults(): # Deprecation warnings were already handled when creating rcParamsOrig, no # need to reemit them here. with _api.suppress_matplotlib_deprecation_warning(): from .style.core import STYLE_BLACKLIST rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig ...
3,587
20,845
153
pipenv/patched/notpip/_vendor/rich/syntax.py
21
12
def lexer(self) -> Optional[Lexer]: if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( self._lexer, stripnl=False, ensurenl=True, tabsize=self.tab_size, ) ...
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...
lexer
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
syntax.py
11
16
https://github.com/pypa/pipenv.git
3
54
0
19
83
Python
{ "docstring": "The lexer for this syntax, or None if no lexer was found.\n\n Tries to find the lexer by name if a string was passed to the constructor.\n ", "language": "en", "n_whitespaces": 41, "n_words": 27, "vocab_size": 21 }
def lexer(self) -> Optional[Lexer]: if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( self._lexer, stripnl=False, ensurenl=True, tabsize=self.tab_size, ) ...
54,182
215,808
19
tests/pytests/functional/modules/file/test_replace.py
10
5
def test_numeric_repl(file, multiline_file): file.replace(multiline_fi
Add some funtional tests Add functional tests for the following: - file.readlink - file.replace - file.symlink Remove unit tests for file.replace as they are duplicated in the added functional test
test_numeric_repl
a35b29b2651bf33c5d5b45e64bc7765ffde4aff4
salt
test_replace.py
8
3
https://github.com/saltstack/salt.git
1
27
0
10
46
Python
{ "docstring": "\n This test covers cases where the replacement string is numeric. The CLI\n parser yaml-fies it into a numeric type. If not converted back to a string\n type in file.replace, a TypeError occurs when the replace is attempted. See\n https://github.com/saltstack/salt/issues/9097 for more inf...
def test_numeric_repl(file, multiline_file): file.replace(multiline_file, r"Etiam", 123) assert "123" in multiline_file.read_text()
43,005
179,715
29
gradio/components.py
8
4
def set_interpret_parameters(self, segments=16): self.interpretation_segments = segments retu
Blocks-Components - fixes - format
set_interpret_parameters
7fa8e45b6782d545fa0ead112d92d13bdad7417c
gradio
components.py
7
3
https://github.com/gradio-app/gradio.git
1
17
0
8
29
Python
{ "docstring": "\n Calculates interpretation score of image subsections by splitting the image into subsections, then using a \"leave one out\" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value.\n Parameters:\n segments (int...
def set_interpret_parameters(self, segments=16): self.interpretation_segments = segments return self
72,207
248,309
24
synapse/storage/engines/sqlite.py
10
5
def can_native_upsert(self) -> bool: return sqlite3.sqlite_version_info >= (3, 2
Tidy up and type-hint the database engine modules (#12734) Co-authored-by: Sean Quah <8349537+squahtx@users.noreply.github.com>
can_native_upsert
1fe202a1a3343fad77da270ffe0923a46f1944dd
synapse
sqlite.py
7
6
https://github.com/matrix-org/synapse.git
1
20
0
10
32
Python
{ "docstring": "\n Do we support native UPSERTs? This requires SQLite3 3.24+, plus some\n more work we haven't done yet to tell what was inserted vs updated.\n ", "language": "en", "n_whitespaces": 46, "n_words": 24, "vocab_size": 23 }
def can_native_upsert(self) -> bool: return sqlite3.sqlite_version_info >= (3, 24, 0)
31,405
138,397
97
dashboard/state_aggregator.py
29
16
async def get_actors(self) -> dict: reply = await self._client.get_all_actor_info(timeout=DEFAULT_RPC_TIMEOUT) result = {} for message in rep
[State Observability] Tasks and Objects API (#23912) This PR implements ray list tasks and ray list objects APIs. NOTE: You can ignore the merge conflict for now. It is because the first PR was reverted. There's a fix PR open now.
get_actors
30ab5458a7e4ba2351d5e1beef8c8797b5946493
ray
state_aggregator.py
13
14
https://github.com/ray-project/ray.git
2
67
0
22
111
Python
{ "docstring": "List all actor information from the cluster.\n\n Returns:\n {actor_id -> actor_data_in_dict}\n actor_data_in_dict's schema is in ActorState\n ", "language": "en", "n_whitespaces": 52, "n_words": 16, "vocab_size": 16 }
async def get_actors(self) -> dict: reply = await self._client.get_all_actor_info(timeout=DEFAULT_RPC_TIMEOUT) result = {} for message in reply.actor_table_data: data = self._message_to_dict(message=message, fields_to_decode=["actor_id"]) data = filter_fields(dat...
25,051
113,876
833
mindsdb/api/mysql/mysql_proxy/mysql_proxy.py
181
42
def insert_predictor_answer(self, insert): model_interface = self.session.model_interface data_store = self.session.data_store select_data_query = insert.get('select_data_query') if isinstance(select_data_query, str) is False or len(select_data_query) == 0: self.pac...
fix
insert_predictor_answer
551205a18ac2ac19626f4e4ffb2ed88fcad705b9
mindsdb
mysql_proxy.py
16
63
https://github.com/mindsdb/mindsdb.git
18
445
0
109
713
Python
{ "docstring": " Start learn new predictor.\n Parameters:\n - insert - dict with keys as columns of mindsb.predictors table.\n ", "language": "en", "n_whitespaces": 47, "n_words": 16, "vocab_size": 15 }
def insert_predictor_answer(self, insert): model_interface = self.session.model_interface data_store = self.session.data_store select_data_query = insert.get('select_data_query') if isinstance(select_data_query, str) is False or len(select_data_query) == 0: self.pac...
85,115
285,032
469
openbb_terminal/portfolio/portfolio_model.py
78
23
def populate_historical_trade_data(self): trade_data = self.__orderbook.pivot( index="Date", columns="Ticker", values=[ "Type", "Sector", "Industry", "Country", "Price", "...
Overhaul Portfolio class (#2021) * adds pythonic portfolio class * start calculate trades refactoring * adds comments to portfolio model - delete afterwards * finish calculate trades refactoring * restore original portfolio_model.py * implement calculate_allocations * adapt and test controller load, ...
populate_historical_trade_data
2c3e10a128fa0ce4e937d8d50dc0cd6d7cd11485
OpenBBTerminal
portfolio_model.py
12
34
https://github.com/OpenBB-finance/OpenBBTerminal.git
1
164
0
65
282
Python
{ "docstring": "Create a new dataframe to store historical prices by ticker", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def populate_historical_trade_data(self): trade_data = self.__orderbook.pivot( index="Date", columns="Ticker", values=[ "Type", "Sector", "Industry", "Country", "Price", "...
@fails_if_pypy @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
75,979
259,898
129
sklearn/datasets/tests/test_openml.py
47
20
def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): pytest.importorskip("pandas") data_id = 61 _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) bunch_as_frame_true = fetch_openml( data_id=data_id, as_frame=True, cache=False, ...
ENH improve ARFF parser using pandas (#21938) Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com> Co-authored-by: Olivier Grisel <olivier.grisel@gmail.com> Co-authored-by: Adrin Jalali <adrin.jalali@gmail.com>
test_fetch_openml_equivalence_array_dataframe
a47d569e670fd4102af37c3165c9b1ddf6fd3005
scikit-learn
test_openml.py
9
18
https://github.com/scikit-learn/scikit-learn.git
1
89
1
39
167
Python
{ "docstring": "Check the equivalence of the dataset when using `as_frame=False` and\n `as_frame=True`.\n ", "language": "en", "n_whitespaces": 17, "n_words": 11, "vocab_size": 10 }
def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): pytest.importorskip("pandas") data_id = 61 _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True) bunch_as_frame_true = fetch_openml( data_id=data_id, as_frame=True, cache=False, ...
73,944
252,396
76
mitmproxy/contrib/kaitaistruct/google_protobuf.py
17
12
def wire_type(self): if hasattr(self, '_m_wire_type'): return self._m_wire_type self._m_wire_type = Kaita
update kaitai definitions
wire_type
002f919dda5f01d067c2e786426c68751551d15c
mitmproxy
google_protobuf.py
12
5
https://github.com/mitmproxy/mitmproxy.git
2
51
0
15
83
Python
{ "docstring": "\"Wire type\" is a part of the \"key\" that carries enough\n information to parse value from the wire, i.e. read correct\n amount of bytes, but there's not enough informaton to\n interprete in unambiguously. For example, one can't clearly\n distinguish 64-bi...
def wire_type(self): if hasattr(self, '_m_wire_type'): return self._m_wire_type self._m_wire_type = KaitaiStream.resolve_enum(GoogleProtobuf.Pair.WireTypes, (self.key.value & 7)) return getattr(self, '_m_wire_type', None)
73,687
251,333
80
mitmproxy/connection.py
18
7
def address(self): # pragma: no cover warnings.warn( "Client.address is deprecated, use Client.peername instead.", D
make it black!
address
b3587b52b25077f68116b9852b041d33e7fc6601
mitmproxy
connection.py
8
7
https://github.com/mitmproxy/mitmproxy.git
1
23
0
18
40
Python
{ "docstring": "*Deprecated:* An outdated alias for Client.peername.", "language": "en", "n_whitespaces": 5, "n_words": 6, "vocab_size": 6 }
def address(self): # pragma: no cover warnings.warn( "Client.address is deprecated, use Client.peername instead.", DeprecationWarning, stacklevel=2, ) return self.peername
f"""\ To get asquare Jordan block matrix use a morebanded matrix
48,242
196,907
80
sympy/matrices/common.py
28
21
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): if 'r
Update the Matrix.jordan_block() rows and cols kwargs deprecation
jordan_block
a4fdabab38def4bf6b4007f8cd67d6944740b303
sympy
common.py
12
45
https://github.com/sympy/sympy.git
16
239
3
19
109
Python
{ "docstring": "Returns a Jordan block\n\n Parameters\n ==========\n\n size : Integer, optional\n Specifies the shape of the Jordan block matrix.\n\n eigenvalue : Number or Symbol\n Specifies the value for the main diagonal of the matrix.\n\n .. note::\n ...
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): if 'rows' in kwargs or 'cols' in kwargs: msg = if 'rows' in kwargs and 'cols' in kwargs: msg += f
75,236
258,441
71
rest_api/rest_api/utils.py
17
11
def get_openapi_specs() -> dict: app = get_app()
bug: fix the docs rest api reference url (#3775) * bug: fix the docs rest api reference url * revert openapi json changes * remove last line on json files * Add explanation about `servers` and remove `servers` parameter from FastAPI * generate openapi schema without empty end line
get_openapi_specs
86ade4817eda3142d2ddef65a0b1e29ffee770e3
haystack
utils.py
12
17
https://github.com/deepset-ai/haystack.git
1
56
0
17
89
Python
{ "docstring": "\n Used to autogenerate OpenAPI specs file to use in the documentation.\n\n Returns `servers` to specify base URL for OpenAPI Playground (see https://swagger.io/docs/specification/api-host-and-base-path/)\n\n See `.github/utils/generate_openapi_specs.py`\n ", "language": "en", "n_white...
def get_openapi_specs() -> dict: app = get_app() return get_openapi( title=app.title, version=app.version, openapi_version=app.openapi_version, description=app.description, routes=app.routes, servers=[{"url": "http://localhost:8000"}], )
14,099
66,068
32
erpnext/hr/doctype/employee/employee.py
47
16
def get_all_employee_emails(company): employee_list = frappe.get_all( "Employee", fields=["name", "employee_name"], filters={"status": "Active", "company": company} ) employee_emails = [] for
style: format code with black
get_all_employee_emails
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
employee.py
12
15
https://github.com/frappe/erpnext.git
6
90
0
38
156
Python
{ "docstring": "Returns list of employee emails either based on user_id or company_email", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def get_all_employee_emails(company): employee_list = frappe.get_all( "Employee", fields=["name", "employee_name"], filters={"status": "Active", "company": company} ) employee_emails = [] for employee in employee_list: if not employee: continue user, company_email, personal_email = frappe.db.get_value( ...
18,657
90,257
368
tests/snuba/api/endpoints/test_organization_group_index.py
81
43
def test_in_non_semver_projects_resolved_in_next_release_is_equated_to_in_release(self): release_1 = self.create_release( date_added=timezon
ref(tests): Remove `get_valid_response()` (#34822)
test_in_non_semver_projects_resolved_in_next_release_is_equated_to_in_release
096b5511e244eecd8799b2a0324655207ce8985e
sentry
test_organization_group_index.py
17
33
https://github.com/getsentry/sentry.git
1
249
0
59
407
Python
{ "docstring": "\n Test that ensures that if we basically know the next release when clicking on Resolved\n In Next Release because that release exists, then we can short circuit setting\n GroupResolution to type \"inNextRelease\", and then having `clear_exrired_resolutions` run\n once a n...
def test_in_non_semver_projects_resolved_in_next_release_is_equated_to_in_release(self): release_1 = self.create_release( date_added=timezone.now() - timedelta(minutes=45), version="foobar 1" ) release_2 = self.create_release(version="foobar 2") self.create_release(v...
@pytest.fixture
4,995
26,436
21
saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
10
8
def subscription_order_updated_webhook(subscription_webhook): return subscription_webhook( ORDER_UPDATED_SUBSCRIPTION_QUERY, Webhook
Add Webhook payload via graphql subscriptions (#9394) * Add PoC of webhook subscriptions * add async webhooks subscription payloads feature * remove unneeded file * add translations subscription handling, fixes after review * remove todo * add descriptions * add descriptions, move subsrciption_payloa...
subscription_order_updated_webhook
aca6418d6c36956bc1ab530e6ef7e146ec9df90c
saleor
fixtures.py
8
4
https://github.com/saleor/saleor.git
1
14
1
10
36
Python
{ "docstring": "\n subscription{\n event{\n ...on OrderConfirmed{\n order{\n id\n }\n }\n }\n }\n", "language": "en", "n_whitespaces": 69, "n_words": 10, "vocab_size": 7 }
def subscription_order_updated_webhook(subscription_webhook): return subscription_webhook( ORDER_UPDATED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.ORDER_UPDATED ) ORDER_CONFIRMED_SUBSCRIPTION_QUERY = @pytest.fixture
35,391
153,357
1,180
modin/experimental/core/execution/native/implementations/omnisci_on_native/omnisci_worker.py
295
55
def cast_to_compatible_types(table): schema = table.schema new_schema = schema need_cast = False uint_to_int_cast = False new_cols = {} uint_to_int_map = { pa.uint8(): pa.int16(), pa.uint16(): pa.int32(), pa.uint32(): pa.int64(...
FIX-#3368: support unsigned integers in OmniSci backend (#4256) Signed-off-by: Dmitry Chigarev <dmitry.chigarev@intel.com> Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
cast_to_compatible_types
241a46dd5f4dce7bc7f630b58c80d15222d6bde7
modin
omnisci_worker.py
16
56
https://github.com/modin-project/modin.git
11
382
0
171
613
Python
{ "docstring": "\n Cast PyArrow table to be fully compatible with OmniSci.\n\n Parameters\n ----------\n table : pyarrow.Table\n Source table.\n\n Returns\n -------\n pyarrow.Table\n Table with fully compatible types with OmniSci.\n ", "l...
def cast_to_compatible_types(table): schema = table.schema new_schema = schema need_cast = False uint_to_int_cast = False new_cols = {} uint_to_int_map = { pa.uint8(): pa.int16(), pa.uint16(): pa.int32(), pa.uint32(): pa.int64(...
1,807
9,959
20
jina/types/request/data.py
6
5
def data(self) -> 'DataRequest._DataContent': return DataRequest._DataCon
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 ...
data
933415bfa1f9eb89f935037014dfed816eb9815d
jina
data.py
9
6
https://github.com/jina-ai/jina.git
1
19
0
6
35
Python
{ "docstring": "Get the data contaned in this data request\n\n :return: the data content as an instance of _DataContent wrapping docs and groundtruths\n ", "language": "en", "n_whitespaces": 35, "n_words": 21, "vocab_size": 18 }
def data(self) -> 'DataRequest._DataContent': return DataRequest._DataContent(self.proto.data)
81,498
275,883
35
keras/saving/model_config.py
15
6
def model_from_json(json_string, custom_objects=None): from keras.layers import ( deserialize_from_json, ) # pylint: disable=g-import-not
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
model_from_json
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
model_config.py
8
5
https://github.com/keras-team/keras.git
1
28
0
15
44
Python
{ "docstring": "Parses a JSON model configuration string and returns a model instance.\n\n Usage:\n\n >>> model = tf.keras.Sequential([\n ... tf.keras.layers.Dense(5, input_shape=(3,)),\n ... tf.keras.layers.Softmax()])\n >>> config = model.to_json()\n >>> loaded_model = tf.keras.models.mode...
def model_from_json(json_string, custom_objects=None): from keras.layers import ( deserialize_from_json, ) # pylint: disable=g-import-not-at-top return deserialize_from_json(json_string, custom_objects=custom_objects)
116,987
319,727
43
src/documents/tests/test_management_convert_thumbnail.py
15
8
def test_do_nothing_if_converted(self, run_convert_mock): stdout, _ = self.call_command() run_convert_mock.assert_not_called() self.assertIn("Converting all PNG thumbnails to WebP", stdout)
Fixes existing testing, adds test coverage of new command
test_do_nothing_if_converted
08c3d6e84b17da2acfb10250438fe357398e5e0e
paperless-ngx
test_management_convert_thumbnail.py
8
4
https://github.com/paperless-ngx/paperless-ngx.git
1
30
0
15
53
Python
{ "docstring": "\n GIVEN:\n - Document exists with default WebP thumbnail path\n WHEN:\n - Thumbnail conversion is attempted\n THEN:\n - Nothing is converted\n ", "language": "en", "n_whitespaces": 82, "n_words": 20, "vocab_size": 17 }
def test_do_nothing_if_converted(self, run_convert_mock): stdout, _ = self.call_command() run_convert_mock.assert_not_called() self.assertIn("Converting all PNG thumbnails to WebP", stdout)
3,433
20,578
140
pipenv/patched/notpip/_vendor/pyparsing/core.py
30
11
def __ror__(self, other): if isinstance(other, str_type): other = self._literalStringClass(other) if not isinstance(other, ParserElement): raise TypeError( "Cannot combine element of type {} with ParserElement".format(
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...
__ror__
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
core.py
14
10
https://github.com/pypa/pipenv.git
3
52
0
26
86
Python
{ "docstring": "\n Implementation of ``|`` operator when left operand is not a :class:`ParserElement`\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 11 }
def __ror__(self, other): if isinstance(other, str_type): other = self._literalStringClass(other) if not isinstance(other, ParserElement): raise TypeError( "Cannot combine element of type {} with ParserElement".format( type(other).__na...
53,616
213,062
151
samtranslator/third_party/py27hash/hash.py
48
10
def shash(value): length = len(value) if length == 0: return 0 x = Hash.ordinal(value[0]) << 7 for c in value: x = (1000003 * x) ^ Hash.ordinal(c) x ^= length x &= 0xFFFFFFFFFFFFFFFF if x == -1: x = -2 # Co...
fix: Py27hash fix (#2182) * Add third party py27hash code * Add Py27UniStr and unit tests * Add py27hash_fix utils and tests * Add to_py27_compatible_template and tests * Apply py27hash fix to wherever it is needed * Apply py27hash fix, all tests pass except api_with_any_method_in_swagger * apply py2...
shash
a5db070f446b7cfebdaa6ad2e3dcf78f6105a272
serverless-application-model
hash.py
11
12
https://github.com/aws/serverless-application-model.git
4
77
0
35
125
Python
{ "docstring": "\n Returns a Python 2.7 hash for a string.\n\n Logic ported from the 2.7 Python branch: cpython/Objects/stringobject.c\n Method: static long string_hash(PyStringObject *a)\n\n Args:\n value: input string\n\n Returns:\n Python 2.7 hash\n "...
def shash(value): length = len(value) if length == 0: return 0 x = Hash.ordinal(value[0]) << 7 for c in value: x = (1000003 * x) ^ Hash.ordinal(c) x ^= length x &= 0xFFFFFFFFFFFFFFFF if x == -1: x = -2 # Co...
@pytest.fixture
22,138
105,508
152
tests/packaged_modules/test_folder_based_builder.py
74
27
def data_files_with_one_split_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) filename = data_dir / "file.txt" shutil.co...
Add AudioFolder packaged loader (#4530) * add audiofolder loader (almost identical to imagefolder except for inferring labels is not default) * add instruction on how to obtain list of audio extensions * add a generic loader * patch autofolder for streaming manually * align autofolder with the latest image...
data_files_with_one_split_and_metadata
6ea46d88c6a09244d785e55e2681bc4033740442
datasets
test_folder_based_builder.py
12
27
https://github.com/huggingface/datasets.git
1
145
1
48
255
Python
{ "docstring": "\\\n {\"file_name\": \"file.txt\", \"additional_feature\": \"Dummy file\"}\n {\"file_name\": \"file2.txt\", \"additional_feature\": \"Second dummy file\"}\n {\"file_name\": \"subdir/file3.txt\", \"additional_feature\": \"Third dummy file\"}\n ", "language": "en", "n_whi...
def data_files_with_one_split_and_metadata(tmp_path, auto_text_file): data_dir = tmp_path / "autofolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) filename = data_dir / "file.txt" shutil.co...
73,371
250,293
345
tests/handlers/test_e2e_room_keys.py
47
16
def test_upload_room_keys_wrong_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, { "algorithm": "m.megolm_backup.v1", "auth_data": "first_version_auth_data", ...
Add missing type hints to tests.handlers. (#14680) And do not allow untyped defs in tests.handlers.
test_upload_room_keys_wrong_version
652d1669c5a103b1c20478770c4aaf18849c09a3
synapse
test_e2e_room_keys.py
13
27
https://github.com/matrix-org/synapse.git
1
120
0
30
202
Python
{ "docstring": "Check that we get a 403 on uploading keys for an old version", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 13 }
def test_upload_room_keys_wrong_version(self) -> None: version = self.get_success( self.handler.create_version( self.local_user, { "algorithm": "m.megolm_backup.v1", "auth_data": "first_version_auth_data", ...
20,913
101,501
24
lib/gui/utils.py
10
11
def previewtrain(self) -> Dict[str, List[Union[Image.Image, ImageTk.PhotoImage, None, float]]]: return self._previewtrain
Bugfix: Preview for extract in batch mode
previewtrain
dc18c74eea0c7837a820d27628cb12b0824fa30e
faceswap
utils.py
8
10
https://github.com/deepfakes/faceswap.git
1
33
0
10
48
Python
{ "docstring": " dict or ``None``: The training preview images. Dictionary key is the image name\n (`str`). Dictionary values are a `list` of the training image (:class:`PIL.Image`), the\n image formatted for tkinter display (:class:`PIL.ImageTK.PhotoImage`), the last\n modification time of the i...
def previewtrain(self) -> Dict[str, List[Union[Image.Image, ImageTk.PhotoImage, None, float]]]: return self._previewtrain
12,083
60,305
204
code/deep/BJMMD/caffe/python/caffe/test/test_coord_map.py
71
18
def test_padding(self):
Balanced joint maximum mean discrepancy for deep transfer learning
test_padding
cc4d0564756ca067516f71718a3d135996525909
transferlearning
test_coord_map.py
9
16
https://github.com/jindongwang/transferlearning.git
1
165
0
36
254
Python
{ "docstring": "\n Padding conv adds offset while padding deconv subtracts offset.\n ", "language": "en", "n_whitespaces": 24, "n_words": 9, "vocab_size": 9 }
def test_padding(self): n = coord_net_spec() ax, a, b = coord_map_from_to(n.deconv, n.data) pad = random.randint(0, 10) # conv padding n = coord_net_spec(pad=pad) _, a_pad, b_pad = coord_map_from_to(n.deconv, n.data) self.assertEquals(a, a_pad) se...
121,060
337,458
14
src/accelerate/test_utils/testing.py
8
7
def require_cuda(test_case): return unittest.skipUnless(torch.cuda.is_a
Clean up tests + fix import (#330)
require_cuda
e5c17f36a8b5bf8b9478d416c4a80841a353fb19
accelerate
testing.py
11
2
https://github.com/huggingface/accelerate.git
1
24
0
8
43
Python
{ "docstring": "\n Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available.\n ", "language": "en", "n_whitespaces": 24, "n_words": 17, "vocab_size": 16 }
def require_cuda(test_case): return unittest.skipUnless(torch.cuda.is_available(), "test requires a GPU")(test_case)
72,191
248,286
66
synapse/logging/handlers.py
19
7
def _flush_periodically(self) -> None: while self._active: # flush is thread-safe; it acquires and releases the lock internally self.flush() time.sleep(self._flush_period)
Another batch of type annotations (#12726)
_flush_periodically
aec69d2481e9ea1d8ea1c0ffce1706a65a7896a8
synapse
handlers.py
10
7
https://github.com/matrix-org/synapse.git
2
26
0
19
47
Python
{ "docstring": "\n Whilst this handler is active, flush the handler periodically.\n ", "language": "en", "n_whitespaces": 24, "n_words": 9, "vocab_size": 8 }
def _flush_periodically(self) -> None: while self._active: # flush is thread-safe; it acquires and releases the lock internally self.flush() time.sleep(self._flush_period)
43,183
180,503
150
gradio/components.py
28
11
def save_flagged(self, dir, label, data, encryption_key) -> str | Dict: if "confidences" in data: return json.dumps( { example["label"]: example["confidence"]
Live website changes (#1578) * fix audio output cache (#804) * fix audio output cache * changes * version update Co-authored-by: Ali Abid <aliabid94@gmail.com> * Website Tracker Slackbot (#797) * added commands to reload script * catch errors with git pull * read new webhook from os variable ...
save_flagged
70ebf698fa75ad094a2ba52cd1de645fa58eff85
gradio
components.py
13
14
https://github.com/gradio-app/gradio.git
3
54
0
26
90
Python
{ "docstring": "\n Returns:\n Either a string representing the main category label, or a dictionary with category keys mapping to confidence levels.\n ", "language": "en", "n_whitespaces": 45, "n_words": 19, "vocab_size": 17 }
def save_flagged(self, dir, label, data, encryption_key) -> str | Dict: if "confidences" in data: return json.dumps( { example["label"]: example["confidence"] for example in data["confidences"] } ) e...
30,091
133,740
583
rllib/agents/impala/tests/test_vtrace.py
96
23
def test_higher_rank_inputs_for_importance_weights(self): for fw in framework_iterator(frameworks=("torch", "tf"), session=True): vtrace = vtrace_tf if fw != "torch" else vtrace_torch if fw ==
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
test_higher_rank_inputs_for_importance_weights
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
test_vtrace.py
18
29
https://github.com/ray-project/ray.git
4
315
0
47
447
Python
{ "docstring": "Checks support for additional dimensions in inputs.", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 7 }
def test_higher_rank_inputs_for_importance_weights(self): for fw in framework_iterator(frameworks=("torch", "tf"), session=True): vtrace = vtrace_tf if fw != "torch" else vtrace_torch if fw == "tf": inputs_ = { "log_rhos": tf1.placeholder( ...
9,232
47,727
314
tests/www/views/test_views_tasks.py
104
46
def test_task_fail_duration(app, admin_client, dag_maker, session): with dag_maker() as dag: op1 = BashOperator(task_id='fail', bash_command='exit 1') op2 = BashOperator(task_id='success', bash_command='exit 0') with pytest.raises(AirflowException): op1.run() op2.run() op1...
Fix TaskFail queries in views after run_id migration (#23008) Two problems here: 1. TaskFail no longer has a executin_date property -- switch to run_id 2. We weren't joining to DagRun correctly, meaning we'd end up with a cross-product effect(? Something weird anyway) Co-authored-by: Karthikeyan Singaravela...
test_task_fail_duration
70049f19e4ac82ea922d7e59871a3b4ebae068f1
airflow
test_views_tasks.py
15
34
https://github.com/apache/airflow.git
3
268
0
63
458
Python
{ "docstring": "Task duration page with a TaskFail entry should render without error.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def test_task_fail_duration(app, admin_client, dag_maker, session): with dag_maker() as dag: op1 = BashOperator(task_id='fail', bash_command='exit 1') op2 = BashOperator(task_id='success', bash_command='exit 0') with pytest.raises(AirflowException): op1.run() op2.run() op1...
71,062
246,168
137
tests/rest/admin/test_user.py
30
16
def test_all_users(self) -> None: self._create_users(2) channel = self.make_request( "GET", self.url + "
Add type hints to `tests/rest/admin` (#11851)
test_all_users
901b264c0c88f39cbfb8b2229e0dc57968882658
synapse
test_user.py
11
15
https://github.com/matrix-org/synapse.git
1
96
0
29
157
Python
{ "docstring": "\n List all users, including deactivated users.\n ", "language": "en", "n_whitespaces": 21, "n_words": 6, "vocab_size": 6 }
def test_all_users(self) -> None: self._create_users(2) channel = self.make_request( "GET", self.url + "?deactivated=true", {}, access_token=self.admin_user_tok, ) self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_bo...
56,586
222,485
69
python3.10.4/Lib/difflib.py
31
12
def real_quick_ratio(self): la, lb = len(self.a), len(self.b) # can't have more matches than the number of elements in the # shorter sequence return _calculate_ratio(min(la, lb), la + lb) __class_getitem__ = classmethod(GenericAlias)
add python 3.10.4 for windows
real_quick_ratio
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
difflib.py
10
3
https://github.com/XX-net/XX-Net.git
1
37
0
28
72
Python
{ "docstring": "Return an upper bound on ratio() very quickly.\n\n This isn't defined beyond that it is an upper bound on .ratio(), and\n is faster to compute than either .ratio() or .quick_ratio().\n ", "language": "en", "n_whitespaces": 51, "n_words": 30, "vocab_size": 25 }
def real_quick_ratio(self): la, lb = len(self.a), len(self.b) # can't have more matches than the number of elements in the # shorter sequence return _calculate_ratio(min(la, lb), la + lb) __class_getitem__ = classmethod(GenericAlias)
15,672
71,415
201
wagtail/admin/tests/pages/test_bulk_actions/test_bulk_unpublish.py
35
9
def test_unpublish_view_invalid_page_id(self): # Request confirm unpublish page but with illegal page id response = self.client.get( reverse( "wagtail_bulk_action", args=( "wagtailcore", "page", ...
Reformat with black
test_unpublish_view_invalid_page_id
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
test_bulk_unpublish.py
13
12
https://github.com/wagtail/wagtail.git
1
41
0
31
73
Python
{ "docstring": "\n This tests that the unpublish view returns an error if the page id is invalid\n ", "language": "en", "n_whitespaces": 30, "n_words": 15, "vocab_size": 14 }
def test_unpublish_view_invalid_page_id(self): # Request confirm unpublish page but with illegal page id response = self.client.get( reverse( "wagtail_bulk_action", args=( "wagtailcore", "page", ...
30,250
134,305
59
python/ray/train/tests/test_session.py
23
14
def test_warn_report(): fn = report with warnings.catch_warnings(
[AIR] Hard deprecate train.report, warn on air.session misuse (#29613) Signed-off-by: Antoni Baum antoni.baum@protonmail.com Hard deprecates `ray.train.report` and other session functions and ensures that the user is informed when using `ray.air.session` if they are not in session for consistency with the old funct...
test_warn_report
9b29fd6501ff0e3e69d0333bf214482b86f9e97f
ray
test_session.py
12
7
https://github.com/ray-project/ray.git
1
60
0
22
104
Python
{ "docstring": "Checks if calling session.report function outside of session raises warning.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def test_warn_report(): fn = report with warnings.catch_warnings(record=True) as record: # Ignore Deprecation warnings. warnings.filterwarnings("ignore", category=DeprecationWarning) assert not fn(dict()) assert fn.__name__ in record[0].message.args[0] reset_log_once_wit...
70,258
244,142
828
mmdet/models/dense_heads/mask2former_head.py
201
54
def forward(self, feats, img_metas): batch_size = len(img_metas) mask_features, multi_scale_memorys = self.pixel_decoder(feats) # multi_scale_memorys (from low resolution to high resolution) decoder_inputs = [] decoder_positional_encodings = [] for i in range(sel...
[Feature] Add Mask2Former to mmdet (#6938) update doc update doc format deepcopy pixel_decoder cfg move mask_pseudo_sampler cfg to config file move part of postprocess from head to detector fix bug in postprocessing move class setting from head to config file remove if else move mask2bbox to ma...
forward
14f0e9585c15c28f0c31dcc3ea352449bbe5eb96
mmdetection
mask2former_head.py
16
50
https://github.com/open-mmlab/mmdetection.git
3
412
0
121
632
Python
{ "docstring": "Forward function.\n\n Args:\n feats (list[Tensor]): Multi scale Features from the\n upstream network, each is a 4D-tensor.\n img_metas (list[dict]): List of image information.\n\n Returns:\n tuple: A tuple contains two elements.\n\n ...
def forward(self, feats, img_metas): batch_size = len(img_metas) mask_features, multi_scale_memorys = self.pixel_decoder(feats) # multi_scale_memorys (from low resolution to high resolution) decoder_inputs = [] decoder_positional_encodings = [] for i in range(sel...
50,383
203,453
627
django/contrib/admin/options.py
139
36
def formfield_for_manytomany(self, db_field, request, **kwargs): # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widg...
Refs #33476 -- Reformatted code with Black.
formfield_for_manytomany
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
options.py
15
38
https://github.com/django/django.git
11
237
0
89
376
Python
{ "docstring": "\n Get a form Field for a ManyToManyField.\n ", "language": "en", "n_whitespaces": 22, "n_words": 7, "vocab_size": 6 }
def formfield_for_manytomany(self, db_field, request, **kwargs): # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widg...
73,276
250,109
374
tests/storage/test_cleanup_extrems.py
57
8
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_...
Require types in tests.storage. (#14646) Adds missing type hints to `tests.storage` package and does not allow untyped definitions.
test_expiry_logic
3ac412b4e2f8c5ba11dc962b8a9d871c1efdce9b
synapse
test_cleanup_extrems.py
11
35
https://github.com/matrix-org/synapse.git
1
114
0
35
186
Python
{ "docstring": "Simple test to ensure that _expire_rooms_to_exclude_from_dummy_event_insertion()\n expires old entries correctly.\n ", "language": "en", "n_whitespaces": 24, "n_words": 10, "vocab_size": 10 }
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_...