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
39,462
163,605
58
pandas/core/indexers/utils.py
34
11
def is_empty_indexer(indexer) -> bool: if is_list_like(indexer) and not len(indexer): return True if not isinstance(indexer, tuple): indexer = (indexer,)
REF: simplify Block.setitem (#45403)
is_empty_indexer
6b43a78f2f1036ebae205d2d35ab96f07549fe96
pandas
utils.py
11
17
https://github.com/pandas-dev/pandas.git
6
60
0
29
98
Python
{ "docstring": "\n Check if we have an empty indexer.\n\n Parameters\n ----------\n indexer : object\n\n Returns\n -------\n bool\n ", "language": "en", "n_whitespaces": 40, "n_words": 15, "vocab_size": 15 }
def is_empty_indexer(indexer) -> bool: if is_list_like(indexer) and not len(indexer): return True if not isinstance(indexer, tuple): indexer = (indexer,) return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer) # ----------------------------------------------------...
22,565
107,046
510
lib/matplotlib/_constrained_layout.py
134
29
def make_layoutgrids_gs(layoutgrids, gs): if gs in layoutgrids or gs.figure is None: return layoutgrids # in order to do constrained_layout there has to be at least *one* # gridspec in the tree: layoutgrids['hasgrids'] = True if not hasattr(gs, '_subplot_spec'): # normal gridsp...
FIX: better repr for subgridspecs
make_layoutgrids_gs
c682ca40c647770a967b6b8a7615eb91c7cb3fc9
matplotlib
_constrained_layout.py
16
33
https://github.com/matplotlib/matplotlib.git
6
230
0
80
361
Python
{ "docstring": "\n Make the layoutgrid for a gridspec (and anything nested in the gridspec)\n ", "language": "en", "n_whitespaces": 19, "n_words": 12, "vocab_size": 11 }
def make_layoutgrids_gs(layoutgrids, gs): if gs in layoutgrids or gs.figure is None: return layoutgrids # in order to do constrained_layout there has to be at least *one* # gridspec in the tree: layoutgrids['hasgrids'] = True if not hasattr(gs, '_subplot_spec'): # normal gridsp...
17,396
82,430
212
cms/tests/test_sitemap.py
44
22
def test_sitemap_published_titles(self): sitemap = CMSSitemap() locations = [] urlset = sitemap.get_urls() for item in urlset: locations.append(item['location']) for title in Title.objects.public(): page = title.page.get_public_object() ...
ci: Added codespell (#7355) Co-authored-by: Christian Clauss <cclauss@me.com> * ci: codespell config taken from #7292
test_sitemap_published_titles
c1290c9ff89cb00caa5469129fd527e9d82cd820
django-cms
test_sitemap.py
14
16
https://github.com/django-cms/django-cms.git
6
102
0
31
203
Python
{ "docstring": "\n Check that published titles are in the urls\n ", "language": "en", "n_whitespaces": 23, "n_words": 8, "vocab_size": 8 }
def test_sitemap_published_titles(self): sitemap = CMSSitemap() locations = [] urlset = sitemap.get_urls() for item in urlset: locations.append(item['location']) for title in Title.objects.public(): page = title.page.get_public_object() ...
@derived_from(np)
36,471
155,800
343
dask/array/creation.py
121
27
def eye(N, chunks="auto", M=None, k=0, dtype=float): eye = {} if M is None: M = N if dtype is None: dtype = float if not isinstance(chunks, (int, str)): raise ValueError("chunks must be an int or string") vchunks, hchunks = normalize_chunks(chunks, shape=(N, M), dtype=...
Fix eye inconsistency with NumPy for dtype=None (#8669) (#8685)
eye
e25284dced9749f02bd5d8c80b6225153aa282d8
dask
creation.py
17
25
https://github.com/dask/dask.git
7
230
1
80
342
Python
{ "docstring": "\n Return a 2-D Array with ones on the diagonal and zeros elsewhere.\n\n Parameters\n ----------\n N : int\n Number of rows in the output.\n chunks : int, str\n How to chunk the array. Must be one of the following forms:\n\n - A blocksize like 1000.\n - A s...
def eye(N, chunks="auto", M=None, k=0, dtype=float): eye = {} if M is None: M = N if dtype is None: dtype = float if not isinstance(chunks, (int, str)): raise ValueError("chunks must be an int or string") vchunks, hchunks = normalize_chunks(chunks, shape=(N, M), dtype=...
80,885
271,876
93
keras/engine/training_utils_v1.py
24
11
def is_composite_or_composite_value(tensor): # TODO(b/125094323): This sho
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
is_composite_or_composite_value
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
training_utils_v1.py
12
9
https://github.com/keras-team/keras.git
1
39
0
23
61
Python
{ "docstring": "Returns true if 'tensor' is a CompositeTensor or a CT Value object.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 11 }
def is_composite_or_composite_value(tensor): # TODO(b/125094323): This should be isinstance(CompositeTensor) or # isinstance(CompositeTensorValue) once we support that. return isinstance( tensor, ( tf.__internal__.CompositeTensor, tf.compat.v1.SparseTensorValue, ...
17,125
80,990
346
awx/main/utils/common.py
99
28
def create_partition(tblname, start=None, end=None, partition_label=None, minutely=False): current_time = now() if not start: if minutely: start = current_time.replace(microsecond=0, second=0) else: start = current_time.replace(microsecond=0, second=0, minute=0) ...
Handle error for create_partition Occasionally the create_partition will error with, relation "main_projectupdateevent_20220323_19" already exists This change wraps the db command into a try except block with its own transaction
create_partition
24152555c5d1b52d5024197bcaf80fdb87b8b14e
awx
common.py
16
29
https://github.com/ansible/awx.git
8
201
0
67
360
Python
{ "docstring": "Creates new partition table for events.\n - start defaults to beginning of current hour\n - end defaults to end of current hour\n - partition_label defaults to YYYYMMDD_HH\n\n - minutely will create partitions that span _a single minute_ for testing purposes\n ", "language": "en", "...
def create_partition(tblname, start=None, end=None, partition_label=None, minutely=False): current_time = now() if not start: if minutely: start = current_time.replace(microsecond=0, second=0) else: start = current_time.replace(microsecond=0, second=0, minute=0) ...
76,319
260,529
63
sklearn/metrics/pairwise.py
34
11
def rbf_kernel(X, Y=None, gamma=None): X, Y = check_pairwise_arrays(X, Y)
DOC Ensure `rbf_kernel` passes numpydoc validation (#23954) Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com>
rbf_kernel
095e46670a1e21e8c49972b23e75f2d2a48c6c93
scikit-learn
pairwise.py
11
8
https://github.com/scikit-learn/scikit-learn.git
2
68
0
28
101
Python
{ "docstring": "Compute the rbf (gaussian) kernel between X and Y.\n\n K(x, y) = exp(-gamma ||x-y||^2)\n\n for each pair of rows x in X and y in Y.\n\n Read more in the :ref:`User Guide <rbf_kernel>`.\n\n Parameters\n ----------\n X : ndarray of shape (n_samples_X, n_features)\n A feature...
def rbf_kernel(X, Y=None, gamma=None): X, Y = check_pairwise_arrays(X, Y) if gamma is None: gamma = 1.0 / X.shape[1] K = euclidean_distances(X, Y, squared=True) K *= -gamma np.exp(K, K) # exponentiate K in-place return K
78,517
266,698
974
lib/ansible/module_utils/common/parameters.py
248
35
def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None): if errors is None: errors = AnsibleValidationErrorMultiple() for param, spec in argument_spec.items(): choices = spec.get('choices') if choices is None: continue if is...
parameters: handle blank values when argument is a list (#77119) Fixes: #77108 Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
_validate_argument_values
4f48f375a0203b0d09c55522a86300a52da5b24a
ansible
parameters.py
24
38
https://github.com/ansible/ansible.git
22
356
0
128
578
Python
{ "docstring": "Ensure all arguments have the requested values, and there are no stray arguments", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 12 }
def _validate_argument_values(argument_spec, parameters, options_context=None, errors=None): if errors is None: errors = AnsibleValidationErrorMultiple() for param, spec in argument_spec.items(): choices = spec.get('choices') if choices is None: continue if is...
2,892
19,145
41
mlflow/models/evaluation/base.py
9
4
def content(self): if self._content is None: self._load()
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...
content
4c58179509e6f6047789efb0a95c2b0e20cb6c8f
mlflow
base.py
9
4
https://github.com/mlflow/mlflow.git
2
22
0
8
39
Python
{ "docstring": "\n The content of the artifact (representation varies)\n ", "language": "en", "n_whitespaces": 22, "n_words": 7, "vocab_size": 7 }
def content(self): if self._content is None: self._load() return self._content
@frappe.whitelist(allow_guest=True)
13,657
64,540
95
erpnext/e_commerce/api.py
143
37
def get_product_filter_data(query_args=None): if isinstance(query_args, str): query_args = json.loads(query_args) query_args = frappe._dict(query_args) if query_args: search = query_args.get("search") field_filters = query_args.get("field_filters", {}) attribute_filters = query_args.get("attribute_filters...
feat: Include child item group products in Item Group Page & cleanup - Added 'Include descendants' checkbox, which will pull child item group products too - Build item group filters in query engine file - Include logic in filter engine - Clean up Website section of Item Group page (UX) - Add util to fetch child item g...
get_product_filter_data
b2755f6fdddd3e1b0a305b57c18651c98fee8f7e
erpnext
api.py
13
46
https://github.com/frappe/erpnext.git
9
271
1
100
464
Python
{ "docstring": "\n\t\tReturns filtered products and discount filters.\n\t\t:param query_args (dict): contains filters to get products list\n\n\t\tQuery Args filters:\n\t\tsearch (str): Search Term.\n\t\tfield_filters (dict): Keys include item_group, brand, etc.\n\t\tattribute_filters(dict): Keys include Color, Size, ...
def get_product_filter_data(query_args=None): if isinstance(query_args, str): query_args = json.loads(query_args) query_args = frappe._dict(query_args) if query_args: search = query_args.get("search") field_filters = query_args.get("field_filters", {}) attribute_filters = query_args.get("attribute_filters...
89,421
290,303
35
homeassistant/components/mqtt/light/schema_basic.py
13
7
async def async_turn_on(self, **kwargs): # noqa: C901 should
Use `_attr_` for MQTT light (#81465) * Schema basic * Schema json * Schema template * add color_mode - follow up comments * Fix regression * Follow up comments 2 * Fix mypy errors * Update homeassistant/components/mqtt/light/schema_template.py Co-authored-by: epenet <6771947+epenet@users.norepl...
async_turn_on
d66d079330b92c02c38fb1c9dca539617161fdbc
core
schema_basic.py
8
126
https://github.com/home-assistant/core.git
43
909
0
12
36
Python
{ "docstring": "Turn the device on.\n\n This method is a coroutine.\n ", "language": "en", "n_whitespaces": 23, "n_words": 9, "vocab_size": 9 }
async def async_turn_on(self, **kwargs): # noqa: C901 should_update = False on_command_type = self._config[CONF_ON_COMMAND_TYPE]
117,683
321,374
54
tests/unit/keyinput/test_keyutils.py
19
16
def test_fake_mac(self, modifiers, expected): seq = keyutils.KeySequence() info = keyutils.KeyInfo(key=Qt.K
Run scripts/dev/rewrite_enums.py
test_fake_mac
0877fb0d78635692e481c8bde224fac5ad0dd430
qutebrowser
test_keyutils.py
11
5
https://github.com/qutebrowser/qutebrowser.git
1
65
0
17
102
Python
{ "docstring": "Make sure Control/Meta are swapped with a simulated Mac.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_fake_mac(self, modifiers, expected): seq = keyutils.KeySequence() info = keyutils.KeyInfo(key=Qt.Key.Key_A, modifiers=modifiers) new = seq.append_event(info.to_event()) assert new[0] == keyutils.KeyInfo(Qt.Key.Key_A, expected)
628
4,171
25
airbyte-integrations/connectors/source-recurly/source_recurly/streams.py
11
5
def default_params(self) -> dict: return {"order": "asc", "sort": self.sort_key, "limit": self.limit}
🎉 Recurly Schema Revamp (#9866) * Cleanup Recurly connector schemas * Add more Recurly schemas to the connector - `billing_infos` - `shipping_addresses` - `shipping_methods` - `subscription_changes` * Add Recurly `add-on` resouce * Add Recurly's account notes resource schema * Add unique coupons to ...
default_params
63af98e3b999d4b223237b51472a819915c5a558
airbyte
streams.py
8
5
https://github.com/airbytehq/airbyte.git
1
26
0
11
49
Python
{ "docstring": "\n Returns the parameters to be sent together with the API call to Recurly\n ", "language": "en", "n_whitespaces": 28, "n_words": 13, "vocab_size": 11 }
def default_params(self) -> dict: return {"order": "asc", "sort": self.sort_key, "limit": self.limit}
33,312
144,810
154
python/ray/serve/deployment_state.py
69
11
def _should_start_new_health_check(self) -> bool: if self._health_check_ref is not None: # There's already an active health check. return False # If there's no active health check, kick off another and reset # the timer if it's been long enough since the last he...
[serve] Improve health check failure semantics (#22297)
_should_start_new_health_check
610930ae6aeafb37be75851a8c1b9ff39d5f7d22
ray
deployment_state.py
9
16
https://github.com/ray-project/ray.git
2
51
0
55
81
Python
{ "docstring": "Determines if a new health check should be kicked off.\n\n A health check will be started if:\n 1) There is not already an active health check.\n 2) It has been more than self._health_check_period_s since the\n previous health check was *started*.\n\n ...
def _should_start_new_health_check(self) -> bool: if self._health_check_ref is not None: # There's already an active health check. return False # If there's no active health check, kick off another and reset # the timer if it's been long enough since the last he...
6,885
37,910
104
src/transformers/trainer_pt_utils.py
64
14
def numpy_pad_and_concatenate(array1, array2, padding_index=-100): array1 = atleas
Ensure tensors are at least 1d for pad and concat (#17179) * Ensure tensors are at least 1d for pad and concat * Compatibility * Fix * Fix * Add test * Retrigger CI * Consistency with master * Retrigger CI
numpy_pad_and_concatenate
47412c7d434f6ddfc02a9b7ecd6182b86ae0a164
transformers
trainer_pt_utils.py
12
10
https://github.com/huggingface/transformers.git
3
162
0
49
242
Python
{ "docstring": "Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.", "language": "en", "n_whitespaces": 13, "n_words": 14, "vocab_size": 13 }
def numpy_pad_and_concatenate(array1, array2, padding_index=-100): array1 = atleast_1d(array1) array2 = atleast_1d(array2) if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]: return np.concatenate((array1, array2), axis=0) # Let's figure out the new shape new_shape = (arr...
10,926
53,859
146
src/prefect/task_runners.py
32
6
def _ray(self) -> "ray": global ray if r
First draft `RayTaskRunner` implementation
_ray
f97603bba836c215e153d7d3d5b3b9de4d0ae822
prefect
task_runners.py
13
14
https://github.com/PrefectHQ/prefect.git
3
33
0
29
61
Python
{ "docstring": "\n Delayed import of `ray` allowing configuration of the task runner\n without the extra installed and improves `prefect` import times.\n ", "language": "en", "n_whitespaces": 41, "n_words": 19, "vocab_size": 16 }
def _ray(self) -> "ray": global ray if ray is None: try: import ray except ImportError as exc: raise RuntimeError( "Using the `RayTaskRunner` requires `ray` to be installed." ) from exc return ...
89,349
290,231
90
homeassistant/components/zwave_js/climate.py
18
10
def temperature_unit(self) -> str: if ( self._unit_value and self._unit_v
Use enums instead of deprecated constants (#81591)
temperature_unit
9a747bafa398185eb3d4fe041c52acfbb8264372
core
climate.py
13
9
https://github.com/home-assistant/core.git
4
45
0
16
75
Python
{ "docstring": "Return the unit of measurement used by the platform.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 8 }
def temperature_unit(self) -> str: if ( self._unit_value and self._unit_value.metadata.unit and "f" in self._unit_value.metadata.unit.lower() ): return UnitOfTemperature.FAHRENHEIT return UnitOfTemperature.CELSIUS
23,870
109,993
544
examples/text_labels_and_annotations/angles_on_bracket_arrows.py
221
48
def get_point_of_rotated_vertical(origin, line_length, degrees): rad = np.deg2rad(-degrees) return [origin[0] + line_length * np.sin(rad), origin[1] + line_length * np.cos(rad)] fig, ax = plt.subplots(figsize=(8, 7)) ax.set(xlim=(0, 6), ylim=(-1, 4)) ax.set_title("Orientation of the bracket a...
Updated Angles on Bracket arrow styles example to make angles clear #23176 (#24145) * removed AngleAnnotation from angle_on_bracket_arrow example * Fixes indentation mistake. * rebase to main, remove conflicting commit
get_point_of_rotated_vertical
f15aeee5e8d380c2ea04bcbed202a8940a7db1d0
matplotlib
angles_on_bracket_arrows.py
16
4
https://github.com/matplotlib/matplotlib.git
1
49
0
150
608
Python
{ "docstring": "Return xy coordinates of the vertical line end rotated by degrees.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def get_point_of_rotated_vertical(origin, line_length, degrees): rad = np.deg2rad(-degrees) return [origin[0] + line_length * np.sin(rad), origin[1] + line_length * np.cos(rad)] fig, ax = plt.subplots(figsize=(8, 7)) ax.set(xlim=(0, 6), ylim=(-1, 4)) ax.set_title("Orientation of the bracket a...
12,977
62,436
19
.venv/lib/python3.8/site-packages/pip/_vendor/html5lib/_tokenizer.py
5
5
def processEntityInAttribute(self, allowedChar): self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
upd; format
processEntityInAttribute
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
_tokenizer.py
8
2
https://github.com/jindongwang/transferlearning.git
1
20
0
5
33
Python
{ "docstring": "This method replaces the need for \"entityInAttributeValueState\".\n ", "language": "en", "n_whitespaces": 14, "n_words": 7, "vocab_size": 7 }
def processEntityInAttribute(self, allowedChar): self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
49,638
200,424
148
sympy/physics/secondquant.py
67
21
def _get_ordered_dummies(mul, verbose=False): # setup dicts to avoid repeated calculations in key() args = Mul.make_args(mul) fac_dum = { fac: fac.atoms(Dummy) for fac in args } fac_repr = { fac: __kprint(fac) for fac in args } all_dums = set().union(*fac_dum.values()) mask = {} for d i...
Fix various typos Found via `codespell -q 3 -L aboves,aline,ans,aother,arithmetics,assum,atleast,braket,clen,declar,declars,dorder,dum,enew,fo,fro,inout,iself,ist,ket,lamda,lightyear,lightyears,nd,numer,numers,orderd,ot,pring,rcall,rever,ro,ser,siz,splitted,sring,supercedes,te,tht,unequality,upto,vas,versin,whet`
_get_ordered_dummies
24f1e7730119fe958cc8e28411f790c9a5ec04eb
sympy
secondquant.py
12
26
https://github.com/sympy/sympy.git
13
258
0
43
211
Python
{ "docstring": "Returns all dummies in the mul sorted in canonical order.\n\n Explanation\n ===========\n\n The purpose of the canonical ordering is that dummies can be substituted\n consistently across terms with the result that equivalent terms can be\n simplified.\n\n It is not possible to determ...
def _get_ordered_dummies(mul, verbose=False): # setup dicts to avoid repeated calculations in key() args = Mul.make_args(mul) fac_dum = { fac: fac.atoms(Dummy) for fac in args } fac_repr = { fac: __kprint(fac) for fac in args } all_dums = set().union(*fac_dum.values()) mask = {} for d i...
9,378
48,153
385
airflow/providers/amazon/aws/example_dags/example_athena.py
107
51
def read_results_from_s3(query_execution_id): s3_hook = S3Hook() file_obj = s3_hook.get_conn().get_object(Bucket=S3_BUCKET, Key=f'{S3_KEY}/{query_execution_id}.csv') file_content = file_obj['Body'].read().decode('utf-8') print(file_content) QUERY_CREATE_TABLE = f QUERY_READ_TABLE = f QUERY_DROP_TABL...
Update the Athena Sample DAG and Docs (#23428) * Update the Athena Sample DAG and Docs
read_results_from_s3
46af5baba810a07eec395e89db08fc5dab175e23
airflow
example_athena.py
12
5
https://github.com/apache/airflow.git
1
48
0
63
462
Python
{ "docstring": "\nCREATE EXTERNAL TABLE IF NOT EXISTS {ATHENA_DATABASE}.{ATHENA_TABLE} ( `name` string, `age` int )\nROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'\nWITH SERDEPROPERTIES ( 'serialization.format' = ',', 'field.delim' = ','\n) LOCATION 's3://{S3_BUCKET}/{S3_KEY}/{ATHENA_TABLE}'\nT...
def read_results_from_s3(query_execution_id): s3_hook = S3Hook() file_obj = s3_hook.get_conn().get_object(Bucket=S3_BUCKET, Key=f'{S3_KEY}/{query_execution_id}.csv') file_content = file_obj['Body'].read().decode('utf-8') print(file_content) QUERY_CREATE_TABLE = f QUERY_READ_TABLE = f QUERY_DROP_TABL...
40,074
167,667
112
pandas/core/dtypes/common.py
37
12
def is_datetime64_ns_dtype(arr_or_dtype) -> bool: if arr_or_dtype is None: return False try: tipo = get_dtype(arr_or_dtype) except TypeError:
ENH: DTI/DTA.astype support non-nano (#47579) * ENH: DTI/DTA.astype support non-nano * whatsnew * GH ref * pyright fixup
is_datetime64_ns_dtype
67e8c4c3761ab1da4b0a341a472c0fe2ea393e8b
pandas
common.py
14
47
https://github.com/pandas-dev/pandas.git
6
63
0
29
106
Python
{ "docstring": "\n Check whether the provided array or dtype is of the datetime64[ns] dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like or dtype\n The array or dtype to check.\n\n Returns\n -------\n bool\n Whether or not the array or dtype is of the datetime64[ns] dtyp...
def is_datetime64_ns_dtype(arr_or_dtype) -> bool: if arr_or_dtype is None: return False try: tipo = get_dtype(arr_or_dtype) except TypeError: if is_datetime64tz_dtype(arr_or_dtype): tipo = get_dtype(arr_or_dtype.dtype) else: return False retur...
@register.tag
50,267
203,239
290
django/template/defaulttags.py
131
15
def regroup(parser, token): bits = token.split_contents() if len(bits) != 6: raise TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(bits[1]) if bits[2] != 'by': raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") if ...
Refs #33476 -- Refactored problematic code before reformatting by Black. In these cases Black produces unexpected results, e.g. def make_random_password( self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789', ): or cursor.execute(""" SELECT ... """, ...
regroup
c5cd8783825b5f6384417dac5f3889b4210b7d08
django
defaulttags.py
10
16
https://github.com/django/django.git
4
95
1
95
172
Python
{ "docstring": "\n Regroup a list of alike objects by a common attribute.\n\n This complex tag is best illustrated by use of an example: say that\n ``musicians`` is a list of ``Musician`` objects that have ``name`` and\n ``instrument`` attributes, and you'd like to display a list that\n looks like:\n\n...
def regroup(parser, token): bits = token.split_contents() if len(bits) != 6: raise TemplateSyntaxError("'regroup' tag takes five arguments") target = parser.compile_filter(bits[1]) if bits[2] != 'by': raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") if ...
5,427
30,242
42
spotdl/types/saved.py
14
7
def create_basic_list(cls) -> "Saved": metadata
fixed arguments for frozen env fixed pylint errors fixed arguments black fixed argument parser for all scenarios black docs black
create_basic_list
773398048b7990ab58e2998fe4d15355f7998774
spotify-downloader
saved.py
9
10
https://github.com/spotDL/spotify-downloader.git
1
39
0
13
70
Python
{ "docstring": "\n Create a basic list with only the required metadata and urls.\n\n ### Returns\n - The Saved object.\n ", "language": "en", "n_whitespaces": 46, "n_words": 17, "vocab_size": 17 }
def create_basic_list(cls) -> "Saved": metadata = cls.get_metadata("saved") urls = cls.get_urls("saved") return cls(**metadata, urls=urls, songs=[])
95,675
296,701
49
tests/common.py
23
5
def assert_lists_same(a, b): assert len(a) == len(b) for i in a: assert i in b for i in b: assert i in a
Mark device actions from hidden or auxiliary entities as secondary (#70278)
assert_lists_same
64381acbaf2930cda5dfa538d00bfa9f5172e690
core
common.py
8
6
https://github.com/home-assistant/core.git
3
36
0
14
57
Python
{ "docstring": "Compare two lists, ignoring order.\n\n Check both that all items in a are in b and that all items in b are in a,\n otherwise assert_lists_same([\"1\", \"1\"], [\"1\", \"2\"]) could be True.\n ", "language": "en", "n_whitespaces": 41, "n_words": 32, "vocab_size": 24 }
def assert_lists_same(a, b): assert len(a) == len(b) for i in a: assert i in b for i in b: assert i in a
36,771
156,780
453
dask/dataframe/tests/test_format.py
100
20
def test_dataframe_format_with_index(): pytest.importorskip("jinja2") df = pd.DataFrame( { "A": [1, 2, 3, 4, 5, 6, 7, 8], "B": list("ABCDEFGH"), "C": pd.Categorical(list("AAABBBCC")), }, index=list("ABCDEFGH"), ) ddf = dd.from_pandas(df, 3) ...
Change repr methods to avoid Layer materialization (#9289) * change task count to layer count in DataFrame and Array reprs * add test * address doctest failure * simplify test * support pluralization * use 'graph layers' instead of 'layers' to be more explicit
test_dataframe_format_with_index
ddcb841903f8f180aa359bd8db0054aa3b5964e3
dask
test_format.py
15
79
https://github.com/dask/dask.git
1
145
0
70
259
Python
{ "docstring": "<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>A</th>\n <th>B</th>\n <th>C</th>\n </tr>\n <tr>\n <th>npartitions=3</th>\n <th></th>\n <th></th>\n <th></th>\n </tr>\n </thead>\n <tbody>\n ...
def test_dataframe_format_with_index(): pytest.importorskip("jinja2") df = pd.DataFrame( { "A": [1, 2, 3, 4, 5, 6, 7, 8], "B": list("ABCDEFGH"), "C": pd.Categorical(list("AAABBBCC")), }, index=list("ABCDEFGH"), ) ddf = dd.from_pandas(df, 3) ...
51,942
207,372
88
tests/admin_scripts/tests.py
28
15
def test_run_from_argv_closes_connections(self):
Refs #33476 -- Reformatted code with Black.
test_run_from_argv_closes_connections
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
11
7
https://github.com/django/django.git
1
61
0
26
111
Python
{ "docstring": "\n A command called from the command line should close connections after\n being executed (#21255).\n ", "language": "en", "n_whitespaces": 36, "n_words": 14, "vocab_size": 13 }
def test_run_from_argv_closes_connections(self): command = BaseCommand() command.check = lambda: [] command.handle = lambda *args, **kwargs: args with mock.patch("django.core.management.base.connections") as mock_connections: command.run_from_argv(["", ""]) #...
26,025
117,547
1,445
tests/unit/test_project_structure.py
536
31
def test_version_managing(self, data_handler): # set up df = pd.DataFrame([ {'a': 1, 'b': dt.datetime(2020, 1, 1)}, {'a': 2, 'b': dt.datetime(2020, 1, 2)}, {'a': 1, 'b': dt.datetime(2020, 1, 3)}, ]) self.set_handler(data_handler, name='pg', tables={'t...
update and delete model version renaming (predictor->model)
test_version_managing
3f1a5c30c2ccbd78b21f1f41b7dfdfca87bb7135
mindsdb
test_project_structure.py
13
130
https://github.com/mindsdb/mindsdb.git
5
716
0
173
1,293
Python
{ "docstring": "\n CREATE PREDICTOR proj.task_model\n from pg (select * from tasks)\n PREDICT a\n using engine='dummy_ml', tag = 'first'\n \n SELECT m.*\n FROM pg.tasks as t\n JOIN proj.task_model as m\n ...
def test_version_managing(self, data_handler): # set up df = pd.DataFrame([ {'a': 1, 'b': dt.datetime(2020, 1, 1)}, {'a': 2, 'b': dt.datetime(2020, 1, 2)}, {'a': 1, 'b': dt.datetime(2020, 1, 3)}, ]) self.set_handler(data_handler, name='pg', tables={'t...
@functools.lru_cache(maxsize=None)
2,979
19,462
58
pipenv/patched/notpip/_internal/locations/__init__.py
25
12
def _looks_like_red_hat_lib() -> bool: from distutils.command.install import INSTALL_SCHEMES # type: ignore return all( k in INSTALL_SCHEMES and _looks_like_red_hat_patched_platlib
Vendor in pip 21.2.4 release (from pip 21.2.2 prior). (#5009) * Vendor in pip 21.2.4 release (from pip 21.2.2 prior). * Add news fragment for pip 21.2.4 vendor update. * Add potentially missing LICENSE files
_looks_like_red_hat_lib
7e33fcae4384563b4c927fd44318c29dd524a097
pipenv
__init__.py
11
11
https://github.com/pypa/pipenv.git
3
38
1
22
79
Python
{ "docstring": "Red Hat patches platlib in unix_prefix and unix_home, but not purelib.\n\n This is the only way I can see to tell a Red Hat-patched Python.\n ", "language": "en", "n_whitespaces": 31, "n_words": 25, "vocab_size": 24 }
def _looks_like_red_hat_lib() -> bool: from distutils.command.install import INSTALL_SCHEMES # type: ignore return all( k in INSTALL_SCHEMES and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k]) for k in ("unix_prefix", "unix_home") ) @functools.lru_cache(maxsi...
15,958
73,144
331
wagtail/contrib/modeladmin/helpers/permission.py
83
27
def get_valid_parent_pages(self, user): # Get queryset of pages where this page type can be added allowed_parent_page_content_types = list( ContentType.objects.get_for_models( *self.model.allowed_parent_page_models() ).values() ) allowed_p...
Reformat with black
get_valid_parent_pages
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
permission.py
16
19
https://github.com/wagtail/wagtail.git
3
109
0
58
184
Python
{ "docstring": "\n Identifies possible parent pages for the current user by first looking\n at allowed_parent_page_models() on self.model to limit options to the\n correct type of page, then checking permissions on those individual\n pages to make sure we have permission to add a subpage t...
def get_valid_parent_pages(self, user): # Get queryset of pages where this page type can be added allowed_parent_page_content_types = list( ContentType.objects.get_for_models( *self.model.allowed_parent_page_models() ).values() ) allowed_p...
14,149
66,255
22
erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
35
19
def get_attendance_list(conditions, filters): attendance_list = frapp
style: format code with black
get_attendance_list
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
monthly_attendance_sheet.py
13
15
https://github.com/frappe/erpnext.git
3
94
0
31
149
Python
{ "docstring": "select employee, day(attendance_date) as day_of_month,\n\t\tstatus from tabAttendance where docstatus = 1 %s order by employee, attendance_date", "language": "en", "n_whitespaces": 15, "n_words": 17, "vocab_size": 16 }
def get_attendance_list(conditions, filters): attendance_list = frappe.db.sql( % conditions, filters, as_dict=1, ) if not attendance_list: msgprint(_("No attendance record found"), alert=True, indicator="orange") att_map = {} for d in attendance_list: att_map.setdefault(d.employee, frappe._dict()).s...
@add_start_docstrings( """ RemBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks. """, REMBERT_START_DOCSTRING, )
6,559
35,987
60
src/transformers/models/rembert/modeling_tf_rembert.py
25
12
def _reorder_cache(past, beam_idx): reordered_past = () for layer_past in past: reordered_past += (tuple(tf.gather(past_state, bea
TF generate refactor - past without encoder outputs (#15944) * Remove packed past from generation_tf_utils * update models with the new past format * update template accordingly
_reorder_cache
70203b59379b1841013980b6941bddfd34bfe816
transformers
modeling_tf_rembert.py
14
5
https://github.com/huggingface/transformers.git
3
42
1
21
76
Python
{ "docstring": "\n RemBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.\n ", "language": "en", "n_whitespaces": 21, "n_words": 14, "vocab_size": 14 }
def _reorder_cache(past, beam_idx): reordered_past = () for layer_past in past: reordered_past += (tuple(tf.gather(past_state, beam_idx, axis=0) for past_state in layer_past),) return reordered_past @add_start_docstrings( , REMBERT_START_DOCSTRING, )
19,756
100,089
223
tests/sentry/api/endpoints/test_team_details.py
66
27
def test_remove_as_admin_not_in_team(self): # an org with closed membership (byproduct of flags=0) org = self.create_organization(owner=self.user, flags=0) team = self.create_team(organization=org) admin_user = self.create_user(email="foo@example.com", is_superuser=False) ...
ref(tests): Remove `get_valid_response()` (#34822)
test_remove_as_admin_not_in_team
096b5511e244eecd8799b2a0324655207ce8985e
sentry
test_team_details.py
10
17
https://github.com/getsentry/sentry.git
1
138
0
49
221
Python
{ "docstring": "Admins can't remove teams of which they're not a part, unless\n open membership is on.", "language": "en", "n_whitespaces": 21, "n_words": 15, "vocab_size": 15 }
def test_remove_as_admin_not_in_team(self): # an org with closed membership (byproduct of flags=0) org = self.create_organization(owner=self.user, flags=0) team = self.create_team(organization=org) admin_user = self.create_user(email="foo@example.com", is_superuser=False) ...
29,474
131,087
239
python/ray/tests/aws/test_aws_batch_tag_update.py
61
29
def batch_test(num_threads, delay): with mock.patch( "ray.autoscaler._private.aws.node_provider.make_ec2_client" ), mock.patch.object(AWSNodeProvider, "_create_tags", mock_create_tags): provider = AWSNodeProvider( provider_config={"region": "nowhere"}, cluster_name="default" ...
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
batch_test
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
test_aws_batch_tag_update.py
17
22
https://github.com/ray-project/ray.git
5
154
0
43
256
Python
{ "docstring": "Run AWSNodeProvider.set_node_tags in several threads, with a\n specified delay between thread launches.\n\n Return the number of batches of tag updates and the number of tags\n updated.\n ", "language": "en", "n_whitespaces": 38, "n_words": 26, "vocab_size": 22 }
def batch_test(num_threads, delay): with mock.patch( "ray.autoscaler._private.aws.node_provider.make_ec2_client" ), mock.patch.object(AWSNodeProvider, "_create_tags", mock_create_tags): provider = AWSNodeProvider( provider_config={"region": "nowhere"}, cluster_name="default" ...
@PLUGIN_LAYERS.register_module()
70,215
244,048
142
mmdet/models/plugins/pixel_decoder.py
42
22
def forward(self, feats, img_metas): y = self.last_feat_conv(feats[-1]) for i in range(self.num_inputs - 2, -1, -1): x = feats[i] cur_fpn = self.lateral_convs[i](x) y = cur_fpn + \ F.interpolate(y, size=cur_fpn.shape[-2:], mode='nearest') ...
[Feature] Add Maskformer to mmdet (#7212) * first commit * add README * move model description from config to readme add description for binary_input add description for dice loss add a independent panoptic gt processing function add a independent panoptic gt processing function remove compatibili...
forward
cac356380d505bf15587f07c0529218cc36b9652
mmdetection
pixel_decoder.py
15
11
https://github.com/open-mmlab/mmdetection.git
2
113
1
32
186
Python
{ "docstring": "\n Args:\n feats (list[Tensor]): Feature maps of each level. Each has\n shape of (batch_size, c, h, w).\n img_metas (list[dict]): List of image information. Pass in\n for creating more accurate padding mask. Not used here.\n\n Returns:\...
def forward(self, feats, img_metas): y = self.last_feat_conv(feats[-1]) for i in range(self.num_inputs - 2, -1, -1): x = feats[i] cur_fpn = self.lateral_convs[i](x) y = cur_fpn + \ F.interpolate(y, size=cur_fpn.shape[-2:], mode='nearest') ...
89,709
290,594
97
tests/components/bluetooth/test_models.py
23
12
async def test_remote_scanner_expires_non_connectable(hass): manager = _get_manager() switchbot_device = BLEDevice(
Move bluetooth remote scanner implementation into a base class (#82012)
test_remote_scanner_expires_non_connectable
f584efa0c24df19ef1f805ecf95a95cecec5ff99
core
test_models.py
12
64
https://github.com/home-assistant/core.git
1
301
0
19
95
Python
{ "docstring": "Test the remote scanner expires stale non connectable data.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
async def test_remote_scanner_expires_non_connectable(hass): manager = _get_manager() switchbot_device = BLEDevice( "44:44:33:11:23:45", "wohand", {}, rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", service_uuids...
78,972
267,605
73
lib/ansible/plugins/inventory/toml.py
30
9
def convert_yaml_objects_to_native(obj): if isinstance(obj, dict):
Support for Python 3.11+ tomllib for inventory (#77435)
convert_yaml_objects_to_native
bcdc2e167af61cf978e589c753764f76e301a6fa
ansible
toml.py
12
9
https://github.com/ansible/ansible.git
6
72
0
21
113
Python
{ "docstring": "Older versions of the ``toml`` python library, and tomllib, don't have\n a pluggable way to tell the encoder about custom types, so we need to\n ensure objects that we pass are native types.\n\n Used with:\n - ``toml<0.10.0`` where ``toml.TomlEncoder`` is missing\n - ``tomli`` or ``...
def convert_yaml_objects_to_native(obj): if isinstance(obj, dict): return dict((k, convert_yaml_objects_to_native(v)) for k, v in obj.items()) elif isinstance(obj, list): return [convert_yaml_objects_to_native(v) for v in obj] elif isinstance(obj, text_type): return text_type(ob...
437
3,302
274
python/prophet/forecaster.py
94
19
def make_future_dataframe(self, periods, freq='D', include_history=True): if self.history_dates is None: raise Exception('Model has not been fit.') if freq is None: # taking the tail makes freq inference more reliable freq = pd.infer_freq(self.history_dates.t...
Speed Up Uncertainty Predictions (#2186)
make_future_dataframe
8fbf8ba2a5bfcdb892e8ca596e338894614000b5
prophet
forecaster.py
14
17
https://github.com/facebook/prophet.git
5
135
0
66
223
Python
{ "docstring": "Simulate the trend using the extrapolated generative model.\n\n Parameters\n ----------\n periods: Int number of periods to forecast forward.\n freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.\n include_history: Boolean to include the historical dates...
def make_future_dataframe(self, periods, freq='D', include_history=True): if self.history_dates is None: raise Exception('Model has not been fit.') if freq is None: # taking the tail makes freq inference more reliable freq = pd.infer_freq(self.history_dates.t...
12,044
60,251
41
code/deep/BJMMD/caffe/python/caffe/io.py
16
13
def array_to_blobproto(arr, diff=None): blob = caffe_pb2.BlobProt
Balanced joint maximum mean discrepancy for deep transfer learning
array_to_blobproto
cc4d0564756ca067516f71718a3d135996525909
transferlearning
io.py
12
7
https://github.com/jindongwang/transferlearning.git
2
67
0
15
109
Python
{ "docstring": "Converts a N-dimensional array to blob proto. If diff is given, also\n convert the diff. You need to make sure that arr and diff have the same\n shape, and this function does not do sanity check.\n ", "language": "en", "n_whitespaces": 45, "n_words": 36, "vocab_size": 32 }
def array_to_blobproto(arr, diff=None): blob = caffe_pb2.BlobProto() blob.shape.dim.extend(arr.shape) blob.data.extend(arr.astype(float).flat) if diff is not None: blob.diff.extend(diff.astype(float).flat) return blob
72,114
248,122
767
tests/test_federation.py
145
27
def test_cross_signing_keys_retry(self): remote_user_id = "@john:test_remote" remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY" remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ" # Register mock device list retrieval on the federation client...
Prefer `make_awaitable` over `defer.succeed` in tests (#12505) When configuring the return values of mocks, prefer awaitables from `make_awaitable` over `defer.succeed`. `Deferred`s are only awaitable once, so it is inappropriate for a mock to return the same `Deferred` multiple times. Also update `run_in_backgr...
test_cross_signing_keys_retry
78b99de7c206b106340e12cdee0af9aa246bd5ad
synapse
test_federation.py
19
45
https://github.com/matrix-org/synapse.git
1
263
0
87
464
Python
{ "docstring": "Tests that resyncing a device list correctly processes cross-signing keys from\n the remote server.\n ", "language": "en", "n_whitespaces": 28, "n_words": 14, "vocab_size": 14 }
def test_cross_signing_keys_retry(self): remote_user_id = "@john:test_remote" remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY" remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ" # Register mock device list retrieval on the federation client...
8,783
46,113
239
tests/providers/databricks/operators/test_databricks.py
50
30
def test_exec_success(self, db_mock_class): run = { 'new_cluster': NEW_CLUSTER, 'notebook_task': NOTEBOOK_TASK, } op = DatabricksSubmitRunOperator(task_id=TASK_ID, json=run) db_mock = db_mock_class.return_value db_mock.submit_run.return_value = 1 ...
Databricks hook - retry on HTTP Status 429 as well (#21852) * Databricks hook - retry on HTTP Status 429 as well this fixes #21559 * Reimplement retries using tenacity it's now uses exponential backoff by default
test_exec_success
12e9e2c695f9ebb9d3dde9c0f7dfaa112654f0d6
airflow
test_databricks.py
11
23
https://github.com/apache/airflow.git
1
137
0
41
224
Python
{ "docstring": "\n Test the execute function in case where the run is successful.\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 10 }
def test_exec_success(self, db_mock_class): run = { 'new_cluster': NEW_CLUSTER, 'notebook_task': NOTEBOOK_TASK, } op = DatabricksSubmitRunOperator(task_id=TASK_ID, json=run) db_mock = db_mock_class.return_value db_mock.submit_run.return_value = 1 ...
7,513
42,253
62
seaborn/palettes.py
41
18
def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"): rgb = _color_to_rgb(color, input) h, s, l = husl.rgb_to_husl(*rgb) gray_s, gray_l = .15 * s, 15 gray = _color_to_rgb
Convert color palette docstrings to notebooks (#3034) * Convert color palette docstrings to notebooks and rerun all with py310 kernel * Add v0.12.1 release notes to index * Improve failure mode when ipywidgets is not involved * Update palettes docstrings * Remove all other doctest-style examples * Remov...
dark_palette
e644793f0ac2b1be178425f20f529121f37f29de
seaborn
palettes.py
10
7
https://github.com/mwaskom/seaborn.git
2
93
0
35
137
Python
{ "docstring": "Make a sequential palette that blends from dark to ``color``.\n\n This kind of palette is good for data that range between relatively\n uninteresting low values and interesting high values.\n\n The ``color`` parameter can be specified in a number of ways, including\n all options for defini...
def dark_palette(color, n_colors=6, reverse=False, as_cmap=False, input="rgb"): rgb = _color_to_rgb(color, input) h, s, l = husl.rgb_to_husl(*rgb) gray_s, gray_l = .15 * s, 15 gray = _color_to_rgb((h, gray_s, gray_l), input="husl") colors = [rgb, gray] if reverse else [gray, rgb] return ble...
22,462
106,834
26
py/visdom/__init__.py
12
8
def contour(self, X, win=None, env=None, opts=None): return self._surface(X=X, stype="contour", opts=opts, win=win, env=env
apply black py to all python files
contour
5b8b7f267cfaf76a2a39a727ef31a62b3909a093
visdom
__init__.py
9
2
https://github.com/fossasia/visdom.git
1
45
0
12
66
Python
{ "docstring": "\n This function draws a contour plot. It takes as input an `NxM` tensor\n `X` that specifies the value at each location in the contour plot.\n\n The following `opts` are supported:\n\n - `opts.colormap`: colormap (`string`; default = `'Viridis'`)\n - `opts.xmin` ...
def contour(self, X, win=None, env=None, opts=None): return self._surface(X=X, stype="contour", opts=opts, win=win, env=env)
57,207
224,060
230
mkdocs/utils/__init__.py
87
16
def get_themes(): themes = {} eps = set(importlib_metadata.entry_points(group='mkdocs.themes')) builtins = {ep.name for ep in eps if ep.dist.name == 'mkdocs'} for theme in eps: if theme.name in builtins and
Remove spaces at the ends of docstrings, normalize quotes
get_themes
e7f07cc82ab2be920ab426ba07456d8b2592714d
mkdocs
__init__.py
19
17
https://github.com/mkdocs/mkdocs.git
7
96
0
60
224
Python
{ "docstring": "Return a dict of all installed themes as {name: EntryPoint}.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def get_themes(): themes = {} eps = set(importlib_metadata.entry_points(group='mkdocs.themes')) builtins = {ep.name for ep in eps if ep.dist.name == 'mkdocs'} for theme in eps: if theme.name in builtins and theme.dist.name != 'mkdocs': raise exceptions.ConfigurationError( ...
19,757
100,127
94
tests/sentry/api/endpoints/test_user_notification_details.py
15
16
def test_subscribe_by_default(self): NotificationSetting
ref(tests): Remove `get_valid_response()` (#34822)
test_subscribe_by_default
096b5511e244eecd8799b2a0324655207ce8985e
sentry
test_user_notification_details.py
9
9
https://github.com/getsentry/sentry.git
1
50
0
15
82
Python
{ "docstring": "\n Test that we expect project-independent issue alert preferences to be\n returned as `subscribe_by_default`.\n ", "language": "en", "n_whitespaces": 35, "n_words": 13, "vocab_size": 13 }
def test_subscribe_by_default(self): NotificationSetting.objects.update_settings( ExternalProviders.EMAIL, NotificationSettingTypes.ISSUE_ALERTS, NotificationSettingOptionValues.NEVER, user=self.user, ) response = self.get_success_respons...
16,175
73,918
98
wagtail/core/permission_policies/base.py
19
15
def _get_users_with_any_permission_codenames_filter(self, permission_codenames): permissions = Permission.objects.filter( content_type=self._content_type, codename__in=permission_codenames ) return ( Q(is_superuser=True)
Reformat with black
_get_users_with_any_permission_codenames_filter
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
base.py
12
9
https://github.com/wagtail/wagtail.git
1
56
0
17
89
Python
{ "docstring": "\n Given a list of permission codenames, return a filter expression which\n will find all users which have any of those permissions - either\n through group permissions, user permissions, or implicitly through\n being a superuser.\n ", "language": "en", "n_whites...
def _get_users_with_any_permission_codenames_filter(self, permission_codenames): permissions = Permission.objects.filter( content_type=self._content_type, codename__in=permission_codenames ) return ( Q(is_superuser=True) | Q(user_permissions__in=permi...
88,977
289,847
541
homeassistant/components/ibeacon/coordinator.py
56
21
def _async_update_rssi_and_transients(self) -> None: for ( unique_id, ibeacon_advert
Update ibeacon-ble to 1.0.1 (#80785)
_async_update_rssi_and_transients
e15f2e050e7afadbb19d32973104e4e2f5a172ae
core
coordinator.py
14
40
https://github.com/home-assistant/core.git
6
139
0
39
213
Python
{ "docstring": "Check to see if the rssi has changed and update any devices.\n\n We don't callback on RSSI changes so we need to check them\n here and send them over the dispatcher periodically to\n ensure the distance calculation is update.\n\n If the transient flag is set we also need to...
def _async_update_rssi_and_transients(self) -> None: for ( unique_id, ibeacon_advertisement, ) in self._last_ibeacon_advertisement_by_unique_id.items(): address = unique_id.split("_")[-1] service_info = bluetooth.async_last_service_info( ...
52,162
207,935
43
celery/contrib/testing/worker.py
22
11
def setup_app_for_worker(app, loglevel, logfile) -> None: # type: (Celery, Union[str, int], str) -> None app.finalize() app.set_current() app.set_default() type(app.log)._setup = False app.log.setup(loglevel=loglevel, logfile=logfile)
Add `mypy` to the pipeline (#7383) * Add typing to Celery This is a simple bootstrap of the process, adding some types to a few selected functions, based on comment annotations. MyPy is chosen as the default static analyzer for the types. * Add mypy to the pipeline * [pre-commit.ci] auto fixes from pre-comm...
setup_app_for_worker
fbda0089f08d7f2a8f00925dbc0b6e10bd779251
celery
worker.py
10
7
https://github.com/celery/celery.git
1
51
0
21
85
Python
{ "docstring": "Setup the app to be used for starting an embedded worker.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def setup_app_for_worker(app, loglevel, logfile) -> None: # type: (Celery, Union[str, int], str) -> None app.finalize() app.set_current() app.set_default() type(app.log)._setup = False app.log.setup(loglevel=loglevel, logfile=logfile)
47,598
196,098
44
sympy/combinatorics/graycode.py
12
6
def rank(self): if self._rank is None: self._rank
Updated import locations
rank
498015021131af4dbb07eb110e5badaba8250c7b
sympy
graycode.py
13
4
https://github.com/sympy/sympy.git
2
32
0
10
53
Python
{ "docstring": "\n Ranks the Gray code.\n\n A ranking algorithm determines the position (or rank)\n of a combinatorial object among all the objects w.r.t.\n a given order. For example, the 4 bit binary reflected\n Gray code (BRGC) '0101' has a rank of 6 as it appears in\n the...
def rank(self): if self._rank is None: self._rank = int(gray_to_bin(self.current), 2) return self._rank
88,457
289,315
500
homeassistant/components/rest/data.py
91
38
async def async_update(self, log_errors=True): if not self._async_client: self._async_client = get_async_client( self._hass, verify_ssl=self._verify_ssl ) rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_para...
Fix payload in rest (#80544)
async_update
599d61a4da096227ce4d5ba1dc0eaabceea56f49
core
data.py
13
35
https://github.com/home-assistant/core.git
6
202
0
56
317
Python
{ "docstring": "Get the latest data from REST service with provided method.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
async def async_update(self, log_errors=True): if not self._async_client: self._async_client = get_async_client( self._hass, verify_ssl=self._verify_ssl ) rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_para...
85,683
286,285
33
openbb_terminal/helper_funcs.py
14
8
def set_default_timezone() -> None: dotenv.load_dotenv(USER_ENV_FILE) user_tz = os.ge
[SDK] Allow silencing verbose output in commands that use stocks/load (#3180) * remove verbose on load * Revert implementation of the verbosity setting in stocks controller * Edit docstrings to comply with pydocstyle linting rules * Fix typos in variable names and help text * Add verbosity setting to forex...
set_default_timezone
47549cbd9f52a436c06b040fda5b88a7d2bf700a
OpenBBTerminal
helper_funcs.py
10
6
https://github.com/OpenBB-finance/OpenBBTerminal.git
2
35
0
14
65
Python
{ "docstring": "Set a default (America/New_York) timezone if one doesn't exist.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def set_default_timezone() -> None: dotenv.load_dotenv(USER_ENV_FILE) user_tz = os.getenv("OPENBB_TIMEZONE") if not user_tz: dotenv.set_key(USER_ENV_FILE, "OPENBB_TIMEZONE", "America/New_York")
46,839
191,733
30
langchain/agents/agent.py
16
5
def return_stopped_response(self) -> dict: return {k: "Agent stopped due to max iterations." for k in self.return_values}
add logic for agent stopping (#420)
return_stopped_response
d0f194de73c942cb89d731dbfa5ae809111fb07a
langchain
agent.py
8
3
https://github.com/hwchase17/langchain.git
2
20
0
16
35
Python
{ "docstring": "Return response when agent has been stopped due to max iterations.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def return_stopped_response(self) -> dict: return {k: "Agent stopped due to max iterations." for k in self.return_values}
77,696
264,354
48
netbox/utilities/forms/fields/dynamic.py
16
7
def clean(self, value): if self.null_option is not None and value == settings.FILTERS_NULL_CHOICE_VALUE: return Non
Refactor & document supported form fields
clean
cf3ca5a661cc015baf4ef462be07e91c09db0ede
netbox
dynamic.py
9
4
https://github.com/netbox-community/netbox.git
3
33
0
14
54
Python
{ "docstring": "\n When null option is enabled and \"None\" is sent as part of a form to be submitted, it is sent as the\n string 'null'. This will check for that condition and gracefully handle the conversion to a NoneType.\n ", "language": "en", "n_whitespaces": 61, "n_words": 38, "voc...
def clean(self, value): if self.null_option is not None and value == settings.FILTERS_NULL_CHOICE_VALUE: return None return super().clean(value)
72,397
248,647
320
tests/test_event_auth.py
76
24
def test_unexpected_auth_events(self): creator = "@creator:example.com" create_event = _create_event(RoomVersions.V9, creator) join_event = _join_event(RoomVersions.V9, creator) pl_event = _power_levels_event( RoomVersions.V9, creator, {"stat...
Fix inconsistencies in event validation (#13088)
test_unexpected_auth_events
d4b1c0d800eaa83c4d56a9cf17881ad362b9194b
synapse
test_event_auth.py
13
27
https://github.com/matrix-org/synapse.git
1
154
0
52
239
Python
{ "docstring": "Events with excess auth_events should be rejected\n\n https://spec.matrix.org/v1.3/rooms/v9/#authorization-rules\n 2. Reject if event has auth_events that:\n 2. have entries whose type and state_key don’t match those specified by the\n auth events selection algorit...
def test_unexpected_auth_events(self): creator = "@creator:example.com" create_event = _create_event(RoomVersions.V9, creator) join_event = _join_event(RoomVersions.V9, creator) pl_event = _power_levels_event( RoomVersions.V9, creator, {"stat...
44,000
182,900
506
src/textual/devtools/service.py
67
27
async def _consume_incoming(self) -> None: while True: message_json = await self.incoming_queue.get() if message_json is None: self.incoming_queue.task_done() break type = message_json["type"] if type == "client_log": ...
Seperate server and client handling logic into classes for devtools
_consume_incoming
a72e347ed99333a090377ee438eaf63477cbf98b
textual
service.py
16
32
https://github.com/Textualize/textual.git
5
170
0
49
299
Python
{ "docstring": "Consume messages from the incoming (client -> server) Queue, and print\n the corresponding renderables to the console for each message.\n ", "language": "en", "n_whitespaces": 34, "n_words": 20, "vocab_size": 18 }
async def _consume_incoming(self) -> None: while True: message_json = await self.incoming_queue.get() if message_json is None: self.incoming_queue.task_done() break type = message_json["type"] if type == "client_log": ...
33,397
145,231
75
docker/kuberay-autoscaler/test_autoscaling_config.py
21
12
def _get_basic_ray_cr() -> dict: cr_path = str( Path(__file__).resolve().paren
[KubeRay] Format autoscaling config based on RayCluster CR (#22348) Closes #21655. At the start of each autoscaler iteration, we read the Ray Cluster CR from K8s and use it to extract the autoscaling config.
_get_basic_ray_cr
a402e956a4e1ebe9bc4e2b404536466967c497af
ray
test_autoscaling_config.py
19
11
https://github.com/ray-project/ray.git
1
49
0
17
92
Python
{ "docstring": "Returns the example Ray CR included in the Ray documentation.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 8 }
def _get_basic_ray_cr() -> dict: cr_path = str( Path(__file__).resolve().parents[2] / "python" / "ray" / "autoscaler" / "kuberay" / "ray-cluster.complete.yaml" ) return yaml.safe_load(open(cr_path).read())
41,994
176,595
293
networkx/generators/spectral_graph_forge.py
169
45
def spectral_graph_forge(G, alpha, transformation="identity", seed=None): import numpy as np import scipy as sp import scipy.stats # call as sp.stats available_transformations = ["identity", "modularity"] alpha = np.clip(alpha, 0, 1) A = nx.to_numpy_array(G) n = A.shape[1] level =...
Remove `_mat_spect_approx` in favor of simpler procedure (#5624) * Replace _mat_spect_approx func internal usage. * Rm _mat_spect_approx helper function.
spectral_graph_forge
8bea55e3071ed71eab4fb6650a45f0cdf5c911d4
networkx
spectral_graph_forge.py
13
30
https://github.com/networkx/networkx.git
5
306
0
105
494
Python
{ "docstring": "Returns a random simple graph with spectrum resembling that of `G`\n\n This algorithm, called Spectral Graph Forge (SGF), computes the\n eigenvectors of a given graph adjacency matrix, filters them and\n builds a random graph with a similar eigenstructure.\n SGF has been proved to be parti...
def spectral_graph_forge(G, alpha, transformation="identity", seed=None): import numpy as np import scipy as sp import scipy.stats # call as sp.stats available_transformations = ["identity", "modularity"] alpha = np.clip(alpha, 0, 1) A = nx.to_numpy_array(G) n = A.shape[1] level =...
22,260
106,051
30
src/datasets/features/features.py
9
5
def encode_example(self, example): example = cast_to_python_objects(example) return encode_nested_exa
Clean up remaining Main Classes docstrings (#5349) clean up docstrings
encode_example
c78559cacbb0ca6e0bc8bfc313cc0359f8c23ead
datasets
features.py
8
3
https://github.com/huggingface/datasets.git
1
21
0
9
35
Python
{ "docstring": "\n Encode example into a format for Arrow.\n\n Args:\n example (`dict[str, Any]`):\n Data in a Dataset row.\n\n Returns:\n `dict[str, Any]`\n ", "language": "en", "n_whitespaces": 85, "n_words": 19, "vocab_size": 17 }
def encode_example(self, example): example = cast_to_python_objects(example) return encode_nested_example(self, example)
80,920
271,980
333
keras/engine/training_v1.py
117
11
def _add_unique_metric_name(self, metric_name, metric_fn, output_index): # For multi-output models, prepend the output names to the metric name. if len(self.output_names) > 1: # If we're loading from an already-serialized model, we've already # prepended the output name,...
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
_add_unique_metric_name
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
training_v1.py
14
13
https://github.com/keras-team/keras.git
4
75
0
80
127
Python
{ "docstring": "Makes the metric name unique.\n\n If there are multiple outputs for which the metrics are calculated, the\n metric names have to be made unique by appending an integer.\n\n Args:\n metric_name: Metric name that corresponds to the metric specified by the\n ...
def _add_unique_metric_name(self, metric_name, metric_fn, output_index): # For multi-output models, prepend the output names to the metric name. if len(self.output_names) > 1: # If we're loading from an already-serialized model, we've already # prepended the output name,...
@not_implemented_for("undirected")
41,793
176,253
783
networkx/algorithms/components/strongly_connected.py
126
23
def strongly_connected_components(G): preorder = {} lowlink = {} scc_found = set() scc_queue = [] i = 0 # Preorder counter neighbors = {v: iter(G[v]) for v in G} for source in G: if source not in scc_found: queue = [source] while queue: v...
Fixing Tarjan's strongly connected components algorithm implementation to have O(|E|+|V|) time complexity instead of O(|V|^3). (#5288) Prevent unnecessary traversal of edges multiple times
strongly_connected_components
77c49c16e10693dbe566d20601b28dd2b1e8df03
networkx
strongly_connected.py
25
39
https://github.com/networkx/networkx.git
15
257
1
66
413
Python
{ "docstring": "Generate nodes in strongly connected components of graph.\n\n Parameters\n ----------\n G : NetworkX Graph\n A directed graph.\n\n Returns\n -------\n comp : generator of sets\n A generator of sets of nodes, one for each strongly connected\n component of G.\n\n ...
def strongly_connected_components(G): preorder = {} lowlink = {} scc_found = set() scc_queue = [] i = 0 # Preorder counter neighbors = {v: iter(G[v]) for v in G} for source in G: if source not in scc_found: queue = [source] while queue: v...
75,771
259,437
524
sklearn/linear_model/_glm/glm.py
172
33
def score(self, X, y, sample_weight=None): # TODO: Adapt link to User Guide in the docstring, once # https://github.com/scikit-learn/scikit-learn/pull/22118 is merged. # # Note, default score defined in RegressorMixin is R^2 score. # TODO: make D^2 a score function in mo...
ENH migrate GLMs / TweedieRegressor to linear loss (#22548) Co-authored-by: Olivier Grisel <olivier.grisel@ensta.org> Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
score
75a94f518f7bd7d0bf581ffb67d9f961e3c4efbc
scikit-learn
glm.py
14
28
https://github.com/scikit-learn/scikit-learn.git
4
209
0
115
340
Python
{ "docstring": "Compute D^2, the percentage of deviance explained.\n\n D^2 is a generalization of the coefficient of determination R^2.\n R^2 uses squared error and D^2 uses the deviance of this GLM, see the\n :ref:`User Guide <regression_metrics>`.\n\n D^2 is defined as\n :math:`D^...
def score(self, X, y, sample_weight=None): # TODO: Adapt link to User Guide in the docstring, once # https://github.com/scikit-learn/scikit-learn/pull/22118 is merged. # # Note, default score defined in RegressorMixin is R^2 score. # TODO: make D^2 a score function in mo...
1,607
9,407
317
reconstruction/ostec/external/stylegan2/dnnlib/tflib/ops/upfirdn_2d.py
198
34
def upsample_conv_2d(x, w, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'): r assert isinstance(factor, int) and factor >= 1 # Check weight shape.
initialize ostec
upsample_conv_2d
7375ee364e0df2a417f92593e09557f1b2a3575a
insightface
upfirdn_2d.py
16
48
https://github.com/deepinsight/insightface.git
4
387
0
110
602
Python
{ "docstring": "Fused `upsample_2d()` followed by `tf.nn.conv2d()`.\n\n Padding is performed only once at the beginning, not between the operations.\n The fused op is considerably more efficient than performing the same calculation\n using standard TensorFlow ops. It supports gradients of arbitrary order.\n\...
def upsample_conv_2d(x, w, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'): r assert isinstance(factor, int) and factor >= 1 # Check weight shape. w = tf.convert_to_tensor(w) assert w.shape.rank == 4 convH = w.shape[0].value convW = w.shape[1].value inC = _shape(w, 2) ou...
1,218
7,491
19
ludwig/contribs/aim.py
5
7
def normalize_config(config): return json.loads(json.dumps(config, cls=NumpyEn
Fixes to serialization, and update to allow set repo location. (#2367) * Updating AimCallback to add init for optional repo. * Fixed numpy serialization for config objects. * Removed print statements, added logging for progress tracker.
normalize_config
7ec0cd13cf5e77d6fe68acbbeef9a7c694fc83c2
ludwig
aim.py
10
2
https://github.com/ludwig-ai/ludwig.git
1
22
0
5
37
Python
{ "docstring": "Convert to json string and back again to remove numpy types.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 10 }
def normalize_config(config): return json.loads(json.dumps(config, cls=NumpyEncoder))
46,467
191,243
487
thumbor/utils.py
203
42
def ensure_srgb(img, srgb_profile=None): img_info = dict(img.info) icc = img_info.pop("icc_profile", None) if not icc: return img if ImageCms is None: raise RuntimeError("ImageCms is required for color profile utilities") if srgb_profile is not None: srgb_profile = Ima...
feat: Support AVIF format encoding (#1476) * feat: Support AVIF format encoding * Increase test coverage * test coverage for remaining uncovered lines * Add simple integration test * Add "filters:format(avif)" integration test * Gracefully handle AVIF encoding when codec unavailable * Don't pass qual...
ensure_srgb
1d9deef4e99f52a08eed9aa973572c4567754f5a
thumbor
utils.py
12
51
https://github.com/thumbor/thumbor.git
10
268
0
126
452
Python
{ "docstring": "\n Ensures that an image either has no ICC profile (and so is implicitly\n sRGB) or has an sRGB color profile. If the image is sRGB, it is returned\n unchanged. If it has a CMYK or Gray color profile, this function will\n return an image converted to sRGB. Any color profiles in other color...
def ensure_srgb(img, srgb_profile=None): img_info = dict(img.info) icc = img_info.pop("icc_profile", None) if not icc: return img if ImageCms is None: raise RuntimeError("ImageCms is required for color profile utilities") if srgb_profile is not None: srgb_profile = Ima...
80,550
270,733
93
keras/engine/base_layer.py
41
7
def _cast_single_input(self, x): if self._should_cast_single_input(x): return tf.cast(x, self._compute_dtype_obje
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
_cast_single_input
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
base_layer.py
10
5
https://github.com/keras-team/keras.git
2
31
0
35
54
Python
{ "docstring": "Cast a single Tensor or TensorSpec to the compute dtype.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def _cast_single_input(self, x): if self._should_cast_single_input(x): return tf.cast(x, self._compute_dtype_object) else: return x # _dtype used to be an attribute set in the constructor. We still expose it # because some clients still use it. # TODO(reedwm...
4,915
25,698
78
saleor/csv/utils/export.py
23
11
def queryset_in_batches(queryset): start_pk = 0 while True: qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE] pks = list(qs.values_list("pk", flat=True)) if not pks: break yield pks
Feature/gift cards post mvp (#7977) * Add giftCardBulkCreate mutation * Extend OrderFilter with giftCardUsed and giftCardBought fields * Allow exporting gift cards * Update the name of the email template for export * Add exportGiftCards muttaion * Add used gift card filter * Export only unused gift c...
queryset_in_batches
f5a45de4a22fecacfcd5b2cd18c07e5cf95ce27c
saleor
export.py
13
9
https://github.com/saleor/saleor.git
3
55
0
18
94
Python
{ "docstring": "Slice a queryset into batches.\n\n Input queryset should be sorted be pk.\n ", "language": "en", "n_whitespaces": 18, "n_words": 12, "vocab_size": 10 }
def queryset_in_batches(queryset): start_pk = 0 while True: qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE] pks = list(qs.values_list("pk", flat=True)) if not pks: break yield pks start_pk = pks[-1]
14,353
66,831
56
erpnext/patches/v13_0/update_returned_qty_in_pr_dn.py
81
19
def execute(): frappe.reload_doc("stock", "doctype", "purchase_receipt") frappe.reload_doc("stock", "doctype", "purchase_receipt_item") frappe.reload_doc("stock", "doctype", "delivery_note") frappe.reload_doc("stock", "doctype", "delivery_note_item") frappe.reload_doc("stock", "doctype", "stock_settings") def up...
style: format code with black
execute
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
update_returned_qty_in_pr_dn.py
15
14
https://github.com/frappe/erpnext.git
2
77
0
63
297
Python
{ "docstring": " update `tabPurchase Receipt Item`\n\t\tset received_stock_qty = received_qty * conversion_factor\n\t\twhere docstatus = 1 ", "language": "en", "n_whitespaces": 13, "n_words": 14, "vocab_size": 13 }
def execute(): frappe.reload_doc("stock", "doctype", "purchase_receipt") frappe.reload_doc("stock", "doctype", "purchase_receipt_item") frappe.reload_doc("stock", "doctype", "delivery_note") frappe.reload_doc("stock", "doctype", "delivery_note_item") frappe.reload_doc("stock", "doctype", "stock_settings") def up...
85,618
286,204
379
openbb_terminal/cryptocurrency/discovery/discovery_controller.py
55
27
def call_dex(self, other_args): parser = argparse.ArgumentParser( prog="dex", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=, ) parser.add_argument( "-l", "--limit", ...
Combining commands and renaming others (#3000) * Combining commands and renaming others Combining commands with different sources but the same functionality. I also removed indications of source from command names * Fix tests and hugo * Test fixes Co-authored-by: james <jmaslek11@gmail.com>
call_dex
38a53e5f43bccb716e6a6494605f97293077a679
OpenBBTerminal
discovery_controller.py
13
36
https://github.com/OpenBB-finance/OpenBBTerminal.git
2
126
0
47
205
Python
{ "docstring": "Process dex command\n Shows top decentralized exchanges [Source: https://dappradar.com/]\n Accepts --sort {Name,Daily Users,Daily Volume [$]}\n to sort by column\n ", "language": "en", "n_whitespaces": 63, "n_words": 19, "vocab_size": 19 }
def call_dex(self, other_args): parser = argparse.ArgumentParser( prog="dex", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=, ) parser.add_argument( "-l", "--limit", ...
12,562
61,419
257
.venv/lib/python3.8/site-packages/pip/_internal/vcs/versioncontrol.py
86
16
def get_backend_for_dir(self, location): # type: (str) -> Optional[VersionControl] vcs_backends = {} for vcs_backend in self._registry.values(): repo_path = vcs_backend.get_repository_root(location) if not repo_path: continue logger.de...
upd; format
get_backend_for_dir
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
versioncontrol.py
10
13
https://github.com/jindongwang/transferlearning.git
4
75
0
67
126
Python
{ "docstring": "\n Return a VersionControl object if a repository of that type is found\n at the given directory.\n ", "language": "en", "n_whitespaces": 38, "n_words": 16, "vocab_size": 15 }
def get_backend_for_dir(self, location): # type: (str) -> Optional[VersionControl] vcs_backends = {} for vcs_backend in self._registry.values(): repo_path = vcs_backend.get_repository_root(location) if not repo_path: continue logger.de...
8,173
44,123
177
airflow/www/security.py
54
17
def has_access(self, action_name, resource_name, user=None) -> bool: if not user: user = g.user if
Remove `:type` lines now sphinx-autoapi supports typehints (#20951) * Remove `:type` lines now sphinx-autoapi supports typehints Since we have no updated sphinx-autoapi to a more recent version it supports showing type hints in the documentation, so we don't need to have the type hints _and_ the `:type` lines -- ...
has_access
602abe8394fafe7de54df7e73af56de848cdf617
airflow
security.py
13
25
https://github.com/apache/airflow.git
6
96
0
41
150
Python
{ "docstring": "\n Verify whether a given user could perform a certain action\n (e.g can_read, can_write) on the given resource.\n\n :param action_name: action_name on resource (e.g can_read, can_edit).\n :param resource_name: name of view-menu or resource.\n :param user: user name\...
def has_access(self, action_name, resource_name, user=None) -> bool: if not user: user = g.user if user.is_anonymous: user.roles = self.get_user_roles(user) has_access = self._has_access(user, action_name, resource_name) # FAB built-in view access metho...
26,290
118,557
30
lib/streamlit/forward_msg_cache.py
8
5
def has_refs(self) -> bool: return len(self._session_report_run_counts) > 0
Rename and refactor `Report` machinery (#4141) This refactor renames (almost) everything related to the outdated "report" concept with more precise concepts that we use throughout our code, primarily "script run", "session", and "app".
has_refs
704eab3478cf69847825b23dabf15813a8ac9fa2
streamlit
forward_msg_cache.py
9
6
https://github.com/streamlit/streamlit.git
1
17
0
8
30
Python
{ "docstring": "True if this Entry has references from any AppSession.\n\n If not, it can be removed from the cache.\n ", "language": "en", "n_whitespaces": 40, "n_words": 18, "vocab_size": 17 }
def has_refs(self) -> bool: return len(self._session_report_run_counts) > 0
47,191
195,092
117
projects/director/director_agent.py
32
15
def _reshape_to_record_metrics(self, batch, losses, num_target_tokens, indices): val_id_shape = batch.
Added director agent and safety experiment commands. (#4602) * Added director agent and safety. * ran autoformat.sh
_reshape_to_record_metrics
2ef5586ed0d644abe18cd3ff45ef9fa01981e87c
ParlAI
director_agent.py
10
11
https://github.com/facebookresearch/ParlAI.git
1
79
0
25
116
Python
{ "docstring": "\n MultitaskAgent shuffles and combines examples from both classifier and the\n generator tasks in a single batch. We compute losses only for those exs in the\n batch resulting in losses and num_target_tokens vectors that are smaller than\n the.\n\n This method resha...
def _reshape_to_record_metrics(self, batch, losses, num_target_tokens, indices): val_id_shape = batch.valid_indices.shape reshaped_losses = torch.zeros( val_id_shape, device=losses.device, dtype=losses.dtype ) reshaped_num_target_tokens = torch.zeros( val...
48,805
198,126
65
sympy/physics/continuum_mechanics/truss.py
22
7
def add_support(self, location, type): if location not in s
Truss class initialized and documentation added
add_support
158f441d4fae4bd406597a41ba8af142e5eeb593
sympy
truss.py
11
5
https://github.com/sympy/sympy.git
2
33
0
22
55
Python
{ "docstring": "\n This method adds a pinned or roller support at a particular node\n\n Parameters\n ==========\n\n location: String or Symbol\n Label of the Node at which support is added.\n\n type: String\n Type of the support being provided at the node.\n\n ...
def add_support(self, location, type): if location not in self._node_labels: raise ValueError("Support must be added on a known node") else: self._supports[location] = type
54,789
217,444
132
python3.10.4/Lib/ftplib.py
43
18
def makeport(self): sock = socket.create_server(("", 0), family=self.af, backlog=1) port = sock.getsockname()[1] # Get proper port host =
add python 3.10.4 for windows
makeport
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
ftplib.py
11
11
https://github.com/XX-net/XX-Net.git
3
99
0
30
159
Python
{ "docstring": "Create a new socket and send a PORT command for it.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 10 }
def makeport(self): sock = socket.create_server(("", 0), family=self.af, backlog=1) port = sock.getsockname()[1] # Get proper port host = self.sock.getsockname()[0] # Get proper host if self.af == socket.AF_INET: resp = self.sendport(host, port) else: ...
@pytest.mark.parametrize("url, expected_matches", [ # included ('http://trolol.com/', 1), # neither included nor excluded ('http://aaaaaaaaaa.com/', 0), # excluded ('https://badhost.xxx/', 0), ])
117,470
320,967
69
tests/unit/javascript/test_greasemonkey.py
30
10
def test_all(gm_manager): _save_script(test_gm_script, 'test.user.js') gm_manager.load_scripts() assert (gm_manager.all_scripts()[0].name == "qutebrowser test userscript") @pytest.mark.parametrize("url, expected_matches", [ # included ('http://trolol.com/', 1), # neither incl...
greasemonkey: Don't implicitly load scripts Needed for #7245 and also seems like cleaner code.
test_all
21419c9ef5a90ea36a27afaf2503a57f8f9f8536
qutebrowser
test_greasemonkey.py
11
5
https://github.com/qutebrowser/qutebrowser.git
1
32
1
25
109
Python
{ "docstring": "Test that a script gets read from file, parsed and returned.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def test_all(gm_manager): _save_script(test_gm_script, 'test.user.js') gm_manager.load_scripts() assert (gm_manager.all_scripts()[0].name == "qutebrowser test userscript") @pytest.mark.parametrize("url, expected_matches", [ # included ('http://trolol.com/', 1), # neither incl...
77,443
263,700
130
bootloader/waflib/Utils.py
59
24
def split_path_msys(path): if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')): global msysroot if not msysroot: msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1') msysroot = msysroot.strip() path = ...
Bootloader: Building: Unpack waf's lib archive. Doing so makes it easier to modify. This is a temporary measure until the next waf version is released (although I'm tempted to keep it since it's much more IDE completion friendly).
split_path_msys
64ccb7aea824fbec57f7ed1bbe483ec486183c13
pyinstaller
Utils.py
16
8
https://github.com/pyinstaller/pyinstaller.git
5
88
0
40
247
Python
{ "docstring": "\nSplits a path by / or \\\\; do not confuse this function with with ``os.path.split``\n\n:type path: string\n:param path: path to split\n:return: list of string\n", "language": "en", "n_whitespaces": 28, "n_words": 27, "vocab_size": 23 }
def split_path_msys(path): if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')): global msysroot if not msysroot: msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1') msysroot = msysroot.strip() path = ...
16,631
77,104
19
wagtail/images/utils.py
10
10
def find_image_duplicates(image, user, permission_policy): instances = permi
Add duplicate detection to multiple image upload view Add utility function to find an image's potential duplicates Add logic to detect duplicates on multiple images upload view Add template shown when a user is prompted to confirm a duplicate upload Add client-side logic to confirm a duplicate upload Add/update st...
find_image_duplicates
c136f461bc052cef362991458e1bd1fca37a3da9
wagtail
utils.py
11
3
https://github.com/wagtail/wagtail.git
1
40
0
10
65
Python
{ "docstring": "\n Finds all the duplicates of a given image.\n To keep things simple, two images are considered to be duplicates if they have the same `file_hash` value.\n This function also ensures that the `user` can choose one of the duplicate images returned (if any).\n ", "language": "en", "n_wh...
def find_image_duplicates(image, user, permission_policy): instances = permission_policy.instances_user_has_permission_for(user, "choose") return instances.exclude(pk=image.pk).filter(file_hash=image.file_hash)
3,427
20,562
43
pipenv/patched/notpip/_vendor/pyparsing/core.py
21
10
def _trim_arity(func, maxargs=2): global _trim_arity_call_line if f
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...
_trim_arity
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
core.py
10
19
https://github.com/pypa/pipenv.git
3
100
0
20
56
Python
{ "docstring": "decorator to trim function calls to match the arity of the target", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 10 }
def _trim_arity(func, maxargs=2): global _trim_arity_call_line if func in _single_arg_builtins: return lambda s, l, t: func(t) limit = 0 found_arity = False
85,794
286,407
728
openbb_terminal/cryptocurrency/overview/overview_controller.py
101
36
def call_exmarkets(self, other_args): parser = argparse.ArgumentParser( prog="exmarkets", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=, ) parser.add_argument( "-e", "--exchan...
More Fixes to Crypto + key sort (#3244) * fix #3095 - autocomplete and command working + key sort * fix #3056 * fix [Bug] bugs #3048 * fix [Bug] bug #3017 * sort -> sortby, not ascend, tests * fix my goof ups Co-authored-by: james <jmaslek11@gmail.com>
call_exmarkets
09f753da1c2a2f03c41fe6a3ca2eb79f6ea58995
OpenBBTerminal
overview_controller.py
12
69
https://github.com/OpenBB-finance/OpenBBTerminal.git
4
241
0
85
388
Python
{ "docstring": "Process exmarkets commandGet all exchange markets found for given exchange\n You can display only N number of records with --limit parameter.\n You can sort data by pair, base_currency_name, quote_currency_name, market_url, category,\n reported_volume_24h_s...
def call_exmarkets(self, other_args): parser = argparse.ArgumentParser( prog="exmarkets", add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=, ) parser.add_argument( "-e", "--exchan...
91,872
292,803
27
tests/components/lcn/test_cover.py
15
11
async def test_unload_config_entry(hass, entry, lcn_connection): await hass.config_entries.async_unload(entry.entry_id) assert hass.states.get("cover.cover_outputs").state == STATE_UNAVAILABLE assert hass.s
Add tests for LCN cover platform (#64832)
test_unload_config_entry
684f01f4664ad490a314ae983194c0f439445a16
core
test_cover.py
10
4
https://github.com/home-assistant/core.git
1
47
0
12
80
Python
{ "docstring": "Test the cover is removed when the config entry is unloaded.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 9 }
async def test_unload_config_entry(hass, entry, lcn_connection): await hass.config_entries.async_unload(entry.entry_id) assert hass.states.get("cover.cover_outputs").state == STATE_UNAVAILABLE assert hass.states.get("cover.cover_relays").state == STATE_UNAVAILABLE
36,511
156,029
35
dask/array/core.py
14
8
def topk(self, k, axis=-1, split_every=None): from dask.array.reductions import topk return topk(self, k, axis=axis, split_every
absolufy-imports - No relative - PEP8 (#8796) Conversation in https://github.com/dask/distributed/issues/5889
topk
cccb9d8d8e33a891396b1275c2448c352ef40c27
dask
core.py
8
3
https://github.com/dask/dask.git
1
40
0
12
58
Python
{ "docstring": "The top k elements of an array.\n\n See :func:`dask.array.topk` for docstring.\n\n ", "language": "en", "n_whitespaces": 25, "n_words": 11, "vocab_size": 11 }
def topk(self, k, axis=-1, split_every=None): from dask.array.reductions import topk return topk(self, k, axis=axis, split_every=split_every)
68,398
240,287
49
packages/python/plotly/plotly/graph_objs/_figure.py
17
8
def for_each_ternary(self, fn, selector=None, row=None, col=None) -> "Figure": for obj in self.select_ternaries(selector=selector, row=row, col=col): fn(obj) r
type annotations for chainable Figure methods
for_each_ternary
c95b4fa4388f29e50b6966e45c94c5980013a01d
plotly.py
_figure.py
9
32
https://github.com/plotly/plotly.py.git
2
48
0
17
73
Python
{ "docstring": "\n Apply a function to all ternary objects that satisfy the\n specified selection criteria\n\n Parameters\n ----------\n fn:\n Function that inputs a single ternary object.\n selector: dict, function, or None (default None)\n Dict to use ...
def for_each_ternary(self, fn, selector=None, row=None, col=None) -> "Figure": for obj in self.select_ternaries(selector=selector, row=row, col=col): fn(obj) return self
13,507
63,798
69
.venv/lib/python3.8/site-packages/pip/_vendor/tenacity/__init__.py
19
8
def call(self, *args, **kwargs): warnings.warn(
upd; format
call
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
__init__.py
9
6
https://github.com/jindongwang/transferlearning.git
1
34
0
19
58
Python
{ "docstring": "Use ``__call__`` instead because this method is deprecated.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def call(self, *args, **kwargs): warnings.warn( "'call()' method is deprecated. " + "Use '__call__()' instead", DeprecationWarning, ) return self.__call__(*args, **kwargs)
79,913
269,121
156
keras/distribute/distributed_training_utils_v1.py
86
19
def validate_per_replica_inputs(distribution_strategy, x): # Convert the inputs and targets into a list of PerReplica objects. per_replica_list = tf.nest.flatten(x) x_values_list = [] for x in per_replica_list: # At this point x should contain only tensors. x_values = distribution_strategy.unwrap(x) ...
Rework a test to avoid instantiating DistributedValues directly. PiperOrigin-RevId: 438824819
validate_per_replica_inputs
2d7dc6080f0824200e317f255e3290da60e0f98a
keras
distributed_training_utils_v1.py
17
14
https://github.com/keras-team/keras.git
5
94
0
64
159
Python
{ "docstring": "Validates PerReplica dataset input list.\n\n Args:\n distribution_strategy: The current DistributionStrategy used to call\n `fit`, `evaluate` and `predict`.\n x: A list of PerReplica objects that represent the input or\n target values.\n\n Returns:\n List containing the first elem...
def validate_per_replica_inputs(distribution_strategy, x): # Convert the inputs and targets into a list of PerReplica objects. per_replica_list = tf.nest.flatten(x) x_values_list = [] for x in per_replica_list: # At this point x should contain only tensors. x_values = distribution_strategy.unwrap(x) ...
112,213
313,595
116
homeassistant/components/lifx/light.py
33
12
def get_mac_addr(self): if ( self.bulb.host_firmware_version and AwesomeVersion(self.bulb.host_firmware_version) >= FIX_MAC_FW ): octets = [int(octet, 16) for octet in self.mac_addr.split(":")] octets[5] = (octets[5] + 1) % 256 return ...
Refactor LIFX discovery to prevent duplicate discovery response handling (#72213) * Partially revert #70458 and allow duplicate LIFX discoveries Signed-off-by: Avi Miller <me@dje.li> * Only process one discovery at a time * Revert all LIFX duplicate/inflight discovery checks Also remember LIFX Switches and...
get_mac_addr
a0974e0c7297537149985f93544dd6f8ed8cfded
core
light.py
13
9
https://github.com/home-assistant/core.git
5
78
0
28
131
Python
{ "docstring": "Increment the last byte of the mac address by one for FW>3.70.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 11 }
def get_mac_addr(self): if ( self.bulb.host_firmware_version and AwesomeVersion(self.bulb.host_firmware_version) >= FIX_MAC_FW ): octets = [int(octet, 16) for octet in self.mac_addr.split(":")] octets[5] = (octets[5] + 1) % 256 return ...
43,384
181,595
19
tests/driver_tests.py
10
2
def test_positive_integer_or_none_4(): assert positive_integer_or_none('none') is None
Revert "Deployed 7ccda9a with MkDocs version: 1.3.0" This reverts commit bd9629c40e01241766197119b581a99409b07068.
test_positive_integer_or_none_4
388616b6247ca4ea8de4e2f340d6206aee523541
tpot
driver_tests.py
9
3
https://github.com/EpistasisLab/tpot.git
1
19
0
7
38
Python
{ "docstring": "Assert that the TPOT CLI interface's positive_integer_or_none parsing return None when value is string 'None' or 'none'.", "language": "en", "n_whitespaces": 16, "n_words": 17, "vocab_size": 17 }
def test_positive_integer_or_none_4(): assert positive_integer_or_none('none') is None assert positive_integer_or_none('None') is None
56,941
223,511
361
python3.10.4/Lib/email/_header_value_parser.py
112
26
def get_local_part(value): local_part = LocalPart() leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(val...
add python 3.10.4 for windows
get_local_part
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_header_value_parser.py
15
35
https://github.com/XX-net/XX-Net.git
13
222
0
71
377
Python
{ "docstring": " local-part = dot-atom / quoted-string / obs-local-part\n\n ", "language": "en", "n_whitespaces": 11, "n_words": 7, "vocab_size": 6 }
def get_local_part(value): local_part = LocalPart() leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(val...
5,984
32,803
238
tests/test_feature_extraction_common.py
57
20
def prepare_video_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" video_inputs = [] for i in range(feature_extract_te
Add VideoMAE (#17821) * First draft * Add VideoMAEForVideoClassification * Improve conversion script * Add VideoMAEForPreTraining * Add VideoMAEFeatureExtractor * Improve VideoMAEFeatureExtractor * Improve docs * Add first draft of model tests * Improve VideoMAEForPreTraining * Fix base_mode...
prepare_video_inputs
f9a0008d2d3082a665f711b24f5314e4a8205fab
transformers
test_feature_extraction_common.py
16
19
https://github.com/huggingface/transformers.git
4
111
0
49
169
Python
{ "docstring": "This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if\n one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True.\n\n One can specify whether the videos are of the same resolution or not.\n ", "lan...
def prepare_video_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" video_inputs = [] for i in range(feature_extract_tester.batch_size): if equal_resolu...
45,468
186,372
191
certbot-apache/certbot_apache/_internal/configurator.py
38
18
def _verify_no_matching_http_header(self, ssl_vhost, header_substring): header_path = self.parser.find_dir("Header", None, start=ssl_vhost.path) if header_path: # "Existing Header directive for virtualhost" pat = '(?:[ "]|^)(%s)...
Various clean-ups in certbot-apache. Use f-strings. (#9132) * Various clean-ups in certbot-apache. Use f-strings. * Smaller tweaks
_verify_no_matching_http_header
eeca208c8f57304590ac1af80b496e61021aaa45
certbot
configurator.py
17
9
https://github.com/certbot/certbot.git
4
79
0
32
130
Python
{ "docstring": "Checks to see if there is an existing Header directive that\n contains the string header_substring.\n\n :param ssl_vhost: vhost to check\n :type vhost: :class:`~certbot_apache._internal.obj.VirtualHost`\n\n :param header_substring: string that uniquely identifies a header.\...
def _verify_no_matching_http_header(self, ssl_vhost, header_substring): header_path = self.parser.find_dir("Header", None, start=ssl_vhost.path) if header_path: # "Existing Header directive for virtualhost" pat = '(?:[ "]|^)(%s)...
@_wraps(np.repeat, lax_description=_TOTAL_REPEAT_LENGTH_DOC)
26,809
120,281
99
jax/_src/numpy/lax_numpy.py
67
30
def indices(dimensions, dtype=int32, sparse=False): dimensions = tuple( core.concrete_or_error(operator.index, d, "dimensions argument of jnp.indices") for d in dimensions) N = len(dimensions) output = [] s = dimensio
replace int with operator.index part2 This change align the behavior of `ravel_multi_index`, `split` and `indices` to their `numpy` counterparts. Also ensure size argument of `nonzero` should be integer. The changes with `*space` are only simplification
indices
667d63aa2d4fbf7c9da73aab0e24c5c4c33cb5ba
jax
lax_numpy.py
15
15
https://github.com/google/jax.git
6
141
1
50
237
Python
{ "docstring": "\\\nJax adds the optional `total_repeat_length` parameter which specifies the total\nnumber of repeat, and defaults to sum(repeats). It must be specified for repeat\nto be compilable. If `sum(repeats)` is larger than the specified\n`total_repeat_length` the remaining values will be discarded. In the c...
def indices(dimensions, dtype=int32, sparse=False): dimensions = tuple( core.concrete_or_error(operator.index, d, "dimensions argument of jnp.indices") for d in dimensions) N = len(dimensions) output = [] s = dimensions for i, dim in enumerate(dimensions): idx = lax.iota(dtype, dim) if spa...
73,887
251,914
27
test/mitmproxy/proxy/layers/test_tcp.py
15
8
def test_open_connection(tctx): assert Playbook(tcp.TCPLayer(tctx,
make it black!
test_open_connection
b3587b52b25077f68116b9852b041d33e7fc6601
mitmproxy
test_tcp.py
10
4
https://github.com/mitmproxy/mitmproxy.git
1
48
0
11
74
Python
{ "docstring": "\n If there is no server connection yet, establish one,\n because the server may send data first.\n ", "language": "en", "n_whitespaces": 26, "n_words": 16, "vocab_size": 15 }
def test_open_connection(tctx): assert Playbook(tcp.TCPLayer(tctx, True)) << OpenConnection(tctx.server) tctx.server.timestamp_start = 1624544785 assert Playbook(tcp.TCPLayer(tctx, True)) << None
77,903
264,900
74
netbox/dcim/api/serializers.py
20
11
def get_connected_endpoints(self, obj): endpoints = obj.connected_endpoints if endpoints: serializer = get_serializer_for_model(endpoints[0], prefix='Nested') context = {'request': self.context['request']}
Update connected_endpoint serializer field to support multiple objects
get_connected_endpoints
4c51dbba809b6b199a96da30f32f4dd3cd6ea6ed
netbox
serializers.py
12
6
https://github.com/netbox-community/netbox.git
2
56
0
18
92
Python
{ "docstring": "\n Return the appropriate serializer for the type of connected object.\n ", "language": "en", "n_whitespaces": 25, "n_words": 10, "vocab_size": 9 }
def get_connected_endpoints(self, obj): endpoints = obj.connected_endpoints if endpoints: serializer = get_serializer_for_model(endpoints[0], prefix='Nested') context = {'request': self.context['request']} return serializer(endpoints, many=True, context=conte...
41,930
176,485
60
networkx/algorithms/tree/tests/test_operations.py
25
11
def test_basic(self): trees = [(nx.full_rary_tree(2, 2**2 - 1), 0) for i in range(2)] actual = nx.join(trees) expected = nx.full_rary_tree(2, 2**3 - 1)
Update black (#5438) * CI: sync up black dev requirements version with precommit * Run black Co-authored-by: Jarrod Millman <jarrod.millman@gmail.com>
test_basic
f6755ffa00211b523c6c0bec5398bc6c3c43c8b1
networkx
test_operations.py
12
5
https://github.com/networkx/networkx.git
2
64
0
22
99
Python
{ "docstring": "Tests for joining multiple subtrees at a root node.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_basic(self): trees = [(nx.full_rary_tree(2, 2**2 - 1), 0) for i in range(2)] actual = nx.join(trees) expected = nx.full_rary_tree(2, 2**3 - 1) assert nx.is_isomorphic(actual, expected)
51,805
206,949
251
tests/admin_changelist/tests.py
77
36
def test_result_list_html(self): new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_c...
Refs #33476 -- Reformatted code with Black.
test_result_list_html
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
11
22
https://github.com/django/django.git
1
150
0
59
251
Python
{ "docstring": "\n Inclusion tag result_list generates a table when with default\n ModelAdmin settings.\n ", "language": "en", "n_whitespaces": 33, "n_words": 11, "vocab_size": 11 }
def test_result_list_html(self): new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_c...
16,376
75,179
176
wagtail/images/tests/test_admin_views.py
37
22
def test_delete_uploaded_image(self): # Send request response = self.client.post( reverse( "wagtailimages:delete_upload_multiple", args=(self.uploaded_image.id,) ) )
Reformat with black
test_delete_uploaded_image
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
test_admin_views.py
14
13
https://github.com/wagtail/wagtail.git
1
97
0
29
166
Python
{ "docstring": "\n This tests that a POST request to the delete view deletes the UploadedImage\n ", "language": "en", "n_whitespaces": 28, "n_words": 13, "vocab_size": 12 }
def test_delete_uploaded_image(self): # Send request response = self.client.post( reverse( "wagtailimages:delete_upload_multiple", args=(self.uploaded_image.id,) ) ) # Check response self.assertEqual(response.status_code, 200) ...
20,625
101,204
120
lib/align/aligned_face.py
30
12
def matrix(self) -> np.ndarray:
lib.align.aligned_face updates - Typing - Legacy support for pre-aligned faces - Coverage support for pre-aligned faces - Standardized retrieval of sub-crops
matrix
a2de4a97985dc62db3b140a924aeac2be733abf8
faceswap
aligned_face.py
12
11
https://github.com/deepfakes/faceswap.git
2
89
0
26
144
Python
{ "docstring": " :class:`numpy.ndarray`: The 3x2 transformation matrix for extracting and aligning the\n core face area out of the original frame, with no padding or sizing applied. The returned\n matrix is offset for the given :attr:`centering`. ", "language": "en", "n_whitespaces": 48, "n_words"...
def matrix(self) -> np.ndarray: if not np.any(self._matrices[self._centering]): matrix = self._matrices["legacy"].copy() matrix[:, 2] -= self.pose.offset[self._centering] self._matrices[self._centering] = matrix logger.trace("original matrix: %s, new matr...
78,755
267,137
364
lib/ansible/parsing/plugin_docs.py
100
21
def read_docstub(filename): in_documentation = False capturing = False indent_detection = '' doc_stub = [] with open(filename, 'r') as t_module_data: for line in t_module_data: if in_documentation:
expand ansible-doc coverage (#74963) * Expand ansible-doc to tests/filters and fix existing issues enable filter/test docs if in single file or companion yaml add docs for several filters/tests plugins allow .yml companion for docs for other plugins, must be colocated verify plugins are valid (not module...
read_docstub
b439e41a915ccec0ccbabecc966919ea406db74e
ansible
plugin_docs.py
23
21
https://github.com/ansible/ansible.git
11
162
0
63
287
Python
{ "docstring": "\n Quickly find short_description using string methods instead of node parsing.\n This does not return a full set of documentation strings and is intended for\n operations like ansible-doc -l.\n ", "language": "en", "n_whitespaces": 41, "n_words": 28, "vocab_size": 27 }
def read_docstub(filename): in_documentation = False capturing = False indent_detection = '' doc_stub = [] with open(filename, 'r') as t_module_data: for line in t_module_data: if in_documentation: # start capturing the stub until indentation returns ...
25,535
115,740
71
mindsdb/integrations/handlers/lightwood_handler/tests/test_lightwood_handler.py
27
12
def test_02_train_predictor(self): query = f response = self.handler.native_query(query) self.assertTrue(response.type == R
lw handler tests
test_02_train_predictor
91e73cdd2402a12373379b85ef1934d8ecfa364e
mindsdb
test_lightwood_handler.py
9
8
https://github.com/mindsdb/mindsdb.git
1
31
0
14
66
Python
{ "docstring": "\n CREATE PREDICTOR {self.test_model_name_1}\n FROM {PG_HANDLER_NAME} (SELECT * FROM demo_data.home_rentals limit 50)\n PREDICT rental_price\n ", "language": "en", "n_whitespaces": 54, "n_words": 13, "vocab_size": 12 }
def test_02_train_predictor(self): query = f response = self.handler.native_query(query) self.assertTrue(response.type == RESPONSE_TYPE.OK) # def test_03_retrain_predictor(self): # query = f"RETRAIN {self.test_model_name_1}" # response = self.handler.native_query(query) ...
36,541
156,079
68
dask/core.py
32
9
def get_dependencies(dsk, key=None, task=no_default, as_list=False): if key is not None: arg = dsk[key] elif task is not no_default: arg = task else: raise ValueError("Provide either key or task") return keys_in_tasks(dsk, [arg], as_list=as_list)
absolufy-imports - No relative - PEP8 (#8796) Conversation in https://github.com/dask/distributed/issues/5889
get_dependencies
cccb9d8d8e33a891396b1275c2448c352ef40c27
dask
core.py
11
8
https://github.com/dask/dask.git
3
59
0
26
92
Python
{ "docstring": "Get the immediate tasks on which this task depends\n\n Examples\n --------\n >>> inc = lambda x: x + 1\n >>> add = lambda x, y: x + y\n >>> dsk = {'x': 1,\n ... 'y': (inc, 'x'),\n ... 'z': (add, 'x', 'y'),\n ... 'w': (inc, 'z'),\n ... 'a': (add, (...
def get_dependencies(dsk, key=None, task=no_default, as_list=False): if key is not None: arg = dsk[key] elif task is not no_default: arg = task else: raise ValueError("Provide either key or task") return keys_in_tasks(dsk, [arg], as_list=as_list)
33,589
146,016
87
python/ray/ml/tests/test_checkpoints.py
24
13
def test_dict_checkpoint_fs(self): checkpoint = self._prepare_dict_checkpoint() # Convert into fs c
[ml] Add Ray ML / AIR checkpoint implementation (#22691) This PR splits up the changes in #22393 and introduces an implementation of the ML Checkpoint interface used by Ray Tune. This means, the TuneCheckpoint class implements the to/from_[bytes|dict|directory|object_ref|uri] conversion functions, as well as more h...
test_dict_checkpoint_fs
b267be475863a66e9feedb2be5f0a30a2ed8c493
ray
test_checkpoints.py
8
7
https://github.com/ray-project/ray.git
1
50
0
18
87
Python
{ "docstring": "Test conversion from dict to FS checkpoint and back.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_dict_checkpoint_fs(self): checkpoint = self._prepare_dict_checkpoint() # Convert into fs checkpoint path = checkpoint.to_directory() self.assertIsInstance(path, str) # Create from path checkpoint = Checkpoint.from_directory(path) self.assertTru...