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
23,671
109,612
271
lib/matplotlib/axes/_base.py
77
22
def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): if cbook._str_equal(aspect, 'equal'): aspect = 1 if not cbook._str_equal(aspect, 'auto'): aspect = float(aspect) # raise ValueError if
Update _base.py
set_aspect
9d616615417eac104e12f2915f3fe875177bb2e4
matplotlib
_base.py
14
20
https://github.com/matplotlib/matplotlib.git
10
146
0
50
232
Python
{ "docstring": "\n Set the aspect ratio of the axes scaling, i.e. y/x-scale.\n\n Parameters\n ----------\n aspect : {'auto', 'equal'} or float\n Possible values:\n\n - 'auto': fill the position rectangle with data.\n - 'equal': same as ``aspect=1``, i.e. sa...
def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): if cbook._str_equal(aspect, 'equal'): aspect = 1 if not cbook._str_equal(aspect, 'auto'): aspect = float(aspect) # raise ValueError if necessary if aspect<0: raise Value...
50,145
202,525
144
tests/custom_pk/tests.py
59
12
def test_pk_attributes(self): # pk can be used as a substitute for the primary key. # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.ass
Refs #33476 -- Reformatted code with Black.
test_pk_attributes
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
10
8
https://github.com/django/django.git
1
51
0
44
89
Python
{ "docstring": "\n pk and attribute name are available on the model\n No default id attribute is added\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 14 }
def test_pk_attributes(self): # pk can be used as a substitute for the primary key. # The primary key can be accessed via the pk property on the model. e = Employee.objects.get(pk=123) self.assertEqual(e.pk, 123) # Or we can use the real attribute name for the primary ke...
11,152
54,803
294
src/prefect/client.py
95
12
async def __aenter__(self): if self._closed: # httpx.AsyncClient does not allow reuse so we will not either. raise RuntimeError( "The client cannot be started again after closing. "
Disable lifespan management during logging
__aenter__
05b92d7c7f6cf21c5d6033df7242c331fc66b92e
prefect
client.py
14
16
https://github.com/PrefectHQ/prefect.git
5
80
0
65
145
Python
{ "docstring": "\n Start the client.\n\n If the client is already started, this will raise an exception.\n\n If the client is already closed, this will raise an exception. Use a new client\n instance instead.\n ", "language": "en", "n_whitespaces": 67, "n_words": 31, "vocab_...
async def __aenter__(self): if self._closed: # httpx.AsyncClient does not allow reuse so we will not either. raise RuntimeError( "The client cannot be started again after closing. " "Retrieve a new client with `get_client()` instead." ...
31,501
138,659
665
rllib/agents/qmix/qmix.py
224
42
def training_iteration(self) -> ResultDict: # Sample n batches from n workers. new_sample_batches = synchronous_parallel_sample( worker_set=self.workers, concat=False ) for batch in new_sample_batches: # Update counters. self._counters[NUM_EN...
[RLlib] QMIX training iteration function and new replay buffer API. (#24164)
training_iteration
627b9f2e888b05434bb67f547b390409f26538e7
ray
qmix.py
13
46
https://github.com/ray-project/ray.git
6
238
0
139
397
Python
{ "docstring": "QMIX training iteration function.\n\n - Sample n MultiAgentBatches from n workers synchronously.\n - Store new samples in the replay buffer.\n - Sample one training MultiAgentBatch from the replay buffer.\n - Learn on the training batch.\n - Update the target network...
def training_iteration(self) -> ResultDict: # Sample n batches from n workers. new_sample_batches = synchronous_parallel_sample( worker_set=self.workers, concat=False ) for batch in new_sample_batches: # Update counters. self._counters[NUM_EN...
@cli.command() @click.option("--gh-token", envvar=["GH_TOKEN", "GITHUB_TOKEN"], required=True)
72,929
249,457
105
scripts-dev/release.py
27
11
def _announce() -> None: current_version = get_package_version() tag_name = f"v{current_version}" click.echo( f
Extend the release script to wait for GitHub Actions to finish and to be usable as a guide for the whole process. (#13483)
_announce
c7b18d9d44c90acfd4ceaec1fa2f8275e03f14af
synapse
release.py
11
31
https://github.com/matrix-org/synapse.git
2
42
1
22
147
Python
{ "docstring": "Generate markdown to announce the release.\nHi everyone. Synapse {current_version} has just been released.\n\n[notes](https://github.com/matrix-org/synapse/releases/tag/{tag_name}) | \\\n[docker](https://hub.docker.com/r/matrixdotorg/synapse/tags?name={tag_name}) | \\\n[debs](https://packages.matrix.o...
def _announce() -> None: current_version = get_package_version() tag_name = f"v{current_version}" click.echo( f ) if "rc" in tag_name: click.echo( ) else: click.echo( ) @cli.command() @click.option("--gh-token", envvar=[...
53,460
212,852
154
PySimpleGUI.py
45
15
def update(self, value=None, visible=None):
Completed switching all elements over to the new way of handling visiblity
update
ed2bc288ff17344f6406c49623036620f18e65bb
PySimpleGUI
PySimpleGUI.py
12
12
https://github.com/PySimpleGUI/PySimpleGUI.git
6
98
0
32
158
Python
{ "docstring": "\n Changes some of the settings for the Output Element. Must call `Window.Read` or `Window.Finalize` prior\n\n Changes will not be visible in your window until you call window.read or window.refresh.\n\n If you change visibility, your element may MOVE. If you want it to remain sta...
def update(self, value=None, visible=None): if not self._widget_was_created(): # if widget hasn't been created yet, then don't allow return if value is not None: self._TKOut.output.delete('1.0', tk.END) self._TKOut.output.insert(tk.END, value) if vi...
34,801
150,631
111
freqtrade/freqai/prediction_models/RLPredictionModel.py
39
8
def example(self): result = getattr(self, "_example", None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = result return re...
callback function and TDQN model added
example
01232e9a1f8e28e3611e38af3816edb026600767
freqtrade
RLPredictionModel.py
13
6
https://github.com/freqtrade/freqtrade.git
2
39
0
32
68
Python
{ "docstring": "Get and cache an example batch of `inputs, labels` for plotting.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 11 }
def example(self): result = getattr(self, "_example", None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = result return re...
50,635
204,114
151
django/contrib/gis/measure.py
39
7
def unit_attname(cls, unit_str): lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception( ...
Refs #33476 -- Reformatted code with Black.
unit_attname
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
measure.py
12
12
https://github.com/django/django.git
4
56
0
28
93
Python
{ "docstring": "\n Retrieve the unit attribute name for the given unit string.\n For example, if the given unit string is 'metre', return 'm'.\n Raise an exception if an attribute cannot be found.\n ", "language": "en", "n_whitespaces": 59, "n_words": 30, "vocab_size": 22 }
def unit_attname(cls, unit_str): lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception( ...
30,776
135,932
63
rllib/tests/test_nn_framework_import_errors.py
30
15
def test_dont_import_tf_error(): # Do n
[RLlib] AlgorithmConfigs: Make None a valid value for methods to set properties; Use new `NotProvided` singleton, instead, to indicate no changes wanted on that property. (#30020)
test_dont_import_tf_error
087548031bcf22dd73364b58acb70e61a49f2427
ray
test_nn_framework_import_errors.py
13
6
https://github.com/ray-project/ray.git
2
58
0
28
108
Python
{ "docstring": "Check error being thrown, if tf not installed but configured.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def test_dont_import_tf_error(): # Do not import tf for testing purposes. os.environ["RLLIB_TEST_NO_TF_IMPORT"] = "1" config = ppo.PPOConfig().environment("CartPole-v1") for _ in framework_iterator(config, frameworks=("tf", "tf2")): with pytest.raises(ImportError, match="However, no instal...
54,870
217,655
78
python3.10.4/Lib/hmac.py
13
9
def _current(self): if self._hmac: return self._hmac else: h = self._outer.copy()
add python 3.10.4 for windows
_current
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
hmac.py
13
7
https://github.com/XX-net/XX-Net.git
2
40
0
11
69
Python
{ "docstring": "Return a hash object for the current state.\n\n To be used only internally with digest() and hexdigest().\n ", "language": "en", "n_whitespaces": 31, "n_words": 17, "vocab_size": 17 }
def _current(self): if self._hmac: return self._hmac else: h = self._outer.copy() h.update(self._inner.digest()) return h
13,559
64,064
12
erpnext/patches/v13_0/delete_old_sales_reports.py
16
8
def delete_links_from_desktop_icons(report): desktop_icons = frappe.db.get_values("Desktop Icon", {"_report": report}, ["name"]) for desktop_icon in desktop_icons: frappe.delete_doc("Desktop Icon", desktop_icon[0])
fix: broken patches (backport #29067) (#29406) * chore: patch fixes (cherry picked from commit 8b5b146f6d2720587a16f78a8d47840be8dca2b7) # Conflicts: # erpnext/patches/v13_0/make_homepage_products_website_items.py * fix: remove desktop icons while deleting sales reports (cherry picked from commit 5f72026c...
delete_links_from_desktop_icons
f469ec87d94d4639ff4eb99a45496721c4779bf3
erpnext
delete_old_sales_reports.py
11
4
https://github.com/frappe/erpnext.git
2
42
0
15
73
Python
{ "docstring": " Check for one or multiple Desktop Icons and delete ", "language": "en", "n_whitespaces": 10, "n_words": 9, "vocab_size": 9 }
def delete_links_from_desktop_icons(report): desktop_icons = frappe.db.get_values("Desktop Icon", {"_report": report}, ["name"]) for desktop_icon in desktop_icons: frappe.delete_doc("Desktop Icon", desktop_icon[0])
4,761
24,519
143
ppstructure/table/table_master_match.py
64
18
def get_bboxes_list(end2end_result, structure_master_result): # end2end e
add SLANet
get_bboxes_list
ddaa2c2552e19635cd6cdf38619f1f176c358f89
PaddleOCR
table_master_match.py
10
16
https://github.com/PaddlePaddle/PaddleOCR.git
2
93
0
37
159
Python
{ "docstring": "\n This function is use to convert end2end results and structure master results to\n List of xyxy bbox format and List of xywh bbox format\n :param end2end_result: bbox's format is xyxy\n :param structure_master_result: bbox's format is xywh\n :return: 4 kind list of bbox ()\n ", "...
def get_bboxes_list(end2end_result, structure_master_result): # end2end end2end_xyxy_list = [] end2end_xywh_list = [] for end2end_item in end2end_result: src_bbox = end2end_item['bbox'] end2end_xyxy_list.append(src_bbox) xywh_bbox = xyxy2xywh(src_bbox) end2end_xywh_l...
3,424
20,557
145
pipenv/patched/notpip/_vendor/pyparsing/core.py
134
46
def autoname_elements() -> None: for name, var in sys._getframe().f_back.f_locals.items(): if isinstance(var, ParserElement) and not var.customName: var.set_name(name) dbl_quoted_string = Combine( Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' ).set_name("string ...
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...
autoname_elements
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
core.py
13
8
https://github.com/pypa/pipenv.git
4
45
0
87
339
Python
{ "docstring": "\n Utility to simplify mass-naming of parser elements, for\n generating railroad diagram with named subdiagrams.\n ", "language": "en", "n_whitespaces": 24, "n_words": 14, "vocab_size": 14 }
def autoname_elements() -> None: for name, var in sys._getframe().f_back.f_locals.items(): if isinstance(var, ParserElement) and not var.customName: var.set_name(name) dbl_quoted_string = Combine( Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' ).set_name("string ...
21,486
102,171
58
tools/test/test_gen_backend_stubs.py
30
4
def test_valid_zero_ops_doesnt_require_backend_dispatch_key(self) -> None: yaml_str = # External codegen on a yaml file with no operators is effectively a no-op,
Revert "Revert D32498569: allow external backend codegen to toggle whether to generate out= and inplace kernels" (#69950) Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/69950 This reverts commit f6cad53443704dfe5a20cc62bee14d91e3bffcaa. Test Plan: Imported from OSS Reviewed By: albanD Diff...
test_valid_zero_ops_doesnt_require_backend_dispatch_key
bb5b4cceb6f737448eaaa6817cd773b6f4b0e77d
pytorch
test_gen_backend_stubs.py
7
6
https://github.com/pytorch/pytorch.git
1
16
0
27
32
Python
{ "docstring": "\\\nbackend: BAD_XLA\ncpp_namespace: torch_xla\nsupported:", "language": "en", "n_whitespaces": 2, "n_words": 6, "vocab_size": 6 }
def test_valid_zero_ops_doesnt_require_backend_dispatch_key(self) -> None: yaml_str = # External codegen on a yaml file with no operators is effectively a no-op, # so there's no reason to parse the backend self.assert_success_from_gen_backend_stubs(yaml_str)
1,809
9,995
322
tests/distributed/test_remote_peas/test_remote_peas.py
132
41
async def test_pseudo_remote_peas_topologies(gateway, head, worker): worker_port = random_port() head_port = random_port() port_expose = random_port() graph_description = '{"start-gateway": ["pod0"], "pod0": ["end-gateway"]}' if head == 'remote': pods_addresses = f'{{"pod0": ["{HOST}:{h...
feat: star routing (#3900) * feat(proto): adjust proto for star routing (#3844) * feat(proto): adjust proto for star routing * feat(proto): generate proto files * feat(grpc): refactor grpclet interface (#3846) * feat: refactor connection pool for star routing (#3872) * feat(k8s): add more labels to k8s ...
test_pseudo_remote_peas_topologies
933415bfa1f9eb89f935037014dfed816eb9815d
jina
test_remote_peas.py
12
33
https://github.com/jina-ai/jina.git
4
210
0
85
316
Python
{ "docstring": "\n g(l)-h(l)-w(l) - works\n g(l)-h(l)-w(r) - works - head connects to worker via localhost\n g(l)-h(r)-w(r) - works - head (inside docker) connects to worker via dockerhost\n g(l)-h(r)-w(l) - doesn't work remote head need remote worker\n g(r)-... - doesn't work, as distributed parser no...
async def test_pseudo_remote_peas_topologies(gateway, head, worker): worker_port = random_port() head_port = random_port() port_expose = random_port() graph_description = '{"start-gateway": ["pod0"], "pod0": ["end-gateway"]}' if head == 'remote': pods_addresses = f'{{"pod0": ["{HOST}:{h...
1,728
9,848
217
jina/peapods/peas/__init__.py
50
19
async def async_wait_start_success(self): import asyncio _timeout = self.args.timeout_ready if _timeout <= 0: _timeout = None else: _timeout /= 1e3 timeout_ns = 1e9 * _timeout if _timeout else None now = time.time_ns() while time...
feat: star routing (#3900) * feat(proto): adjust proto for star routing (#3844) * feat(proto): adjust proto for star routing * feat(proto): generate proto files * feat(grpc): refactor grpclet interface (#3846) * feat: refactor connection pool for star routing (#3872) * feat(k8s): add more labels to k8s ...
async_wait_start_success
933415bfa1f9eb89f935037014dfed816eb9815d
jina
__init__.py
13
17
https://github.com/jina-ai/jina.git
6
102
0
34
168
Python
{ "docstring": "\n Wait for the `Pea` to start successfully in a non-blocking manner\n ", "language": "en", "n_whitespaces": 26, "n_words": 11, "vocab_size": 11 }
async def async_wait_start_success(self): import asyncio _timeout = self.args.timeout_ready if _timeout <= 0: _timeout = None else: _timeout /= 1e3 timeout_ns = 1e9 * _timeout if _timeout else None now = time.time_ns() while time...
23,550
109,359
55
lib/matplotlib/offsetbox.py
16
9
def set_fontsize(self, s=None): if s is None: s = mpl.rcParams["legend.fontsize"] self.prop = FontProperties(size=s) self.stale = True
Get rcParams from mpl
set_fontsize
438d30b227b1fef7e8733578f851e76a8e360f24
matplotlib
offsetbox.py
10
5
https://github.com/matplotlib/matplotlib.git
2
38
0
13
64
Python
{ "docstring": "\n Set the fontsize in points.\n\n If *s* is not given, reset to :rc:`legend.fontsize`.\n ", "language": "en", "n_whitespaces": 35, "n_words": 13, "vocab_size": 13 }
def set_fontsize(self, s=None): if s is None: s = mpl.rcParams["legend.fontsize"] self.prop = FontProperties(size=s) self.stale = True
29,858
132,899
233
python/ray/util/actor_pool.py
71
25
def get_next(self, timeout=None): if not s
[CI] Format Python code with Black (#21975) See #21316 and #21311 for the motivation behind these changes.
get_next
7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065
ray
actor_pool.py
12
18
https://github.com/ray-project/ray.git
6
133
0
54
218
Python
{ "docstring": "Returns the next pending result in order.\n\n This returns the next result produced by submit(), blocking for up to\n the specified timeout until it is available.\n\n Returns:\n The next result.\n\n Raises:\n TimeoutError if the timeout is reached.\n\n...
def get_next(self, timeout=None): if not self.has_next(): raise StopIteration("No more results to get") if self._next_return_index >= self._next_task_index: raise ValueError( "It is not allowed to call get_next() after " "get_next_unordered()." ...
3,716
21,185
259
pipenv/environment.py
44
26
def expand_egg_links(self) -> None: prefixes = [ Path(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if vistir.path.is_in_path(prefix, self.prefix.as_posix()) ] for loc in prefixes: if not loc.exists(): ...
Convert type comments to type annotations
expand_egg_links
4b996c0fa85824b323ad9eff3364dbe2213ebb4c
pipenv
environment.py
16
21
https://github.com/pypa/pipenv.git
8
120
0
31
200
Python
{ "docstring": "\n Expand paths specified in egg-link files to prevent pip errors during\n reinstall\n ", "language": "en", "n_whitespaces": 34, "n_words": 12, "vocab_size": 12 }
def expand_egg_links(self) -> None: prefixes = [ Path(prefix) for prefix in self.base_paths["libdirs"].split(os.pathsep) if vistir.path.is_in_path(prefix, self.prefix.as_posix()) ] for loc in prefixes: if not loc.exists(): ...
17,698
83,638
56
zerver/tests/test_link_embed.py
22
10
def test_page_with_og(self) -> None:
preview: Use a dataclass for the embed data. This is significantly cleaner than passing around `Dict[str, Any]` all of the time.
test_page_with_og
327ff9ea0f5e4712a34d767fee55a549cc1d3f39
zulip
test_link_embed.py
9
14
https://github.com/zulip/zulip.git
1
46
0
19
79
Python
{ "docstring": "<html>\n <head>\n <meta property=\"og:title\" content=\"The Rock\" />\n <meta property=\"og:type\" content=\"video.movie\" />\n <meta property=\"og:url\" content=\"http://www.imdb.com/title/tt0117500/\" />\n <meta property=\"og:image\" content=\"http://ia.m...
def test_page_with_og(self) -> None: html = b parser = OpenGraphParser(html, "text/html; charset=UTF-8") result = parser.extract_data() self.assertEqual(result.title, "The Rock") self.assertEqual(result.description, "The Rock film")
48,207
196,831
120
sympy/core/expr.py
26
9
def is_rational_function(self, *syms): if self in _illegal: return False if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return True return self._eval_is_rational_function(syms)...
Moved definition of illegal
is_rational_function
117f9554466e08aa4178137ad65fae1f2d49b340
sympy
expr.py
12
10
https://github.com/sympy/sympy.git
4
50
0
19
83
Python
{ "docstring": "\n Test whether function is a ratio of two polynomials in the given\n symbols, syms. When syms is not given, all free symbols will be used.\n The rational function does not have to be in expanded or in any kind of\n canonical form.\n\n This function returns False for...
def is_rational_function(self, *syms): if self in _illegal: return False if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return True return self._eval_is_rational_function(syms)...
48,713
197,838
39
sympy/polys/numberfields/primes.py
11
14
def reduce_alg_num(self, a): elt = self.ZK.parent.element_from_alg_num(a) red = self.reduce_element(elt) return a.field_element(list(reversed(red.QQ_col.f
Improve `PrimeIdeal` reduction methods.
reduce_alg_num
af44b30d68265acb25340374b648e198fb5570e7
sympy
primes.py
14
4
https://github.com/sympy/sympy.git
1
47
0
10
78
Python
{ "docstring": "\n Reduce an :py:class:`~.AlgebraicNumber` to a \"small representative\"\n modulo this prime ideal.\n\n Parameters\n ==========\n\n elt : :py:class:`~.AlgebraicNumber`\n The element to be reduced.\n\n Returns\n =======\n\n :py:class:`~...
def reduce_alg_num(self, a): elt = self.ZK.parent.element_from_alg_num(a) red = self.reduce_element(elt) return a.field_element(list(reversed(red.QQ_col.flat())))
118,204
322,610
452
paddlenlp/taskflow/task.py
79
24
def _auto_joiner(self, short_results, input_mapping, is_dict=False): concat_results = [] elem_type = {} if is_dict else [] for k, vs in input_mapping.items(): single_results = elem_type for v in vs: if len(single_results) == 0: ...
Update Taskflow word_segmentation and ner tasks (#1666) * Add AutoSplitter & AutoJoiner * codestyle fix * unify auto joiner * add comments * add sentence split mode * update params * add paddle version check * add wordtag for word_segmentation * add wordtag for word_segmentation * add ner-la...
_auto_joiner
1e2ee01dade0d4076ba98aa613c3eb150c615abb
PaddleNLP
task.py
21
23
https://github.com/PaddlePaddle/PaddleNLP.git
9
159
0
59
252
Python
{ "docstring": "\n Join the short results automatically and generate the final results to match with the user inputs.\n Args:\n short_results (List[dict] / List[List[str]] / List[str]): input raw texts.\n input_mapping (dict): cutting length.\n is_dict (bool): whether th...
def _auto_joiner(self, short_results, input_mapping, is_dict=False): concat_results = [] elem_type = {} if is_dict else [] for k, vs in input_mapping.items(): single_results = elem_type for v in vs: if len(single_results) == 0: ...
80,043
269,373
125
keras/applications/efficientnet_weight_update_util.py
66
9
def get_variable_names_from_ckpt(path_ckpt, use_ema=True): v_all = tf.train.list_variables(path_ckpt) # keep name only v_name_all = [x[0] for x in v_all] if use_ema: v_name_all = [x for x in v_name_all if "ExponentialMovingAverage" in x] else: v_name_all = [ x for ...
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
get_variable_names_from_ckpt
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
efficientnet_weight_update_util.py
13
11
https://github.com/keras-team/keras.git
9
80
0
32
130
Python
{ "docstring": "Get list of tensor names from checkpoint.\n\n Args:\n path_ckpt: str, path to the ckpt files\n use_ema: Bool, whether to use ExponentialMovingAverage result or not.\n Returns:\n List of variable names from checkpoint.\n ", "language": "en", "n_whitespaces": 55, "n_words":...
def get_variable_names_from_ckpt(path_ckpt, use_ema=True): v_all = tf.train.list_variables(path_ckpt) # keep name only v_name_all = [x[0] for x in v_all] if use_ema: v_name_all = [x for x in v_name_all if "ExponentialMovingAverage" in x] else: v_name_all = [ x for ...
48,925
198,418
103
sympy/solvers/deutils.py
38
14
def ode_order(expr, func):
Improve loop performance in solvers
ode_order
bd9f607176c58dfba01e27c05c2b7d49ff97c901
sympy
deutils.py
17
11
https://github.com/sympy/sympy.git
6
103
0
26
161
Python
{ "docstring": "\n Returns the order of a given differential\n equation with respect to func.\n\n This function is implemented recursively.\n\n Examples\n ========\n\n >>> from sympy import Function\n >>> from sympy.solvers.deutils import ode_order\n >>> from sympy.abc import x\n >>> f, g =...
def ode_order(expr, func): a = Wild('a', exclude=[func]) if expr.match(a): return 0 if isinstance(expr, Derivative): if expr.args[0] == func: return len(expr.variables) else: return max(ode_order(arg, func) for arg in expr.args[0].args) + len(expr.variab...
91,035
291,932
866
homeassistant/components/discord/notify.py
170
53
async def async_send_message(self, message, **kwargs): nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() images = None embedding = None if ATTR_TARGET not in kwargs: _LOGGER.error("No target specified") return None d...
Replace discord.py with nextcord (#66540) * Replace discord.py with nextcord * Typing tweak * Another pip check decrease :)
async_send_message
cb03db8df4bf8b50945b36a4b0debcaaed1190a8
core
notify.py
18
51
https://github.com/home-assistant/core.git
19
347
0
102
564
Python
{ "docstring": "Login to Discord, send message to channel(s) and log out.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 9 }
async def async_send_message(self, message, **kwargs): nextcord.VoiceClient.warn_nacl = False discord_bot = nextcord.Client() images = None embedding = None if ATTR_TARGET not in kwargs: _LOGGER.error("No target specified") return None d...
@pytest.fixture( params=[ ( Interval(left=0, right=5, inclusive="right"), IntervalDtype("int64", inclusive="right"), ), ( Interval(left=0.1, right=0.5, inclusive="right"), IntervalDtype("float64", inclusive="right"), ), (Period(...
40,065
167,613
290
pandas/conftest.py
78
24
def rand_series_with_duplicate_datetimeindex() -> Series: dates = [ datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 4), datetime(2000, 1, 4), ...
TYP: misc return type annotations (#47558)
rand_series_with_duplicate_datetimeindex
f538568afc2c76c2d738d32e3544cf9fe6742960
pandas
conftest.py
13
17
https://github.com/pandas-dev/pandas.git
1
120
1
43
360
Python
{ "docstring": "\n Fixture for Series with a DatetimeIndex that has duplicates.\n ", "language": "en", "n_whitespaces": 16, "n_words": 9, "vocab_size": 9 }
def rand_series_with_duplicate_datetimeindex() -> Series: dates = [ datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 3), datetime(2000, 1, 4), datetime(2000, 1, 4), ...
12,285
60,770
18
.venv/lib/python3.8/site-packages/pip/_internal/locations/base.py
9
4
def get_major_minor_version(): # typ
upd; format
get_major_minor_version
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
base.py
9
2
https://github.com/jindongwang/transferlearning.git
1
15
0
9
31
Python
{ "docstring": "\n Return the major-minor version of the current Python as a string, e.g.\n \"3.7\" or \"3.10\".\n ", "language": "en", "n_whitespaces": 25, "n_words": 15, "vocab_size": 14 }
def get_major_minor_version(): # type: () -> str return "{}.{}".format(*sys.version_info)
70,501
244,731
1,066
tests/test_models/test_dense_heads/test_ssd_head.py
232
61
def test_ssd_head_loss(self): s = 300 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, }] cfg = Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, ...
Update SSD and PISA-SSD model config
test_ssd_head_loss
9d7511d8c35df1f9c13b17eb770136859bf370be
mmdetection
test_ssd_head.py
15
64
https://github.com/open-mmlab/mmdetection.git
2
471
0
154
677
Python
{ "docstring": "Tests ssd head loss when truth is empty and non-empty.", "language": "en", "n_whitespaces": 9, "n_words": 10, "vocab_size": 10 }
def test_ssd_head_loss(self): s = 300 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, }] cfg = Config( dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, ...
20,129
100,671
394
tools/alignments/jobs.py
160
24
def _legacy_check(self) -> None: if self._min_size > 0 or self._arguments.extract_every_n != 1: logger.warning("This alignments file was generated with the legacy extraction method.") logger.warning("You should run this extraction job, but with 'min_size' set to 0 and " ...
Alignments tool - Replace 'extract-large' with 'min-size'
_legacy_check
a9908b46f77dc66ac7efe7100ea0eed4b1f2b460
faceswap
jobs.py
12
26
https://github.com/deepfakes/faceswap.git
7
143
0
103
256
Python
{ "docstring": " Check whether the alignments file was created with the legacy extraction method.\n\n If so, force user to re-extract all faces if any options have been specified, otherwise\n raise the appropriate warnings and set the legacy options.\n ", "language": "en", "n_whitespaces": 58...
def _legacy_check(self) -> None: if self._min_size > 0 or self._arguments.extract_every_n != 1: logger.warning("This alignments file was generated with the legacy extraction method.") logger.warning("You should run this extraction job, but with 'min_size' set to 0 and " ...
48,106
196,688
18
sympy/stats/crv_types.py
15
6
def FisherZ(name, d1, d2): r return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution -----
Documentation cleanup 5
FisherZ
9ad8ab9fe58051cf11626ba6654852fcfec60147
sympy
crv_types.py
8
61
https://github.com/sympy/sympy.git
1
24
0
15
36
Python
{ "docstring": "\n Create a Continuous Random Variable with an Fisher's Z distribution.\n\n Explanation\n ===========\n\n The density of the Fisher's Z distribution is given by\n\n .. math::\n f(x) := \\frac{2d_1^{d_1/2} d_2^{d_2/2}} {\\mathrm{B}(d_1/2, d_2/2)}\n \\frac{e^{d_1z}}{...
def FisherZ(name, d1, d2): r return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution ---------------------------------------------------------
6,828
37,529
177
src/transformers/trainer_pt_utils.py
60
17
def find_batch_size(tensors): if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance(tensors, Mapping): for key, value in tensors.items(): result = find_bat...
Replace dict/BatchEncoding instance checks by Mapping (#17014) * Replace dict/BatchEncoding instance checks by Mapping * Typo
find_batch_size
18df440709f1b19d1c5617c0d987c5ff8fd0915d
transformers
trainer_pt_utils.py
13
15
https://github.com/huggingface/transformers.git
11
126
0
31
192
Python
{ "docstring": "\n Find the first dimension of a tensor in a nested list/tuple/dict of tensors.\n ", "language": "en", "n_whitespaces": 20, "n_words": 13, "vocab_size": 11 }
def find_batch_size(tensors): if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance(tensors, Mapping): for key, value in tensors.items(): result = find_bat...
6,842
37,632
35
src/transformers/models/yolos/feature_extraction_yolos.py
14
11
def post_process_segmentation(self, outputs, target_sizes, threshold=0.9, mask_threshold=0.5): out_logits, raw_masks = outputs.logits, outputs.pred_masks preds = []
Add YOLOS (#16848) * First draft * Add YolosForObjectDetection * Make forward pass work * Add mid position embeddings * Add interpolation of position encodings * Add expected values * Add YOLOS to tests * Add integration test * Support tiny model as well * Support all models in conversion sc...
post_process_segmentation
1ac698744c4dbdf1495d303246d08ffacdf4f5b8
transformers
feature_extraction_yolos.py
8
16
https://github.com/huggingface/transformers.git
2
196
0
13
51
Python
{ "docstring": "\n Converts the output of [`DetrForSegmentation`] into image segmentation predictions. Only supports PyTorch.\n\n Parameters:\n outputs ([`DetrSegmentationOutput`]):\n Raw outputs of the model.\n target_sizes (`torch.Tensor` of shape `(batch_size, 2)`...
def post_process_segmentation(self, outputs, target_sizes, threshold=0.9, mask_threshold=0.5): out_logits, raw_masks = outputs.logits, outputs.pred_masks preds = []
47,707
196,207
114
sympy/combinatorics/subsets.py
14
12
def iterate_graycode(self, k): unranked_code = GrayCode.unrank(self.superset_size,
Updated import locations
iterate_graycode
498015021131af4dbb07eb110e5badaba8250c7b
sympy
subsets.py
12
5
https://github.com/sympy/sympy.git
1
41
0
14
64
Python
{ "docstring": "\n Helper function used for prev_gray and next_gray.\n It performs ``k`` step overs to get the respective Gray codes.\n\n Examples\n ========\n\n >>> from sympy.combinatorics import Subset\n >>> a = Subset([1, 2, 3], [1, 2, 3, 4])\n >>> a.iterate_grayco...
def iterate_graycode(self, k): unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) return Subset.subset_from_bitlist(self.superset, unranked_code)
81,150
273,879
32
keras/layers/rnn/gru_lstm_utils.py
17
15
def is_sequence_right_padded(mask): max_seq_length = tf.shape(mask)[1] count_of_true = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) right_padded_mask = tf.sequence_mask(count_of_true, maxlen=max_seq_length)
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
is_sequence_right_padded
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
gru_lstm_utils.py
11
5
https://github.com/keras-team/keras.git
1
64
0
15
100
Python
{ "docstring": "Check the mask tensor and see if it right padded.\n\n For cuDNN kernel, it uses the sequence length param to skip the tailing\n timestep. If the data is left padded, or not a strict right padding (has\n masked value in the middle of the sequence), then cuDNN kernel won't be work\n properly...
def is_sequence_right_padded(mask): max_seq_length = tf.shape(mask)[1] count_of_true = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) right_padded_mask = tf.sequence_mask(count_of_true, maxlen=max_seq_length) return tf.reduce_all(tf.equal(mask, right_padded_mask))
71,154
246,321
385
tests/rest/client/test_third_party_rules.py
49
17
def _send_event_over_federation(self) -> None: body = { "pdus": [ { "sender": self.user_id, "type": EventTypes.Message, "state_key": "", "content": {"body": "hello world", "msgtype": "m.text"}, ...
Tests: replace mocked Authenticator with the real thing (#11913) If we prepopulate the test homeserver with a key for a remote homeserver, we can make federation requests to it without having to stub out the authenticator. This has two advantages: * means that what we are testing is closer to reality (ie, we now...
_send_event_over_federation
c3db7a0b59d48b8872bc24096f9a2467ef35f703
synapse
test_third_party_rules.py
14
25
https://github.com/matrix-org/synapse.git
1
120
0
44
211
Python
{ "docstring": "Send a dummy event over federation and check that the request succeeds.", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 12 }
def _send_event_over_federation(self) -> None: body = { "pdus": [ { "sender": self.user_id, "type": EventTypes.Message, "state_key": "", "content": {"body": "hello world", "msgtype": "m.text"}, ...
19,876
100,391
88
plugins/train/trainer/_base.py
26
15
def _print_loss(self, loss): output = ", ".join([f"Loss {side}: {side_loss:.5f}" for side, side_loss in zip(("A", "B"), loss)]) timestamp = time.strftime("%H:%M:%S") output = f"[{timestamp}] [#{self._model.iterations:05d}] {output}"
Update code to support Tensorflow versions up to 2.8 (#1213) * Update maximum tf version in setup + requirements * - bump max version of tf version in launcher - standardise tf version check * update keras get_custom_objects for tf>2.6 * bugfix: force black text in GUI file dialogs (linux) * dssim loss -...
_print_loss
c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf
faceswap
_base.py
14
6
https://github.com/deepfakes/faceswap.git
2
55
0
23
132
Python
{ "docstring": " Outputs the loss for the current iteration to the console.\n\n Parameters\n ----------\n loss: list\n The loss for each side. List should contain 2 ``floats`` side \"a\" in position 0 and\n side \"b\" in position `.\n ", "language": "en", "n_whit...
def _print_loss(self, loss): output = ", ".join([f"Loss {side}: {side_loss:.5f}" for side, side_loss in zip(("A", "B"), loss)]) timestamp = time.strftime("%H:%M:%S") output = f"[{timestamp}] [#{self._model.iterations:05d}] {output}" print(f"\r{output}...
56,285
221,238
41
python3.10.4/Lib/calendar.py
16
9
def itermonthdays2(self, year, month): for i, d in enumerate(self.itermonthdays(year, mont
add python 3.10.4 for windows
itermonthdays2
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
calendar.py
10
3
https://github.com/XX-net/XX-Net.git
2
37
0
16
57
Python
{ "docstring": "\n Like itermonthdates(), but will yield (day number, weekday number)\n tuples. For days outside the specified month the day number is 0.\n ", "language": "en", "n_whitespaces": 43, "n_words": 21, "vocab_size": 20 }
def itermonthdays2(self, year, month): for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday): yield d, i % 7
99,493
300,633
36
tests/helpers/test_template.py
17
11
def test_distance_function_return_none_if_invalid_state(hass): hass.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test.object_2) | round }}", hass) with pytes
Fail template functions when no default specified (#71687)
test_distance_function_return_none_if_invalid_state
4885331509eeffe50f42d76b234996467b06170f
core
test_template.py
10
5
https://github.com/home-assistant/core.git
1
45
0
17
83
Python
{ "docstring": "Test distance function return None if invalid state.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def test_distance_function_return_none_if_invalid_state(hass): hass.states.async_set("test.object_2", "happy", {"latitude": 10}) tpl = template.Template("{{ distance(states.test.object_2) | round }}", hass) with pytest.raises(TemplateError): tpl.async_render()
elif sys.version_info[:2] >= (3, 7):sys
3,609
20,890
25
pipenv/patched/notpip/_vendor/typing_extensions.py
13
7
def Concatenate(self, parameters): return _con
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...
Concatenate
f3166e673fe8d40277b804d35d77dcdb760fc3b3
pipenv
typing_extensions.py
7
2
https://github.com/pypa/pipenv.git
1
15
2
13
48
Python
{ "docstring": "Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n higher order function which adds, removes or transforms parameters of a\n callable.\n\n For example::\n\n Callable[Concatenate[int, P], int]\n\n See PEP 612 for detailed information.\n ...
def Concatenate(self, parameters): return _concatenate_getitem(self, parameters) # 3.7-8 elif sys.version_info[:2] >= (3, 7):
26,587
119,349
116
tests/ann_test.py
55
19
def compute_recall(result_neighbors, ground_truth_neighbors) -> float:
[JAX] Move ann.ann_recall back to tests. The function is simple enough for users to implement their own on the host. PiperOrigin-RevId: 430696789
compute_recall
8372b98c4856b6b2363b7bb28abdb4579440a656
jax
ann_test.py
16
25
https://github.com/google/jax.git
5
105
0
37
164
Python
{ "docstring": "Computes the recall of an approximate nearest neighbor search.\n\n Args:\n result_neighbors: int32 numpy array of the shape [num_queries,\n neighbors_per_query] where the values are the indices of the dataset.\n ground_truth_neighbors: int32 numpy array of with shape [num_queries,\n g...
def compute_recall(result_neighbors, ground_truth_neighbors) -> float: assert len( result_neighbors.shape) == 2, "shape = [num_queries, neighbors_per_query]" assert len(ground_truth_neighbors.shape ) == 2, "shape = [num_queries, ground_truth_neighbors_per_query]" assert result_neighbors.shape...
39,469
163,635
108
pandas/core/arrays/datetimes.py
30
15
def isocalendar(self) -> DataFrame: from pandas import DataFrame values = self._local_timestamps() sarray = fields.build_isocalendar_sarray(values) iso_calendar_df = DataFrame( sarray, columns=["year", "week", "day"], dtype="UInt32" ) if self._hasna:...
EA interface: rename ExtensionArray._hasnans to ._hasna (#45519)
isocalendar
a0b40c0f2ad73420a54e48ec4f564b9667e3f452
pandas
datetimes.py
11
44
https://github.com/pandas-dev/pandas.git
2
64
0
26
109
Python
{ "docstring": "\n Returns a DataFrame with the year, week, and day calculated according to\n the ISO 8601 standard.\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n DataFrame\n with columns year, week and day\n\n See Also\n --------\n Times...
def isocalendar(self) -> DataFrame: from pandas import DataFrame values = self._local_timestamps() sarray = fields.build_isocalendar_sarray(values) iso_calendar_df = DataFrame( sarray, columns=["year", "week", "day"], dtype="UInt32" ) if self._hasna:...
70,002
243,180
264
src/PIL/Image.py
71
17
def putpixel(self, xy, value): if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) i...
Allow RGB and RGBA values for PA image putpixel
putpixel
a37593f004247ebf69d5582524da6dc5143cb023
Pillow
Image.py
14
18
https://github.com/python-pillow/Pillow.git
9
142
0
49
225
Python
{ "docstring": "\n Modifies the pixel at the given position. The color is given as\n a single numerical value for single-band images, and a tuple for\n multi-band images. In addition to this, RGB and RGBA tuples are\n accepted for P and PA images.\n\n Note that this method is relati...
def putpixel(self, xy, value): if self.readonly: self._copy() self.load() if self.pyaccess: return self.pyaccess.putpixel(xy, value) if ( self.mode in ("P", "PA") and isinstance(value, (list, tuple)) and len(value) i...
99,301
300,441
293
tests/components/template/test_switch.py
55
14
async def test_available_template_with_entities(hass): await setup.async_setup_component( hass, "switch", { "switch": { "platform": "template", "switches": { "test_template_switch": { **OPTIMISTIC_SW...
Tweak template switch tests (#71738)
test_available_template_with_entities
11cc1feb853bcfd9633ebfc44eae142c10a7f983
core
test_switch.py
17
26
https://github.com/home-assistant/core.git
1
123
0
34
224
Python
{ "docstring": "Test availability templates with values from other entities.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
async def test_available_template_with_entities(hass): await setup.async_setup_component( hass, "switch", { "switch": { "platform": "template", "switches": { "test_template_switch": { **OPTIMISTIC_SW...
84,345
282,896
1,278
bots/etf/tops.py
247
84
def etfs_disc_command(sort=""): # Debug i
Discord bot massive improvement (#1481) * allow logs feature flag * Adding log collection md * upload last log at startup * additions/refractor * refactor * lint/black ++ * disc * TimeRotating Logger and upload to s3 * corrected regex error * makeup for config * logging/disc/sia/etf/++ ...
etfs_disc_command
50cafd500ece43df98e3cf076d81084b2806ea03
OpenBBTerminal
tops.py
18
98
https://github.com/OpenBB-finance/OpenBBTerminal.git
10
599
0
146
945
Python
{ "docstring": "Displays ETF's Top Gainers/Decliners, Most Active [Wall Street Journal]", "language": "en", "n_whitespaces": 9, "n_words": 9, "vocab_size": 9 }
def etfs_disc_command(sort=""): # Debug if cfg.DEBUG: logger.debug("etfs") df_etfs = wsj_model.etf_movers(sort, export=True) if df_etfs.empty: raise Exception("No available data found") df_etfs.set_index(" ", inplace=True) prfx = "Top" if sort == "active": pr...
35,584
153,753
75
modin/core/execution/ray/implementations/pandas_on_ray/partitioning/partition.py
15
12
def get(self):
FEAT-#4371: Add logging to Modin (#4372) Co-authored-by: Devin Petersohn <devin.petersohn@gmail.com> Co-authored-by: Mahesh Vashishtha <mvashishtha@users.noreply.github.com> Co-authored-by: Anatoly Myachev <anatoliimyachev@mail.com> Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru> Signed-off-by: Naren Krish...
get
49fc2cf3733f20ac6cf8a7c61e42ef7aa5cf4b03
modin
partition.py
10
8
https://github.com/modin-project/modin.git
2
50
0
13
101
Python
{ "docstring": "\n Get the object wrapped by this partition out of the Plasma store.\n\n Returns\n -------\n pandas.DataFrame\n The object from the Plasma store.\n ", "language": "en", "n_whitespaces": 68, "n_words": 21, "vocab_size": 16 }
def get(self): logger = get_logger() logger.debug(f"ENTER::Partition.get::{self._identity}") if len(self.call_queue): self.drain_call_queue() result = ray.get(self.oid) logger.debug(f"EXIT::Partition.get::{self._identity}") return result
@pytest.fixture
9,197
47,660
243
tests/sensors/test_external_task_sensor.py
111
36
def dag_bag_ext(): clear_db_runs() dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False) dag_0 = DAG("dag_0", start_date=DEFAULT_DATE, schedule_interval=None) task_a_0 = EmptyOperator(task_id="task_a_0", dag=dag_0) task_b_0 = ExternalTaskMarker( task_id="task_b_0", external_da...
Replace usage of `DummyOperator` with `EmptyOperator` (#22974) * Replace usage of `DummyOperator` with `EmptyOperator`
dag_bag_ext
49e336ae0302b386a2f47269a6d13988382d975f
airflow
test_external_task_sensor.py
10
35
https://github.com/apache/airflow.git
2
290
1
69
460
Python
{ "docstring": "\n Create a DagBag with DAGs looking like this. The dotted lines represent external dependencies\n set up using ExternalTaskMarker and ExternalTaskSensor.\n\n dag_0: task_a_0 >> task_b_0\n |\n |\n dag_1: ---> task_...
def dag_bag_ext(): clear_db_runs() dag_bag = DagBag(dag_folder=DEV_NULL, include_examples=False) dag_0 = DAG("dag_0", start_date=DEFAULT_DATE, schedule_interval=None) task_a_0 = EmptyOperator(task_id="task_a_0", dag=dag_0) task_b_0 = ExternalTaskMarker( task_id="task_b_0", external_da...
@image_comparison(['constrained_layout4.png'])
22,615
107,160
93
lib/matplotlib/tests/test_constrainedlayout.py
34
16
def test_constrained_layout3(): fig, axs = plt.subplots(2, 2, layout="constrained") for nn, ax in enumerate(axs.flat): pcm = example_pcolor(ax, fontsize=24) if nn == 3: pad = 0.08 else: pad = 0.02 # default fig.colorbar(pcm, ax=ax, pad=pad) @image...
ENH: implement and use base layout_engine for more flexible layout.
test_constrained_layout3
ec4dfbc3c83866f487ff0bc9c87b0d43a1c02b22
matplotlib
test_constrainedlayout.py
11
9
https://github.com/matplotlib/matplotlib.git
3
74
1
30
127
Python
{ "docstring": "Test constrained_layout for colorbars with subplots", "language": "en", "n_whitespaces": 5, "n_words": 6, "vocab_size": 6 }
def test_constrained_layout3(): fig, axs = plt.subplots(2, 2, layout="constrained") for nn, ax in enumerate(axs.flat): pcm = example_pcolor(ax, fontsize=24) if nn == 3: pad = 0.08 else: pad = 0.02 # default fig.colorbar(pcm, ax=ax, pad=pad) @image...
40,114
167,771
21
pandas/core/groupby/groupby.py
7
9
def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]: return self.grouper.indi
TYP: more return annotations in core/ (#47618) * TYP: more return annotations in core/ * from __future__ import annotations * more __future__
indices
f65417656ba8c59438d832b6e2a431f78d40c21c
pandas
groupby.py
7
5
https://github.com/pandas-dev/pandas.git
1
26
0
7
41
Python
{ "docstring": "\n Dict {group name -> group indices}.\n ", "language": "en", "n_whitespaces": 21, "n_words": 6, "vocab_size": 6 }
def indices(self) -> dict[Hashable, npt.NDArray[np.intp]]: return self.grouper.indices
12,773
61,950
146
.venv/lib/python3.8/site-packages/pip/_vendor/distlib/database.py
42
13
def get_hash(self, data, hasher=None): if
upd; format
get_hash
f638f5d0e6c8ebed0e69a6584bc7f003ec646580
transferlearning
database.py
12
12
https://github.com/jindongwang/transferlearning.git
3
89
0
25
151
Python
{ "docstring": "\n Get the hash of some data, using a particular hash algorithm, if\n specified.\n\n :param data: The data to be hashed.\n :type data: bytes\n :param hasher: The name of a hash implementation, supported by hashlib,\n or ``None``. Examples of val...
def get_hash(self, data, hasher=None): if hasher is None: hasher = self.hasher if hasher is None: hasher = hashlib.md5 prefix = '' else: hasher = getattr(hashlib, hasher) prefix = '%s=' % self.hasher digest = hasher(dat...
30,656
135,565
173
rllib/utils/tests/test_actor_manager.py
63
23
def test_async_call_same_actor_multiple_times(self): actors = [Actor.remote(i, maybe_crash=False) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # 2 asynchronous call to actor 0. num_of_calls = manager.foreach_actor_async( lambda w: w.call(), ...
[RLlib] Introduce FaultTolerantActorManager (#29703) Signed-off-by: Jun Gong <jungong@anyscale.com>
test_async_call_same_actor_multiple_times
d329147ae28c57b290f6b932f9f3044523f67c4e
ray
test_actor_manager.py
11
11
https://github.com/ray-project/ray.git
3
107
0
51
168
Python
{ "docstring": "Test multiple asynchronous remote calls to the same actor.", "language": "en", "n_whitespaces": 8, "n_words": 9, "vocab_size": 9 }
def test_async_call_same_actor_multiple_times(self): actors = [Actor.remote(i, maybe_crash=False) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # 2 asynchronous call to actor 0. num_of_calls = manager.foreach_actor_async( lambda w: w.call(), ...
20,731
101,313
389
scripts/fsmedia.py
119
19
def _load(self): data = {} if not self._is_extract: if not self.have_alignments_file: return data data = super()._load() return data skip_existing = hasattr(self._args, 'skip_existing') and self._args.skip_existing skip_faces ...
bugfix: debug landmarks
_load
9e503bdaa2bfe2baaea50ad2e4bf742f309d9d10
faceswap
fsmedia.py
14
24
https://github.com/deepfakes/faceswap.git
15
171
0
73
290
Python
{ "docstring": " Override the parent :func:`~lib.align.Alignments._load` to handle skip existing\n frames and faces on extract.\n\n If skip existing has been selected, existing alignments are loaded and returned to the\n calling script.\n\n Returns\n -------\n dict\n ...
def _load(self): data = {} if not self._is_extract: if not self.have_alignments_file: return data data = super()._load() return data skip_existing = hasattr(self._args, 'skip_existing') and self._args.skip_existing skip_faces ...
@log_start_end(log=logger)
85,189
285,147
24
openbb_terminal/stocks/discovery/yahoofinance_model.py
9
7
def get_gtech() -> pd.DataFrame: return get_df( "https://finance.y
Fixed bad yfinance urls (#2282)
get_gtech
bd12c203a0585dab6ca3ff81c3b4500e088b41d6
OpenBBTerminal
yahoofinance_model.py
8
11
https://github.com/OpenBB-finance/OpenBBTerminal.git
1
14
1
9
40
Python
{ "docstring": "Get technology stocks with revenue and earnings growth in excess of 25%. [Source: Yahoo Finance]\n\n Returns\n -------\n pd.DataFrame\n Growth technology stocks\n ", "language": "en", "n_whitespaces": 40, "n_words": 21, "vocab_size": 19 }
def get_gtech() -> pd.DataFrame: return get_df( "https://finance.yahoo.com/screener/predefined/growth_technology_stocks" ) @log_start_end(log=logger)
@require_torch
6,455
35,457
100
tests/encoder_decoder/test_modeling_encoder_decoder.py
30
21
def test_bert2gpt2_summarization(self): model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16") model.to(torch_device) tokenizer_in = AutoTokenizer.from_pretrained("bert-base-case
[Test refactor 1/5] Per-folder tests reorganization (#15725) * Per-folder tests reorganization Co-authored-by: sgugger <sylvain.gugger@gmail.com> Co-authored-by: Stas Bekman <stas@stason.org>
test_bert2gpt2_summarization
29c10a41d04f855c433a6cde7797b325651417d2
transformers
test_modeling_encoder_decoder.py
12
11
https://github.com/huggingface/transformers.git
1
89
1
23
162
Python
{ "docstring": "(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David Boren took it a step further, saying the university's affiliation with the fraternity is permanent...
def test_bert2gpt2_summarization(self): model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2gpt2-cnn_dailymail-fp16") model.to(torch_device) tokenizer_in = AutoTokenizer.from_pretrained("bert-base-cased") tokenizer_out = AutoTokenizer.from_pretrained("../gpt2") A...
5,294
30,056
106
saleor/permission/management.py
27
8
def _get_builtin_permissions(opts): # noqa: D205, D212 perms = [] for action in opts.default_permissions: perms.append( ( get_permission_codename(action, opts), "Can %s %s" % (action, opts.verbose_name_raw), ) )
Move create_permission post migrate signal
_get_builtin_permissions
3981ae09888569eafe9cbb3a0c659dd337028fa4
saleor
management.py
13
10
https://github.com/saleor/saleor.git
2
43
0
25
70
Python
{ "docstring": "\n Return (codename, name) for all autogenerated permissions.\n By default, this is ('add', 'change', 'delete', 'view')\n ", "language": "en", "n_whitespaces": 25, "n_words": 15, "vocab_size": 15 }
def _get_builtin_permissions(opts): # noqa: D205, D212 perms = [] for action in opts.default_permissions: perms.append( ( get_permission_codename(action, opts), "Can %s %s" % (action, opts.verbose_name_raw), ) ) return perms
121,117
337,787
84
src/accelerate/accelerator.py
16
9
def accumulate(self, model): self._do_sync() if self.sync_gradients: context = contextl
Introduce automatic gradient accumulation wrapper + fix a few test issues (#484) * Have accelerator handle gradient accumulation Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>
accumulate
86ce737d7fc94f8000dbd5e13021d0411bb4204a
accelerate
accelerator.py
10
8
https://github.com/huggingface/accelerate.git
2
37
0
14
67
Python
{ "docstring": "\n A context manager that will lightly wrap around and perform gradient accumulation automatically\n\n Args:\n model (`torch.nn.Module`):\n PyTorch Module that was prepared with `Accelerator.prepare`\n ", "language": "en", "n_whitespaces": 71, "n_wo...
def accumulate(self, model): self._do_sync() if self.sync_gradients: context = contextlib.nullcontext else: context = self.no_sync with context(model): yield
56,951
223,525
118
python3.10.4/Lib/email/_header_value_parser.py
48
13
def get_attribute(value): attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and value[0] in ATTRIBUTE_ENDS: raise errors.H
add python 3.10.4 for windows
get_attribute
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
_header_value_parser.py
12
14
https://github.com/XX-net/XX-Net.git
7
99
0
25
163
Python
{ "docstring": " [CFWS] 1*attrtext [CFWS]\n\n This version of the BNF makes the CFWS explicit, and as usual we use a\n value terminal for the actual run of characters. The RFC equivalent of\n attrtext is the token characters, with the subtraction of '*', \"'\", and '%'.\n We include tab in the excluded s...
def get_attribute(value): attribute = Attribute() if value and value[0] in CFWS_LEADER: token, value = get_cfws(value) attribute.append(token) if value and value[0] in ATTRIBUTE_ENDS: raise errors.HeaderParseError( "expected token but found '{}'".format(value)) t...
@pytest.fixture
35,948
154,378
282
modin/pandas/test/test_io.py
82
21
def eval_to_file(modin_obj, pandas_obj, fn, extension, **fn_kwargs): with ensure_clean_dir() as dirname: unique_filename_modin = get_unique_filename( extension=extension, data_dir=dirname ) unique_filename_pandas = get_unique_filename( extension=extension, data_d...
TEST-#4879: Use pandas `ensure_clean()` in place of `io_tests_data` (#4881) Signed-off-by: Karthik Velayutham <vkarthik@ponder.io>
eval_to_file
5086a9ea37bc37e6e58da0ceaf5864b16cc8e0ed
modin
test_io.py
14
20
https://github.com/modin-project/modin.git
3
104
1
63
176
Python
{ "docstring": "Helper function to test `to_<extension>` methods.\n\n Args:\n modin_obj: Modin DataFrame or Series to test `to_<extension>` method.\n pandas_obj: Pandas DataFrame or Series to test `to_<extension>` method.\n fn: name of the method, that should be tested.\n extension: Ext...
def eval_to_file(modin_obj, pandas_obj, fn, extension, **fn_kwargs): with ensure_clean_dir() as dirname: unique_filename_modin = get_unique_filename( extension=extension, data_dir=dirname ) unique_filename_pandas = get_unique_filename( extension=extension, data_d...
50,522
203,731
70
django/contrib/contenttypes/fields.py
16
9
def _is_matching_generic_foreign_key(self, field): return ( isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name )
Refs #33476 -- Reformatted code with Black.
_is_matching_generic_foreign_key
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
fields.py
10
6
https://github.com/django/django.git
3
33
0
14
52
Python
{ "docstring": "\n Return True if field is a GenericForeignKey whose content type and\n object id fields correspond to the equivalent attributes on this\n GenericRelation.\n ", "language": "en", "n_whitespaces": 51, "n_words": 22, "vocab_size": 22 }
def _is_matching_generic_foreign_key(self, field): return ( isinstance(field, GenericForeignKey) and field.ct_field == self.content_type_field_name and field.fk_field == self.object_id_field_name )
20,628
101,207
102
lib/align/alignments.py
25
13
def hashes_to_frame(self): if not self._hashes_to_frame: logger.debug("Generating hashes to frame") for frame_name, val in self._data.items(): for idx, face in enumerate(val["faces"]): sel
lib.align updates: - alignments.py - Add typed dicts for imported alignments - Explicitly check for presence of thumb value in alignments dict - linting - detected_face.py - Typing - Linting - Legacy support for pre-aligned face - Update dependencies to new property names
hashes_to_frame
5e73437be47f2410439a3c6716de96354e6a0c94
faceswap
alignments.py
17
7
https://github.com/deepfakes/faceswap.git
4
67
0
23
112
Python
{ "docstring": " dict: The SHA1 hash of the face mapped to the frame(s) and face index within the frame\n that the hash corresponds to. The structure of the dictionary is:\n\n {**SHA1_hash** (`str`): {**filename** (`str`): **face_index** (`int`)}}.\n\n Notes\n -----\n This method is...
def hashes_to_frame(self): if not self._hashes_to_frame: logger.debug("Generating hashes to frame") for frame_name, val in self._data.items(): for idx, face in enumerate(val["faces"]): self._hashes_to_frame.setdefault(face["hash"], {})[frame_n...
117,338
320,770
466
qutebrowser/completion/completiondelegate.py
90
55
def _get_textdoc(self, index): assert self._opt is not None # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptio...
mypy: Upgrade to PyQt5-stubs 5.15.6.0 For some unknown reason, those new stubs cause a *lot* of things now to be checked by mypy which formerly probably got skipped due to Any being implied somewhere. The stubs themselves mainly improved, with a couple of regressions too. In total, there were some 337 (!) new mypy e...
_get_textdoc
a20bb67a878b2e68abf8268c1b0a27f018d01352
qutebrowser
completiondelegate.py
19
33
https://github.com/qutebrowser/qutebrowser.git
7
292
0
68
469
Python
{ "docstring": "Create the QTextDocument of an item.\n\n Args:\n index: The QModelIndex of the item to draw.\n ", "language": "en", "n_whitespaces": 40, "n_words": 15, "vocab_size": 13 }
def _get_textdoc(self, index): assert self._opt is not None # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptio...
1,585
9,296
159
reconstruction/ostec/external/face_detector/detect_face.py
34
11
def feed(self, *args): assert len(args) != 0 self.terminals = []
initialize ostec
feed
7375ee364e0df2a417f92593e09557f1b2a3575a
insightface
detect_face.py
16
11
https://github.com/deepinsight/insightface.git
4
65
0
32
107
Python
{ "docstring": "Set the input(s) for the next operation by replacing the terminal nodes.\n The arguments can be either layer names or the actual layers.\n ", "language": "en", "n_whitespaces": 37, "n_words": 23, "vocab_size": 20 }
def feed(self, *args): assert len(args) != 0 self.terminals = [] for fed_layer in args: if isinstance(fed_layer, str): try: fed_layer = self.layers[fed_layer] except KeyError: raise KeyError('Unknown lay...
80,862
271,843
315
keras/engine/training_utils_v1.py
101
16
def unpack_iterator_input(iterator): try: next_element = iterator.get_next() except tf.errors.OutOfRangeError: raise RuntimeError( "Your dataset iterator ran out of data; " "Make sure that your dataset can generate " "required number of samples." ...
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
unpack_iterator_input
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
training_utils_v1.py
14
26
https://github.com/keras-team/keras.git
5
105
0
67
180
Python
{ "docstring": "Convert a dataset iterator to a tuple of tensors `x, y, sample_weights`.\n\n Args:\n iterator: Instance of a dataset iterator.\n\n Returns:\n Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None.\n ", "language": "en", "n_whitespaces": 52, "n_words": 33, "vo...
def unpack_iterator_input(iterator): try: next_element = iterator.get_next() except tf.errors.OutOfRangeError: raise RuntimeError( "Your dataset iterator ran out of data; " "Make sure that your dataset can generate " "required number of samples." ...
26,798
120,211
11
tests/mesh_utils_test.py
9
3
def mock_2x2x4_devices(one_device_per_chip): return mock_devices(2, 2, 4, 'TPU v4', one_device_pe
[mesh_utils] Support creating device meshes for hybrid networks Also makes some NFCs to other mesh_utils code. PiperOrigin-RevId: 442581767
mock_2x2x4_devices
3f9e45e0c5b035de27b14588cd3b4cfd5f3c1f04
jax
mesh_utils_test.py
8
2
https://github.com/google/jax.git
1
19
0
9
31
Python
{ "docstring": "Hard-coded reproduction of jax.devices() output on 2x2x4.", "language": "en", "n_whitespaces": 6, "n_words": 7, "vocab_size": 7 }
def mock_2x2x4_devices(one_device_per_chip): return mock_devices(2, 2, 4, 'TPU v4', one_device_per_chip)
1,079
6,855
61
ludwig/export.py
31
15
def export_triton(model_path, output_path="model_repository", model_name="ludwig_model", model_version=1, **kwargs): logger.info(f"Model path: {model_path}") logger.info(f"Output path: {output_path}"
Adding new export for Triton (#2078) * Adding new export for triton. Fixes for load model for neuropod export, add output dict format * Adding test for triton. Fix to cast int to string for os.path.join. Added annotation for neurpod * Minor tweaks to config.pbtxt output * Remove logger that is not being us...
export_triton
698a0e0f1ed95d20116dc51aa9c6a7ed48446deb
ludwig
export.py
9
10
https://github.com/ludwig-ai/ludwig.git
1
90
0
27
170
Python
{ "docstring": "Exports a model in torchscript format with config for Triton serving.\n\n # Inputs\n\n :param model_path: (str) filepath to pre-trained model.\n :param output_path: (str, default: `'model_repository'`) directory to store the\n triton models.\n :param model_name: (str, default: `'lu...
def export_triton(model_path, output_path="model_repository", model_name="ludwig_model", model_version=1, **kwargs): logger.info(f"Model path: {model_path}") logger.info(f"Output path: {output_path}") logger.info(f"Model name: {model_name}") logger.info(f"Model version: {model_version}") logger...
17,983
85,389
327
src/sentry/eventstore/models.py
93
24
def tags(self) -> Sequence[Tuple[str, str]]: tags_key_column = self._get_column_name(Columns.TAGS_KEY) tags_value_column = self._get_column_name(Columns.TAGS_VALUE) if tags_key_column in self._snuba_data and tags_value_column in self._snuba_data: keys = self._snuba_data[tag...
feat(perf_issues): Add `GroupEvent` and split some functionality in `Event` into a base class. (#38143) Since we can now have events with multiple groups, we can no longer rely on the `Event.group` property. This pr adds in a `GroupEvent` subclass that should be passed around wherever we expect an event to have a si...
tags
6aaaf5089b2c39757883179df5a8512db3b0c716
sentry
models.py
15
23
https://github.com/getsentry/sentry.git
11
145
0
67
229
Python
{ "docstring": "\n Tags property uses tags from snuba if loaded otherwise falls back to\n nodestore.\n ", "language": "en", "n_whitespaces": 35, "n_words": 13, "vocab_size": 13 }
def tags(self) -> Sequence[Tuple[str, str]]: tags_key_column = self._get_column_name(Columns.TAGS_KEY) tags_value_column = self._get_column_name(Columns.TAGS_VALUE) if tags_key_column in self._snuba_data and tags_value_column in self._snuba_data: keys = self._snuba_data[tag...
77,934
264,988
116
netbox/dcim/tests/test_models.py
38
12
def test_cable_validates_compatible_types(self): # An interface cannot be connected to a power port cable = Cable(a_terminations=[self.interface1, self.interface2], b_terminations=[self.interface3]) with self.assertRaises(ValidationError): cable.clean() # TODO: Remove t...
Clean up tests
test_cable_validates_compatible_types
6280398bc17211bbc5b321039144c1eb0461f4a9
netbox
test_models.py
11
4
https://github.com/netbox-community/netbox.git
1
43
0
26
81
Python
{ "docstring": "\n The clean method should have a check to ensure only compatible port types can be connected by a cable\n \n # A cable cannot connect a front port to its corresponding rear port\n # ", "language": "en", "n_whitespaces": 63, "n_words": 33, "vocab_size": 26 }
def test_cable_validates_compatible_types(self): # An interface cannot be connected to a power port cable = Cable(a_terminations=[self.interface1, self.interface2], b_terminations=[self.interface3]) with self.assertRaises(ValidationError): cable.clean() # TODO: Remove t...
81,490
275,865
766
keras/saving/hdf5_format.py
235
55
def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): if h5py is None: raise ImportError( "`save_model()` using h5 format requires h5py. Could not " "import h5py." ) # TODO(psv) Add warning when we save models that contain non-serializabl...
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
save_model_to_hdf5
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
hdf5_format.py
18
54
https://github.com/keras-team/keras.git
16
290
0
164
490
Python
{ "docstring": "Saves a model to a HDF5 file.\n\n The saved model contains:\n - the model's configuration (topology)\n - the model's weights\n - the model's optimizer's state (if any)\n\n Thus the saved model can be reinstantiated in\n the exact same state, without any of the code\n u...
def save_model_to_hdf5(model, filepath, overwrite=True, include_optimizer=True): if h5py is None: raise ImportError( "`save_model()` using h5 format requires h5py. Could not " "import h5py." ) # TODO(psv) Add warning when we save models that contain non-serializabl...
270
2,278
299
packages/syft/src/syft/core/node/common/node_manager/user_manager.py
79
24
def set(self, **kwargs) -> None: # nosec attributes = {} user_id = kwargs["u
replaced all methods of usermanager class, working login Co-Authored By: Ionesio
set
066545e8a88e842aa7d0a5d57bac88716001bced
PySyft
user_manager.py
11
41
https://github.com/OpenMined/PySyft.git
10
205
0
55
351
Python
{ "docstring": "Updates the information for the given user id.\n\n Args:\n user_id (str): unique id of the user in the database.\n email (str, optional): email of the user. Defaults to \"\".\n password (str, optional): password of the user. Defaults to \"\".\n role (...
def set(self, **kwargs) -> None: # nosec attributes = {} user_id = kwargs["user_id"] user = self.first(id_int=int(user_id)) if not user: raise UserNotFoundError for k, v in kwargs.items(): if k in user.__attr_searchable__: attrib...
18,963
92,964
336
tests/sentry/snuba/metrics/fields/test_base.py
62
31
def test_get_entity_and_validate_dependency_tree_of_a_single_entity_derived_metric(self): use_case_id = UseCaseKey.RELEASE_HEALTH expected_derived_metrics_entities = { SessionMRI.ALL.value: "metrics_counters", SessionMRI.ALL_USER.value: "metrics_sets", Sessio...
fix(snuba): Add appropriate `UseCaseKey` for indexer [TET-146] (#36308) * fix(snuba): Add appropriate `UseCaseKey` for indexer Update indexer invocation call to have the appropriate `UseCaseKey` depending on use case. In `src/sentry/sentry_metrics/indexer/base.py::StringIndexer` when using `resolve` and `rever...
test_get_entity_and_validate_dependency_tree_of_a_single_entity_derived_metric
cd803d173c72b64d06c0687170bf9a945d0b503c
sentry
test_base.py
14
25
https://github.com/getsentry/sentry.git
2
180
0
47
292
Python
{ "docstring": "\n Tests that ensures that get_entity method works expected in the sense that:\n - Since it is the first function that is called by the query_builder, validation is\n applied there to ensure that if it is an instance of a SingleEntityDerivedMetric,\n then it is composed of ...
def test_get_entity_and_validate_dependency_tree_of_a_single_entity_derived_metric(self): use_case_id = UseCaseKey.RELEASE_HEALTH expected_derived_metrics_entities = { SessionMRI.ALL.value: "metrics_counters", SessionMRI.ALL_USER.value: "metrics_sets", Sessio...
76,202
260,356
83
sklearn/decomposition/_sparse_pca.py
23
13
def transform(self, X): check_is_fitted(self) X = self._validate_data(X, reset=False) X = X - self.mean_ U = ridge_regression( self.components_.T, X.T, self.ridge_alpha, solver="cholesky" ) return U
MAINT Use _validate_params in SparsePCA and MiniBatchSparsePCA (#23710) Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> Co-authored-by: jeremiedbb <jeremiedbb@yahoo.fr>
transform
db6123fe40400828918037f3fae949bfcc4d9d05
scikit-learn
_sparse_pca.py
10
8
https://github.com/scikit-learn/scikit-learn.git
1
55
0
18
87
Python
{ "docstring": "Least Squares projection of the data onto the sparse components.\n\n To avoid instability issues in case the system is under-determined,\n regularization can be applied (Ridge regression) via the\n `ridge_alpha` parameter.\n\n Note that Sparse PCA components orthogonality i...
def transform(self, X): check_is_fitted(self) X = self._validate_data(X, reset=False) X = X - self.mean_ U = ridge_regression( self.components_.T, X.T, self.ridge_alpha, solver="cholesky" ) return U
77,797
264,756
233
netbox/utilities/utils.py
117
27
def serialize_object(obj, extra=None): json_str = serialize('json', [obj]) print(json_str) data = json.loads(json_str)[0]['fields'] # Exclude any MPTTModel fields if issubclass(obj.__class__, MPTTModel): for field in ['level', 'lft', 'rght', 'tree_id']: data.pop
Extend Cable model to support multiple A/B terminations
serialize_object
4bb9b6ee2639db683b70d6ddbee055497e0a3647
netbox
utils.py
12
18
https://github.com/netbox-community/netbox.git
11
167
0
86
285
Python
{ "docstring": "\n Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like\n change logging, not the REST API.) Optionally include a dictionary to supplement the object data. A list of keys\n can be provided to exclude them from the returned diction...
def serialize_object(obj, extra=None): json_str = serialize('json', [obj]) print(json_str) data = json.loads(json_str)[0]['fields'] # Exclude any MPTTModel fields if issubclass(obj.__class__, MPTTModel): for field in ['level', 'lft', 'rght', 'tree_id']: data.pop(field) ...
88,520
289,378
405
tests/components/history/test_init.py
112
20
async def test_statistics_during_period(recorder_mock, hass, hass_ws_client, caplog): now = dt_util.utcnow() await async_setup_component(hass, "history", {}) client = await hass_ws_client() # Test the WS API works and issues a warning await client.send_json( { "id": 1, ...
Ensure recorder test fixture is setup before hass fixture (#80528) * Ensure recorder test fixture is setup before hass fixture * Adjust more tests
test_statistics_during_period
31a787558fd312331b55e5c2c4b33341fc3601fc
core
test_init.py
14
37
https://github.com/home-assistant/core.git
1
173
0
76
319
Python
{ "docstring": "Test history/statistics_during_period forwards to recorder.", "language": "en", "n_whitespaces": 4, "n_words": 5, "vocab_size": 5 }
async def test_statistics_during_period(recorder_mock, hass, hass_ws_client, caplog): now = dt_util.utcnow() await async_setup_component(hass, "history", {}) client = await hass_ws_client() # Test the WS API works and issues a warning await client.send_json( { "id": 1, ...
16,427
75,606
104
wagtail/search/management/commands/update_index.py
24
8
def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE): i = 0
Reformat with black
queryset_chunks
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
update_index.py
14
8
https://github.com/wagtail/wagtail.git
3
44
0
21
73
Python
{ "docstring": "\n Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded\n will be a list, not a queryset. Iterating over the chunks is done in a\n transaction so that the order and count of items in the queryset\n remains stable.\n ", "language": "en", "n_whit...
def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE): i = 0 while True: items = list(qs[i * chunk_size :][:chunk_size]) if not items: break yield items i += 1
19,211
95,431
229
src/sentry/search/events/builder.py
45
15
def flattened_having(self) -> List[Condition]: flattened: List[Condition] = [] boolean_conditions: List[BooleanCondition] = [] for condition in self.having: if isinstance(condition, Condition): flattened.append(condition) elif isinstance(conditio...
fix(snql): Add aggregations to select in auto_aggregation (#31061) - This is to fix an issue for queries that have the uniq aggregation in the HAVING clause, and is not selected. - Previously we would not add the aggregation to the select clause in these cases - Now anything in the having clause will get...
flattened_having
2a4da479b2d4a2faa901701f4c73ff823236e9e8
sentry
builder.py
14
20
https://github.com/getsentry/sentry.git
8
116
0
30
184
Python
{ "docstring": "Return self.having as a flattened list ignoring boolean operators\n This is because self.having can have a mix of BooleanConditions and Conditions. And each BooleanCondition can in\n turn be a mix of either type.\n ", "language": "en", "n_whitespaces": 54, "n_words": 33, "...
def flattened_having(self) -> List[Condition]: flattened: List[Condition] = [] boolean_conditions: List[BooleanCondition] = [] for condition in self.having: if isinstance(condition, Condition): flattened.append(condition) elif isinstance(conditio...
39,468
163,634
211
pandas/core/arrays/datetimelike.py
64
27
def _add_timedelta_arraylike(self, other): # overridden by PeriodArray if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray):
EA interface: rename ExtensionArray._hasnans to ._hasna (#45519)
_add_timedelta_arraylike
a0b40c0f2ad73420a54e48ec4f564b9667e3f452
pandas
datetimelike.py
10
15
https://github.com/pandas-dev/pandas.git
5
122
0
57
191
Python
{ "docstring": "\n Add a delta of a TimedeltaIndex\n\n Returns\n -------\n Same type as self\n ", "language": "en", "n_whitespaces": 48, "n_words": 12, "vocab_size": 11 }
def _add_timedelta_arraylike(self, other): # overridden by PeriodArray if len(self) != len(other): raise ValueError("cannot add indices of unequal length") if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op from ...
80,737
271,248
1,164
keras/engine/functional.py
488
55
def _map_graph_network(inputs, outputs): # "depth" is number of layers between output Node and the Node. # Nodes are ordered from inputs -> outputs. nodes_in_decreasing_depth, layer_indices = _build_map(outputs) network_nodes = { _make_node_key(node.layer.name, node.layer._inbound_nodes.ind...
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
_map_graph_network
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
functional.py
21
65
https://github.com/keras-team/keras.git
20
470
0
245
792
Python
{ "docstring": "Validates a network's topology and gather its layers and nodes.\n\n Args:\n inputs: List of input tensors.\n outputs: List of outputs tensors.\n\n Returns:\n A tuple `(nodes, nodes_by_depth, layers, layers_by_depth)`.\n - nodes: list of Node instances.\n - nodes_by_depth...
def _map_graph_network(inputs, outputs): # "depth" is number of layers between output Node and the Node. # Nodes are ordered from inputs -> outputs. nodes_in_decreasing_depth, layer_indices = _build_map(outputs) network_nodes = { _make_node_key(node.layer.name, node.layer._inbound_nodes.ind...
28,513
127,723
138
python/ray/data/dataset.py
40
18
def default_batch_format(self) -> Type: # noqa: E501 import pandas as pd import pyarrow as pa schema = self.schema() assert isinstance(schema,
[Datasets] Add `Dataset.default_batch_format` (#28434) Participants in the PyTorch UX study couldn't understand how the "native" batch format works. This PR introduces a method Dataset.native_batch_format that tells users exactly what the native batch format is, so users don't have to guess.
default_batch_format
206e847694cba414dc4664e4ae02b20e10e3f25d
ray
dataset.py
10
72
https://github.com/ray-project/ray.git
4
79
0
32
124
Python
{ "docstring": "Return this dataset's default batch format.\n\n The default batch format describes what batches of data look like. To learn more\n about batch formats, read\n :ref:`writing user-defined functions <transform_datasets_writing_udfs>`.\n\n Example:\n\n If your datase...
def default_batch_format(self) -> Type: # noqa: E501 import pandas as pd import pyarrow as pa schema = self.schema() assert isinstance(schema, (type, PandasBlockSchema, pa.Schema)) if isinstance(schema, type): return list if isinstance(schema, (Pa...
@pytest.mark.parametrize("Tree", REG_TREES.values()) @pytest.mark.parametrize( "old_criterion, new_criterion", [ ("mse", "squared_error"), ("mae", "absolute_error"), ], )
75,740
259,378
282
sklearn/tree/tests/test_tree.py
159
40
def test_decision_tree_regressor_sample_weight_consistency(criterion): tree_params = dict(criterion=criterion) tree = DecisionTreeRegressor(**tree_params, random_state=42) for kind in ["zeros", "ones"]: check_sample_weights_invariance( "DecisionTreeRegressor_" + criterion, tree, kin...
MNT fix typo in tree test name (#22943)
test_decision_tree_regressor_sample_weight_consistency
f89a40bd92004368dee38ea76a1b9eaddaff4d7a
scikit-learn
test_tree.py
12
22
https://github.com/scikit-learn/scikit-learn.git
2
212
1
123
431
Python
{ "docstring": "Test that the impact of sample_weight is consistent.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def test_decision_tree_regressor_sample_weight_consistency(criterion): tree_params = dict(criterion=criterion) tree = DecisionTreeRegressor(**tree_params, random_state=42) for kind in ["zeros", "ones"]: check_sample_weights_invariance( "DecisionTreeRegressor_" + criterion, tree, kin...
52,020
207,608
110
tests/admin_views/tests.py
24
9
def test_with_fk_to_field(self): response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_V
Refs #33476 -- Reformatted code with Black.
test_with_fk_to_field
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
12
10
https://github.com/django/django.git
1
46
0
22
83
Python
{ "docstring": "\n The to_field GET parameter is preserved when a search is performed.\n Refs #10918.\n ", "language": "en", "n_whitespaces": 35, "n_words": 13, "vocab_size": 12 }
def test_with_fk_to_field(self): response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertContains(response, "\n1 user\n") self.assertContains( response, '<input type="hidden" name="%s" val...
46,351
190,450
27
fastai/torch_core.py
15
7
def remove_module_load(state_dict): new_state_dict = OrderedDict() fo
Upgrading to support latest Pytorch version
remove_module_load
4fc3616712edb19179b17dd270ad6cf63abf99c2
DeOldify
torch_core.py
11
4
https://github.com/jantic/DeOldify.git
2
34
0
12
57
Python
{ "docstring": "create new OrderedDict that does not contain `module.`", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def remove_module_load(state_dict): new_state_dict = OrderedDict() for k, v in state_dict.items(): new_state_dict[k[7:]] = v return new_state_dict
@add_start_docstrings( "The bare LayoutLMv3 Model transformer outputting raw hidden-states without any specific head on top.", LAYOUTLMV3_START_DOCSTRING, )
6,073
33,182
54
src/transformers/models/layoutlmv3/modeling_tf_layoutlmv3.py
31
9
def serving(self, inputs): output = self.call(inputs) return self.serving_output(output) LAYOUTLMV3_START_DOCSTRING = r LAYOUTLMV3_INPUTS_DOCSTRING = r @add_start_docstrings( "The bare LayoutLMv3 Model transformer outputting raw hidden-states w
[LayoutLMv3] Add TensorFlow implementation (#18678) Co-authored-by: Esben Toke Christensen <esben.christensen@visma.com> Co-authored-by: Lasse Reedtz <lasse.reedtz@visma.com> Co-authored-by: amyeroberts <22614925+amyeroberts@users.noreply.github.com> Co-authored-by: Joao Gante <joaofranciscocardosogante@gmail.com>
serving
de8548ebf3242305d0f9792dacb6f86b196a3a33
transformers
modeling_tf_layoutlmv3.py
8
3
https://github.com/huggingface/transformers.git
1
23
1
28
67
Python
{ "docstring": "\n Method used for serving the model.\n\n Args:\n inputs (`Dict[str, tf.Tensor]`):\n The input of the saved model as a dictionary of tensors.\n \n This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic method...
def serving(self, inputs): output = self.call(inputs) return self.serving_output(output) LAYOUTLMV3_START_DOCSTRING = r LAYOUTLMV3_INPUTS_DOCSTRING = r @add_start_docstrings( "The bare LayoutLMv3 Model transformer outputting raw hidden-states without any specific head on top.", LA...
107,305
308,556
40
homeassistant/components/sisyphus/media_player.py
8
9
def media_image_url(self): if self._table.active_track: return self._table.active_track.get_th
Sisyphus: Fix bad super call (#63327) Co-authored-by: Franck Nijhof <git@frenck.dev>
media_image_url
9f0805f51293851096d7ece48f48a041e4a809e0
core
media_player.py
11
4
https://github.com/home-assistant/core.git
2
34
0
7
57
Python
{ "docstring": "Return the URL for a thumbnail image of the current track.", "language": "en", "n_whitespaces": 10, "n_words": 11, "vocab_size": 10 }
def media_image_url(self): if self._table.active_track: return self._table.active_track.get_thumbnail_url(Track.ThumbnailSize.LARGE) return super().media_image_url
@pytest.mark.parametrize( "ongoing_requests", [[7, 1, 8, 4], [8, 1, 8, 4], [6, 1, 8, 4], [0, 1, 8, 4]])
28,953
129,433
385
python/ray/serve/tests/test_autoscaling_policy.py
107
26
def test_fluctuating_ongoing_requests(delay_s): config = AutoscalingConfig( min_replicas=1, max_replicas=10, target_num_ongoing_requests_per_replica=50, upscale_delay_s=delay_s, downscale_delay_s=delay_s) policy = BasicAutoscalingPolicy(config) if delay_s > 0:...
[Serve] Serve Autoscaling Release tests (#21208)
test_fluctuating_ongoing_requests
75b3080834bceb184e9ba19e21511eb0ea19955b
ray
test_autoscaling_policy.py
14
31
https://github.com/ray-project/ray.git
6
155
1
55
301
Python
{ "docstring": "\n Simulates a workload that switches between too many and too few\n ongoing requests.\n ", "language": "en", "n_whitespaces": 23, "n_words": 13, "vocab_size": 12 }
def test_fluctuating_ongoing_requests(delay_s): config = AutoscalingConfig( min_replicas=1, max_replicas=10, target_num_ongoing_requests_per_replica=50, upscale_delay_s=delay_s, downscale_delay_s=delay_s) policy = BasicAutoscalingPolicy(config) if delay_s > 0:...
10,583
52,487
78
modules/audio/svs/diffsinger/utils/audio.py
47
7
def librosa_pad_lr(x, fsize, fshift, pad_sides=1):
Add Diffsinger Module (#2120) * add diffsinger * update README * update README
librosa_pad_lr
7eef3bfde63d03acbd1fc9a15a5e56bef47c0ef7
PaddleHub
audio.py
13
7
https://github.com/PaddlePaddle/PaddleHub.git
2
46
0
32
105
Python
{ "docstring": "compute right padding (final frame) or both sides padding (first and final frames)\n ", "language": "en", "n_whitespaces": 16, "n_words": 13, "vocab_size": 12 }
def librosa_pad_lr(x, fsize, fshift, pad_sides=1): assert pad_sides in (1, 2) # return int(fsize // 2) pad = (x.shape[0] // fshift + 1) * fshift - x.shape[0] if pad_sides == 1: return 0, pad else: return pad // 2, pad // 2 + pad % 2 # Conversions
27,112
122,164
55
jax/tools/colab_tpu.py
37
14
def setup_tpu(tpu_driver_version='tpu_driver-0.2'): global TPU_DRIVER_MODE if not TPU_DRIVER_MODE: colab_tpu_addr = os.environ['COLAB_TPU_ADDR'].split(':')[0] url = f
Pin default jax.tools.colab_tpu.setup_tpu driver version. Prior to this change, we were defaulting to the TPU nightly driver version. We should instead pin to the version associated with the default jaxlib version that Colab uses.
setup_tpu
0cc4066bb7bf758a5ba8c5def9c2c32a1c98fb89
jax
colab_tpu.py
13
9
https://github.com/google/jax.git
2
64
0
32
125
Python
{ "docstring": "Sets up Colab to run on TPU.\n\n Note: make sure the Colab Runtime is set to Accelerator: TPU.\n\n Args\n ----\n tpu_driver_version : (str) specify the version identifier for the tpu driver.\n Defaults to \"tpu_driver-0.2\", which can be used with jaxlib 0.3.20. Set to\n \"tpu_driver_nightly...
def setup_tpu(tpu_driver_version='tpu_driver-0.2'): global TPU_DRIVER_MODE if not TPU_DRIVER_MODE: colab_tpu_addr = os.environ['COLAB_TPU_ADDR'].split(':')[0] url = f'http://{colab_tpu_addr}:8475/requestversion/{tpu_driver_version}' requests.post(url) TPU_DRIVER_MODE = 1 # The following is re...
71,987
247,899
133
tests/storage/databases/main/test_lock.py
49
16
def test_timeout_lock(self): lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None self.get_success(lock.__aenter__()) # We simulate the process getting stuck by cancelling the looping call # that keeps the lock active.
Add type hints for `tests/unittest.py`. (#12347) In particular, add type hints for get_success and friends, which are then helpful in a bunch of places.
test_timeout_lock
f0b03186d96305fd44d74a89bf4230beec0c5c31
synapse
test_lock.py
11
9
https://github.com/matrix-org/synapse.git
1
95
0
38
166
Python
{ "docstring": "Test that we time out locks if they're not updated for ages", "language": "en", "n_whitespaces": 11, "n_words": 12, "vocab_size": 12 }
def test_timeout_lock(self): lock = self.get_success(self.store.try_acquire_lock("name", "key")) assert lock is not None self.get_success(lock.__aenter__()) # We simulate the process getting stuck by cancelling the looping call # that keeps the lock active. lo...
81,454
275,725
81
keras/preprocessing/image.py
33
11
def random_brightness(x, brightness_range, scale=True): if len(brightness_range) != 2: raise ValueError( "`brightness_range should be tuple or list of two floats. " "Received: %s" % (brightness_range,) ) u = np.random.uniform(brightness_range[0], bri
Reformatting the codebase with black. PiperOrigin-RevId: 450093126
random_brightness
84afc5193d38057e2e2badf9c889ea87d80d8fbf
keras
image.py
12
8
https://github.com/keras-team/keras.git
2
58
0
33
92
Python
{ "docstring": "Performs a random brightness shift.\n\n Deprecated: `tf.keras.preprocessing.image.random_brightness` does not operate\n on tensors and is not recommended for new code. Prefer\n `tf.keras.layers.RandomBrightness` which provides equivalent functionality as\n a preprocessing layer. For more i...
def random_brightness(x, brightness_range, scale=True): if len(brightness_range) != 2: raise ValueError( "`brightness_range should be tuple or list of two floats. " "Received: %s" % (brightness_range,) ) u = np.random.uniform(brightness_range[0], brightness_range[1]...
107,962
309,255
23
tests/util/test_async.py
14
5
def test_check_loop_sync(caplog): hasync.check_loop() assert "Detected block
Warn on`time.sleep` in event loop (#63766) Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
test_check_loop_sync
dc58bc375ae203e3d394225f9c3a5a14d43cb2f3
core
test_async.py
7
3
https://github.com/home-assistant/core.git
1
18
0
14
34
Python
{ "docstring": "Test check_loop does nothing when called from thread.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def test_check_loop_sync(caplog): hasync.check_loop() assert "Detected blocking call inside the event loop" not in caplog.text
28,641
128,240
279
python/ray/serve/_private/deployment_state.py
70
20
def update(self) -> bool: try: # Add or remove DeploymentReplica instances in self._replicas. # This should be the only place we adjust total number of replicas # we manage. running_replicas_changed = self._scale_deployment_replicas() # Chec...
[Serve] add alpha gRPC support (#28175)
update
65d0c0aa48be8f9f7faae857d3ab71444997755a
ray
deployment_state.py
17
24
https://github.com/ray-project/ray.git
3
72
0
56
138
Python
{ "docstring": "Attempts to reconcile this deployment to match its goal state.\n\n This is an asynchronous call; it's expected to be called repeatedly.\n\n Also updates the internal DeploymentStatusInfo based on the current\n state of the system.\n\n Returns true if this deployment was suc...
def update(self) -> bool: try: # Add or remove DeploymentReplica instances in self._replicas. # This should be the only place we adjust total number of replicas # we manage. running_replicas_changed = self._scale_deployment_replicas() # Chec...
50,095
202,382
165
tests/csrf_tests/tests.py
48
18
def test_https_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["S
Refs #33476 -- Reformatted code with Black.
test_https_malformed_host
9c19aff7c7561e3a82978a272ecdaad40dda5c00
django
tests.py
10
15
https://github.com/django/django.git
1
99
0
41
176
Python
{ "docstring": "\n CsrfViewMiddleware generates a 403 response if it receives an HTTPS\n request with a bad host.\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 14 }
def test_https_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(toke...
594
3,894
63
airbyte-integrations/connectors/source-orb/source_orb/source.py
24
18
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: # TODO: self.authenticator should optionally pull from sel
🎉 New Source: Orb (#9985) * V1 of source_orb connector * add boostrap.md file * add clause on Pagination to bootstrap.md * add SUMMARY documentation * add lookback_window_days connector parameter * Add support for start_date parameter * Add ability to transform record in order to un-nest IDs * Ad...
stream_slices
1e0ac30ebdcfce55a5644bcd486044da45c93dd6
airbyte
source.py
12
11
https://github.com/airbytehq/airbyte.git
2
57
0
24
93
Python
{ "docstring": "\n This stream is sliced per `customer_id`. This has two implications:\n (1) State can be checkpointed after processing each slice\n (2) The other parameters (e.g. request_params, path) can be dependent on this slice.\n\n This allows us to pull data on a per customer_id bas...
def stream_slices(self, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: # TODO: self.authenticator should optionally pull from self._session.auth customers_stream = Customers(authenticator=self._session.auth) for customer in customers_stream.read_records(sync_mode=SyncMode.full_refr...
82,567
278,476
526
keras/utils/metrics_utils.py
193
24
def ragged_assert_compatible_and_get_flat_values(values, mask=None): if isinstance(values, list): is_all_ragged = all(isinstance(rt, tf.RaggedTensor) for rt in values) is_any_ragged = any(isinstance(rt, tf.RaggedTensor) for rt in values) else: is_all_ragged = isinstance(values, tf.R...
resolve line-too-long in utils
ragged_assert_compatible_and_get_flat_values
80ee2fa4e1db2dda14370110830db82be3eb97b7
keras
metrics_utils.py
16
36
https://github.com/keras-team/keras.git
14
244
0
107
405
Python
{ "docstring": "If ragged, it checks the compatibility and then returns the flat_values.\n\n Note: If two tensors are dense, it does not check their compatibility.\n Note: Although two ragged tensors with different ragged ranks could have\n identical overall rank and dimension sizes and hence ...
def ragged_assert_compatible_and_get_flat_values(values, mask=None): if isinstance(values, list): is_all_ragged = all(isinstance(rt, tf.RaggedTensor) for rt in values) is_any_ragged = any(isinstance(rt, tf.RaggedTensor) for rt in values) else: is_all_ragged = isinstance(values, tf.R...
2,286
12,428
124
jina/orchestrate/deployments/__init__.py
25
12
def update_sandbox_args(self): if self.is_sandbox: host, port = HubIO.deploy_public_sandbox(self.args) self._sandbox_deployed = True self.first_pod_args.host = host self.first_pod_args.port = port if self.head_args: self.pod_ar...
fix: do not deploy sandbox on init (#4844)
update_sandbox_args
7c4c39a9d82c58ef2493c21a288c755901a9594e
jina
__init__.py
13
9
https://github.com/jina-ai/jina.git
3
67
0
16
112
Python
{ "docstring": "Update args of all its pods based on the host and port returned by Hubble", "language": "en", "n_whitespaces": 14, "n_words": 15, "vocab_size": 15 }
def update_sandbox_args(self): if self.is_sandbox: host, port = HubIO.deploy_public_sandbox(self.args) self._sandbox_deployed = True self.first_pod_args.host = host self.first_pod_args.port = port if self.head_args: self.pod_ar...
37,328
158,146
44
d2l/mxnet.py
21
5
def download_all(): for name in DATA_HUB: download(name) DATA_HUB['kaggle_house_train'] = ( DATA_URL + 'kaggle_house_pred_train.csv', '585e9cc93e70b39160e7921475f9bcd7d31219ce') DATA_HUB['kaggle_house_test'] = ( DATA_URL + 'kaggle_house
[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...
download_all
b64b41d8c1ac23c43f7a4e3f9f6339d6f0012ab2
d2l-zh
mxnet.py
9
3
https://github.com/d2l-ai/d2l-zh.git
2
14
0
17
72
Python
{ "docstring": "Download all files in the DATA_HUB.\n\n Defined in :numref:`sec_kaggle_house`", "language": "en", "n_whitespaces": 11, "n_words": 9, "vocab_size": 8 }
def download_all(): for name in DATA_HUB: download(name) DATA_HUB['kaggle_house_train'] = ( DATA_URL + 'kaggle_house_pred_train.csv', '585e9cc93e70b39160e7921475f9bcd7d31219ce') DATA_HUB['kaggle_house_test'] = ( DATA_URL + 'kaggle_house_pred_test.csv', 'fa19780a7b011d9b009e8bff8e99922...
55,519
218,873
46
python3.10.4/Lib/lib2to3/pytree.py
14
5
def generate_matches(self, nodes): r = {} if nodes and self.match(nodes[0], r): yield 1, r
add python 3.10.4 for windows
generate_matches
8198943edd73a363c266633e1aa5b2a9e9c9f526
XX-Net
pytree.py
9
4
https://github.com/XX-net/XX-Net.git
3
31
0
13
51
Python
{ "docstring": "\n Generator yielding all matches for this pattern.\n\n Default implementation for non-wildcard patterns.\n ", "language": "en", "n_whitespaces": 34, "n_words": 12, "vocab_size": 11 }
def generate_matches(self, nodes): r = {} if nodes and self.match(nodes[0], r): yield 1, r
15,953
73,139
31
wagtail/contrib/modeladmin/helpers/permission.py
10
7
def user_can_delete_obj(self, user, obj): perm_codenam
Reformat with black
user_can_delete_obj
d10f15e55806c6944827d801cd9c2d53f5da4186
wagtail
permission.py
9
3
https://github.com/wagtail/wagtail.git
1
27
0
10
45
Python
{ "docstring": "\n Return a boolean to indicate whether `user` is permitted to 'delete'\n a specific `self.model` instance.\n ", "language": "en", "n_whitespaces": 37, "n_words": 15, "vocab_size": 13 }
def user_can_delete_obj(self, user, obj): perm_codename = self.get_perm_codename("delete") return self.user_has_specific_permission(user, perm_codename)
20,823
101,409
69
tools/preview/preview.py
18
9
def _busy_indicator_trace(self, *args) -> None: logger.trace("Busy indicator trace: %s", args) # type: ignor
Bugfix: convert - Gif Writer - Fix non-launch error on Gif Writer - convert plugins - linting - convert/fs_media/preview/queue_manager - typing - Change convert items from dict to Dataclass
_busy_indicator_trace
1022651eb8a7741014f5d2ec7cbfe882120dfa5f
faceswap
preview.py
10
13
https://github.com/deepfakes/faceswap.git
2
40
0
18
72
Python
{ "docstring": " Show or hide busy indicator based on whether the preview is updating.\n\n Parameters\n ----------\n args: unused\n Required for tkinter event, but unused\n ", "language": "en", "n_whitespaces": 62, "n_words": 22, "vocab_size": 21 }
def _busy_indicator_trace(self, *args) -> None: logger.trace("Busy indicator trace: %s", args) # type: ignore if self._busy_tkvar.get(): self._start_busy_indicator() else: self._stop_busy_indicator()
46,056
189,448
356
manim/mobject/svg/code_mobject.py
41
20
def _gen_html_string(self): self.html_string = _hilite_me( self.code_string, self.language, self.style, self.insert_line_no, "border:solid gray;bor
Hide more private methods from the docs. (#2468) * hide privs from text_mobject.py * hide privs from tex_mobject.py * hide privs from code_mobject.py * hide privs from svg_mobject.py * remove SVGPath and utils from __init__.py * don't import string_to_numbers * hide privs from geometry.py * hide p...
gen_html_string
902e7eb4f0147b5882a613b67467e38a1d47f01e
manim
code_mobject.py
16
25
https://github.com/ManimCommunity/manim.git
2
103
0
37
170
Python
{ "docstring": "Function to generate html string with code highlighted and stores in variable html_string.", "language": "en", "n_whitespaces": 12, "n_words": 13, "vocab_size": 13 }
def _gen_html_string(self): self.html_string = _hilite_me( self.code_string, self.language, self.style, self.insert_line_no, "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;", self.file_path, self....
4,155
22,074
49
pipenv/patched/pip/_vendor/requests/cookies.py
14
6
def __getstate__(self): state = self.__di
Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir.
__getstate__
cd5a9683be69c86c8f3adcd13385a9bc5db198ec
pipenv
cookies.py
9
4
https://github.com/pypa/pipenv.git
1
23
0
13
44
Python
{ "docstring": "Unlike a normal CookieJar, this class is pickleable.", "language": "en", "n_whitespaces": 7, "n_words": 8, "vocab_size": 8 }
def __getstate__(self): state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state