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
@receiver(post_save, sender=Annotation)
42,524
177,853
220
label_studio/tasks/models.py
67
22
def delete_project_summary_annotations_before_updating_annotation(sender, instance, **kwargs): try: old_annotation = sender.objects.get(id=instance.id) except Annotation.DoesNotExist: # annotation just created - do nothing return old_annotation.decrease_project_summary_counters(...
fix: DEV-2406: Fix counters for skipped annotations (#2364) * fix: DEV-2406: Fix counters for skipped annotations * Fixes Co-authored-by: makseq-ubnt <makseq@gmail.com>
delete_project_summary_annotations_before_updating_annotation
50583d9ed6bfd2a837d0168e1690529a31efa2f7
label-studio
models.py
14
20
https://github.com/heartexlabs/label-studio.git
4
135
1
44
231
Python
{ "docstring": "Before updating annotation fields - ensure previous info removed from project.summary", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def delete_project_summary_annotations_before_updating_annotation(sender, instance, **kwargs): try: old_annotation = sender.objects.get(id=instance.id) except Annotation.DoesNotExist: # annotation just created - do nothing return old_annotation.decrease_project_summary_counters(...
10,250
50,991
699
modules/image/keypoint_detection/hand_pose_localization/model.py
151
28
def load_config(self, modelpath, use_gpu, gpu_id, use_mkldnn, cpu_threads): # 对运行位置进行配置 if use_gpu:
update hand_pose_localization (#1967) * update hand_pose_localization * add clean func
load_config
6b42963d62833925ffed1cdb73400e7d528a5353
PaddleHub
model.py
16
40
https://github.com/PaddlePaddle/PaddleHub.git
11
291
0
76
496
Python
{ "docstring": "\r\n load the model config\r\n modelpath: inference model path\r\n use_gpu: use gpu or not\r\n use_mkldnn: use mkldnn or not\r\n Error! Unable to use GPU. Please set the environment variables \"CUDA_VISIBLE_DEVICES=GPU_id\" to use GPU. Now switch to CPU to continue.....
def load_config(self, modelpath, use_gpu, gpu_id, use_mkldnn, cpu_threads): # 对运行位置进行配置 if use_gpu: try: int(os.environ.get('CUDA_VISIBLE_DEVICES')) except Exception: print( ) use_gpu = False ...
18,399
88,553
256
src/sentry/lang/javascript/processor_smcache.py
139
10
def trim_line(line, column=0): line = line.strip("\n") ll = len(line) if ll <= 150: return line if column > ll: column = ll start = max(column - 60, 0) # Round down if it brings us close to the edge if start < 5: start = 0 end = min(start + 140, ll) # Rou...
feat(processor): Use JavaScriptSmCacheStacktraceProcessor by default for internal projects (#41390) This PR builds on top of https://github.com/getsentry/sentry/pull/40951/ and prepares us for gradual rollout.
trim_line
67c8215ba3f246937fd7e1fbb02f33050a1c0456
sentry
processor_smcache.py
11
21
https://github.com/getsentry/sentry.git
8
120
0
68
204
Python
{ "docstring": "\n Trims a line down to a goal of 140 characters, with a little\n wiggle room to be sensible and tries to trim around the given\n `column`. So it tries to extract 60 characters before and after\n the provided `column` and yield a better context.\n ", "language": "en", "n_whitespaces...
def trim_line(line, column=0): line = line.strip("\n") ll = len(line) if ll <= 150: return line if column > ll: column = ll start = max(column - 60, 0) # Round down if it brings us close to the edge if start < 5: start = 0 end = min(start + 140, ll) # Rou...
71,747
247,569
189
tests/storage/test_background_update.py
45
17
def test_background_update_default_batch_set_by_config(self): self.get_success( self.store.db_pool.simple_insert( "background_updates", values={"update_name": "test_update", "progress_json": '{"my_key": 1}'}, ) ) self.update_hand...
Add config settings for background update parameters (#11980)
test_background_update_default_batch_set_by_config
ef3619e61d84493d98470eb2a69131d15eb1166b
synapse
test_background_update.py
13
15
https://github.com/matrix-org/synapse.git
1
92
0
39
154
Python
{ "docstring": "\n Test that the background update is run with the default_batch_size set by the config\n ", "language": "en", "n_whitespaces": 29, "n_words": 14, "vocab_size": 12 }
def test_background_update_default_batch_set_by_config(self): self.get_success( self.store.db_pool.simple_insert( "background_updates", values={"update_name": "test_update", "progress_json": '{"my_key": 1}'}, ) ) self.update_hand...
50,689
204,304
54
django/contrib/sessions/backends/file.py
11
9
def _expiry_date(self, session_data): return session_data.get("_session_expiry") or ( self._last_modification() + datetime.timedelta(seconds=self.get_session_cookie_ag
Refs #33476 -- Reformatted code with Black.
_expiry_date
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
file.py
13
5
https://github.com/django/django.git
2
36
0
11
62
Python
{ "docstring": "\n Return the expiry time of the file storing the session's content.\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 9 }
def _expiry_date(self, session_data): return session_data.get("_session_expiry") or ( self._last_modification() + datetime.timedelta(seconds=self.get_session_cookie_age()) )
5,973
32,709
283
src/transformers/models/trocr/processing_trocr.py
89
15
def __call__(self, *args, **kwargs): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*args, **kwargs) images = kwargs.pop("images", None) text = kwargs.pop("text", None) if len(args) > 0: images = ar...
Change audio kwarg to images in TROCR processor (#18421) Co-authored-by: ydshieh <ydshieh@users.noreply.github.com>
__call__
0b8c1b6994082950044452a670e8417a5ebc2db0
transformers
processing_trocr.py
11
21
https://github.com/huggingface/transformers.git
9
147
0
50
240
Python
{ "docstring": "\n When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's\n [`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context\n [`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's\n ...
def __call__(self, *args, **kwargs): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*args, **kwargs) images = kwargs.pop("images", None) text = kwargs.pop("text", None) if len(args) > 0: images = ar...
78,158
265,638
61
netbox/extras/reports.py
26
8
def get_report(module_name, report_name): reports = get_reports() module = reports.get(module_name) if module is None: return None report = module.get(report_name) if report is None: return None return report
Allow reports to be nested in submodules
get_report
356ff457be08d5527920c617eb598f24a6edbc3d
netbox
reports.py
8
9
https://github.com/netbox-community/netbox.git
3
45
0
15
75
Python
{ "docstring": "\n Return a specific report from within a module.\n ", "language": "en", "n_whitespaces": 15, "n_words": 8, "vocab_size": 7 }
def get_report(module_name, report_name): reports = get_reports() module = reports.get(module_name) if module is None: return None report = module.get(report_name) if report is None: return None return report
72,159
248,221
243
tests/config/test_workers.py
32
12
def test_worker_duty_configs(self) -> None: worker1_config = self._make_worker_config( worker_app="synapse.app.generic_worker", worker_name="worker1", extras={ "notify_appservice
Add the `update_user_directory_from_worker` configuration option (superseding `update_user_directory`) to allow a generic worker to be designated as the worker to update the user directory. (#12654) Co-authored-by: Shay <hillerys@element.io>
test_worker_duty_configs
699192fc1a1055a4bec2345bc80f120f28470c73
synapse
test_workers.py
12
24
https://github.com/matrix-org/synapse.git
1
96
0
22
170
Python
{ "docstring": "\n Additional tests for the worker duties\n ", "language": "en", "n_whitespaces": 21, "n_words": 6, "vocab_size": 6 }
def test_worker_duty_configs(self) -> None: worker1_config = self._make_worker_config( worker_app="synapse.app.generic_worker", worker_name="worker1", extras={ "notify_appservices_from_worker": "worker2", "update_user_directory_from_w...
29,383
130,818
107
python/ray/runtime_context.py
38
7
def actor_id(self): # only worker mode has actor_id assert ( self.worker.mode == ray.worker.
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
actor_id
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
runtime_context.py
9
7
https://github.com/ray-project/ray.git
2
41
0
34
78
Python
{ "docstring": "Get the current actor ID in this worker.\n\n ID of the actor of the current process.\n This shouldn't be used in a driver process.\n\n Returns:\n The current actor id in this worker. None if there's no actor id.\n ", "language": "en", "n_whitespaces": 77, "...
def actor_id(self): # only worker mode has actor_id assert ( self.worker.mode == ray.worker.WORKER_MODE ), f"This method is only available when the process is a\ worker. Current mode: {self.worker.mode}" actor_id = self.worker.actor_id return...
16,032
73,502
117
wagtail/contrib/settings/tests/test_admin.py
28
17
def test_redirect_to_current(self): start_url = reverse("wagtailsettings
Reformat with black
test_redirect_to_current
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
test_admin.py
12
11
https://github.com/wagtail/wagtail.git
1
78
0
23
127
Python
{ "docstring": "\n Should redirect to the setting for the current site taken from the URL,\n by default\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 13 }
def test_redirect_to_current(self): start_url = reverse("wagtailsettings:edit", args=["tests", "testsetting"]) dest_url = reverse( "wagtailsettings:edit", args=["tests", "testsetting", self.other_site.pk] ) response = self.client.get( start_url, follow=Tr...
35,052
151,576
407
freqtrade/freqai/base_models/FreqaiMultiOutputClassifier.py
114
27
def fit(self, X, y, sample_weight=None, fit_params=None): if not hasattr(self.estimator, "fit"): raise ValueError("The base estimator should implement a fit method") y = self._validate_data(X="no_validation", y=y, multi_output=True) if is_classifier(self): che...
add strat and config for testing on PR
fit
217add70bd010cae584db5aa13a7d5e76011e2bd
freqtrade
FreqaiMultiOutputClassifier.py
13
31
https://github.com/freqtrade/freqtrade.git
11
239
0
87
379
Python
{ "docstring": "Fit the model to data, separately for each output variable.\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input data.\n y : {array-like, sparse matrix} of shape (n_samples, n_outputs)\n Multi-output ...
def fit(self, X, y, sample_weight=None, fit_params=None): if not hasattr(self.estimator, "fit"): raise ValueError("The base estimator should implement a fit method") y = self._validate_data(X="no_validation", y=y, multi_output=True) if is_classifier(self): che...
24,472
111,721
54
nni/retiarii/nn/pytorch/api.py
14
7
def inner_choices(self) -> Iterable['ValueChoice']: for arg in self.arguments: if isinstance(arg, ValueChoiceX): yield from arg.inner_choices()
Composition of `ValueChoice` (#4435)
inner_choices
a36dc07e8d39ec4438fd660c98f6f4551ff5f4a6
nni
api.py
12
9
https://github.com/microsoft/nni.git
3
33
0
14
56
Python
{ "docstring": "\n Return an iterable of all leaf value choices.\n Useful for composition of value choices.\n No deduplication on labels. Mutators should take care.\n ", "language": "en", "n_whitespaces": 51, "n_words": 22, "vocab_size": 19 }
def inner_choices(self) -> Iterable['ValueChoice']: for arg in self.arguments: if isinstance(arg, ValueChoiceX): yield from arg.inner_choices()
49,661
200,455
451
sympy/tensor/index_methods.py
152
29
def get_indices(expr): # We call ourself recursively to d
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_indices
24f1e7730119fe958cc8e28411f790c9a5ec04eb
sympy
index_methods.py
16
30
https://github.com/sympy/sympy.git
13
186
0
102
311
Python
{ "docstring": "Determine the outer indices of expression ``expr``\n\n By *outer* we mean indices that are not summation indices. Returns a set\n and a dict. The set contains outer indices and the dict contains\n information about index symmetries.\n\n Examples\n ========\n\n >>> from sympy.tensor...
def get_indices(expr): # We call ourself recursively to determine indices of sub expressions. # break recursion if isinstance(expr, Indexed): c = expr.indices inds, dummies = _remove_repeated(c) return inds, {} elif expr is None: return set(), {} elif isinstance...
12,478
61,265
38
.venv/lib/python3.8/site-packages/pip/_internal/utils/misc.py
16
6
def dist_location(dist): # type: (Distribution) -> str egg_link = egg_link_path(dist) if egg_link: return normalize_path(egg_lin
upd; format
dist_location
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
misc.py
9
5
https://github.com/jindongwang/transferlearning.git
2
27
0
15
48
Python
{ "docstring": "\n Get the site-packages location of this distribution. Generally\n this is dist.location, except in the case of develop-installed\n packages, where dist.location is the source code location, and we\n want to know where the egg-link file is.\n\n The returned location is normalized (in p...
def dist_location(dist): # type: (Distribution) -> str egg_link = egg_link_path(dist) if egg_link: return normalize_path(egg_link) return normalize_path(dist.location)
39,618
164,908
119
pandas/_testing/_io.py
41
8
def can_connect(url, error_classes=None): if error_classes is None: error_classes = _get_default_network_errors() try: with urlopen(url, time
TST: Check network URL statuses in tests (#45949)
can_connect
4bc68b39511fdf1dffe91bd315ffee9565b90d1a
pandas
_io.py
13
11
https://github.com/pandas-dev/pandas.git
4
52
0
33
92
Python
{ "docstring": "\n Try to connect to the given url. True if succeeds, False if OSError\n raised\n\n Parameters\n ----------\n url : basestring\n The URL to try to connect to\n\n Returns\n -------\n connectable : bool\n Return True if no OSError (unable to connect) or URLError (ba...
def can_connect(url, error_classes=None): if error_classes is None: error_classes = _get_default_network_errors() try: with urlopen(url, timeout=20) as response: # Timeout just in case rate-limiting is applied if response.status != 200: return False ...
19,247
95,842
448
tests/sentry/incidents/endpoints/test_serializers.py
73
46
def test_valid_slack_channel_id(self): integration = Integration.objects.create( external_id="1", provider="slack", metadata={"access_token": "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"}, ) integration.add_organization(self.organization, self.user) ...
ref(serializers): Split up large file (#31359)
test_valid_slack_channel_id
efb962b72c649c18c466afae41722384d111824b
sentry
test_serializers.py
15
36
https://github.com/getsentry/sentry.git
1
210
0
63
360
Python
{ "docstring": "\n Test that when a valid Slack channel ID is provided, we look up the channel name and validate it against the targetIdentifier.\n ", "language": "en", "n_whitespaces": 37, "n_words": 22, "vocab_size": 20 }
def test_valid_slack_channel_id(self): integration = Integration.objects.create( external_id="1", provider="slack", metadata={"access_token": "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"}, ) integration.add_organization(self.organization, self.user) ...
56,520
221,804
194
python3.10.4/Lib/ctypes/_aix.py
77
9
def get_legacy(members): if AIX_ABI == 64: # AIX 64-bit member is
add python 3.10.4 for windows
get_legacy
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_aix.py
15
12
https://github.com/XX-net/XX-Net.git
5
59
0
54
103
Python
{ "docstring": "\n This routine provides historical aka legacy naming schemes started\n in AIX4 shared library support for library members names.\n e.g., in /usr/lib/libc.a the member name shr.o for 32-bit binary and\n shr_64.o for 64-bit binary.\n ", "language": "en", "n_whitespaces": 49, "n_wor...
def get_legacy(members): if AIX_ABI == 64: # AIX 64-bit member is one of shr64.o, shr_64.o, or shr4_64.o expr = r'shr4?_?64\.o' member = get_one_match(expr, members) if member: return member else: # 32-bit legacy names - both shr.o and shr4.o exist. ...
54,425
216,136
542
salt/states/iptables.py
176
12
def set_policy(name, table="filter", family="ipv4", **kwargs): ret = {"name": name, "changes": {}, "result": None, "comment": ""} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] if ( __salt__["iptables.get_policy"](table, kwargs["chain"], fa...
salt.states.iptables: Document the save parameter The examples mention this, but the reference documentation did not, and it isn't obvious from the example that minimal installations of some operating systems (in particular Debian) don't have all the necessary packages to make it effective, even if iptables itself is ...
set_policy
497ebde11325333cf8e1c0e4eeec185a55fb6ace
salt
iptables.py
14
46
https://github.com/saltstack/salt.git
9
281
0
83
491
Python
{ "docstring": "\n .. versionadded:: 2014.1.0\n\n Sets the default policy for iptables firewall tables\n\n table\n The table that owns the chain that should be modified\n\n family\n Networking family, either ipv4 or ipv6\n\n policy\n The requested table policy\n\n save\n ...
def set_policy(name, table="filter", family="ipv4", **kwargs): ret = {"name": name, "changes": {}, "result": None, "comment": ""} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] if ( __salt__["iptables.get_policy"](table, kwargs["chain"], fa...
117,938
321,839
99
tests/end2end/fixtures/quteprocess.py
20
12
def _after_start(self): delay = self.request.config.getoption('--qute-delay-start') if delay: with self.disable_capturing(): print(f"- waiting {delay}ms for quteprocess " f"(PID: {self.proc.processId()})...") time.
quteprocess: Add --qute-delay-start Allows for some rudimentary debugging of subprocesses.
_after_start
496c14bc9e0afb6c6787a0a167a1cb623ce5e2ff
qutebrowser
quteprocess.py
17
7
https://github.com/qutebrowser/qutebrowser.git
2
43
0
20
97
Python
{ "docstring": "Wait before continuing if requested, e.g. for debugger attachment.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def _after_start(self): delay = self.request.config.getoption('--qute-delay-start') if delay: with self.disable_capturing(): print(f"- waiting {delay}ms for quteprocess " f"(PID: {self.proc.processId()})...") time.sleep(delay / 1000)...
54,326
216,018
192
salt/modules/vault.py
66
19
def list_secrets(path, default=None): if default is None: default = CommandExecutionError log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path) version2 = __utils__["vault.is_v2"](path) if version2["v2"]: path = version2["metadata"] try: url = "v1/{...
Don't pass Error as default value in vault.py
list_secrets
681ea37f212619266424f00173d0affa27002071
salt
vault.py
17
19
https://github.com/saltstack/salt.git
6
123
0
54
215
Python
{ "docstring": "\n .. versionchanged:: 3001\n The ``default`` argument has been added. When the path or path/key\n combination is not found, an exception will be raised, unless a default\n is provided.\n\n List secret keys at the path in vault. The vault policy used must allow this.\n Th...
def list_secrets(path, default=None): if default is None: default = CommandExecutionError log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path) version2 = __utils__["vault.is_v2"](path) if version2["v2"]: path = version2["metadata"] try: url = "v1/{...
@RunIf(skip_windows=True, fairscale=True) @mock.patch("pytorch_lightning.strategies.DDPShardedStrategy._wrap_optimizers", autospec=True) @pytest.mark.parametrize(["params", "expected_buffer_size"], [(dict(), 0), (dict(reduce_buffer_size=128), 128)]) @pytest.mark.parametrize("num_nodes", [1, 2])
69,609
241,584
79
tests/strategies/test_sharded_strategy.py
49
29
def test_custom_kwargs_sharded(tmpdir, cls): strategy = cls(reduce_fp16=True) strategy.model = Mock(spec=LightningModule) strategy.model.trainer = Mock() class_name = "sharded" if isinstance(strategy, DDPShardedStrategy) else "sharded_spawn" with mock.patch(f"pytorch_lightning.strategies.{clas...
Rename training plugin test files & names to strategy (#11303)
test_custom_kwargs_sharded
650c710efacd633fa283955145342bb64063c883
lightning
test_sharded_strategy.py
12
10
https://github.com/Lightning-AI/lightning.git
2
83
1
42
257
Python
{ "docstring": "Tests to ensure that if custom kwargs are passed, they are set correctly.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 12 }
def test_custom_kwargs_sharded(tmpdir, cls): strategy = cls(reduce_fp16=True) strategy.model = Mock(spec=LightningModule) strategy.model.trainer = Mock() class_name = "sharded" if isinstance(strategy, DDPShardedStrategy) else "sharded_spawn" with mock.patch(f"pytorch_lightning.strategies.{clas...
""" # This file was generated by 'versioneer.py' (0.21) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import
47,323
195,608
170
versioneer.py
58
21
def versions_from_parentdir(parentdir_prefix, root, verbose): rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parent
add auto tag
versions_from_parentdir
f0194812568c83585ff09488fe7f67df300938cc
rembg
versioneer.py
15
14
https://github.com/danielgatis/rembg.git
4
106
1
51
199
Python
{ "docstring": "Try to determine the version from the parent directory name.\n\n Source tarballs conventionally unpack into a directory that includes both\n the project name and a version string. We will also support searching up\n two directory levels for an appropriately named parent directory\n \n# Thi...
def versions_from_parentdir(parentdir_prefix, root, verbose): rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, ...
50,354
203,405
1,211
django/contrib/admin/options.py
248
51
def response_add(self, request, obj, post_url_continue=None): opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self...
Refs #33476 -- Reformatted code with Black.
response_add
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
options.py
15
77
https://github.com/django/django.git
12
410
0
152
665
Python
{ "docstring": "\n Determine the HttpResponse for the add_view stage.\n ", "language": "en", "n_whitespaces": 22, "n_words": 7, "vocab_size": 6 }
def response_add(self, request, obj, post_url_continue=None): opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self...
117,110
320,280
61
src/paperless_mail/tests/test_parsers.py
26
8
def test_tika_parse_unreachable(self): html = '<html><he
add test comments
test_tika_parse_unreachable
4aa318598fd0dc6c5d4e08dd2a13e7bf614511ec
paperless-ngx
test_parsers.py
9
4
https://github.com/paperless-ngx/paperless-ngx.git
1
30
0
25
54
Python
{ "docstring": "\n GIVEN:\n - Fresh start\n WHEN:\n - tika parsing is called but tika is not available\n THEN:\n - a ParseError Exception is thrown\n ", "language": "en", "n_whitespaces": 84, "n_words": 22, "vocab_size": 17 }
def test_tika_parse_unreachable(self): html = '<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><p>Some Text</p></body></html>' # Check if exception is raised when Tika cannot be reached. self.parser.tika_server = "" self.assertRaises(...
43,543
181,757
17
tests/tpot_tests.py
8
6
def test_read_config_file_2(): tpot_obj = TPOTRegressor() assert_raises(ValueError, tpot
Revert "Deployed 7ccda9a with MkDocs version: 1.3.0" This reverts commit bd9629c40e01241766197119b581a99409b07068.
test_read_config_file_2
388616b6247ca4ea8de4e2f340d6206aee523541
tpot
tpot_tests.py
8
3
https://github.com/EpistasisLab/tpot.git
1
20
0
8
37
Python
{ "docstring": "Assert that _read_config_file rasies ValueError with wrong dictionary format", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_read_config_file_2(): tpot_obj = TPOTRegressor() assert_raises(ValueError, tpot_obj._read_config_file, "tests/test_config.py.bad")
78,295
266,105
70
netbox/netbox/staging.py
28
17
def pre_delete_handler(self, sender, instance, **kwargs): key = self.get_key_for_instance(instance) object_type = instance._meta.verbose_name # Delete an existing object logger.debug(f"[{self.branch}] Staging deletion of {object_type} {instance} (PK: {instance.pk})") se...
Closes #10851: New staging mechanism (#10890) * WIP * Convert checkout() context manager to a class * Misc cleanup * Drop unique constraint from Change model * Extend staging tests * Misc cleanup * Incorporate M2M changes * Don't cancel wipe out creation records when an object is deleted * Rena...
pre_delete_handler
a5308ea28e851a4ddb65a4e7ca2297b641e5891f
netbox
staging.py
10
5
https://github.com/netbox-community/netbox.git
1
49
0
26
100
Python
{ "docstring": "\n Hooks to the pre_delete signal when a branch is active to queue delete actions.\n ", "language": "en", "n_whitespaces": 29, "n_words": 14, "vocab_size": 13 }
def pre_delete_handler(self, sender, instance, **kwargs): key = self.get_key_for_instance(instance) object_type = instance._meta.verbose_name # Delete an existing object logger.debug(f"[{self.branch}] Staging deletion of {object_type} {instance} (PK: {instance.pk})") se...
28,421
127,346
98
python/ray/serve/experimental/gradio_visualize_graph.py
42
11
def _reset_state(self): self.cache = {}
[serve] Visualize Deployment Graph with Gradio (#27897)
_reset_state
4c970cc88247f7cfa7351297b8b5050f2372742e
ray
gradio_visualize_graph.py
8
6
https://github.com/ray-project/ray.git
1
48
0
27
79
Python
{ "docstring": "Resets state for each new RayServeHandle representing a new DAG.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 9 }
def _reset_state(self): self.cache = {} self.resolved_nodes = 0 self.finished_last_inference = True # maps DAGNode uuid to unique instance of a gradio block self.node_to_block: Dict[DAGNode, Any] = {} # maps InputAttributeNodes to unique instance of interactive ...
7,318
40,109
20
dash/testing/browser.py
6
6
def find_element(self, selector):
:hocho: deprecated find_element(s)_by_css_selector
find_element
5dfa6b0782803cb0635119ee1dcf8775dd76c8a7
dash
browser.py
8
2
https://github.com/plotly/dash.git
1
21
0
6
34
Python
{ "docstring": "find_element returns the first found element by the css `selector`\n shortcut to `driver.find_element(By.CSS_SELECTOR, ...)`.", "language": "en", "n_whitespaces": 20, "n_words": 14, "vocab_size": 13 }
def find_element(self, selector): return self.driver.find_element(By.CSS_SELECTOR, selector)
26,265
118,518
20
lib/tests/streamlit/caching/memo_test.py
6
5
def test_bad_persist_value(self): with self.assertRaises(StreamlitAPIException) as e:
st.memo/singleton: cache-specific clear() functionality (#4184) Gives `@st.memo` and `@st.singleton` a per-cache `clear()` function, similar to Python's [functools.lru_cache API](https://docs.python.org/3/library/functools.html#functools.lru_cache). You can use it like this: ```python @st.experimental_memo def...
test_bad_persist_value
b7f417f86ed4ca12c522d8ae5c147f932ffc7d40
streamlit
memo_test.py
10
8
https://github.com/streamlit/streamlit.git
1
41
0
6
32
Python
{ "docstring": "Throw an error if an invalid value is passed to 'persist'.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 10 }
def test_bad_persist_value(self): with self.assertRaises(StreamlitAPIException) as e:
42,847
178,863
2,090
nuitka/OptionParsing.py
859
33
def _getDataFileTagsOptionHelp(): return % ", ".join( "'%s' (%s)" % d for d in data_files_tags ) data_file_tags_option = data_group.add_option( "--data-file-tags", action="append", dest="data_file_tags", metavar="DATA_TAGS", default=[], ) parser.add_option_group(data_group) exe...
Plugins: Added ability to provide data file tags
_getDataFileTagsOptionHelp
e940705671f341139487d79b0eb0b6b9104f0a71
Nuitka
OptionParsing.py
12
9
https://github.com/Nuitka/Nuitka.git
2
19
0
399
3,971
Python
{ "docstring": "\\\nFor included data files, special handlings can be chosen. With the\ncommercial plugins, e.g. files can be included directly in the\nbinary. The list is completed by some plugins. With the current\nlist of plugins, these are available: %s.\nThe default is empty.\\\nExecute immediately the created b...
def _getDataFileTagsOptionHelp(): return % ", ".join( "'%s' (%s)" % d for d in data_files_tags ) data_file_tags_option = data_group.add_option( "--data-file-tags", action="append", dest="data_file_tags", metavar="DATA_TAGS", default=[], ) parser.add_option_group(data_group) exe...
15,867
72,267
236
wagtail/admin/tests/test_workflows.py
34
16
def test_collect_workflow_action_data_post(self): response = self.client.post( reverse( "wagtailadmin_pages:collect_workflow_action_data", args=( self.page
Reformat with black
test_collect_workflow_action_data_post
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
test_workflows.py
15
18
https://github.com/wagtail/wagtail.git
1
94
0
27
159
Python
{ "docstring": "\n This tests that a POST request to the collect_workflow_action_data view (for the approve action) returns a modal response with the validated data\n ", "language": "en", "n_whitespaces": 37, "n_words": 22, "vocab_size": 19 }
def test_collect_workflow_action_data_post(self): response = self.client.post( reverse( "wagtailadmin_pages:collect_workflow_action_data", args=( self.page.id, "approve", self.page.current_workflow_t...
25,581
115,841
31
mindsdb/integrations/handlers/lightwood_handler/tests/test_lightwood_handler.py
11
13
def test_02_train_predictor(self): query = f response = self.handler.native_query(query) self.assertTrue(response.type ==
add more TS tests
test_02_train_predictor
871793d4fbd99f454c0c1ff14db6ce3c385e656c
mindsdb
test_lightwood_handler.py
9
8
https://github.com/mindsdb/mindsdb.git
1
31
0
10
69
Python
{ "docstring": "\n CREATE PREDICTOR {self.test_model_1}\n FROM {PG_HANDLER_NAME} (SELECT * FROM {self.data_table_1} 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)
@TRANSFORMS.register_module()
70,426
244,549
123
mmdet/datasets/pipelines/loading.py
36
13
def __call__(self, results): img = results['img'] if self.to_float32: img = img.astype(np.float32) results['img_path'] = None results['img'] = img height, width = img.shape[:2] results['height'] = height results['width'] = width resu...
Refacter Visualization
__call__
c71a160c5193b92f6a4f56c113e96b63decf8354
mmdetection
loading.py
11
12
https://github.com/open-mmlab/mmdetection.git
2
78
1
22
147
Python
{ "docstring": "Call functions to add image meta information.\n\n Args:\n results (dict): Result dict with Webcam read image in\n ``results['img']``.\n\n Returns:\n dict: The dict contains loaded image and meta information.\n ", "language": "en", "n_whites...
def __call__(self, results): img = results['img'] if self.to_float32: img = img.astype(np.float32) results['img_path'] = None results['img'] = img height, width = img.shape[:2] results['height'] = height results['width'] = width resu...
29,488
131,233
381
python/ray/tests/test_advanced_4.py
114
20
def test_jemalloc_env_var_propagate(): gcs_ptype = ray.ray_constants.PROCESS_TYPE_GCS_SERVER expected = {} actual = ray._private.services.propagate_jemalloc_env_var( jemalloc_path="", jemalloc_conf="", jemalloc_comps=[], process_type=gcs_ptype ) assert actual == expected actual...
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
test_jemalloc_env_var_propagate
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
test_advanced_4.py
12
57
https://github.com/ray-project/ray.git
1
258
0
52
420
Python
{ "docstring": "Test `propagate_jemalloc_env_var`\n If the shared library path is not specified,\n it should return an empty dict.\n \n When the shared library is specified\n \n When the malloc config is specified\n ", "language": "en", "n_whitespaces": 51, "n_words": 28, "vocab_size": 20...
def test_jemalloc_env_var_propagate(): gcs_ptype = ray.ray_constants.PROCESS_TYPE_GCS_SERVER expected = {} actual = ray._private.services.propagate_jemalloc_env_var( jemalloc_path="", jemalloc_conf="", jemalloc_comps=[], process_type=gcs_ptype ) assert actual == expected actual...
70,341
244,349
674
mmdet/models/dense_heads/dense_test_mixins.py
171
54
def aug_test_bboxes(self, feats, img_metas, rescale=False): # check with_nms argument gb_sig = signature(self.get_results) gb_args = [p.name for p in gb_sig.parameters.values()] gbs_sig = signature(self._get_results_single) gbs_args = [p.name for p in gbs_sig.parameters....
[Refactor] Refactor dense head outputs to InstanceResults.
aug_test_bboxes
9a3bf7660e6ced54672741095f96df07919f9ba7
mmdetection
dense_test_mixins.py
14
46
https://github.com/open-mmlab/mmdetection.git
9
361
0
122
567
Python
{ "docstring": "Test det bboxes with test time augmentation, can be applied in\n DenseHead except for ``RPNHead`` and its variants, e.g., ``GARPNHead``,\n etc.\n\n Args:\n feats (list[Tensor]): the outer list indicates test-time\n augmentations and inner Tensor should ha...
def aug_test_bboxes(self, feats, img_metas, rescale=False): # check with_nms argument gb_sig = signature(self.get_results) gb_args = [p.name for p in gb_sig.parameters.values()] gbs_sig = signature(self._get_results_single) gbs_args = [p.name for p in gbs_sig.parameters....
71,136
246,294
32
synapse/replication/tcp/protocol.py
11
8
def pauseProducing(self) -> None: logger.info("[%s] Pause producing", self.id()) self.state = ConnectionStat
Add missing type hints to synapse.replication. (#11938)
pauseProducing
d0e78af35e519ff76bd23e786007f3e7130d90f7
synapse
protocol.py
9
10
https://github.com/matrix-org/synapse.git
1
27
0
11
48
Python
{ "docstring": "This is called when both the kernel send buffer and the twisted\n tcp connection send buffers have become full.\n\n We don't actually have any control over those sizes, so we buffer some\n commands ourselves before knifing the connection due to the remote\n failing to keep ...
def pauseProducing(self) -> None: logger.info("[%s] Pause producing", self.id()) self.state = ConnectionStates.PAUSED
55,605
219,497
104
python3.10.4/Lib/_collections_abc.py
28
6
def throw(self, typ, val=None, tb=None): if val is None: if tb is None: raise typ val = typ() if tb is not None: va
add python 3.10.4 for windows
throw
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_collections_abc.py
10
8
https://github.com/XX-net/XX-Net.git
4
49
0
16
78
Python
{ "docstring": "Raise an exception in the coroutine.\n Return next yielded value or raise StopIteration.\n ", "language": "en", "n_whitespaces": 27, "n_words": 13, "vocab_size": 13 }
def throw(self, typ, val=None, tb=None): if val is None: if tb is None: raise typ val = typ() if tb is not None: val = val.with_traceback(tb) raise val
3,497
20,715
29
pipenv/patched/notpip/_vendor/rich/console.py
8
4
def _exit_buffer(self) -> None: se
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...
_exit_buffer
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
console.py
7
4
https://github.com/pypa/pipenv.git
1
18
0
8
33
Python
{ "docstring": "Leave buffer context, and render content if required.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def _exit_buffer(self) -> None: self._buffer_index -= 1 self._check_buffer()
116,193
317,626
27
homeassistant/components/switchbot/coordinator.py
11
2
def flatten_sensors_data(sensor): if "temp" in sensor["data"]: sensor["data"]["temp
Add Switchbot hygrometers (#75325) * Switchbot add support for hygrometers * Update CODEOWNERS * Improve debug * Remove redundant mention to temp unit * Adopt FlowResultType * Modify SwitchBot data within coordinator * Increase logging for switchbot sensor * Revert "Increase logging for switchbot ...
flatten_sensors_data
148f96351052b0a4ba31e7d15dad16d7639e1ceb
core
coordinator.py
12
4
https://github.com/home-assistant/core.git
2
34
0
11
67
Python
{ "docstring": "Deconstruct SwitchBot library temp object C/Fº readings from dictionary.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def flatten_sensors_data(sensor): if "temp" in sensor["data"]: sensor["data"]["temperature"] = sensor["data"]["temp"]["c"] return sensor
82,378
278,120
696
keras/feature_column/sequence_feature_column_test.py
115
29
def test_shared_embedding_column_with_non_sequence_categorical(self): with tf.Graph().as_default(): vocabulary_size = 3 sparse_input_a = tf.compat.v1.SparseTensorValue( # example 0, ids [2] # example 1, ids [0, 1] indices=((0, 0), ...
resolve line-too-long in feature_column
test_shared_embedding_column_with_non_sequence_categorical
6fafb567af4e4d9f42974d0b6c55b18bc03e17eb
keras
sequence_feature_column_test.py
15
39
https://github.com/keras-team/keras.git
1
218
0
64
332
Python
{ "docstring": "Tests that error is raised for non-sequence shared embedding\n column.", "language": "en", "n_whitespaces": 16, "n_words": 10, "vocab_size": 10 }
def test_shared_embedding_column_with_non_sequence_categorical(self): with tf.Graph().as_default(): vocabulary_size = 3 sparse_input_a = tf.compat.v1.SparseTensorValue( # example 0, ids [2] # example 1, ids [0, 1] indices=((0, 0), ...
85,472
285,879
320
openbb_terminal/helper_funcs.py
90
18
def get_next_stock_market_days(last_stock_day, n_next_days) -> list: n_days = 0 l_pred_days = [] years: list = [] holidays: list = [] if isinstance(last_stock_day, datetime): while n_days < n_next_days: last_stock_day += timedelta(ho
Forecasting Menu [Work in Progress] (#1933) * Gave forecasting memory * Fixed scripts, refactored * FIxed poetry lock * edge case check for forecast target * Improved combine and load functionality * Cleaned up translations * Fixed issue with covariates * Fixed issue checking covariates * Anoth...
get_next_stock_market_days
7fd72d9ee1e8847717195859bf6d608268a94e2f
OpenBBTerminal
helper_funcs.py
14
24
https://github.com/OpenBB-finance/OpenBBTerminal.git
7
133
0
52
225
Python
{ "docstring": "Gets the next stock market day. Checks against weekends and holidays", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def get_next_stock_market_days(last_stock_day, n_next_days) -> list: n_days = 0 l_pred_days = [] years: list = [] holidays: list = [] if isinstance(last_stock_day, datetime): while n_days < n_next_days: last_stock_day += timedelta(hours=24) year = last_stock_day....
@pytest.mark.asyncio @pytest.mark.parametrize( "failures", [ [True, True, True, True, True], [False, False, False, False, False], [False, True, False, True, False], [False, False, False, True, True], [True, True, False, False, False], ], )
27,665
124,708
225
dashboard/tests/test_state_head.py
120
21
async def test_max_concurrent_in_progress_functions(extra_req_num): max_req = 10 a = A(max_num_call=max_req) # Run more than allowed concurrent async functions should trigger rate limiting res_arr = await asyncio.gather( *[a.fn1() if i % 2 == 0 else a.fn2() for i in range(max_req + extra_r...
[Core | State Observability] Implement API Server (Dashboard) HTTP Requests Throttling (#26257) This is to limit the max number of HTTP requests the dashboard (API server) will accept before rejecting more requests. This will make sure the observability requests do not overload the downstream systems (raylet/gcs) whe...
test_max_concurrent_in_progress_functions
365ffe21e592589880e3116302705b5e08a5b81f
ray
test_state_head.py
15
15
https://github.com/ray-project/ray.git
5
96
1
78
270
Python
{ "docstring": "Test rate limiting for concurrent in-progress requests on StateHead", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
async def test_max_concurrent_in_progress_functions(extra_req_num): max_req = 10 a = A(max_num_call=max_req) # Run more than allowed concurrent async functions should trigger rate limiting res_arr = await asyncio.gather( *[a.fn1() if i % 2 == 0 else a.fn2() for i in range(max_req + extra_r...
37,330
158,149
132
d2l/mxnet.py
87
6
def transpose_qkv(X, num_heads): # Shape of input `X`: # (`batch_size`, no.
[PaddlePaddle] Merge master into Paddle branch (#1186) * change 15.2 title in chinese version (#1109) change title ’15.2. 情感分析:使用递归神经网络‘ to ’15.2. 情感分析:使用循环神经网络‘ * 修改部分语义表述 (#1105) * Update r0.17.5 (#1120) * Bump versions in installation * 94行typo: (“bert.mall”)->(“bert.small”) (#1129) * line 313: "b...
transpose_qkv
b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2
d2l-zh
mxnet.py
10
4
https://github.com/d2l-ai/d2l-zh.git
1
69
0
37
111
Python
{ "docstring": "Transposition for parallel computation of multiple attention heads.\n\n Defined in :numref:`sec_multihead-attention`", "language": "en", "n_whitespaces": 13, "n_words": 11, "vocab_size": 11 }
def transpose_qkv(X, num_heads): # Shape of input `X`: # (`batch_size`, no. of queries or key-value pairs, `num_hiddens`). # Shape of output `X`: # (`batch_size`, no. of queries or key-value pairs, `num_heads`, # `num_hiddens` / `num_heads`) X = X.reshape(X.shape[0], X.shape[1], num_heads, ...
9,018
46,849
131
airflow/models/taskinstance.py
21
13
def current_state(self, session=NEW_SESSION) -> str: return ( session.query(TaskInstance.state) .filter( TaskInstance.dag_id == self.dag_id, TaskInstance.task_id == self.ta
No need to load whole ti in current_state (#22764) Co-authored-by: Jed Cunningham <66968678+jedcunningham@users.noreply.github.com> Co-authored-by: Tzu-ping Chung <uranusjr@gmail.com>
current_state
4eaf9bcddfb370222b4386b02975974bb253f614
airflow
taskinstance.py
13
17
https://github.com/apache/airflow.git
1
55
0
18
85
Python
{ "docstring": "\n Get the very latest state from the database, if a session is passed,\n we use and looking up the state becomes part of the session, otherwise\n a new session is used.\n\n :param session: SQLAlchemy ORM Session\n ", "language": "en", "n_whitespaces": 72, "n_w...
def current_state(self, session=NEW_SESSION) -> str: return ( session.query(TaskInstance.state) .filter( TaskInstance.dag_id == self.dag_id, TaskInstance.task_id == self.task_id, TaskInstance.run_id == self.run_id, ) ...
41,724
176,154
71
networkx/generators/small.py
28
5
def house_graph(create_using=None): description = [ "adjacencylist", "House Graph", 5, [[2, 3],
Docstrings for the small.py module (#5240) * added description for the first 5 small graphs * modified descriptions based on comment and added description for two more functions * added doctrings to all the functions * Minor touchups. Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
house_graph
dec723f072eb997a497a159dbe8674cd39999ee9
networkx
small.py
9
9
https://github.com/networkx/networkx.git
1
64
0
24
90
Python
{ "docstring": "\n Returns the House graph (square with triangle on top)\n\n The house graph is a simple undirected graph with\n 5 nodes and 6 edges [1]_.\n\n Parameters\n ----------\n create_using : NetworkX graph constructor, optional (default=nx.Graph)\n Graph type to create. If graph insta...
def house_graph(create_using=None): description = [ "adjacencylist", "House Graph", 5, [[2, 3], [1, 4], [1, 4, 5], [2, 3, 5], [3, 4]], ] G = make_small_undirected_graph(description, create_using) return G
4,208
22,136
114
pipenv/patched/pip/_vendor/requests/utils.py
40
9
def check_header_validity(header): name, value = header for part in header: if type(part) not in HEADER_VALIDATORS: raise InvalidHeader( f"Header part ({part!r})
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
check_header_validity
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
utils.py
16
10
https://github.com/pypa/pipenv.git
3
67
0
37
134
Python
{ "docstring": "Verifies that header parts don't contain leading whitespace\n reserved characters, or return characters.\n\n :param header: tuple, in the format (name, value).\n ", "language": "en", "n_whitespaces": 30, "n_words": 21, "vocab_size": 21 }
def check_header_validity(header): name, value = header for part in header: if type(part) not in HEADER_VALIDATORS: raise InvalidHeader( f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be " f"of type str or bytes, not {type(part)}" ...
5,130
27,800
330
saleor/graphql/order/tests/test_order.py
129
45
def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_order): order = fulfilled_order query = line = order.lines.first() metadata_key = "md key" metadata_value = "md value" line.store_value_in_private_metadata({metadata_key: metadata_value}) line.store_value_in_me...
Metadata added to checkout and order lines (#10040) * Metadata added to checkout and order lines * CHANGELOG.md update * Missing tests added
test_orderline_query
a68553e1a55e3a1bd32826cdce294d27f74175e9
saleor
test_order.py
15
93
https://github.com/saleor/saleor.git
1
349
0
78
595
Python
{ "docstring": "\n query OrdersQuery {\n orders(first: 1) {\n edges {\n node {\n lines {\n thumbnail(size: 540) {\n url\n }\n varia...
def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_order): order = fulfilled_order query = line = order.lines.first() metadata_key = "md key" metadata_value = "md value" line.store_value_in_private_metadata({metadata_key: metadata_value}) line.store_value_in_me...
52,612
209,122
370
scapy/layers/inet.py
132
28
def in4_pseudoheader(proto, u, plen): # type: (int, IP, int) -> bytes if u.len is not None: if u.ihl is None: olen = sum(len(x) for x in u.options) ihl = 5 + olen // 4 + (1 if olen % 4 else 0) else: ihl = u.ihl ln = max(u.len - 4 * ihl, 0) els...
Support TCP-MD5 and TCP-AO (#3358) Support TCP-MD5 and TCP-AO
in4_pseudoheader
20ac1d00389d0735e6d8cd1347f0a53f478144ba
scapy
inet.py
14
24
https://github.com/secdev/scapy.git
10
182
0
95
302
Python
{ "docstring": "IPv4 Pseudo Header as defined in RFC793 as bytes\n\n :param proto: value of upper layer protocol\n :param u: IP layer instance\n :param plen: the length of the upper layer and payload\n ", "language": "en", "n_whitespaces": 43, "n_words": 31, "vocab_size": 23 }
def in4_pseudoheader(proto, u, plen): # type: (int, IP, int) -> bytes if u.len is not None: if u.ihl is None: olen = sum(len(x) for x in u.options) ihl = 5 + olen // 4 + (1 if olen % 4 else 0) else: ihl = u.ihl ln = max(u.len - 4 * ihl, 0) els...
35,399
153,405
270
modin/core/storage_formats/base/doc_utils.py
91
23
def doc_resample_fillna(method, refer_to, params=None, overwrite_template_params=False): action = f"fill missing values in each group in
REFACTOR-#4093: Refactor base to be smaller (#4220) Signed-off-by: jeffreykennethli <jkli@ponder.io>
doc_resample_fillna
be9d382e35a9b87565499c029056afe1ddce6f37
modin
doc_utils.py
13
20
https://github.com/modin-project/modin.git
3
70
0
62
256
Python
{ "docstring": "\n Build decorator which adds docstring for the resample fillna query compiler method.\n\n Parameters\n ----------\n method : str\n Fillna method name.\n refer_to : str\n Method name in ``modin.pandas.resample.Resampler`` module to refer to for\n more information ab...
def doc_resample_fillna(method, refer_to, params=None, overwrite_template_params=False): action = f"fill missing values in each group independently using {method} method" params_substitution = "limit : int\n" if params: params_substitution = ( params if overwrite_templa...
14,730
68,154
9
erpnext/utilities/transaction_base.py
19
9
def delete_events(ref_type, ref_name): events = ( frappe.db.sql_list( , (ref_type, ref_name), ) or [] ) if events: frappe.delete_doc("Event", events, for_reload=True)
style: format code with black
delete_events
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
transaction_base.py
11
18
https://github.com/frappe/erpnext.git
3
44
0
18
69
Python
{ "docstring": " SELECT\n\t\t\tdistinct `tabEvent`.name\n\t\tfrom\n\t\t\t`tabEvent`, `tabEvent Participants`\n\t\twhere\n\t\t\t`tabEvent`.name = `tabEvent Participants`.parent\n\t\t\tand `tabEvent Participants`.reference_doctype = %s\n\t\t\tand `tabEvent Participants`.reference_docname = %s\n\t\t", "language": "en"...
def delete_events(ref_type, ref_name): events = ( frappe.db.sql_list( , (ref_type, ref_name), ) or [] ) if events: frappe.delete_doc("Event", events, for_reload=True)
31,990
140,519
115
python/ray/serve/deployment_state.py
39
9
def check_started(self) -> ReplicaStartupStatus: status, version = self._actor.check_ready() if status == ReplicaStartupStatus.SUCCEEDED: # Re-assign Depl
Clean up docstyle in python modules and add LINT rule (#25272)
check_started
905258dbc19753c81039f993477e7ab027960729
ray
deployment_state.py
11
14
https://github.com/ray-project/ray.git
3
39
0
30
67
Python
{ "docstring": "Check if the replica has started. If so, transition to RUNNING.\n\n Should handle the case where the replica has already stopped.\n\n Returns:\n status: Most recent state of replica by\n querying actor obj ref\n ", "language": "en", "n_whitespaces": 8...
def check_started(self) -> ReplicaStartupStatus: status, version = self._actor.check_ready() if status == ReplicaStartupStatus.SUCCEEDED: # Re-assign DeploymentVersion if start / update / recover succeeded # by reading re-computed version in RayServeReplica ...
110,202
311,537
164
tests/components/homekit_controller/test_sensor.py
44
15
async def test_battery_low(hass, utcnow): helper = await setup_test_component( hass, create_battery_level_sensor, suffix="battery" ) state = await helper.async_update(
Improve homekit_controller tests (#65266)
test_battery_low
58b8c30221a6f6e5acbbe98b7e3298b03fb741f5
core
test_sensor.py
12
20
https://github.com/home-assistant/core.git
1
93
0
26
149
Python
{ "docstring": "Test reading the state of a HomeKit battery's low state.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
async def test_battery_low(hass, utcnow): helper = await setup_test_component( hass, create_battery_level_sensor, suffix="battery" ) state = await helper.async_update( ServicesTypes.BATTERY_SERVICE, { CharacteristicsTypes.BATTERY_LEVEL: 1, Characteristic...
20,496
101,059
59
lib/model/loss/perceptual_loss_plaid.py
24
13
def _hyab(self, y_true, y_pred): delta = y_true
Add Flip Loss Function - Add Flip for AMD and TF - Split Perceptual Loss functions to own modules - Fix allowed input shape for models - Allow GUI tooltip to display at higher width
_hyab
582c2ce40c11ef235dd3f9100f70e1e2832f8dd3
faceswap
perceptual_loss_plaid.py
14
5
https://github.com/deepfakes/faceswap.git
1
65
0
20
97
Python
{ "docstring": " Compute the HyAB distance between true and predicted images.\n\n Parameters\n ----------\n y_true: :class:`plaidml.tile.Value`\n The ground truth batch of images in standard or Hunt-adjusted L*A*B* color space\n y_pred: :class:`plaidml.tile.Value`\n T...
def _hyab(self, y_true, y_pred): delta = y_true - y_pred root = K.sqrt(K.clip(K.pow(delta[..., 0:1], 2), self._epsilon, None)) delta_norm = frobenius_norm(delta[..., 1:3]) return root + delta_norm
7,862
43,199
231
tests/cli/commands/test_db_command.py
26
19
def test_dry_run(self, run_cleanup_mock, dry_run_arg, expected): args = self.parser.parse_args( [ 'db', 'clean', '--clean-before-timestamp', '2021-01-01', *dry_run_arg, ] ) db_command...
Don't rely on current ORM structure for db clean command (#23574) For command DB clean, by not relying on the ORM models, we will be able to use the command even when the metadatabase is not yet upgraded to the version of Airflow you have installed. Additionally we archive all rows before deletion.
test_dry_run
95bd6b71cc9f5da377e272707f7b68000d980939
airflow
test_db_command.py
11
19
https://github.com/apache/airflow.git
1
74
0
25
116
Python
{ "docstring": "\n When tz included in the string then default timezone should not be used.\n ", "language": "en", "n_whitespaces": 28, "n_words": 13, "vocab_size": 13 }
def test_dry_run(self, run_cleanup_mock, dry_run_arg, expected): args = self.parser.parse_args( [ 'db', 'clean', '--clean-before-timestamp', '2021-01-01', *dry_run_arg, ] ) db_command...
107,978
309,272
11
homeassistant/components/homekit/util.py
5
5
def async_dismiss_setup_message(hass, entry_id):
Import persistent notification (part 3) (#63900)
async_dismiss_setup_message
2eab3c8de1fd80a8f1456fd97389ca687c11ecb7
core
util.py
7
2
https://github.com/home-assistant/core.git
1
16
0
5
27
Python
{ "docstring": "Dismiss persistent notification and remove QR code.", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 7 }
def async_dismiss_setup_message(hass, entry_id): persistent_notification.async_dismiss(hass, entry_id)
50,294
203,309
139
django/apps/registry.py
33
16
def get_containing_app_config(self, object_name): self.check_apps_ready() candidates = [] for app_config in self.app_configs.values(): if object_name.startswith(app_config.name): subpath = object_name[len(app_config.name) :] if subpath == "" o...
Refs #33476 -- Reformatted code with Black.
get_containing_app_config
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
registry.py
16
10
https://github.com/django/django.git
6
92
0
28
152
Python
{ "docstring": "\n Look for an app config containing a given object.\n\n object_name is the dotted Python path to the object.\n\n Return the app config for the inner application in case of nesting.\n Return None if the object isn't in any registered app config.\n ", "language": "e...
def get_containing_app_config(self, object_name): self.check_apps_ready() candidates = [] for app_config in self.app_configs.values(): if object_name.startswith(app_config.name): subpath = object_name[len(app_config.name) :] if subpath == "" o...
82,926
279,328
158
keras/engine/base_layer.py
28
15
def _track_variables(self, value): for val in tf.nest.flatten(value): if isinstance(val, tf.Variable): self._track_variable(val) elif tf_utils.is_extension_type(val): # Manually expand extension types to track resource variables. n...
Prepare keras for making ResourceVariables as CompositeTensors. We are going to let ResourceVariable be a subclass of CompositeTensor. Changes in this CL are necessary to not break existing code. Specifically, to track resource variables embedded in composite tensors, we will need to manually expand composite tensors...
_track_variables
102ab667f513956d89f55f2f9480b9cdc5372eef
keras
base_layer.py
15
9
https://github.com/keras-team/keras.git
4
63
0
27
103
Python
{ "docstring": "Tracks `Variable`s including `Variable`s in `CompositeTensor`s.", "language": "en", "n_whitespaces": 5, "n_words": 6, "vocab_size": 5 }
def _track_variables(self, value): for val in tf.nest.flatten(value): if isinstance(val, tf.Variable): self._track_variable(val) elif tf_utils.is_extension_type(val): # Manually expand extension types to track resource variables. n...
45,489
186,573
386
certbot-apache/certbot_apache/_internal/configurator.py
111
30
def _create_vhost_v2(self, node): addrs = set() for param in node.parameters: addr = obj.Addr.fromstring(param) if addr: addrs.add(addr) is_ssl = False # Exclusion to match the behavior in get_virtual_hosts_v2 sslengine = node.fin...
Fully type certbot-nginx module (#9124) * Work in progress * Fix type * Work in progress * Work in progress * Work in progress * Work in progress * Work in progress * Oups. * Fix typing in UnspacedList * Fix logic * Finish typing * List certbot-nginx as fully typed in tox * Fix lint...
_create_vhost_v2
16aad35d31a887dab157f9d4f5e0fe9218d06064
certbot
configurator.py
14
25
https://github.com/certbot/certbot.git
9
159
0
76
259
Python
{ "docstring": "Used by get_virtual_hosts_v2 to create vhost objects using ParserNode\n interfaces.\n :param interfaces.BlockNode node: The BlockNode object of VirtualHost block\n :returns: newly created vhost\n :rtype: :class:`~certbot_apache.obj.VirtualHost`\n ", "language": "en...
def _create_vhost_v2(self, node): addrs = set() for param in node.parameters: addr = obj.Addr.fromstring(param) if addr: addrs.add(addr) is_ssl = False # Exclusion to match the behavior in get_virtual_hosts_v2 sslengine = node.fin...
13,203
63,204
710
.venv/lib/python3.8/site-packages/pip/_vendor/pkg_resources/__init__.py
154
24
def insert_on(self, path, loc=None, replace=False): loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [(p and _normalize_cached(p) or p) for p in path] fo
upd; format
insert_on
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
__init__.py
14
38
https://github.com/jindongwang/transferlearning.git
18
210
0
96
343
Python
{ "docstring": "Ensure self.location is on path\n\n If replace=False (default):\n - If location is already in path anywhere, do nothing.\n - Else:\n - If it's an egg and its parent directory is on path,\n insert just ahead of the parent.\n - Else: ...
def insert_on(self, path, loc=None, replace=False): loc = loc or self.location if not loc: return nloc = _normalize_cached(loc) bdir = os.path.dirname(nloc) npath = [(p and _normalize_cached(p) or p) for p in path] for p, item in enumerate(npath): ...
@add_start_docstrings( """ The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). """, XGLM_START_DOCSTRING, )
6,060
33,107
187
src/transformers/models/xglm/modeling_tf_xglm.py
47
22
def serving_output(self, output): pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions e...
Add TF implementation of `XGLMModel` (#16543) * Add TFXGLM models * Add todo: self.supports_xla_generation = False Co-authored-by: Daniel Stancl <stancld@Daniels-MacBook-Pro.local> Co-authored-by: Daniel Stancl <stancld@daniels-mbp.home> Co-authored-by: Joao Gante <joaofranciscocardosogante@gmail.com> Co-aut...
serving_output
c72d7d91bf4899760725793421eff9da640c8527
transformers
modeling_tf_xglm.py
11
16
https://github.com/huggingface/transformers.git
6
113
1
32
180
Python
{ "docstring": "\n The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input\n embeddings).\n ", "language": "en", "n_whitespaces": 30, "n_words": 20, "vocab_size": 19 }
def serving_output(self, output): pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions e...
36,047
154,524
124
modin/core/execution/ray/implementations/cudf_on_ray/partitioning/partition_manager.py
30
15
def _apply_func_to_list_of_partitions(cls, func, partitions, **kwargs): preprocessed_map_func = cls.preprocess_func(func) key_futures = RayWrapper.materialize( [ partition.apply(preprocessed_map_func, **kwargs) for partition in partitions ...
REFACTOR-#5009: use RayWrapper.materialize instead of ray.get (#5010) Signed-off-by: Myachev <anatoly.myachev@intel.com>
_apply_func_to_list_of_partitions
1dc16415333bf2428ee2b1f4d31ff94e66b9a0a6
modin
partition_manager.py
12
10
https://github.com/modin-project/modin.git
3
65
0
25
100
Python
{ "docstring": "\n Apply `func` to a list of remote partitions from `partitions`.\n\n Parameters\n ----------\n func : callable\n The function to apply.\n partitions : np.ndarray\n NumPy array with partitions.\n **kwargs : dict\n Additional ke...
def _apply_func_to_list_of_partitions(cls, func, partitions, **kwargs): preprocessed_map_func = cls.preprocess_func(func) key_futures = RayWrapper.materialize( [ partition.apply(preprocessed_map_func, **kwargs) for partition in partitions ...
31,884
140,169
43
python/ray/serve/deployment_function_executor_node.py
11
9
def _execute_impl(self, *args, **kwargs) -> ObjectRef: return self._deployment_function_handle.remote( *
[Serve][Deployment Graph][Perf] Add minimal executor DAGNode (#24754) closes #24475 Current deployment graph has big perf issues compare with using plain deployment handle, mostly because overhead of DAGNode traversal mechanism. We need this mechanism to empower DAG API, specially deeply nested objects in args wher...
_execute_impl
f27e85cd7df5ca2873ef6231200a1530e16ac35d
ray
deployment_function_executor_node.py
9
10
https://github.com/ray-project/ray.git
1
31
0
11
50
Python
{ "docstring": "Executor of DeploymentNode getting called each time on dag.execute.\n\n The execute implementation is recursive, that is, the method nodes will\n receive whatever this method returns. We return a handle here so method\n node can directly call upon.\n ", "language": "en", ...
def _execute_impl(self, *args, **kwargs) -> ObjectRef: return self._deployment_function_handle.remote( *self._bound_args, **self._bound_kwargs )
@keras_export('keras.utils.load_img', 'keras.preprocessing.image.load_img')
79,779
268,948
81
keras/preprocessing/image.py
51
18
def save_img(path, x, data_format=None, file_format=None, scale=True, **kwargs): if data_format is None: data_format = backend.image_data_format() img = array_to_img(x, data_format=data_format, scale=scale) if img.mode == 'RGBA' and (file_format == 'jpg' or file_format == 'jpeg'): warnings.warn('The JP...
Copy image utils from keras_preprocessing directly into core keras This is not new code, we are just moving these utilities directly into keras from keras-preprocessing. For the library code, just fixed linting errors. For the test code, had to do more major changes to port from pytest, but hopefully any errors have ...
save_img
373ad97c72ed1ac4b6898e85b2cfd7b016e4b469
keras
image.py
11
9
https://github.com/keras-team/keras.git
5
94
1
44
171
Python
{ "docstring": "Saves an image stored as a Numpy array to a path or file object.\n\n Args:\n path: Path or file object.\n x: Numpy array.\n data_format: Image data format, either \"channels_first\" or\n \"channels_last\".\n file_format: Optional file format override. If omitted, the format...
def save_img(path, x, data_format=None, file_format=None, scale=True, **kwargs): if data_format is None: data_format = backend.image_data_format() img = array_to_img(x, data_format=data_format, scale=scale) if img.mode == 'RGBA' and (file_format == 'jpg' or file_format == 'jpeg'): warnings.warn('The JP...
15,900
72,483
239
wagtail/admin/views/pages/edit.py
61
14
def log_commenting_changes(self, changes, revision): for comment in changes["new_comments"]: comment.log_create(page_revision=revision, user=self.request.user) for comment in changes["edited_comments"]: comment.log_edit(page_revision=revision, user=self.request.user) ...
Reformat with black
log_commenting_changes
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
edit.py
14
18
https://github.com/wagtail/wagtail.git
11
199
0
26
306
Python
{ "docstring": "\n Generates log entries for any changes made to comments or replies.\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 11 }
def log_commenting_changes(self, changes, revision): for comment in changes["new_comments"]: comment.log_create(page_revision=revision, user=self.request.user) for comment in changes["edited_comments"]: comment.log_edit(page_revision=revision, user=self.request.user) ...
23,015
108,011
201
lib/matplotlib/patches.py
76
20
def __new__(cls, stylename, **kwargs): # The "class" should have the _style_list attribute, which is a mapping # of style names to style classes. _list = stylename.replace(" ", "").split(",") _name = _list[0].lower() try: _cls = cls._style_list[_name] ...
Small style fixes.
__new__
075ff0952896f44d7d0b0b3318f0978ae53f84d7
matplotlib
patches.py
12
13
https://github.com/matplotlib/matplotlib.git
5
120
0
59
208
Python
{ "docstring": "Return the instance of the subclass with the given style name.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 9 }
def __new__(cls, stylename, **kwargs): # The "class" should have the _style_list attribute, which is a mapping # of style names to style classes. _list = stylename.replace(" ", "").split(",") _name = _list[0].lower() try: _cls = cls._style_list[_name] ...
81,916
277,252
369
keras/engine/base_layer.py
93
14
def losses(self): collected_losses = [] for layer in self._flatten_layers(): # If any eager losses are present, we assume the model to be part of # an eager training loop (either a custom one or the one used when # `run_eagerly=True`) and so we always return ...
reduct too long lines
losses
fa6d9107a498f7c2403ff28c7b389a1a0c5cc083
keras
base_layer.py
14
16
https://github.com/keras-team/keras.git
6
83
0
71
140
Python
{ "docstring": "List of losses added using the `add_loss()` API.\n\n Variable regularization tensors are created when this property is\n accessed, so it is eager safe: accessing `losses` under a\n `tf.GradientTape` will propagate gradients back to the corresponding\n variables.\n\n ...
def losses(self): collected_losses = [] for layer in self._flatten_layers(): # If any eager losses are present, we assume the model to be part of # an eager training loop (either a custom one or the one used when # `run_eagerly=True`) and so we always return ...
76,442
260,724
310
sklearn/linear_model/_least_angle.py
71
32
def fit(self, X, y, Xy=None): self._validate_params() X, y = self._validate_data(X, y, y_numeric=True, multi_output=True) _normalize = _deprecate_normalize( self.normalize, default=True, estimator_name=self.__class__.__name__ ) alpha = getattr(self, "alp
MAINT Parameter Validation for Lars, LarsCV, LassoLars, LassoLarsCV and LassoLarsIC (#24033) Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr>
fit
6c0e0b2e4723d11e29057635c7061a36bc1a8512
scikit-learn
_least_angle.py
13
26
https://github.com/scikit-learn/scikit-learn.git
3
169
0
52
251
Python
{ "docstring": "Fit the model using X, y as training data.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Training data.\n\n y : array-like of shape (n_samples,) or (n_samples, n_targets)\n Target values.\n\n Xy : array-like of ...
def fit(self, X, y, Xy=None): self._validate_params() X, y = self._validate_data(X, y, y_numeric=True, multi_output=True) _normalize = _deprecate_normalize( self.normalize, default=True, estimator_name=self.__class__.__name__ ) alpha = getattr(self, "alpha...
10,055
50,226
363
modules/image/text_to_image/disco_diffusion_ernievil_base/vit_b_16x/ernievil2/transformers/efficientnet.py
73
26
def _decode_block_string(block_string): assert isinstance(block_string, str) ops = block_string.split('_') options = {} for op in ops: splits = re.split(r'(\d.*)', op) if len(splits) >= 2: key, value = splits[:2] options[k...
add disco_diffusion_ernievil_base
_decode_block_string
ffcde21305c61d950a9f93e57e6180c9a9665b87
PaddleHub
efficientnet.py
14
20
https://github.com/PaddlePaddle/PaddleHub.git
7
213
0
56
348
Python
{ "docstring": " Gets a block through a string notation of arguments. ", "language": "en", "n_whitespaces": 10, "n_words": 9, "vocab_size": 8 }
def _decode_block_string(block_string): assert isinstance(block_string, str) ops = block_string.split('_') options = {} for op in ops: splits = re.split(r'(\d.*)', op) if len(splits) >= 2: key, value = splits[:2] options[k...
38,543
160,171
17
numpy/lib/function_base.py
12
5
def copy(a, order='K', subok=False): return
Improve documentation formatting
copy
0307f89d48368a39ed97a252f9faed3c7bf64446
numpy
function_base.py
8
2
https://github.com/numpy/numpy.git
1
31
0
12
49
Python
{ "docstring": "\n Return an array copy of the given object.\n\n Parameters\n ----------\n a : array_like\n Input data.\n order : {'C', 'F', 'A', 'K'}, optional\n Controls the memory layout of the copy. 'C' means C-order,\n 'F' means F-order, 'A' means 'F' if `a` is Fortran contigu...
def copy(a, order='K', subok=False): return array(a, order=order, subok=subok, copy=True) # Basic operations
31,769
139,754
13
python/ray/data/tests/test_context_propagation.py
7
4
def test_context_placement_group(): driver_code = proc = run_string_as_driver_no
[Datasets] Add explicit resource allocation option via a top-level scheduling strategy (#24438) Instead of letting Datasets implicitly use cluster resources in the margins of explicit allocations of other libraries, such as Tune, Datasets should provide an option for explicitly allocating resources for a Datasets work...
test_context_placement_group
68d4dd3a8b2defa5549cfa70e59aa26f2d4825a3
ray
test_context_propagation.py
8
30
https://github.com/ray-project/ray.git
1
23
0
6
27
Python
{ "docstring": "\nimport ray\nfrom ray.data.context import DatasetContext\nfrom ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy\nfrom ray._private.test_utils import placement_group_assert_no_leak\n\nray.init(num_cpus=1)\n\ncontext = DatasetContext.get_current()\n# This placement group will take...
def test_context_placement_group(): driver_code = proc = run_string_as_driver_nonblocking(driver_code)
40,576
170,562
83
pandas/core/arrays/categorical.py
25
9
def reorder_categories(self, new_categories, ordered=None): if set(self.dtype.categories) != set(new_categories): raise ValueError( "items in new_categories are not the same as in old categories" ) return self.set_categories(new_categories, ordered=ordere...
DEPR: remove inplace arg in Categorical methods (#49321) * deprecate inplace arg in categorical methods * fix tests * add back test * doc fix * doc fixes * avoid constructing new objects on every iteration * cleanup
reorder_categories
ab6562a20bd894d02fb28675809698d5be0436f9
pandas
categorical.py
10
6
https://github.com/pandas-dev/pandas.git
2
43
0
24
70
Python
{ "docstring": "\n Reorder categories as specified in new_categories.\n\n `new_categories` need to include all old categories and no new category\n items.\n\n Parameters\n ----------\n new_categories : Index-like\n The categories in new order.\n ordered : boo...
def reorder_categories(self, new_categories, ordered=None): if set(self.dtype.categories) != set(new_categories): raise ValueError( "items in new_categories are not the same as in old categories" ) return self.set_categories(new_categories, ordered=ordere...
71,391
246,887
361
tests/rest/client/test_rooms.py
150
17
def test_get_member_list_no_permission_former_member_with_at_token(self): # create a room, invite the user and the user joins room_id = self.helper.create_room_as("@alice:red") self.helper.invite(room_id, "@alice:red", self.user_id) self.helper.join(room_id, self.user_id) ...
Replace assertEquals and friends with non-deprecated versions. (#12092)
test_get_member_list_no_permission_former_member_with_at_token
02d708568b476f2f7716000b35c0adfa4cbd31b3
synapse
test_rooms.py
10
21
https://github.com/matrix-org/synapse.git
1
206
0
78
351
Python
{ "docstring": "\n Tests that a former member of the room can not get the member list\n (in the case that they use an at token).\n ", "language": "en", "n_whitespaces": 45, "n_words": 23, "vocab_size": 19 }
def test_get_member_list_no_permission_former_member_with_at_token(self): # create a room, invite the user and the user joins room_id = self.helper.create_room_as("@alice:red") self.helper.invite(room_id, "@alice:red", self.user_id) self.helper.join(room_id, self.user_id) ...
56,599
222,501
45
python3.10.4/Lib/difflib.py
22
8
def _keep_original_ws(s, tag_s): return ''.join( c if tag_c == " " and c.isspace() else tag_c for c, tag_c in zip(s, tag_s) )
add python 3.10.4 for windows
_keep_original_ws
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
difflib.py
11
5
https://github.com/XX-net/XX-Net.git
4
38
0
19
63
Python
{ "docstring": "Replace whitespace with the original whitespace characters in `s`", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 8 }
def _keep_original_ws(s, tag_s): return ''.join( c if tag_c == " " and c.isspace() else tag_c for c, tag_c in zip(s, tag_s) )
23,150
108,343
21
lib/matplotlib/cm.py
9
6
def unregister_cmap(name): cmap = _colormaps.get(name, None) _colormaps.unregister(name) return cmap
MNT: Remove cmap_d colormap access
unregister_cmap
fb902f735995372f345a8333804f5c6052f29770
matplotlib
cm.py
8
4
https://github.com/matplotlib/matplotlib.git
1
24
0
8
41
Python
{ "docstring": "\n Remove a colormap recognized by :func:`get_cmap`.\n\n You may not remove built-in colormaps.\n\n If the named colormap is not registered, returns with no error, raises\n if you try to de-register a default colormap.\n\n .. warning::\n\n Colormap names are currently a shared name...
def unregister_cmap(name): cmap = _colormaps.get(name, None) _colormaps.unregister(name) return cmap
22,017
104,902
116
src/datasets/utils/streaming_download_manager.py
53
15
def _get_extraction_protocol_with_magic_number(f) -> Optional[str]: magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH) f.seek(0) for i in range(MAGIC_NUMBER_MAX_LENGTH): compression = MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL.get(magic_number[: MAGIC_NUMBER_MAX_LENGTH - i]) if compression is not...
don't check f.loc in _get_extraction_protocol_with_magic_number (#4318)
_get_extraction_protocol_with_magic_number
17fd2ea68cf75b36369a9f018497875e292db26a
datasets
streaming_download_manager.py
13
11
https://github.com/huggingface/datasets.git
4
81
0
36
135
Python
{ "docstring": "read the magic number from a file-like object and return the compression protocol", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 12 }
def _get_extraction_protocol_with_magic_number(f) -> Optional[str]: magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH) f.seek(0) for i in range(MAGIC_NUMBER_MAX_LENGTH): compression = MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL.get(magic_number[: MAGIC_NUMBER_MAX_LENGTH - i]) if compression is not...
54,275
215,953
322
salt/modules/lxc.py
118
22
def _get_veths(net_data): if isinstance(net_data, dict): net_data = list(net_data.items()) nics = salt.utils.odict.OrderedDict() current_nic = salt.utils.odict.OrderedDict() no_names = True for item in net_data: if item and isinstance(item, dict): item = list(item.it...
Update to latest ``pyupgrade`` hook. Stop skipping it on CI. Signed-off-by: Pedro Algarvio <palgarvio@vmware.com>
_get_veths
f2a783643de61cac1ff3288b40241e5ce6e1ddc8
salt
lxc.py
20
24
https://github.com/saltstack/salt.git
14
206
0
74
342
Python
{ "docstring": "\n Parse the nic setup inside lxc conf tuples back to a dictionary indexed by\n network interface\n ", "language": "en", "n_whitespaces": 26, "n_words": 16, "vocab_size": 16 }
def _get_veths(net_data): if isinstance(net_data, dict): net_data = list(net_data.items()) nics = salt.utils.odict.OrderedDict() current_nic = salt.utils.odict.OrderedDict() no_names = True for item in net_data: if item and isinstance(item, dict): item = list(item.it...
24,799
112,957
42
nni/runtime/log.py
17
10
def start_stdout_logging() -> None: if '_stdout_' in _handlers: return
Logging refactor (step 1) - experiment handlers (#4792)
start_stdout_logging
4feab0e34b490500b06efd6e7e8a34d686702c2f
nni
log.py
9
14
https://github.com/microsoft/nni.git
2
41
0
15
75
Python
{ "docstring": "\n Register the stdout handler.\n\n This function should be invoked on importing nni.\n\n It is safe to call it multiple times.\n ", "language": "en", "n_whitespaces": 33, "n_words": 20, "vocab_size": 20 }
def start_stdout_logging() -> None: if '_stdout_' in _handlers: return handler = StreamHandler(sys.stdout) handler.setFormatter(_StdoutFormatter()) _handlers['_stdout_'] = handler _root_logger.addHandler(handler)
@frappe.whitelist()
14,109
66,146
14
erpnext/hr/doctype/job_offer/job_offer.py
22
12
def get_staffing_plan_detail(designation, company, offer_date): detail = frappe.db.sql( , (designation, company, offer_date), as_dict=1, ) return frappe._dict(detail[0]) if (detail and detail[0].parent) else None @frappe.whitelist()
style: format code with black
get_staffing_plan_detail
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
job_offer.py
10
21
https://github.com/frappe/erpnext.git
3
55
1
21
90
Python
{ "docstring": "\n\t\tSELECT DISTINCT spd.parent,\n\t\t\tsp.from_date as from_date,\n\t\t\tsp.to_date as to_date,\n\t\t\tsp.name,\n\t\t\tsum(spd.vacancies) as vacancies,\n\t\t\tspd.designation\n\t\tFROM `tabStaffing Plan Detail` spd, `tabStaffing Plan` sp\n\t\tWHERE\n\t\t\tsp.docstatus=1\n\t\t\tAND spd.designation=%s...
def get_staffing_plan_detail(designation, company, offer_date): detail = frappe.db.sql( , (designation, company, offer_date), as_dict=1, ) return frappe._dict(detail[0]) if (detail and detail[0].parent) else None @frappe.whitelist()
71,912
247,777
217
tests/push/test_push_rule_evaluator.py
94
8
def test_display_name(self) -> None: evaluator = self._get_evaluator({"body": "foo bar baz"}) condition = { "kind": "contains_display_name", } # Blank names are skipped. self.assertFalse(evaluator.matches(condition, "@user:test", "")) # Check a dis...
Add type hints to tests files. (#12256)
test_display_name
9d21ecf7ceab55bc19c4457b8b07401b0b1623a7
synapse
test_push_rule_evaluator.py
11
12
https://github.com/matrix-org/synapse.git
1
118
0
58
217
Python
{ "docstring": "Check for a matching display name in the body of the event.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 11 }
def test_display_name(self) -> None: evaluator = self._get_evaluator({"body": "foo bar baz"}) condition = { "kind": "contains_display_name", } # Blank names are skipped. self.assertFalse(evaluator.matches(condition, "@user:test", "")) # Check a dis...
54,176
215,784
33
tests/pytests/functional/modules/file/test_readlink.py
17
11
def test_readlink_not_a_link(file, source): with pytest.raises(Salt
Add some funtional tests Add functional tests for the following: - file.readlink - file.replace - file.symlink Remove unit tests for file.replace as they are duplicated in the added functional test
test_readlink_not_a_link
a35b29b2651bf33c5d5b45e64bc7765ffde4aff4
salt
test_readlink.py
10
4
https://github.com/saltstack/salt.git
1
34
0
17
61
Python
{ "docstring": "\n Test readlink where the path is not a link\n Should throw a SaltInvocationError\n ", "language": "en", "n_whitespaces": 23, "n_words": 13, "vocab_size": 12 }
def test_readlink_not_a_link(file, source): with pytest.raises(SaltInvocationError) as exc: file.readlink(path=source) assert "A valid link was not specified" in exc.value.message
14,660
67,910
76
erpnext/stock/report/stock_analytics/stock_analytics.py
106
21
def get_periodic_data(entry, filters): periodic_data = {} for d in entry: period = get_period(d.posting_date, filters) bal_qty = 0 # if period against item does not exist yet, instantiate it # insert existing balance dict against period, and add/subtract to it if periodic_data.get(d.item_code) and not pe...
style: format code with black
get_periodic_data
494bd9ef78313436f0424b918f200dab8fc7c20b
erpnext
stock_analytics.py
17
27
https://github.com/frappe/erpnext.git
8
274
0
67
435
Python
{ "docstring": "Structured as:\n\tItem 1\n\t - Balance (updated and carried forward):\n\t - Warehouse A : bal_qty/value\n\t - Warehouse B : bal_qty/value\n\t - Jun 2021 (sum of warehouse quantities used in report)\n\t - Warehouse A : b...
def get_periodic_data(entry, filters): periodic_data = {} for d in entry: period = get_period(d.posting_date, filters) bal_qty = 0 # if period against item does not exist yet, instantiate it # insert existing balance dict against period, and add/subtract to it if periodic_data.get(d.item_code) and not pe...
76,516
260,817
27
sklearn/utils/__init__.py
11
6
def shuffle(*arrays, random_state=None, n_samples=None): return resample( *arrays, replace=False, n_samples=n_samples, random_state=random_state )
DOC ensures sklearn.utils.shuffle passes numpydoc validation (#24367) Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com>
shuffle
49279c3267c0c54cdba80a571820c46f25fbe883
scikit-learn
__init__.py
8
4
https://github.com/scikit-learn/scikit-learn.git
1
33
0
11
50
Python
{ "docstring": "Shuffle arrays or sparse matrices in a consistent way.\n\n This is a convenience alias to ``resample(*arrays, replace=False)`` to do\n random permutations of the collections.\n\n Parameters\n ----------\n *arrays : sequence of indexable data-structures\n Indexable data-structures...
def shuffle(*arrays, random_state=None, n_samples=None): return resample( *arrays, replace=False, n_samples=n_samples, random_state=random_state )
78,567
266,763
483
test/lib/ansible_test/_internal/commands/sanity/integration_aliases.py
118
45
def check_changes(self, args, results): # type: (SanityConfig, Results) -> None integration_targets = list(walk_integration_targets()) module_targets = list(walk_module_targets()) integration_targets_by_name = dict((target.name, target) for target in integration_targets) modul...
ansible-test - Code cleanup and refactoring. (#77169) * Remove unnecessary PyCharm ignores. * Ignore intentional undefined attribute usage. * Add missing type hints. Fix existing type hints. * Fix docstrings and comments. * Use function to register completion handler. * Pass strings to display functions. * Fix C...
check_changes
a06fa496d3f837cca3c437ab6e9858525633d147
ansible
integration_aliases.py
14
36
https://github.com/ansible/ansible.git
14
298
0
76
456
Python
{ "docstring": "Check changes and store results in the provided result dictionary.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def check_changes(self, args, results): # type: (SanityConfig, Results) -> None integration_targets = list(walk_integration_targets()) module_targets = list(walk_module_targets()) integration_targets_by_name = dict((target.name, target) for target in integration_targets) modul...
42,449
177,582
377
label_studio/tests/test_next_task.py
122
42
def test_overlap_first(business_client, setup_before_upload, show_overlap_first): c = business_client config = dict( title='test_overlap_first',
fix: DEV-1348: Fix _rearrange_overlap_cohort filter condition for overlap bulk update with concurrent import (#1844) * [fix] Rearrange overlap depending in annotations count * Fix next task test for not random overlap assignment * Delete unused method * Rename rearrange method to have back compatibility * ...
test_overlap_first
35125cca12ba1e8703c4284894e4e2db44ce7009
label-studio
test_next_task.py
17
63
https://github.com/heartexlabs/label-studio.git
8
396
0
84
474
Python
{ "docstring": "\n <View>\n <Text name=\"text\" value=\"$text\"></Text>\n <Choices name=\"text_class\" choice=\"single\">\n <Choice value=\"class_A\"></Choice>\n <Choice value=\"class_B\"></Choice>\n </Choices>\n </View>", "l...
def test_overlap_first(business_client, setup_before_upload, show_overlap_first): c = business_client config = dict( title='test_overlap_first', is_published=True, maximum_annotations=1, show_overlap_first=show_overlap_first, sampling="Uniform sampling", label_con...
76,710
261,252
136
sklearn/utils/extmath.py
54
15
def svd_flip(u, v, u_based_decision=True): if u_based_decision: # columns of u, rows of v max_abs_cols = np.argmax(np.abs(u), axis=0) signs = np.sign(u[max_abs_cols, range(u.shape[1])]) u *= signs v *= signs[:, np.newaxis] else: # rows of v, columns of u ...
DOC Ensures that svd_flip passes numpydoc validation (#24581) Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
svd_flip
97057d329da1786aa03206251aab68bf51312390
scikit-learn
extmath.py
16
12
https://github.com/scikit-learn/scikit-learn.git
2
127
0
30
191
Python
{ "docstring": "Sign correction to ensure deterministic output from SVD.\n\n Adjusts the columns of u and the rows of v such that the loadings in the\n columns in u that are largest in absolute value are always positive.\n\n Parameters\n ----------\n u : ndarray\n Parameters u and v are the outp...
def svd_flip(u, v, u_based_decision=True): if u_based_decision: # columns of u, rows of v max_abs_cols = np.argmax(np.abs(u), axis=0) signs = np.sign(u[max_abs_cols, range(u.shape[1])]) u *= signs v *= signs[:, np.newaxis] else: # rows of v, columns of u ...
31,802
139,905
118
rllib/policy/tf_policy.py
36
13
def extra_action_out_fn(self) -> Dict[str, TensorType]: extra_fetches = {} # Action-logp and action-prob. if self._sampled_action_logp is not None: extra_fetches
[RLlib] Migrate MAML, MB-MPO, MARWIL, and BC to use Policy sub-classing implementation. (#24914)
extra_action_out_fn
d5a6d46049d0ea0490c90366a081de79a87d0fac
ray
tf_policy.py
10
17
https://github.com/ray-project/ray.git
3
65
0
25
103
Python
{ "docstring": "Extra values to fetch and return from compute_actions().\n\n By default we return action probability/log-likelihood info\n and action distribution inputs (if present).\n\n Returns:\n Dict[str, TensorType]: An extra fetch-dict to be passed to and\n return...
def extra_action_out_fn(self) -> Dict[str, TensorType]: extra_fetches = {} # Action-logp and action-prob. if self._sampled_action_logp is not None: extra_fetches[SampleBatch.ACTION_PROB] = self._sampled_action_prob extra_fetches[SampleBatch.ACTION_LOGP] = self._s...
8,562
45,432
733
airflow/jobs/triggerer_job.py
162
24
async def cleanup_finished_triggers(self): for trigger_id, details in list(self.triggers.items()): if details["task"].done(): # Check to see if it exited for
Log traceback in trigger excs (#21213)
cleanup_finished_triggers
4ad21f5f7c2d416cf813a860564bc2bf3e161d46
airflow
triggerer_job.py
18
25
https://github.com/apache/airflow.git
7
160
0
116
275
Python
{ "docstring": "\n Go through all trigger tasks (coroutines) and clean up entries for\n ones that have exited, optionally warning users if the exit was\n not normal.\n ", "language": "en", "n_whitespaces": 53, "n_words": 24, "vocab_size": 24 }
async def cleanup_finished_triggers(self): for trigger_id, details in list(self.triggers.items()): if details["task"].done(): # Check to see if it exited for good reasons saved_exc = None try: result = details["task"].resul...
30,145
133,910
89
rllib/contrib/sumo/utils.py
26
8
def get_global_travel_time(self): gtt = 0 for entity in self.tripinfo: gtt += self.get_duration(entity, default=0.0
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
get_global_travel_time
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
utils.py
11
7
https://github.com/ray-project/ray.git
3
53
0
17
79
Python
{ "docstring": "\n Returns the global travel time computed from SUMO tripinfo data.\n\n The functions process_tripinfo_file() needs to be called in advance\n to initialize the data structures required.\n ", "language": "en", "n_whitespaces": 54, "n_words": 25, "vocab_size": 23 }
def get_global_travel_time(self): gtt = 0 for entity in self.tripinfo: gtt += self.get_duration(entity, default=0.0) for entity in self.personinfo: gtt += self.get_duration(entity, default=0.0) return gtt #############################################...
4,190
22,114
26
pipenv/patched/pip/_vendor/requests/sessions.py
13
7
def post(self, url, data=None, json=None, **kwargs): r re
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
post
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
sessions.py
8
11
https://github.com/pypa/pipenv.git
1
40
0
12
58
Python
{ "docstring": "Sends a POST request. Returns :class:`Response` object.\n\n :param url: URL for the new :class:`Request` object.\n :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n object to send in the body of the :class:`Request`.\n :param json: (optional) jso...
def post(self, url, data=None, json=None, **kwargs): r return self.request("POST", url, data=data, json=json, **kwargs)
52,723
209,531
162
scapy/contrib/http2.py
44
10
def __getitem__(self, idx): # type: (int) -> HPackHdrEntry assert idx >= 0 if idx > type(self)._static_entries_last_idx: idx -= type(self)._static_entries_last_idx + 1 if idx >= len(self._dynamic_table): raise KeyError( 'EINVAL...
E275 - Missing whitespace after keyword (#3711) Co-authored-by: Alexander Aring <alex.aring@gmail.com> Co-authored-by: Anmol Sarma <me@anmolsarma.in> Co-authored-by: antoine.torre <torreantoine1@gmail.com> Co-authored-by: Antoine Vacher <devel@tigre-bleu.net> Co-authored-by: Arnaud Ebalard <arno@natisbad.org> Co-...
__getitem__
08b1f9d67c8e716fd44036a027bdc90dcb9fcfdf
scapy
http2.py
16
10
https://github.com/secdev/scapy.git
3
76
0
37
124
Python
{ "docstring": "Gets an element from the header tables (static or dynamic indifferently)\n\n :param int idx: the index number of the entry to retrieve. If the index\n value is superior to the last index of the static entry table, then the\n dynamic entry type is requested, following the procedure...
def __getitem__(self, idx): # type: (int) -> HPackHdrEntry assert idx >= 0 if idx > type(self)._static_entries_last_idx: idx -= type(self)._static_entries_last_idx + 1 if idx >= len(self._dynamic_table): raise KeyError( 'EINVAL...
51,819
206,977
208
tests/admin_changelist/tests.py
67
27
def test_pagination(self): parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) request = self.factory.get("/child/") re...
Refs #33476 -- Reformatted code with Black.
test_pagination
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
12
17
https://github.com/django/django.git
2
209
0
43
327
Python
{ "docstring": "\n Regression tests for #12893: Pagination in admins changelist doesn't\n use queryset set by modeladmin.\n ", "language": "en", "n_whitespaces": 36, "n_words": 14, "vocab_size": 14 }
def test_pagination(self): parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) request = self.factory.get("/child/") re...
75,274
258,522
155
sklearn/discriminant_analysis.py
47
14
def transform(self, X): if self.solver == "lsqr": raise NotImplementedError( "transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')." ) check_is_fitted(self) X = self._validate_data(X, reset=False) if self.solver == "svd": ...
DOC Add documentation on output shape of LDA.transform (#22238)
transform
ab08e4dba5f1f87b8c3395f32469a6ddb5e34f89
scikit-learn
discriminant_analysis.py
12
12
https://github.com/scikit-learn/scikit-learn.git
4
88
0
38
147
Python
{ "docstring": "Project data to maximize class separation.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n X_new : ndarray of shape (n_samples, n_components) or \\\n (n_samples, min(rank...
def transform(self, X): if self.solver == "lsqr": raise NotImplementedError( "transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')." ) check_is_fitted(self) X = self._validate_data(X, reset=False) if self.solver == "svd": ...
110,121
311,456
301
tests/components/homekit_controller/test_climate.py
101
25
async def test_heater_cooler_hvac_mode_vs_hvac_action(hass, utcnow): helper = await setup_test_component(hass, create_heater_cooler_service) # Simulate that current temperature is above target temp # Heating might be on, but hvac_action currently 'off' await helper.async_update( ServicesTy...
Improve homekit_controller tests (#65266)
test_heater_cooler_hvac_mode_vs_hvac_action
58b8c30221a6f6e5acbbe98b7e3298b03fb741f5
core
test_climate.py
11
28
https://github.com/home-assistant/core.git
1
161
0
56
256
Python
{ "docstring": "Check that we haven't conflated hvac_mode and hvac_action.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
async def test_heater_cooler_hvac_mode_vs_hvac_action(hass, utcnow): helper = await setup_test_component(hass, create_heater_cooler_service) # Simulate that current temperature is above target temp # Heating might be on, but hvac_action currently 'off' await helper.async_update( ServicesTy...
74,072
253,415
74
examples/contrib/webscanner_helper/watchdog.py
20
5
def not_in_timeout(cls, last_triggered, timeout): return ( last_triggered is None or timeout is None or (tim
[autofix.ci] apply automated fixes
not_in_timeout
8c2428c9d355ca5fbc3dd90e9820ceb1cc795837
mitmproxy
watchdog.py
12
6
https://github.com/mitmproxy/mitmproxy.git
3
32
0
16
51
Python
{ "docstring": "Checks if current error lies not in timeout after last trigger (potential reset of connection).", "language": "en", "n_whitespaces": 14, "n_words": 15, "vocab_size": 15 }
def not_in_timeout(cls, last_triggered, timeout): return ( last_triggered is None or timeout is None or (time.time() - last_triggered > timeout) )
47,049
194,733
909
parlai/core/torch_generator_agent.py
201
42
def get_rescored_finished(self, n_best=None): # if we never actually finished, force one if not self.finished: self.outputs[-1][0] = self.eos self.finished.append( _HypothesisTail( timestep=len(self.outputs) - 1, hy...
Logging token level losses at inference time (#4169)
get_rescored_finished
daa85bf085c9e275cc65d0b03758d1f70742b57f
ParlAI
torch_generator_agent.py
16
51
https://github.com/facebookresearch/ParlAI.git
9
336
0
140
525
Python
{ "docstring": "\n Return finished hypotheses according to adjusted scores.\n\n Score adjustment is done according to the Google NMT paper, which\n penalizes long utterances.\n\n :param n_best:\n number of finalized hypotheses to return\n\n :return:\n list of (...
def get_rescored_finished(self, n_best=None): # if we never actually finished, force one if not self.finished: self.outputs[-1][0] = self.eos self.finished.append( _HypothesisTail( timestep=len(self.outputs) - 1, hy...
39,870
166,924
22
pandas/core/resample.py
8
5
def quantile(self, q=0.5, **kwargs): return self._do
DEPR: numeric_only default in resampler ops (#47177)
quantile
62b6d25551d006758422c20e7f931858e23054a9
pandas
resample.py
8
2
https://github.com/pandas-dev/pandas.git
1
29
0
8
44
Python
{ "docstring": "\n Return value at the given quantile.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n\n Returns\n -------\n DataFrame or Series\n Quantile of values within each group.\n\n See Also\n --------...
def quantile(self, q=0.5, **kwargs): return self._downsample("quantile", q=q, **kwargs)
45,933
188,795
25
src/calibre/gui2/preferences/create_custom_column.py
11
5
def current_columns(self): return copy.deepcopy(self.custcols) #de
Yet another version of CreateNewCustomColumn. My apologies for the multiple commits. I have been working with @davidfor and we cycled a few times. I hope this is the last, barring bugs.
current_columns
7b9bb6e62424e4b3c960e9e25c45a6946988959c
calibre
create_custom_column.py
8
2
https://github.com/kovidgoyal/calibre.git
1
15
0
11
28
Python
{ "docstring": "\n Return the currently defined custom columns\n\n Return the currently defined custom columns including the ones that haven't\n yet been created. It is a dict of dicts defined as follows:\n custcols[lookup_name] = {\n 'label': lookup_name,\n ...
def current_columns(self): return copy.deepcopy(self.custcols) #deepcopy to prevent users from changing it
16,345
75,054
59
wagtail/images/image_operations.py
16
8
def transform_vector(self, vector): return Vector( (vector
Reformat with black
transform_vector
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
image_operations.py
12
5
https://github.com/wagtail/wagtail.git
1
52
0
14
78
Python
{ "docstring": "\n Transforms the given vector into the coordinate space of the final image.\n\n Use this to find out where a point on the source image would end up in the\n final image after cropping/resizing has been performed.\n\n Returns a new vector.\n ", "language": "en", ...
def transform_vector(self, vector): return Vector( (vector.x + self.offset[0]) * self.scale[0], (vector.y + self.offset[1]) * self.scale[1], )
17,347
82,306
60
cms/utils/conf.py
27
8
def _load_from_file(module_path): from imp import PY_SOURCE, load_module imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module("mod", openfile, module_path, ('imp
Enabled isort workflow (#7200) * Ran isort * Enabled isort workflow Co-authored-by: Vinit Kumar <mail@vinitkumar.me>
_load_from_file
a3110e1ff24085373898c7d2a85f628abeb8518d
django-cms
conf.py
14
7
https://github.com/django-cms/django-cms.git
2
48
0
24
85
Python
{ "docstring": "\n Load a python module from its absolute filesystem path\n ", "language": "en", "n_whitespaces": 16, "n_words": 9, "vocab_size": 9 }
def _load_from_file(module_path): from imp import PY_SOURCE, load_module imported = None if module_path: with open(module_path, 'r') as openfile: imported = load_module("mod", openfile, module_path, ('imported', 'r', PY_SOURCE)) return imported
50,562
203,858
284
django/contrib/gis/db/backends/postgis/schema.py
60
15
def _alter_column_type_sql(self, table, old_field, new_field, new_type): if not hasattr(old_field, "dim") or not hasattr(new_field, "dim"): return super()._alter_column_type_sql(table, old_field, new_field, new_type) if old_field.dim == 2 and new_field.dim == 3: sql_alt...
Refs #33476 -- Reformatted code with Black.
_alter_column_type_sql
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
schema.py
13
20
https://github.com/django/django.git
7
121
0
42
189
Python
{ "docstring": "\n Special case when dimension changed.\n ", "language": "en", "n_whitespaces": 20, "n_words": 5, "vocab_size": 5 }
def _alter_column_type_sql(self, table, old_field, new_field, new_type): if not hasattr(old_field, "dim") or not hasattr(new_field, "dim"): return super()._alter_column_type_sql(table, old_field, new_field, new_type) if old_field.dim == 2 and new_field.dim == 3: sql_alt...