complexity int64 1 139 | fun_name stringlengths 1 80 | code stringlengths 101 62.2k | commit_id stringlengths 40 40 | ast_errors stringlengths 0 3.11k | ast_levels int64 6 36 | file_name stringlengths 5 79 | n_ast_nodes int64 17 19.2k | commit_message stringlengths 3 15.3k | d_id int64 12 121k | n_ast_errors int64 0 9 | n_whitespaces int64 4 10.8k | token_counts int64 5 3.06k | vocab_size int64 4 1.11k | id int64 20 338k | n_words int64 4 4.82k | repo stringlengths 3 22 | n_identifiers int64 2 176 | path stringlengths 7 134 | language stringclasses 1
value | nloc int64 1 413 | documentation dict | url stringlengths 31 59 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2 | test_id_in_matches | def test_id_in_matches(req_type):
response = graphql_query(
(
f'{req_type} {{'
)
)
assert sorted(set(response['data']['docs'][0].keys())) == sorted(
{'id', 'text', 'matches'}
)
assert len(response['data']['docs'][0]['matches']) == 2
for match in r... | bb8ab48d2008b6165a8d08cd9942c07e938f8dd5 | @pytest.mark.parametrize('req_type', ['mutation', 'query']) | 16 | test_graphql.py | 203 | feat(gateway): add graphql support (#4403) | 2,085 | 1 | 100 | 96 | 27 | 11,718 | 33 | jina | 12 | tests/integration/graphql/test_graphql.py | Python | 21 | {
"docstring": "docs(data: {text: \"abcd\"}) { \n id \n text\n matches {\n id\n }\n } \n }\n ",
"language": "en",
"n_whitespaces": 115,
"n_words": 12,
"vocab_size": 8
} | https://github.com/jina-ai/jina.git |
6 | collect_typelib_data | def collect_typelib_data(self):
datas = []
binaries = []
hiddenimports = []
logger.debug("Collecting module data for %s %s", self.name, self.version)
# Module unavailable
if not self.available:
raise ValueError(f"Module {self.name} {self.version} is... | 684bfac8adcf254fec5777f212c13eb62181f900 | 13 | gi.py | 288 | hooks: refactor GObject introspection (gi) hooks
The modules imported from gi.repository are marked as runtime
modules by their corresponding pre-safe-import-module hooks.
Therefore, their standard hooks are always loaded and executed,
regardless of whether the modue is actually importable or not.
In PyInstaller v5, ... | 77,453 | 0 | 361 | 159 | 92 | 263,828 | 129 | pyinstaller | 26 | PyInstaller/utils/hooks/gi.py | Python | 21 | {
"docstring": "\n Return a tuple of (binaries, datas, hiddenimports) to be used by PyGObject related hooks.\n ",
"language": "en",
"n_whitespaces": 29,
"n_words": 14,
"vocab_size": 14
} | https://github.com/pyinstaller/pyinstaller.git | |
1 | _generate_pdfjs_script | def _generate_pdfjs_script(filename):
url = QUrl('qute://pdfjs/file')
url_query = QUrlQuery()
url_query.addQueryItem('filename', filename)
url.setQuery(url_query)
js_url = javascript.to_js(
url.toString(QUrl.ComponentFormattingOption.FullyEncoded)) # type: ignore[arg-type]
return... | 0877fb0d78635692e481c8bde224fac5ad0dd430 | 12 | pdfjs.py | 113 | Run scripts/dev/rewrite_enums.py | 117,534 | 0 | 49 | 64 | 18 | 321,106 | 20 | qutebrowser | 18 | qutebrowser/browser/pdfjs.py | Python | 22 | {
"docstring": "Generate the script that shows the pdf with pdf.js.\n\n Args:\n filename: The name of the file to open.\n \n document.addEventListener(\"DOMContentLoaded\", function() {\n if (typeof window.PDFJS !== 'undefined') {\n // v1.x\n window.PDFJS.verbosi... | https://github.com/qutebrowser/qutebrowser.git | |
3 | _auto_format_str | def _auto_format_str(fmt, value):
try:
lbl = fmt % value
# when used in `Axes.bar_label()`` this doesn't always raise an error
# when the {}-style formatting should be used instead of %-style
if lbl == fmt:
raise TypeError
return lbl
except (TypeError, Va... | f57f30e14de5dfb59dfc22522a602084ba8c8081 | 10 | __init__.py | 64 | Add cbook function for str formatting. | 23,611 | 0 | 106 | 38 | 37 | 109,500 | 44 | matplotlib | 7 | lib/matplotlib/cbook/__init__.py | Python | 8 | {
"docstring": "\n Apply *value* to the format string *fmt*.\n\n This works both with unnamed %-style formatting and\n unnamed {}-style formatting. %-style formatting has priority.\n If *fmt* is %-style formattable that will be used. Otherwise,\n {}-formatting is applied. Strings without formatting pla... | https://github.com/matplotlib/matplotlib.git | |
2 | get_destination | def get_destination(self, obj):
if obj.destination_id is not None:
serializer = get_serializer_for_model(obj.destination, prefix=NESTED_SERIALIZER_PREFIX)
context = {'request': self.context['request']}
return serializer(obj.destination, context=context).data
... | e07dd3ddcb2b8453d5a72ccb984e456297fb8296 | 12 | serializers.py | 89 | Define NESTED_SERIALIZER_PREFIX constant | 78,093 | 0 | 75 | 55 | 19 | 265,414 | 21 | netbox | 11 | netbox/dcim/api/serializers.py | Python | 6 | {
"docstring": "\n Return the appropriate serializer for the destination, if any.\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 8
} | https://github.com/netbox-community/netbox.git | |
2 | exports | def exports(self):
result = {}
r = self.get_distinfo_resource(EXPORTS_FILENAME)
if r:
result = self.read_exports()
return result
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 10 | database.py | 53 | upd; format | 12,760 | 0 | 61 | 30 | 11 | 61,936 | 15 | transferlearning | 7 | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/database.py | Python | 6 | {
"docstring": "\n Return the information exported by this distribution.\n :return: A dictionary of exports, mapping an export category to a dict\n of :class:`ExportEntry` instances describing the individual\n export entries, and keyed by name.\n ",
"language": "... | https://github.com/jindongwang/transferlearning.git | |
2 | text | def text(self) -> str:
if self.error is None:
return str(self)
return self.error.databaseText()
| ee4d6e0396a6b570f4d5592a9c4c1a9fee1027b6 | 9 | sql.py | 48 | sql: Add *all* primary sqlite result codes
For three reasons:
- There are only 31 of them, and we don't really expect any more to
turn up (last happened in 2013, and we have a test for it happening)
- It makes for nicer debug output
- It always felt strange to only have a small subset in the enum | 117,945 | 0 | 44 | 28 | 11 | 321,852 | 12 | qutebrowser | 5 | qutebrowser/misc/sql.py | Python | 8 | {
"docstring": "Get a short text description of the error.\n\n This is a string suitable to show to the user as error message.\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 21,
"vocab_size": 18
} | https://github.com/qutebrowser/qutebrowser.git | |
3 | query | def query(self, query, **kwargs) -> Result:
try:
if self.db_conn:
result = self.db_conn.aql.execute(query, **kwargs)
return result
else:
raise AirflowException(
f"Failed to execute AQLQuery, error connecting to ... | c758c76ac336c054fd17d4b878378aa893b7a979 | 15 | arangodb.py | 109 | Adding ArangoDB Provider (#22548)
* Adding ArangoDB Provider | 8,978 | 0 | 172 | 56 | 31 | 46,739 | 39 | airflow | 13 | airflow/providers/arangodb/hooks/arangodb.py | Python | 18 | {
"docstring": "\n Function to create a arangodb session\n and execute the AQL query in the session.\n\n :param query: AQL query\n :return: Result\n ",
"language": "en",
"n_whitespaces": 56,
"n_words": 20,
"vocab_size": 17
} | https://github.com/apache/airflow.git | |
1 | nr_of_successful_entries | def nr_of_successful_entries(self) -> int:
return len(self.select_filled_orders(self.enter_side))
| bcfa73d492e3c150f0b909df58eb2c59ce6a15a6 | 10 | models.py | 35 | Add "nr_of_successfull_entries" | 34,357 | 0 | 20 | 20 | 6 | 149,011 | 6 | freqtrade | 6 | freqtrade/persistence/models.py | Python | 6 | {
"docstring": "\n Helper function to count the number of entry orders that have been filled.\n :return: int count of entry orders that have been filled for this trade.\n ",
"language": "en",
"n_whitespaces": 48,
"n_words": 26,
"vocab_size": 19
} | https://github.com/freqtrade/freqtrade.git | |
8 | argtopk | def argtopk(a_plus_idx, k, axis, keepdims):
assert keepdims is True
axis = axis[0]
if isinstance(a_plus_idx, list):
a_plus_idx = list(flatten(a_plus_idx))
a = np.concatenate([ai for ai, _ in a_plus_idx], axis)
idx = np.concatenate(
[np.broadcast_to(idxi, ai.shape) f... | 20e924618999febeac706b20212104fe4f3ea61d | 14 | chunk.py | 282 | Type annotations, part 1 (#8295) | 36,460 | 0 | 168 | 189 | 58 | 155,766 | 85 | dask | 27 | dask/array/chunk.py | Python | 17 | {
"docstring": "Chunk and combine function of argtopk\n\n Extract the indices of the k largest elements from a on the given axis.\n If k is negative, extract the indices of the -k smallest elements instead.\n Note that, unlike in the parent function, the returned elements\n are not sorted internally.\n ... | https://github.com/dask/dask.git | |
7 | split_filename | def split_filename(filename, project_name=None):
result = None
pyver = None
filename = unquote(filename).replace(' ', '-')
m = PYTHON_VERSION.search(filename)
if m:
pyver = m.group(1)
filename = filename[:m.start()]
if project_name and len(filename) > len(project_name) + 1:
... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 14 | util.py | 270 | upd; format | 12,890 | 0 | 212 | 154 | 54 | 62,169 | 84 | transferlearning | 21 | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/util.py | Python | 18 | {
"docstring": "\n Extract name, version, python version from a filename (no extension)\n\n Return name, version, pyver or None\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 16,
"vocab_size": 14
} | https://github.com/jindongwang/transferlearning.git | |
3 | numpy_pad_and_concatenate | def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
array1 = atleast_1d(array1)
array2 = atleast_1d(array2)
if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]:
return np.concatenate((array1, array2), axis=0)
# Let's figure out the new shape
new_shape = (arr... | 47412c7d434f6ddfc02a9b7ecd6182b86ae0a164 | 12 | trainer_pt_utils.py | 242 | Ensure tensors are at least 1d for pad and concat (#17179)
* Ensure tensors are at least 1d for pad and concat
* Compatibility
* Fix
* Fix
* Add test
* Retrigger CI
* Consistency with master
* Retrigger CI | 6,885 | 0 | 104 | 162 | 49 | 37,910 | 64 | transformers | 14 | src/transformers/trainer_pt_utils.py | Python | 10 | {
"docstring": "Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | https://github.com/huggingface/transformers.git | |
2 | update | def update(self) -> None:
begin = datetime.now()
delta = timedelta(days=2)
end = begin + delta
try:
df_predictions = self._station.get_data(
begin_date=begin.strftime("%Y%m%d %H:%M"),
end_date=end.strftime("%Y%m%d %H:%M"),
... | 420733a064286cfe6fc5cf11483835d15ff83462 | 14 | sensor.py | 226 | Improve entity type hints [n] (#77824) | 104,467 | 0 | 329 | 134 | 50 | 305,683 | 64 | core | 30 | homeassistant/components/noaa_tides/sensor.py | Python | 24 | {
"docstring": "Get the latest data from NOAA Tides and Currents API.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/home-assistant/core.git | |
1 | source_url | def source_url(self):
return self.metadata.source_url
download_url = source_url # Backward compatibility
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 7 | database.py | 28 | upd; format | 12,751 | 0 | 29 | 12 | 10 | 61,926 | 10 | transferlearning | 4 | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/database.py | Python | 2 | {
"docstring": "\n The source archive download URL for this distribution.\n ",
"language": "en",
"n_whitespaces": 23,
"n_words": 8,
"vocab_size": 8
} | https://github.com/jindongwang/transferlearning.git | |
1 | pcap_service_start | def pcap_service_start(askadmin=True):
# type: (bool) -> bool
return _pcap_service_control('sc start', askadmin=askadmin)
| a2b7a28faff1db058dd22ce097a268e0ad5d1d33 | 8 | __init__.py | 32 | [Hinty] Core typing: windows (#3684)
* Core typing: windows
Co-authored-by: Pierre <pierre@droids-corp.org> | 52,782 | 0 | 20 | 17 | 11 | 209,792 | 11 | scapy | 3 | scapy/arch/windows/__init__.py | Python | 2 | {
"docstring": "Starts the pcap adapter. Will ask for admin. Returns True if success",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 12
} | https://github.com/secdev/scapy.git | |
3 | create_systemd_cgroup_v1 | def create_systemd_cgroup_v1(self) -> str:
self.cgroup_path = f'/sys/fs/cgroup/systemd/ansible-test-{self.label}'
# Privileged mode is required to create the cgroup directories on some hosts, such as Fedora 36 and RHEL 9.0.
# The mkdir command will fail with "Permission denied" otherwi... | cda16cc5e9aa8703fb4e1ac0a0be6b631d9076cc | 15 | host_profiles.py | 193 | ansible-test - Improve container management. (#78550)
See changelogs/fragments/ansible-test-container-management.yml for details. | 79,634 | 0 | 251 | 84 | 75 | 268,734 | 89 | ansible | 18 | test/lib/ansible_test/_internal/host_profiles.py | Python | 13 | {
"docstring": "Create a unique ansible-test cgroup in the v1 systemd hierarchy and return its path.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 14
} | https://github.com/ansible/ansible.git | |
1 | close | def close(self):
# XXX: Should have a connect too?
# def connect(self):
#
| ab4803984bce4a4de7cc10910e7310c4babf557e | 6 | base.py | 18 | Start to add base class defs | 53,945 | 0 | 34 | 6 | 10 | 215,394 | 13 | salt | 2 | salt/transport/base.py | Python | 1 | {
"docstring": "\n Close the connection.\n \n # Connect to the server / broker.\n # ",
"language": "en",
"n_whitespaces": 39,
"n_words": 11,
"vocab_size": 9
} | https://github.com/saltstack/salt.git | |
10 | polar | def polar(a, side='right', *, method='qdwh', eps=None, max_iterations=None):
r
a = jnp.asarray(a)
if a.ndim != 2:
raise ValueError("The input `a` must be a 2-D array.")
if side not in ["right", "left"]:
raise ValueError("The argument `side` must be either 'right' or 'left'.")
m, n = a.shape
if met... | 7ba36fc1784a7a286aa13ab7c098f84ff64336f1 | 17 | linalg.py | 439 | Change implementation of jax.scipy.linalg.polar() and jax._src.scipy.eigh to use the QDWH decomposition from jax._src.lax.qdwh.
Remove jax._src.lax.polar.
PiperOrigin-RevId: 448241206 | 26,871 | 0 | 334 | 258 | 103 | 120,507 | 181 | jax | 27 | jax/_src/scipy/linalg.py | Python | 81 | {
"docstring": "Computes the polar decomposition.\n\n Given the :math:`m \\times n` matrix :math:`a`, returns the factors of the polar\n decomposition :math:`u` (also :math:`m \\times n`) and :math:`p` such that\n :math:`a = up` (if side is ``\"right\"``; :math:`p` is :math:`n \\times n`) or\n :math:`a = pu` (if ... | https://github.com/google/jax.git | |
1 | aggregate | def aggregate(self, batch_outs, batch_start=None, batch_end=None):
raise NotImplementedError("Must be implemented in subclasses.")
| 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 8 | training_utils_v1.py | 35 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,886 | 0 | 25 | 21 | 11 | 271,877 | 11 | keras | 6 | keras/engine/training_utils_v1.py | Python | 2 | {
"docstring": "Aggregates batch-level results into total results.\n\n Args:\n batch_outs: A list of batch-level outputs.\n batch_start: The start index of this batch. Always `None` if `use_steps`\n is `True`.\n batch_end: The end index of this batch. Always `None` if `use... | https://github.com/keras-team/keras.git | |
3 | get_default | def get_default():
# Since Engine is imported in django.template and since
# DjangoTemplates is a wrapper around this Engine class,
# local imports are required to avoid import loops.
from django.template import engines
from django.template.backends.django import DjangoT... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 10 | engine.py | 79 | Refs #33476 -- Reformatted code with Black. | 51,461 | 0 | 134 | 47 | 40 | 206,274 | 52 | django | 10 | django/template/engine.py | Python | 7 | {
"docstring": "\n Return the first DjangoTemplates backend that's configured, or raise\n ImproperlyConfigured if none are configured.\n\n This is required for preserving historical APIs that rely on a\n globally available, implicitly configured engine such as:\n\n >>> from django.t... | https://github.com/django/django.git | |
1 | test_get_by_name_3 | def test_get_by_name_3():
# no duplicate
ret_op_class = get_by_name("SelectPercentile", tpot_obj.operators)
# add a copy of TPOTSelectPercentile into operator list
tpot_obj.operators.append(TPOTSelectPercentile)
assert_raises(ValueError, get_by_name, "SelectPercentile", tpot_obj.operators)
| 388616b6247ca4ea8de4e2f340d6206aee523541 | 9 | export_tests.py | 62 | Revert "Deployed 7ccda9a with MkDocs version: 1.3.0"
This reverts commit bd9629c40e01241766197119b581a99409b07068. | 43,409 | 0 | 41 | 35 | 21 | 181,621 | 23 | tpot | 9 | tests/export_tests.py | Python | 4 | {
"docstring": "Assert that get_by_name raises ValueError with duplicate operators in operator dictionary.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/EpistasisLab/tpot.git | |
1 | to_dask_dataframe | def to_dask_dataframe(self, columns=None, index=None, meta=None):
from dask.dataframe import from_dask_array
return from_dask_array(self, columns=columns, index=index, meta=meta)
| cccb9d8d8e33a891396b1275c2448c352ef40c27 | 8 | core.py | 60 | absolufy-imports - No relative - PEP8 (#8796)
Conversation in https://github.com/dask/distributed/issues/5889 | 36,513 | 0 | 35 | 41 | 14 | 156,035 | 14 | dask | 8 | dask/array/core.py | Python | 3 | {
"docstring": "Convert dask Array to dask Dataframe\n\n Parameters\n ----------\n columns: list or string\n list of column names if DataFrame, single string if Series\n index : dask.dataframe.Index, optional\n An optional *dask* Index to use for the output Series or ... | https://github.com/dask/dask.git | |
1 | condition_score_with_grad | def condition_score_with_grad(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
eps = eps - (1 - alpha_bar).sqrt() * cond_fn(x, t, p_mean_var, **mod... | f4d6e64cdc132ae868699a0ba442f4ab1d304a14 | 12 | gaussian_diffusion.py | 187 | add disco_diffusion_cnclip_vitb16 module | 9,905 | 0 | 102 | 124 | 32 | 49,781 | 46 | PaddleHub | 21 | modules/image/text_to_image/disco_diffusion_cnclip_vitb16/reverse_diffusion/model/gaussian_diffusion.py | Python | 8 | {
"docstring": "\n Compute what the p_mean_variance output would have been, should the\n model's score function be conditioned by cond_fn.\n\n See condition_mean() for details on cond_fn.\n\n Unlike condition_mean(), this instead uses the conditioning strategy\n from Song et al (202... | https://github.com/PaddlePaddle/PaddleHub.git | |
3 | get_db_prep_value | def get_db_prep_value(self, value, connection=None, prepared=False):
if value is not None and not isinstance(value, PickledObject):
# We call force_str here explicitly, so that the encoded string
# isn't rejected by the postgresql_psycopg2 backend. Alternatively,
# w... | 0ad4aa9d9fe3beb3fd20aaedd961b3c2c800efb1 | 13 | fields.py | 85 | ref(django-3.2): Vendor django picklefield (#35727)
* ref(django-3.2): Vendor django picklefield
Django-picklefield hasn't been updated in 2 years, but we need it. We also need to upgrade to django 3.2 which means we need to update picklefield.
* Remove reference to django-picklefield
* Fix the module name to... | 18,774 | 0 | 183 | 53 | 70 | 91,654 | 85 | sentry | 12 | src/django_picklefield/fields.py | Python | 4 | {
"docstring": "\n Pickle and b64encode the object, optionally compressing it.\n\n The pickling protocol is specified explicitly (by default 2),\n rather than as -1 or HIGHEST_PROTOCOL, because we don't want the\n protocol to change over time. If it did, ``exact`` and ``in``\n looku... | https://github.com/getsentry/sentry.git | |
1 | test_08_sql_create_predictor | def test_08_sql_create_predictor(self):
resp = self.sql_via_http('show predictors', RESPONSE_TYPE.TABLE)
self.assertTrue(len(resp['data']) == 0)
self.sql_via_http(, RESPONSE_TYPE.OK)
status = self.await_predictor('p_test_1', timeout=120)
self.assertTrue(status == 'complete')
... | ce99adc96da2e6f98f722f9e3733af00204b26f3 | 12 | test_http.py | 313 | http test | 25,244 | 0 | 188 | 180 | 41 | 114,643 | 66 | mindsdb | 15 | tests/integration_tests/flows/test_http.py | Python | 23 | {
"docstring": "\n create predictor p_test_1\n from files (select sqft, location, rental_price from test_file limit 30)\n predict rental_price\n \n select * from mindsdb.p_test_1 where sqft = 1000\n \n select * from files.small_test_file ta join min... | https://github.com/mindsdb/mindsdb.git | |
2 | paired_manhattan_distances | def paired_manhattan_distances(X, Y):
X, Y = check_paired_arrays(X, Y)
diff = X - Y
if issparse(diff):
diff.data = np.abs(diff.data)
return np.squeeze(np.array(diff.sum(axis=1)))
else:
return np.abs(diff).sum(axis=-1)
| 912a71788eaca2a6b87aced510781cb88b38f14c | 14 | pairwise.py | 125 | DOC Update `paired_manhattan_distances` and make it pass numpydoc validation (#23900)
Co-authored-by: Thomas J. Fan <thomasjpfan@gmail.com>
Co-authored-by: Julien Jerphanion <git@jjerphan.xyz> | 76,281 | 0 | 59 | 77 | 19 | 260,485 | 23 | scikit-learn | 13 | sklearn/metrics/pairwise.py | Python | 8 | {
"docstring": "Compute the paired L1 distances between X and Y.\n\n Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ...,\n (X[n_samples], Y[n_samples]).\n\n Read more in the :ref:`User Guide <metrics>`.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n ... | https://github.com/scikit-learn/scikit-learn.git | |
3 | get_path | def get_path(cls, file_path):
if is_fsspec_url(file_path) or is_url(file_path):
return file_path
else:
return os.path.abspath(file_path)
| c5107e5be29089720528c6c0ec4f96bc2a6a1eb3 | 11 | file_dispatcher.py | 54 | FEAT-#4766: Support fsspec URLs in `read_csv` and `read_csv_glob` (#4898)
Signed-off-by: Karthik Velayutham <vkarthik@ponder.io> | 35,943 | 0 | 55 | 32 | 11 | 154,350 | 12 | modin | 8 | modin/core/io/file_dispatcher.py | Python | 5 | {
"docstring": "\n Process `file_path` in accordance to it's type.\n\n Parameters\n ----------\n file_path : str, os.PathLike[str] object or file-like object\n The file, or a path to the file. Paths to S3 buckets are also\n acceptable.\n\n Returns\n ----... | https://github.com/modin-project/modin.git | |
5 | broken_barh | def broken_barh(self, xranges, yrange, **kwargs):
# process the unit information
if len(xranges):
xdata = cbook._safe_first_non_none(xranges)
else:
xdata = None
if len(yrange):
ydata = cbook._safe_first_non_none(yrange)
else:
... | a8c01a42c5bbe96fa6c536c72e6c26954c798908 | 13 | _axes.py | 293 | BUG: modified safe_first_element and added tests
Co-authored-by: Thomas A Caswell <tcaswell@gmail.com> | 23,482 | 0 | 352 | 184 | 78 | 109,223 | 97 | matplotlib | 30 | lib/matplotlib/axes/_axes.py | Python | 24 | {
"docstring": "\n Plot a horizontal sequence of rectangles.\n\n A rectangle is drawn for each element of *xranges*. All rectangles\n have the same vertical position and size defined by *yrange*.\n\n This is a convenience function for instantiating a\n `.BrokenBarHCollection`, addin... | https://github.com/matplotlib/matplotlib.git | |
1 | test_custom_user_pk_not_named_id | def test_custom_user_pk_not_named_id(self):
context = Context({"user": CustomIdUser()})
template = Template(
"{% load log %}{% get_admin_log 10 as admin_log for_user user %}"
)
# This template tag just logs.
self.assertEqual(template.render(context), "")
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 12 | tests.py | 70 | Refs #33476 -- Reformatted code with Black. | 51,831 | 0 | 82 | 37 | 27 | 207,004 | 29 | django | 9 | tests/admin_changelist/tests.py | Python | 6 | {
"docstring": "\n {% get_admin_log %} works if the user model's primary key isn't named\n 'id'.\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 13,
"vocab_size": 13
} | https://github.com/django/django.git | |
5 | dist_is_in_project | def dist_is_in_project(self, dist):
# type: (pkg_resources.Distribution) -> bool
from .environments import normalize_pipfile_path as _normalized
prefixes = [
_normalized(prefix)
for prefix in self.base_paths["libdirs"].split(os.pathsep)
if _normalize... | 9a3b3ce70621af6f9adaa9eeac9cf83fa149319c | 15 | environment.py | 157 | Issue 4993 Add standard pre commit hooks and apply linting. (#4994)
* Add .pre-commit-config.yaml to the project and exclude tests (for now). This does not include the MyPy linting that pip does but does include everything else. | 3,056 | 0 | 149 | 95 | 34 | 19,673 | 42 | pipenv | 18 | pipenv/environment.py | Python | 12 | {
"docstring": "Determine whether the supplied distribution is in the environment.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | https://github.com/pypa/pipenv.git | |
9 | test_rate_limited | def test_rate_limited(indexer):
if isinstance(indexer, RawSimpleIndexer):
pytest.skip("mock indexer does not support rate limiting")
org_strings = {1: {"a", "b", "c"}, 2: {"e", "f"}, 3: {"g"}}
with override_options(
{
"sentry-metrics.writes-limiter.limits.releasehealth.per... | 7bbb85a0d95d23620228a02bb4401fc09658f5f1 | 15 | test_all_indexers.py | 701 | ref(metrics): Split caching out of indexers, random test refactoring [sns-1606] (#37714) | 19,098 | 0 | 626 | 431 | 116 | 94,501 | 216 | sentry | 31 | tests/sentry/sentry_metrics/test_all_indexers.py | Python | 60 | {
"docstring": "\n Assert that rate limits per-org and globally are applied at all.\n\n Since we don't have control over ordering in sets/dicts, we have no\n control over which string gets rate-limited. That makes assertions\n quite awkward and imprecise.\n ",
"language": "en",
"n_whitespaces": 52,... | https://github.com/getsentry/sentry.git | |
2 | key_aliases | def key_aliases(self) -> Iterable[str]:
for alias in _get_key_aliases(self.key):
yield _normalize_key(alias)
| bd3a723d86f9c550b0324153975580b70509cb22 | 10 | events.py | 44 | Move aliasing/normalisation logic into Key | 44,978 | 0 | 35 | 26 | 10 | 185,332 | 10 | textual | 8 | src/textual/events.py | Python | 4 | {
"docstring": "Get the aliases for the key, including the key itself",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 8
} | https://github.com/Textualize/textual.git | |
3 | get_primary_key_column | def get_primary_key_column(self, cursor, table_name):
for constraint in self.get_constraints(cursor, table_name).values():
if constraint["primary_key"]:
return constraint["columns"][0]
return None
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 12 | introspection.py | 68 | Refs #33476 -- Reformatted code with Black. | 50,933 | 0 | 62 | 42 | 14 | 204,855 | 15 | django | 7 | django/db/backends/base/introspection.py | Python | 5 | {
"docstring": "\n Return the name of the primary key column for the given table.\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 12,
"vocab_size": 10
} | https://github.com/django/django.git | |
2 | cosine_similarity | def cosine_similarity(X, Y=None, dense_output=True):
# to avoid recursive import
X, Y = check_pairwise_arrays(X, Y)
X_normalized = normalize(X, copy=True)
if X is Y:
Y_normalized = X_normalized
else:
Y_normalized = normalize(Y, copy=True)
K = safe_sparse_dot(X_normalized,... | 60c5d320e1478514e6bbe31fd0347692591cca9e | 12 | pairwise.py | 110 | DOC Ensure `cosine_similarity` passes numpydoc validation (#23947) | 76,294 | 0 | 75 | 70 | 29 | 260,499 | 37 | scikit-learn | 12 | sklearn/metrics/pairwise.py | Python | 9 | {
"docstring": "Compute cosine similarity between samples in X and Y.\n\n Cosine similarity, or the cosine kernel, computes similarity as the\n normalized dot product of X and Y:\n\n K(X, Y) = <X, Y> / (||X||*||Y||)\n\n On L2-normalized data, this function is equivalent to linear_kernel.\n\n Read m... | https://github.com/scikit-learn/scikit-learn.git | |
2 | _is_env_truthy | def _is_env_truthy(name):
if name not in os.environ:
return False
return os.environ.get(name).lower() not in _false_values
| 9a3b3ce70621af6f9adaa9eeac9cf83fa149319c | 11 | environments.py | 53 | Issue 4993 Add standard pre commit hooks and apply linting. (#4994)
* Add .pre-commit-config.yaml to the project and exclude tests (for now). This does not include the MyPy linting that pip does but does include everything else. | 3,067 | 0 | 30 | 32 | 11 | 19,689 | 14 | pipenv | 7 | pipenv/environments.py | Python | 4 | {
"docstring": "An environment variable is truthy if it exists and isn't one of (0, false, no, off)",
"language": "en",
"n_whitespaces": 15,
"n_words": 16,
"vocab_size": 16
} | https://github.com/pypa/pipenv.git | |
4 | min_weight_matching | def min_weight_matching(G, maxcardinality=False, weight="weight"):
if len(G.edges) == 0:
return max_weight_matching(G, maxcardinality, weight)
G_edges = G.edges(data=weight, default=1)
min_weight = min(w for _, _, w in G_edges)
InvG = nx.Graph()
edges = ((u, v, 1 / (1 + w - min_weight))... | 28b3014d68d2b4e40d3e02219770296a827bd55c | @not_implemented_for("multigraph")
@not_implemented_for("directed") | 12 | matching.py | 191 | Update matching functions for error validation and speed (#4897)
* First steps to update matching functions for #4644
Expand tests
Change API to raise NetworkXError when matching involves nodes not in G
Update is_*_matching to 100+ times faster.
* improve matching_dict_to_set and docs for min_weight_matching
... | 41,855 | 1 | 82 | 114 | 40 | 176,369 | 53 | networkx | 21 | networkx/algorithms/matching.py | Python | 9 | {
"docstring": "Computing a minimum-weight maximal matching of G.\n\n Use reciprocal edge weights with the maximum-weight algorithm.\n\n A matching is a subset of edges in which no node occurs more than once.\n The weight of a matching is the sum of the weights of its edges.\n A maximal matching cannot ad... | https://github.com/networkx/networkx.git |
6 | is_datetime64_ns_dtype | def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
if arr_or_dtype is None:
return False
try:
tipo = get_dtype(arr_or_dtype)
except TypeError:
if is_datetime64tz_dtype(arr_or_dtype):
tipo = get_dtype(arr_or_dtype.dtype)
else:
return False
retur... | 67e8c4c3761ab1da4b0a341a472c0fe2ea393e8b | 14 | common.py | 106 | ENH: DTI/DTA.astype support non-nano (#47579)
* ENH: DTI/DTA.astype support non-nano
* whatsnew
* GH ref
* pyright fixup | 40,074 | 0 | 112 | 63 | 29 | 167,667 | 37 | pandas | 12 | pandas/core/dtypes/common.py | Python | 47 | {
"docstring": "\n Check whether the provided array or dtype is of the datetime64[ns] dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like or dtype\n The array or dtype to check.\n\n Returns\n -------\n bool\n Whether or not the array or dtype is of the datetime64[ns] dtyp... | https://github.com/pandas-dev/pandas.git | |
1 | raise_on_deprecated | def raise_on_deprecated():
with warnings.catch_warnings():
warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
yield
| 6d2bbf80752549276a968fd4af78231c569d55c5 | 11 | runtests.py | 54 | runtests.py: Undo auto-formatting, re-add changes to blacklist for scipy, numpy | 49,585 | 0 | 29 | 27 | 9 | 200,290 | 9 | sympy | 6 | sympy/testing/runtests.py | Python | 4 | {
"docstring": "Context manager to make DeprecationWarning raise an error\n\n This is to catch SymPyDeprecationWarning from library code while running\n tests and doctests. It is important to use this context manager around\n each individual test/doctest in case some tests modify the warning\n filters.\n ... | https://github.com/sympy/sympy.git | |
5 | _update_mean_variance | def _update_mean_variance(n_past, mu, var, X, sample_weight=None):
if X.shape[0] == 0:
return mu, var
# Compute (potentially weighted) mean and variance of new datapoints
if sample_weight is not None:
n_new = float(sample_weight.sum())
if np.isclose(... | 2cce02414d4a7161f0d105450c196d94b1182220 | 13 | naive_bayes.py | 314 | TST Add common tests for single class fitting induced by sample weights (#24140)
Co-authored-by: johayon <johayon.math@gmail.com>
Co-authored-by: Guillaume Lemaitre <g.lemaitre58@gmail.com> | 77,021 | 0 | 402 | 204 | 81 | 261,829 | 162 | scikit-learn | 24 | sklearn/naive_bayes.py | Python | 22 | {
"docstring": "Compute online update of Gaussian mean and variance.\n\n Given starting sample count, mean, and variance, a new set of\n points X, and optionally sample weights, return the updated mean and\n variance. (NB - each dimension (column) in X is treated as independent\n -- you ge... | https://github.com/scikit-learn/scikit-learn.git | |
6 | serving_output | def serving_output(self, output):
pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions e... | c72d7d91bf4899760725793421eff9da640c8527 | @add_start_docstrings(
"""
The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
embeddings).
""",
XGLM_START_DOCSTRING,
) | 11 | modeling_tf_xglm.py | 180 | Add TF implementation of `XGLMModel` (#16543)
* Add TFXGLM models
* Add todo: self.supports_xla_generation = False
Co-authored-by: Daniel Stancl <stancld@Daniels-MacBook-Pro.local>
Co-authored-by: Daniel Stancl <stancld@daniels-mbp.home>
Co-authored-by: Joao Gante <joaofranciscocardosogante@gmail.com>
Co-aut... | 6,060 | 1 | 187 | 113 | 32 | 33,107 | 47 | transformers | 22 | src/transformers/models/xglm/modeling_tf_xglm.py | Python | 16 | {
"docstring": "\n The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input\n embeddings).\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 20,
"vocab_size": 19
} | https://github.com/huggingface/transformers.git |
1 | get_period_wise_query | def get_period_wise_query(bet_dates, trans_date, query_details):
query_details += % {
"trans_date": trans_date,
"sd": bet_dates[0],
"ed": bet_dates[1],
}
return query_details
@frappe.whitelist(allow_guest=True) | 494bd9ef78313436f0424b918f200dab8fc7c20b | @frappe.whitelist(allow_guest=True) | 10 | trends.py | 72 | style: format code with black | 13,987 | 1 | 11 | 35 | 16 | 65,688 | 18 | erpnext | 7 | erpnext/controllers/trends.py | Python | 9 | {
"docstring": "SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.stock_qty, NULL)),\n\t\t\t\t\tSUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.base_net_amount, NULL)),\n\t\t\t\t",
"language": "en",
"n_whitespaces": 12,
"n_words": 14,
"vocab_size": 8
} | https://github.com/frappe/erpnext.git |
2 | DeveloperAPI | def DeveloperAPI(obj):
if not obj.__doc__:
obj.__doc__ = ""
obj.__doc__ += "\n DeveloperAPI: This API may change across minor Ray releases."
return obj
| 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | 9 | annotations.py | 47 | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 29,859 | 0 | 44 | 24 | 21 | 132,900 | 22 | ray | 3 | python/ray/util/annotations.py | Python | 5 | {
"docstring": "Annotation for documenting developer APIs.\n\n Developer APIs are lower-level methods explicitly exposed to advanced Ray\n users and library developers. Their interfaces may change across minor\n Ray releases.\n\n Examples:\n >>> @DeveloperAPI\n >>> def func(x):\n >>> ... | https://github.com/ray-project/ray.git | |
2 | _set_gradient_checkpointing | def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, Data2VecVisionEncoder):
module.gradient_checkpointing = value
DATA2VEC_VISION_START_DOCSTRING = r
DATA2VEC_VISION_INPUTS_DOCSTRING = r
@add_start_docstrings(
"The bare Data2VecVision Model transformer outputti... | 8d3f952adb8c98cec2ea1f59bb7acfbc08232381 | @add_start_docstrings(
"The bare Data2VecVision Model transformer outputting raw hidden-states without any specific head on top.",
DATA2VEC_VISION_START_DOCSTRING,
) | 9 | modeling_data2vec_vision.py | 65 | [Data2Vec] Add data2vec vision (#16760)
* save intermediate
* add vision
* add vision
* save
* finish models
* finish models
* continue
* finish
* up
* up
* up
* tests all pass
* clean up
* up
* up
* fix bugs in beit
* correct docs
* finish
* finish docs
* make ... | 6,754 | 1 | 57 | 24 | 36 | 37,208 | 39 | transformers | 10 | src/transformers/models/data2vec/modeling_data2vec_vision.py | Python | 3 | {
"docstring": "\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`Data2VecVis... | https://github.com/huggingface/transformers.git |
1 | truncate | def truncate(self, size=None):
# type: (Optional[int]) -> int
return self._file.truncate(size)
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 8 | lazy_wheel.py | 33 | upd; format | 12,321 | 0 | 31 | 19 | 10 | 60,887 | 10 | transferlearning | 4 | .venv/lib/python3.8/site-packages/pip/_internal/network/lazy_wheel.py | Python | 2 | {
"docstring": "Resize the stream to the given size in bytes.\n\n If size is unspecified resize to the current position.\n The current stream position isn't changed.\n\n Return the new file size.\n ",
"language": "en",
"n_whitespaces": 57,
"n_words": 29,
"vocab_size": 22
} | https://github.com/jindongwang/transferlearning.git | |
1 | test_crash_rate_alert_for_sessions_with_critical_warning_then_resolved | def test_crash_rate_alert_for_sessions_with_critical_warning_then_resolved(self):
rule = self.crash_rate_alert_rule
trigger = self.crash_rate_alert_critical_trigger
trigger_warning = self.crash_rate_alert_warning_trigger
action_critical = self.crash_rate_alert_critical_action
... | 146fba432a32568be7d0b884dae0c39a6c33a11f | 14 | test_subscription_processor.py | 468 | fix(metric_alerts): Make sure critical triggers resolve properly when no action is set on a warning trigger (#31883)
### Problem
If we have an alert set up like:
- Warning: 50. Action: None
- Critical: 100. Action: Slack
Then if we go from critical -> warning state the slack resolve action will fail to fire.
... | 19,312 | 0 | 476 | 320 | 58 | 96,433 | 108 | sentry | 37 | tests/sentry/incidents/test_subscription_processor.py | Python | 41 | {
"docstring": "\n Test that tests the behavior of going from Critical status to Warning status to Resolved\n for Crash Rate Alerts\n ",
"language": "en",
"n_whitespaces": 41,
"n_words": 19,
"vocab_size": 17
} | https://github.com/getsentry/sentry.git | |
5 | test_dangling_matrix | def test_dangling_matrix(self):
G = self.G
dangling = self.dangling_edges
dangling_sum = sum(dangling.values())
M1 = nx.google_matrix(G, personalization=dangling)
M2 = nx.google_matrix(G, personalization=dangling, dangling=dangling)
for i in range(len(G)):
... | 2a05ccdb07cff88e56661dee8a9271859354027f | 17 | test_pagerank.py | 214 | Remove redundant py2 numeric conversions (#5661)
* Remove redundant float conversion
* Remove redundant int conversion
* Use integer division
Co-authored-by: Miroslav Šedivý <6774676+eumiro@users.noreply.github.com> | 42,054 | 0 | 228 | 145 | 42 | 176,719 | 58 | networkx | 21 | networkx/algorithms/link_analysis/tests/test_pagerank.py | Python | 14 | {
"docstring": "\n Tests that the google_matrix doesn't change except for the dangling\n nodes.\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 11,
"vocab_size": 10
} | https://github.com/networkx/networkx.git | |
6 | search_query | def search_query(self, term, config_read_column, *join):
term.strip().lower()
self.session.connection().connection.connection.create_function("lower", 1, lcase)
q = list()
authorterms = re.split("[, ]+", term)
for authorterm in authorterms:
q.append(Books.authors.any(... | 32a3c45ee0f7e13bd61075f32a4dcebc415585a1 | 17 | db.py | 567 | Refactored load read status for web access and opds access
Refactored and removed discover html page
Bugfix show author
Bugfix open dialog in author page
Fix for #2341 (advanced search with linked read column and read column having a higher number than number of available custom columns) | 40,821 | 0 | 331 | 353 | 64 | 172,886 | 103 | calibre-web | 40 | cps/db.py | Python | 39 | {
"docstring": "if not config_read_column:\n query = (self.session.query(Books, ub.ArchivedBook.is_archived, ub.ReadBook).select_from(Books)\n .outerjoin(ub.ReadBook, and_(Books.id == ub.ReadBook.book_id,\n int(current_user.id) == ub.Read... | https://github.com/janeczku/calibre-web.git | |
2 | get_items | def get_items(filters):
conditions = get_conditions(filters)
match_conditions = frappe.build_match_conditions("Sales Invoice")
if match_conditions:
match_conditions = " and {0} ".format(match_conditions)
items = frappe.db.sql(
% (conditions, match_conditions),
filters,
as_dict=1,
)
=======
`tabSales... | d99b4e29b95db9c3ae9a2852a9757977e4912096 | =======
`tabSales Invoice Item`.`as_dict=1)
>>>>>>> 363752510fix:summary of outward supplies Updated | 11 | hsn_wise_summary_of_outward_supplies.py | 158 | fix: HSN-wise-summary of outward supplies Updated Report
Report changes done in order to meet the specification as per govt guideline - [GUIDELINE](https://taxguru.in/goods-and-service-tax/12-points-note-filing-gstr-1-01st-2021-onwards.html)
(cherry picked from commit 363752510ead7d3b86693d3659b2157753f2762d)
# Conf... | 14,805 | 5 | 20 | 53 | 27 | 68,515 | 33 | erpnext | 27 | erpnext/regional/report/hsn_wise_summary_of_outward_supplies/hsn_wise_summary_of_outward_supplies.py | Python | 38 | {
"docstring": "\n\t\tselect\n\t\t\t`tabSales Invoice Item`.gst_hsn_code,\n\t\t\t`tabSales Invoice Item`.stock_uom,\n\t\t\tsum(`tabSales Invoice Item`.stock_qty) as stock_qty,\n\t\t\tsum(`tabSales Invoice Item`.base_net_amount) as base_net_amount,\n\t\t\tsum(`tabSales Invoice Item`.base_price_list_rate) as base_price... | https://github.com/frappe/erpnext.git |
2 | intersection_over_box | def intersection_over_box(chips, boxes):
M = chips.shape[0]
N = boxes.shape[0]
if M * N == 0:
return np.zeros([M, N], dtype='float32')
box_area = bbox_area(boxes) # B
inter_x2y2 = np.minimum(np.expand_dims(chips, 1)[:, :, 2:],
boxes[:, 2:]) # CxBX2
in... | da0157cf64aef2b7bf54a46e9cd1fbdea8b38f3e | 11 | chip_box_utils.py | 259 | update numpy 1.24 (#7552) | 53,153 | 0 | 174 | 168 | 47 | 211,859 | 73 | PaddleDetection | 22 | ppdet/data/crop_utils/chip_box_utils.py | Python | 15 | {
"docstring": "\n intersection area over box area\n :param chips: C\n :param boxes: B\n :return: iob, CxB\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 14,
"vocab_size": 12
} | https://github.com/PaddlePaddle/PaddleDetection.git | |
1 | samefile | def samefile(f1, f2):
s1 = os.stat(f1)
s2 = os.stat(f2)
return samestat(s1, s2)
# Are two open files really referencing the same file?
# (Not necessarily the same file descriptor!) | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 8 | genericpath.py | 53 | add python 3.10.4 for windows | 54,828 | 0 | 39 | 31 | 25 | 217,515 | 29 | XX-Net | 8 | python3.10.4/Lib/genericpath.py | Python | 4 | {
"docstring": "Test whether two pathnames reference the same actual file or directory\n\n This is determined by the device number and i-node number and\n raises an exception if an os.stat() call on either pathname fails.\n ",
"language": "en",
"n_whitespaces": 42,
"n_words": 33,
"vocab_size": 29
} | https://github.com/XX-net/XX-Net.git | |
2 | line | def line(loc, strg):
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR + 1:nextCR]
else:
return strg[lastCR + 1:]
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 11 | pyparsing.py | 90 | upd; format | 13,281 | 0 | 54 | 54 | 19 | 63,386 | 25 | transferlearning | 7 | .venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py | Python | 7 | {
"docstring": "Returns the line of text containing loc within a string, counting newlines as line separators.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 15,
"vocab_size": 14
} | https://github.com/jindongwang/transferlearning.git | |
2 | _sort_rules | def _sort_rules(self) -> None:
if not self._rules:
return
self._rules.sort(key=len, reverse=True)
| 5f5d69722ff6c28ce46ebc958eb9d44d36cbf75b | 8 | tree.py | 49 | feat(txcluster): Discard rules with all `*`s (#42076)
Rules consisting of all `*`s aren't helpful and provide a worse user
experience, so we want to get rid of them. All `*` rules are produced
when the merge threshold is not high enough for the existing data, and
they look like the following:
```json
"rules":... | 18,542 | 0 | 42 | 29 | 10 | 89,462 | 10 | sentry | 7 | src/sentry/ingest/transaction_clusterer/tree.py | Python | 5 | {
"docstring": "Sorts the rules by path length, descending (most specific rule first).",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/getsentry/sentry.git | |
7 | _resize_worker_group | def _resize_worker_group(self, state_dict, max_retries=10):
old_workers = self.worker_group.num_workers
self.worker_group.reset()
time.sleep(1)
for i in range(max_retries):
new_workers = self.worker_group.new_workers_size()
if new_workers:
... | 7f1bacc7dc9caf6d0ec042e39499bbf1d9a7d065 | 18 | torch_trainer.py | 294 | [CI] Format Python code with Black (#21975)
See #21316 and #21311 for the motivation behind these changes. | 29,987 | 0 | 585 | 169 | 92 | 133,356 | 119 | ray | 33 | python/ray/util/sgd/torch/torch_trainer.py | Python | 26 | {
"docstring": "Resizes the number of remote workers based on available resources.\n Total number of workers will never exceed `num_workers` amount.\n\n Args:\n state_dict (dict): The state dict to load to all workers.\n max_retries (int): How many times to attempt to resize worker... | https://github.com/ray-project/ray.git | |
60 | readfortrancode | def readfortrancode(ffile, dowithline=show, istop=1):
global gotnextfile, filepositiontext, currentfilename, sourcecodeform, strictf77
global beginpattern, quiet, verbose, dolowercase, include_paths
if not istop:
saveglobals = gotnextfile, filepositiontext, currentfilename, sourcecodeform, str... | d4e11c7a2eb64861275facb076d47ccd135fa28c | 22 | crackfortran.py | 3,370 | ENH: Support character string arrays
TST: added test for issue #18684
ENH: f2py opens files with correct encoding, fixes #635
TST: added test for issue #6308
TST: added test for issue #4519
TST: added test for issue #3425
ENH: Implement user-defined hooks support for post-processing f2py data structure. Implement... | 38,652 | 0 | 155 | 1,187 | 57 | 160,531 | 78 | numpy | 119 | numpy/f2py/crackfortran.py | Python | 201 | {
"docstring": "\n Read fortran codes from files and\n 1) Get rid of comments, line continuations, and empty lines; lower cases.\n 2) Call dowithline(line) on every line.\n 3) Recursively call itself when statement \\\"include '<filename>'\\\" is met.\n \")\n if istop:\n dowithline('', -1)... | https://github.com/numpy/numpy.git | |
2 | _get_streams | def _get_streams(self):
self.session.http.headers.update({
"User-Agent": useragents.CHROME,
"Referer": self.url,
})
re_m3u8 = re.compile(
r,
re.VERBOSE,
)
hls_url = self.session.http.get(self.url, schema=validate.Schema(
... | f7cbfae2621d6dd2f9f1189cf98a59ba64ff9721 | 23 | rtpplay.py | 399 | plugins: move and refactor validation schemas
Refactor validation schemas of plugins where schemas are defined as
class attributes and where no major changes are needed:
- Move validation schemas from class attributes to schema definitions
- Apply minor validation schema adjustments (eg. union_get)
- Use `validate.no... | 45,806 | 0 | 634 | 251 | 44 | 187,554 | 63 | streamlink | 38 | src/streamlink/plugins/rtpplay.py | Python | 48 | {
"docstring": "\n hls\\s*:\\s*(?:\n (?P<q>[\"'])(?P<string>.*?)(?P=q)\n |\n decodeURIComponent\\s*\\((?P<obfuscated>\\[.*?])\\.join\\(\n |\n atob\\s*\\(\\s*decodeURIComponent\\s*\\((?P<obfuscated_b64>\\[.*?]... | https://github.com/streamlink/streamlink.git | |
1 | fit | def fit(self, X, y, sample_weight=None):
self._validate_params()
_accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver)
X, y = self._validate_data(
X,
y,
accept_sparse=_accept_sparse,
dtype=[np.float64, np.float32],
... | b7721135a0d3df30e5a1a1c34156421b55fe67ca | 11 | _ridge.py | 126 | MAINT validate parameters in Ridge (#23563)
Co-authored-by: jeremie du boisberranger <jeremiedbb@yahoo.fr>
Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com> | 76,169 | 0 | 134 | 86 | 21 | 260,299 | 26 | scikit-learn | 20 | sklearn/linear_model/_ridge.py | Python | 12 | {
"docstring": "Fit Ridge regression model.\n\n Parameters\n ----------\n X : {ndarray, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : ndarray of shape (n_samples,) or (n_samples, n_targets)\n Target values.\n\n sample_weight : float o... | https://github.com/scikit-learn/scikit-learn.git | |
2 | _prepare_options | def _prepare_options(self) -> None:
super()._prepare_options()
self.options.restart_cmd[0] = 'apachectl'
if not self.options.restart_cmd_alt: # pragma: no cover
raise ValueError("OS option restart_cmd_alt must be set for Fedora.")
self.options.restart_cmd_alt[0] = '... | 7d9e9a49005de7961e84d2a7c608db57dbab3046 | 10 | override_fedora.py | 104 | Add typing to certbot.apache (#9071)
* Add typing to certbot.apache
Co-authored-by: Adrien Ferrand <ferrand.ad@gmail.com> | 45,574 | 0 | 84 | 58 | 26 | 186,667 | 30 | certbot | 8 | certbot-apache/certbot_apache/_internal/override_fedora.py | Python | 12 | {
"docstring": "\n Override the options dictionary initialization to keep using apachectl\n instead of httpd and so take advantages of this new bash script in newer versions\n of Fedora to restart httpd.\n ",
"language": "en",
"n_whitespaces": 58,
"n_words": 29,
"vocab_size": 26
} | https://github.com/certbot/certbot.git | |
4 | johnson_lindenstrauss_min_dim | def johnson_lindenstrauss_min_dim(n_samples, *, eps=0.1):
eps = np.asarray(eps)
n_samples = np.asarray(n_samples)
if np.any(eps <= 0.0) or np.any(eps >= 1):
raise ValueError("The JL bound is defined for eps in ]0, 1[, got %r" % eps)
if np.any(n_samples) <= 0:
raise ValueError(
... | 1fc86b6aacd89da44a3b4e8abf7c3e2ba4336ffe | 12 | random_projection.py | 177 | MNT Update black to stable version (#22474) | 75,490 | 0 | 133 | 112 | 50 | 258,948 | 69 | scikit-learn | 11 | sklearn/random_projection.py | Python | 12 | {
"docstring": "Find a 'safe' number of components to randomly project to.\n\n The distortion introduced by a random projection `p` only changes the\n distance between two points by a factor (1 +- eps) in an euclidean space\n with good probability. The projection `p` is an eps-embedding as defined\n by:\n... | https://github.com/scikit-learn/scikit-learn.git | |
7 | act | def act(self):
obs = self.observation
reply = {'text': INVALID, 'id': self.getID(), 'episode_done': False}
if obs is None or obs['text'] == DO_NOT_RETRIEVE:
return Message(reply)
# construct the search query
labels = obs.get('labels', obs.get('eval_labels', ... | 7e453008fde751aff0cfd752662e19fe2adc7410 | 13 | generate_lm_data.py | 379 | SeeKeR (#4447)
* seeker
* todo
* readme updates; add test
* small config changes
* various updates
* readme fix
* model card
* add arxiv link
* surround spacy with try catch
* more protected
* more protection of imports
* lint | 47,131 | 0 | 343 | 219 | 74 | 194,950 | 102 | ParlAI | 31 | projects/seeker/scripts/generate_lm_data.py | Python | 25 | {
"docstring": "\n Search for overlap with the observation label.\n\n Return the best fitting document. A document is valid if the f1 is above the\n threshold AND the f1 is less than 1.0 AND the target label is not in the\n document.\n ",
"language": "en",
"n_whitespaces": 75,
... | https://github.com/facebookresearch/ParlAI.git | |
1 | test_thread_with_bundled_aggregations_for_latest | def test_thread_with_bundled_aggregations_for_latest(self) -> None:
self._send_relation(RelationTypes.THREAD, "m.room.test")
channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
thread_2 = channel.json_body["event_id"]
self._send_relation(
RelationType... | 75dff3dc980974960f55fa21fc8e672201f63045 | 9 | test_relations.py | 93 | Include bundled aggregations for the latest event in a thread. (#12273)
The `latest_event` field of the bundled aggregations for `m.thread` relations
did not include bundled aggregations itself. This resulted in clients needing to
immediately request the event from the server (and thus making it useless that
the la... | 72,127 | 0 | 72 | 68 | 16 | 248,149 | 19 | synapse | 10 | tests/rest/client/test_relations.py | Python | 12 | {
"docstring": "\n Bundled aggregations should get applied to the latest thread event.\n ",
"language": "en",
"n_whitespaces": 25,
"n_words": 10,
"vocab_size": 10
} | https://github.com/matrix-org/synapse.git | |
1 | map | def map(self, arg, na_action=None) -> Series:
new_values = self._map_values(arg, na_action=na_action)
return self._constructor(new_values, index=self.index).__finalize__(
self, method="map"
)
| 521259299f7829da667ba39302ec77acedde9e5e | 11 | series.py | 75 | DOC: Improve doc summaries in series.rst (#45237) | 39,401 | 0 | 55 | 48 | 16 | 163,193 | 16 | pandas | 11 | pandas/core/series.py | Python | 79 | {
"docstring": "\n Map values of Series according to an input mapping or function.\n\n Used for substituting each value in a Series with another value,\n that may be derived from a function, a ``dict`` or\n a :class:`Series`.\n\n Parameters\n ----------\n arg : functio... | https://github.com/pandas-dev/pandas.git | |
8 | _validate_encoder_architecture | def _validate_encoder_architecture(self):
arch = self.config["enc_architecture"].lower()
model = _MODEL_MAPPING.get(arch)
if not model:
raise FaceswapError(f"'{arch}' is not a valid choice for encoder architecture. Choose "
f"one of {list(_MOD... | aa39234538a8f83e6aa2b60b8275a570e8876ac2 | 16 | phaze_a.py | 281 | Update all Keras Imports to be conditional (#1214)
* Remove custom keras importer
* first round keras imports fix
* launcher.py: Remove KerasFinder references
* 2nd round keras imports update (lib and extract)
* 3rd round keras imports update (train)
* remove KerasFinder from tests
* 4th round keras ... | 19,941 | 0 | 323 | 138 | 65 | 100,467 | 98 | faceswap | 23 | plugins/train/model/phaze_a.py | Python | 16 | {
"docstring": " Validate that the requested architecture is a valid choice for the running system\n configuration.\n\n If the selection is not valid, an error is logged and system exits.\n ",
"language": "en",
"n_whitespaces": 49,
"n_words": 27,
"vocab_size": 22
} | https://github.com/deepfakes/faceswap.git | |
4 | gallery_image_warning_filter | def gallery_image_warning_filter(record):
msg = record.msg
for gallery_dir in sphinx_gallery_conf['gallery_dirs']:
if msg.startswith(f'image file not readable: {gallery_dir}'):
return False
if msg == 'Could not obtain image size. :scale: option is ignored.':
... | 1374e34d2f5cb9c424fc0ae4a9495f3e562e4b06 | 14 | conf.py | 418 | filter warnings | 23,672 | 0 | 507 | 38 | 279 | 109,615 | 446 | matplotlib | 45 | doc/conf.py | Python | 8 | {
"docstring": "\n.. DO NOT EDIT.\n.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.\n.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:\n.. \"{0}\"\n.. LINE NUMBERS ARE GIVEN BELOW.\n\n.. only:: html\n\n .. meta::\n :keywords: codex\n\n .. note::\n :class: sphx-glr-download-link-note\n\n ... | https://github.com/matplotlib/matplotlib.git | |
2 | _create_default_prometheus_configs | def _create_default_prometheus_configs(self):
prometheus_config_output_path = os.path.join(
self.metrics_root, "prometheus", "prometheus.yml"
)
# Copy default prometheus configurations
if os.path.exists(prometheus_config_output_path):
os.remove(prometheu... | 42da4445e7a3cb358a1a02ae433a004e9fa836b5 | 10 | metrics_head.py | 105 | Export default configurations for grafana and prometheus (#28286) | 28,527 | 0 | 92 | 63 | 21 | 127,791 | 21 | ray | 15 | dashboard/modules/metrics/metrics_head.py | Python | 8 | {
"docstring": "\n Creates the prometheus configurations that are by default provided by Ray.\n This will completely replace the `/tmp/ray/metrics/prometheus` folder.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 16
} | https://github.com/ray-project/ray.git | |
3 | set_connectionstyle | def set_connectionstyle(self, connectionstyle=None, **kwargs):
if connectionstyle is None:
return ConnectionStyle.pprint_styles()
self._connector = (
ConnectionStyle(connectionstyle, **kwargs)
if isinstance(connectionstyle, str) else connectionstyle)
... | 0dc472b4c7cdcc1e88228988fff17762c90f1cb9 | 11 | patches.py | 80 | Harmonize docstrings for boxstyle/connectionstyle/arrowstyle.
- Rely on `__init_subclass__` to avoid the need for the out-of-order
`interpd.update`/`dedent_interpd`.
- Use consistent wording for all setters, and add ACCEPTS list in all
cases.
- Move get_boxstyle right next to set_boxstyle (consistently with the
... | 23,577 | 0 | 84 | 51 | 21 | 109,425 | 23 | matplotlib | 10 | lib/matplotlib/patches.py | Python | 7 | {
"docstring": "\n Set the connection style, possibly with further attributes.\n\n Attributes from the previous connection style are not reused.\n\n Without argument (or with ``connectionstyle=None``), the available box\n styles are returned as a human-readable string.\n\n Parameter... | https://github.com/matplotlib/matplotlib.git | |
2 | formatTime | def formatTime(self, record, datefmt=None):
ct = dt.datetime.fromtimestamp(record.created)
if datefmt:
s = ct.strftime(datefmt)
else:
# Format datetime object ct to microseconds
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = f"{t},{record.msecs:... | 49fc2cf3733f20ac6cf8a7c61e42ef7aa5cf4b03 | 12 | config.py | 100 | 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... | 35,586 | 0 | 108 | 51 | 23 | 153,755 | 29 | modin | 13 | modin/logging/config.py | Python | 8 | {
"docstring": "\n Return the creation time of the specified LogRecord as formatted text.\n\n This custom logging formatter inherits from the logging module and\n records timestamps at the microsecond level of granularity.\n\n Parameters\n ----------\n record : LogRecord\n ... | https://github.com/modin-project/modin.git | |
1 | host_local_array_to_global_array | def host_local_array_to_global_array(local_inputs, global_mesh, pspecs):
def _convert(arr, pspec):
if isinstance(arr, array.ArrayImpl) and isinstance(arr.sharding, PmapSharding):
arr = np.array(arr)
local_sharding = MeshPspecSharding(global_mesh.local_mesh, pspec)
arrays = [
device_put(ar... | 4da72cf3988b4918f65b1401e46c40b7c4504963 | 15 | pjit.py | 262 | Add `host_local_array_to_global_array` and `global_array_to_host_local_array` for enabling transition to jax.Array.
Also support `FROM_GDA` for `jax.Array` as a backwards compatible change so that users can continue to use that until they transition to jax.Array. Its currently required because of usage like `in_axis_r... | 27,124 | 0 | 151 | 54 | 55 | 122,219 | 63 | jax | 41 | jax/experimental/pjit.py | Python | 7 | {
"docstring": "Converts a host local value to a globally sharded `jax.Array`.\n\n You can use this function to transition to `jax.Array`. Using `jax.Array` with\n `pjit` has the same semantics of using GDA with pjit i.e. all `jax.Array`\n inputs to pjit should be globally shaped.\n\n If you are currently passing... | https://github.com/google/jax.git | |
2 | get_charsets | def get_charsets(self, failobj=None):
return [part.get_content_charset(failobj) for part in self.walk()]
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 9 | message.py | 44 | add python 3.10.4 for windows | 57,064 | 0 | 23 | 27 | 9 | 223,783 | 9 | XX-Net | 6 | python3.10.4/Lib/email/message.py | Python | 2 | {
"docstring": "Return a list containing the charset(s) used in this message.\n\n The returned list of items describes the Content-Type headers'\n charset parameter for this message and all the subparts in its\n payload.\n\n Each item will either be a string (the value of the charset param... | https://github.com/XX-net/XX-Net.git | |
4 | get_all_lexers | def get_all_lexers(plugins=True):
for item in LEXERS.values():
yield item[1:]
if plugins:
for lexer in find_plugin_lexers():
yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes
| cd5a9683be69c86c8f3adcd13385a9bc5db198ec | 12 | __init__.py | 79 | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 4,117 | 0 | 53 | 49 | 16 | 22,022 | 19 | pipenv | 11 | pipenv/patched/pip/_vendor/pygments/lexers/__init__.py | Python | 6 | {
"docstring": "Return a generator of tuples in the form ``(name, aliases,\n filenames, mimetypes)`` of all know lexers.\n\n If *plugins* is true (the default), plugin lexers supplied by entrypoints\n are also returned. Otherwise, only builtin ones are considered.\n ",
"language": "en",
"n_whitespace... | https://github.com/pypa/pipenv.git | |
2 | get_placement_groups | async def get_placement_groups(self) -> dict:
reply = await self._client.get_all_placement_group_info(
timeout=DEFAULT_RPC_TIMEOUT
)
result = {}
for message in reply.placement_group_table_data:
data = self._message_to_dict(
message=message... | 30ab5458a7e4ba2351d5e1beef8c8797b5946493 | 13 | state_aggregator.py | 112 | [State Observability] Tasks and Objects API (#23912)
This PR implements ray list tasks and ray list objects APIs.
NOTE: You can ignore the merge conflict for now. It is because the first PR was reverted. There's a fix PR open now. | 31,406 | 0 | 160 | 68 | 25 | 138,398 | 33 | ray | 16 | dashboard/state_aggregator.py | Python | 19 | {
"docstring": "List all placement group information from the cluster.\n\n Returns:\n {pg_id -> pg_data_in_dict}\n pg_data_in_dict's schema is in PlacementGroupState\n ",
"language": "en",
"n_whitespaces": 53,
"n_words": 17,
"vocab_size": 17
} | https://github.com/ray-project/ray.git | |
1 | get_prompt_template_names | def get_prompt_template_names(cls) -> List[str]:
return list(cls.prompt_templates.keys())
| 9ebf164cfdfb320503b7161493420c1b0ec577a3 | 10 | prompt_node.py | 38 | feat: Expand LLM support with PromptModel, PromptNode, and PromptTemplate (#3667)
Co-authored-by: ZanSara <sarazanzo94@gmail.com> | 75,224 | 0 | 20 | 22 | 6 | 258,354 | 6 | haystack | 7 | haystack/nodes/prompt/prompt_node.py | Python | 6 | {
"docstring": "\n Returns the list of supported prompt template names.\n :return: List of supported prompt template names.\n ",
"language": "en",
"n_whitespaces": 37,
"n_words": 15,
"vocab_size": 10
} | https://github.com/deepset-ai/haystack.git | |
3 | _handle_meta_tensor_data_access | def _handle_meta_tensor_data_access(self):
try:
yield
except NotImplementedError as error:
if "meta" not in str(error).lower():
raise error
# TODO: See https://github.com/pytorch/pytorch/issues/68592
raise self._make_error_meta(No... | 8d05174defd689cb1cb2346e0cde5b7fa572814a | 13 | _comparison.py | 71 | make meta tensor data access error message for expressive in assert_close (#68802)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/68802
Without this patch, the error message of comparing meta tensors looks like this after #68722 was merged:
```python
>>> t = torch.empty((), device="meta")
>>... | 21,545 | 0 | 108 | 38 | 26 | 102,547 | 28 | pytorch | 7 | torch/testing/_comparison.py | Python | 7 | {
"docstring": "Turns a vanilla :class:`NotImplementedError` stemming from data access on a meta tensor into an expressive\n :class:`ErrorMeta`.\n\n Although it looks like meta tensors could be handled upfront, we need to do it lazily: there are use cases\n where a meta tensor wraps a data tensor... | https://github.com/pytorch/pytorch.git | |
1 | exec_train_and_forecast | def exec_train_and_forecast(self, mock_handler, model_name, using):
# create predictor
create_sql = f
ret = self.run_mindsdb_sql(sql=create_sql)
assert ret.error_code is None, "train failed: " + model_name
self.wait_training(model_name=f'{model_name}_forecaster')
predic... | fca34e2db1ab32fb348abb3b6e9d5feef80b6d23 | 10 | test_merlion_handler.py | 125 | Integration merlion issue2377 (#3435)
* [issue2377] Merlion integrated, forecaster: default, sarima, prophet, mses, detector: default, isolation forest, windstats, prophet.
* [issue2377] 1) Add ref to models; 2) Use url to fetch test data; 3) Set author.
* [issue2377] 1) Replace print with mindsdb.log 2) Add low... | 26,018 | 0 | 94 | 68 | 26 | 117,490 | 39 | mindsdb | 12 | tests/unit/test_merlion_handler.py | Python | 19 | {
"docstring": "\n CREATE PREDICTOR mindsdb.{model_name}_forecaster\n FROM pg\n (select t, H1 from m4 where train = 1) \n PREDICT H1\n USING engine='merlion'{using}\n \n select p.t, p.H1 re... | https://github.com/mindsdb/mindsdb.git | |
10 | load | def load(f, _dict=dict, decoder=None):
if _ispath(f):
with io.open(_getpath(f), encoding='utf-8') as ffile:
return loads(ffile.read(), _dict, decoder)
elif isinstance(f, list):
from os import path as op
from warnings import warn
if not [path for path in f if op.... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 17 | decoder.py | 323 | upd; format | 13,519 | 0 | 421 | 181 | 88 | 63,872 | 127 | transferlearning | 34 | .venv/lib/python3.8/site-packages/pip/_vendor/toml/decoder.py | Python | 29 | {
"docstring": "Parses named file or files as toml and returns a dictionary\n\n Args:\n f: Path to the file to open, array of files to read into single dict\n or a file descriptor\n _dict: (optional) Specifies the class of the returned toml dictionary\n decoder: The decoder to use\n\... | https://github.com/jindongwang/transferlearning.git | |
4 | map_stream_block_value | def map_stream_block_value(stream_block_value, block_def, block_path, **kwargs):
mapped_value = []
for child_block in stream_block_value:
if not should_alter_block(child_block["type"], block_path):
mapped_value.append(child_block)
else:
try:
child_... | ec6229c23600ebae8ec0d5db6846b095a9468151 | 19 | utils.py | 182 | Add StreamField migration helpers from https://github.com/sandilsranasinghe/wagtail-streamfield-migration-toolkit/ | 17,006 | 0 | 262 | 111 | 41 | 80,110 | 46 | wagtail | 16 | wagtail/blocks/migrations/utils.py | Python | 20 | {
"docstring": "\n Maps each child block in a StreamBlock value.\n\n Args:\n stream_block_value:\n The value of the StreamBlock, a list of child blocks\n block_def:\n The definition of the StreamBlock\n block_path:\n A '.' separated list of names of the bloc... | https://github.com/wagtail/wagtail.git | |
2 | test_invite_by_user_ratelimit | def test_invite_by_user_ratelimit(self) -> None:
other_server = "otherserver"
other_user = "@otheruser:" + other_server
# create the room
user_id = self.register_user("kermit", "test")
tok = self.login("kermit", "test")
| 9e06e220649cc0139749c388a894bee0d65d5f4e | 9 | test_federation.py | 72 | Add type hints to more tests files. (#12240) | 71,877 | 0 | 66 | 101 | 19 | 247,727 | 24 | synapse | 8 | tests/handlers/test_federation.py | Python | 27 | {
"docstring": "Tests that invites from federation to a particular user are\n actually rate-limited.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 12,
"vocab_size": 12
} | https://github.com/matrix-org/synapse.git | |
5 | get_authenticated_entity | def get_authenticated_entity(self) -> Tuple[Optional[str], Optional[str]]:
# Convert the requester into a string that we can log
if isinstance(self._requester, str):
return self._requester, None
elif isinstance(self._requester, Requester):
requester = self._reque... | 3dd175b628bab5638165f20de9eade36a4e88147 | 13 | site.py | 156 | `synapse.api.auth.Auth` cleanup: make permission-related methods use `Requester` instead of the `UserID` (#13024)
Part of #13019
This changes all the permission-related methods to rely on the Requester instead of the UserID. This is a first step towards enabling scoped access tokens at some point, since I expect th... | 72,895 | 0 | 273 | 97 | 70 | 249,401 | 105 | synapse | 13 | synapse/http/site.py | Python | 24 | {
"docstring": "\n Get the \"authenticated\" entity of the request, which might be the user\n performing the action, or a user being puppeted by a server admin.\n\n Returns:\n A tuple:\n The first item is a string representing the user making the request.\n\n ... | https://github.com/matrix-org/synapse.git | |
1 | _forward | def _forward(self, *args, **kwargs):
raise NotImplementedError(
f'`_forward` is not implemented in {self.__class__.__name__}')
| 9c1b26726eebe4a196d213249dc22e8017761fab | 11 | d2_wrapper.py | 41 | [Feature] Support training detection models in detectron2 (#8672)
* [Feature]Support using mmengine to train detectron2
* update
* del unnecessary comments
* minor fix
* minor fix
* Support mask rcnn and retinanet
* minor fix
* minor fix
* minor fix
* minor fix
* minor fix
* minor fix
... | 70,906 | 0 | 37 | 18 | 12 | 245,836 | 12 | mmdetection | 7 | mmdet/models/detectors/d2_wrapper.py | Python | 3 | {
"docstring": "Network forward process.\n\n Usually includes backbone, neck and head forward without any post-\n processing.\n ",
"language": "en",
"n_whitespaces": 35,
"n_words": 14,
"vocab_size": 13
} | https://github.com/open-mmlab/mmdetection.git | |
3 | us_indices | def us_indices() -> pd.DataFrame:
url = (
"https://www.wsj.com/market-data/stocks?id=%7B%22application%22%3A%22WSJ%22%2C%22instruments%22%3A%5B%7B"
"%22symbol%22%3A%22INDEX%2FUS%2F%2FDJIA%22%2C%22name%22%3A%22DJIA%22%7D%2C%7B%22symbol%22%3A%22INDEX%2FUS%2F"
"%2FCOMP%22%2C%22name%22%3A%2... | 4304a5c664700cf083f1432fa7523f051492754c | @log_start_end(log=logger) | 15 | wsj_model.py | 304 | Enhances error handling in economy menu (#2819)
* Lots of bug fixes
* Fixed issue | 85,525 | 1 | 259 | 162 | 58 | 286,052 | 72 | OpenBBTerminal | 25 | openbb_terminal/economy/wsj_model.py | Python | 39 | {
"docstring": "Get the top US indices\n\n Returns\n -------\n indices: pd.DataFrame\n Dataframe containing name, price, net change and percent change\n ",
"language": "en",
"n_whitespaces": 37,
"n_words": 18,
"vocab_size": 17
} | https://github.com/OpenBB-finance/OpenBBTerminal.git |
1 | async_activate | async def async_activate(self, **kwargs):
await async_publish(
self.hass,
self._config[CONF_COMMAND_TOPIC],
self._config[CONF_PAYLOAD_ON],
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
| 635d7085cf42dfaf8e60d1e262f096827d56e6e1 | 10 | scene.py | 76 | Move MQTT config schemas and client to separate modules (#71995)
* Move MQTT config schemas and client to separate modules
* Update integrations depending on MQTT | 100,629 | 0 | 100 | 52 | 13 | 301,790 | 13 | core | 11 | homeassistant/components/mqtt/scene.py | Python | 9 | {
"docstring": "Activate the scene.\n\n This method is a coroutine.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 8,
"vocab_size": 8
} | https://github.com/home-assistant/core.git | |
4 | state_updates | def state_updates(self):
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
... | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 13 | training.py | 96 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 80,809 | 0 | 179 | 55 | 41 | 271,578 | 48 | keras | 10 | keras/engine/training.py | Python | 13 | {
"docstring": "Deprecated, do NOT use!\n\n Returns the `updates` from all layers that are stateful.\n\n This is useful for separating training updates and\n state updates, e.g. when we need to update a layer's internal state\n during prediction.\n\n Returns:\n A list of ... | https://github.com/keras-team/keras.git | |
1 | test_get_image_disabled | async def test_get_image_disabled(hass, hass_ws_client):
patch_key, entity_id, config_entry = _setup(CONFIG_ANDROIDTV_DEFAULT)
config_entry.add_to_hass(hass)
hass.config_entries.async_update_entry(
config_entry, options={CONF_SCREENCAP: False}
)
with patchers.patch_connect(True)[patch_... | ea456893f94c7dc88b0cc28f92dadf240fbb1fe7 | 13 | test_media_player.py | 253 | Review AndroidTV tests for media player entity (#71168) | 98,635 | 0 | 169 | 147 | 44 | 299,731 | 55 | core | 28 | tests/components/androidtv/test_media_player.py | Python | 22 | {
"docstring": "Test taking a screen capture with screencap option disabled.\n\n This is based on `test_get_image` in tests/components/media_player/test_init.py.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 16,
"vocab_size": 16
} | https://github.com/home-assistant/core.git | |
1 | test___virtual___fail | def test___virtual___fail(sentry_handler):
with patch("salt.log.handlers.sentry_mod.HAS_RAVEN", False), patch(
"salt.log.handlers.sentry_mod.__opts__", sentry_handler
):
ret = salt.log.handlers.sentry_mod.__virtual__()
assert ret[0] is False
assert ret[1] == "Cannot find 'raven' pyt... | eb8bd12761fdad5abc682bf29c131231736f4616 | 13 | test_sentry_mod.py | 157 | Test that sentry logger does not load grains/modules
Reinforce sentry log handler not wasting time reloading grains/execution
modules with unit tests. | 54,121 | 0 | 103 | 91 | 31 | 215,721 | 48 | salt | 9 | tests/pytests/unit/log/handlers/test_sentry_mod.py | Python | 13 | {
"docstring": "\n Test `__virtual__()` returns a reason for not loading.\n ",
"language": "en",
"n_whitespaces": 15,
"n_words": 8,
"vocab_size": 8
} | https://github.com/saltstack/salt.git | |
1 | install_multiple_bleak_catcher | def install_multiple_bleak_catcher() -> None:
bleak.BleakScanner = HaBleakScannerWrapper # type: ignore[misc, assignment]
bleak.BleakClient = HaBleakClientWrapper # type: ignore[misc, assignment]
| 1b144c0e4dd683e3b47668a89da5eb6da4ae5e08 | 7 | usage.py | 33 | Update to bleak 0.18.0 (#79008) | 86,936 | 0 | 29 | 17 | 13 | 287,748 | 18 | core | 6 | homeassistant/components/bluetooth/usage.py | Python | 4 | {
"docstring": "Wrap the bleak classes to return the shared instance if multiple instances are detected.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 13
} | https://github.com/home-assistant/core.git | |
3 | configure | def configure(self): # type: () -> None
# a target uses a single python version, but a controller may include additional versions for targets running on the controller
python_versions = [self.python.version] + [target.python.version for target in self.targets if isinstance(target, ControllerCo... | 5c2d830dea986a8c7bd8c286b86bdce326cd7eb1 | 12 | host_profiles.py | 245 | ansible-test - Fix subprocess management. (#77641)
* Run code-smell sanity tests in UTF-8 Mode.
* Update subprocess use in sanity test programs.
* Use raw_command instead of run_command with always=True set.
* Add more capture=True usage.
* Don't expose stdin to subprocesses.
* Capture more output. Warn on retry.... | 78,777 | 0 | 222 | 154 | 61 | 267,172 | 75 | ansible | 35 | test/lib/ansible_test/_internal/host_profiles.py | Python | 17 | {
"docstring": "Perform in-band configuration. Executed before delegation for the controller and after delegation for targets.",
"language": "en",
"n_whitespaces": 13,
"n_words": 14,
"vocab_size": 12
} | https://github.com/ansible/ansible.git | |
1 | test_align_labels | def test_align_labels():
fig, (ax3, ax1, ax2) = plt.subplots(3, 1, layout="constrained",
figsize=(6.4, 8),
gridspec_kw={"height_ratios": (1, 1,
0.7)})
ax1.... | ec4dfbc3c83866f487ff0bc9c87b0d43a1c02b22 | 12 | test_constrainedlayout.py | 294 | ENH: implement and use base layout_engine for more flexible layout. | 22,617 | 0 | 317 | 200 | 51 | 107,162 | 58 | matplotlib | 25 | lib/matplotlib/tests/test_constrainedlayout.py | Python | 19 | {
"docstring": "\n Tests for a bug in which constrained layout and align_ylabels on\n three unevenly sized subplots, one of whose y tick labels include\n negative numbers, drives the non-negative subplots' y labels off\n the edge of the plot\n ",
"language": "en",
"n_whitespaces": 52,
"n_words": ... | https://github.com/matplotlib/matplotlib.git | |
1 | test_broken_document_link | def test_broken_document_link(self):
converter = ContentstateConverter(features=["document-link"])
result = json.loads(
converter.from_database_format(
)
)
self.assertContentStateEqual(
result,
{
"entityMap"... | d10f15e55806c6944827d801cd9c2d53f5da4186 | 16 | test_contentstate.py | 203 | Reformat with black | 15,764 | 0 | 501 | 110 | 43 | 71,901 | 53 | wagtail | 10 | wagtail/admin/tests/test_contentstate.py | Python | 31 | {
"docstring": "\n <p>a <a linktype=\"document\" id=\"9999\">document</a> link</p>\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 5,
"vocab_size": 5
} | https://github.com/wagtail/wagtail.git | |
2 | finalize_variable_values | def finalize_variable_values(self, var_list):
if self.use_ema:
# If the optimizer uses EMA, then when finalizing, we replace the model
# variable value with its moving average stored inside optimizer.
self._overwrite_model_variables_with_average_value(var_list)
| 84afc5193d38057e2e2badf9c889ea87d80d8fbf | 9 | optimizer.py | 35 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 81,369 | 0 | 76 | 19 | 27 | 275,284 | 29 | keras | 5 | keras/optimizers/optimizer_experimental/optimizer.py | Python | 3 | {
"docstring": "Set the final value of model's trainable variables.\n\n Sometimes there are some extra steps before ending the variable updates,\n such as overriding the model variables with its average value.\n\n Args:\n var_list: list of model variables.\n ",
"language": "en",... | https://github.com/keras-team/keras.git | |
2 | _get_free_vram | def _get_free_vram(self) -> List[float]:
vram = [pynvml.nvmlDeviceGetMemoryInfo(handle).free / (1024 * 1024)
for handle in self._handles]
self._log("debug", f"GPU VRAM free: {vram}")
return vram
| bdbbad4d310fb606b6f412aa81e9f57ccd994e97 | 11 | nvidia.py | 79 | Refactor lib.gpu_stats (#1218)
* inital gpu_stats refactor
* Add dummy CPU Backend
* Update Sphinx documentation | 20,039 | 0 | 65 | 46 | 21 | 100,575 | 22 | faceswap | 11 | lib/gpu_stats/nvidia.py | Python | 14 | {
"docstring": " Obtain the amount of VRAM that is available, in Megabytes, for each connected Nvidia\n GPU.\n\n Returns\n -------\n list\n List of `float`s containing the amount of VRAM available, in Megabytes, for each\n connected GPU as corresponding to the value... | https://github.com/deepfakes/faceswap.git | |
1 | test_from_is_negative | def test_from_is_negative(self) -> None:
channel = self.make_request(
"GET",
self.url + "?from=-5",
access_token=self.admin_user_tok,
)
self.assertEqual(400, channel.code, msg=channel.json_body)
self.assertEqual(Codes.INVALID_PARAM, channel.... | 2281427175e4c93a30c39607fb4ac23c2a1f399f | 10 | test_event_reports.py | 97 | Use literals in place of `HTTPStatus` constants in tests (#13488)
* Use literals in place of `HTTPStatus` constants in tests
* newsfile
* code style
* code style | 72,812 | 0 | 86 | 60 | 18 | 249,309 | 18 | synapse | 13 | tests/rest/admin/test_event_reports.py | Python | 11 | {
"docstring": "\n Testing that a negative from parameter returns a 400\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 8
} | https://github.com/matrix-org/synapse.git | |
3 | execute | def execute():
if not frappe.db.a_row_exists("Leave Ledger Entry"):
return
leave_application_list = get_denied_leave_application_list()
if leave_application_list:
delete_denied_leaves_from_leave_ledger_entry(leave_application_list)
| 494bd9ef78313436f0424b918f200dab8fc7c20b | 9 | remove_denied_leaves_from_leave_ledger.py | 55 | style: format code with black | 14,264 | 0 | 8 | 29 | 13 | 66,639 | 14 | erpnext | 7 | erpnext/patches/v12_0/remove_denied_leaves_from_leave_ledger.py | Python | 6 | {
"docstring": "Delete leave ledger entry created\n\tvia leave applications with status != Approved",
"language": "en",
"n_whitespaces": 10,
"n_words": 12,
"vocab_size": 11
} | https://github.com/frappe/erpnext.git | |
1 | clear | def clear(self) -> None:
assert self._current_run_info is not None
assert self._current_run_info.end is not None
self._current_run_info = None
| f073f170402bd02e6d6c7597ce5d842a016e97be | 8 | run_history.py | 47 | Refactor tracking of the recorder run history (#70456)
Co-authored-by: Erik Montnemery <erik@montnemery.com> | 98,086 | 0 | 45 | 29 | 11 | 299,149 | 17 | core | 4 | homeassistant/components/recorder/run_history.py | Python | 8 | {
"docstring": "Clear the current run after ending it.\n\n Must run in the recorder thread.\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 13,
"vocab_size": 11
} | https://github.com/home-assistant/core.git | |
1 | test_github_tag_workflow_completed | def test_github_tag_workflow_completed(self) -> None:
expected_topic = "circleci-webhook-test"
expected_message = .strip()
self.check_webhook("github_tag_workflow_completed", expected_topic, expected_message)
| 5346de91647f29ce9e24b520c8fb85a7fa0f72d5 | 9 | tests.py | 49 | circleci: Rewrite integration to support the new webhook format.
CircleCI has updated its webhook format[1] for CircleCI Cloud,
Server version 3.x and 4.x. This commit rewrites the CircleCI
integration to parse the new webhook structure. The tests have also
been rewritten for the new format.
With this commit, we supp... | 17,961 | 0 | 33 | 27 | 12 | 85,163 | 13 | zulip | 6 | zerver/webhooks/circleci/tests.py | Python | 8 | {
"docstring": "\nWorkflow [`sample`](https://app.circleci.com/pipelines/github/prah23/circleci-webhook-test/20/workflows/045c6271-78e2-4802-8a62-f4fa6d25d0c9) within Pipeline #20 has succeeded.\n\nTriggered on the latest tag on [0e6e66c14e6](https://github.com/prah23/circleci-webhook-test/commit/0e6e66c14e61fbcd95db... | https://github.com/zulip/zulip.git | |
3 | rebuild_cablepaths | def rebuild_cablepaths(instance, raw=False, **kwargs):
if not raw:
peer_termination = instance.get_peer_termination()
# if peer_termination:
# rebuild_paths(peer_termination)
| 5667a9c456e0514a2d00d6475e7013748b4a7c1e | 10 | signals.py | 43 | Refactor CablePath.from_origin() | 77,847 | 0 | 46 | 31 | 13 | 264,829 | 15 | netbox | 6 | netbox/circuits/signals.py | Python | 5 | {
"docstring": "\n Rebuild any CablePaths which traverse the peer CircuitTermination.\n ",
"language": "en",
"n_whitespaces": 15,
"n_words": 8,
"vocab_size": 8
} | https://github.com/netbox-community/netbox.git | |
3 | tick_params | def tick_params(self, axis='both', **kwargs):
_api.check_in_list(['x', 'y', 'z', 'both'], axis=axis)
if axis in ['x', 'y', 'both']:
super().tick_params(axis, **kwargs)
if axis in ['z', 'both']:
zkw = dict(kwargs)
zkw.pop('top', None)
zkw.p... | 3b3fb2afbe3264ea3fa39e7e6e547410b402bfa0 | 11 | axes3d.py | 194 | Tweak Axes3D docstrings that refer to 2D plotting methods.
... and minor edits to 2D Axes.margins docs as well. | 22,810 | 0 | 150 | 109 | 34 | 107,554 | 42 | matplotlib | 12 | lib/mpl_toolkits/mplot3d/axes3d.py | Python | 11 | {
"docstring": "\n Convenience method for changing the appearance of ticks and\n tick labels.\n\n See `.Axes.tick_params` for full documentation. Because this function\n applies to 3D Axes, *axis* can also be set to 'z', and setting *axis*\n to 'both' autoscales all three axes.\n\n... | https://github.com/matplotlib/matplotlib.git | |
1 | get_fullname | def get_fullname(self, filesafe=False):
return _get_name_and_version(self['Name'], self['Version'], filesafe)
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 9 | metadata.py | 42 | upd; format | 12,863 | 0 | 21 | 25 | 7 | 62,078 | 7 | transferlearning | 4 | .venv/lib/python3.8/site-packages/pip/_vendor/distlib/metadata.py | Python | 2 | {
"docstring": "Return the distribution name with version.\n\n If filesafe is true, return a filename-escaped form.",
"language": "en",
"n_whitespaces": 20,
"n_words": 14,
"vocab_size": 14
} | https://github.com/jindongwang/transferlearning.git | |
10 | eliminate_word | def eliminate_word(self, gen, by=None, _all=False, inverse=True):
if by is None:
by = self.group.identity
if self.is_independent(gen) or gen == by:
return self
if gen == self:
return by
if gen**-1 == by:
_all = False
word =... | 498015021131af4dbb07eb110e5badaba8250c7b | 15 | free_groups.py | 276 | Updated import locations | 47,567 | 0 | 346 | 176 | 47 | 196,067 | 81 | sympy | 17 | sympy/combinatorics/free_groups.py | Python | 27 | {
"docstring": "\n For an associative word `self`, a subword `gen`, and an associative\n word `by` (identity by default), return the associative word obtained by\n replacing each occurrence of `gen` in `self` by `by`. If `_all = True`,\n the occurrences of `gen` that may appear after the f... | https://github.com/sympy/sympy.git | |
1 | __copy__ | def __copy__(self):
return PandasOnDaskDataframePartition(
self._data,
length=self._length_cache,
width=self._width_cache,
ip=self._ip_cache,
call_queue=self.call_queue,
)
| 4ec7f6347903f9133c65ebc5b6e0e15553b98577 | 9 | partition.py | 57 | REFACTOR-#4530: Standardize access to physical data in partitions (#4563)
Signed-off-by: Alexey Prutskov <lehaprutskov@gmail.com> | 35,665 | 0 | 86 | 38 | 10 | 153,859 | 10 | modin | 11 | modin/core/execution/dask/implementations/pandas_on_dask/partitioning/partition.py | Python | 8 | {
"docstring": "\n Create a copy of this partition.\n\n Returns\n -------\n PandasOnDaskDataframePartition\n A copy of this partition.\n ",
"language": "en",
"n_whitespaces": 61,
"n_words": 14,
"vocab_size": 10
} | https://github.com/modin-project/modin.git | |
1 | Kumaraswamy | def Kumaraswamy(name, a, b):
r
return rv(name, KumaraswamyDistribution, (a, b))
#-------------------------------------------------------------------------------
# Laplace distribution ---------------------------------------------------------
| 9ad8ab9fe58051cf11626ba6654852fcfec60147 | 8 | crv_types.py | 36 | Documentation cleanup 5 | 48,108 | 0 | 18 | 24 | 15 | 196,690 | 15 | sympy | 6 | sympy/stats/crv_types.py | Python | 53 | {
"docstring": "\n Create a Continuous Random Variable with a Kumaraswamy distribution.\n\n Explanation\n ===========\n\n The density of the Kumaraswamy distribution is given by\n\n .. math::\n f(x) := a b x^{a-1} (1-x^a)^{b-1}\n\n with :math:`x \\in [0,1]`.\n\n Parameters\n ==========\... | https://github.com/sympy/sympy.git | |
1 | num_healthy_workers | def num_healthy_workers(self) -> int:
return (
int(bool(self._local_worker)) + self.__worker_manager.num_healthy_actors()
)
| e707ce4fb3717e3c05118c57f503dfbd03552ca9 | 12 | worker_set.py | 48 | [RLlib] Refactor `WorkerSet` on top of `FaultTolerantActorManager`. (#29938)
Signed-off-by: Jun Gong <jungong@anyscale.com> | 30,792 | 0 | 42 | 28 | 10 | 136,001 | 10 | ray | 7 | rllib/evaluation/worker_set.py | Python | 5 | {
"docstring": "Returns the number of healthy workers, including local and remote workers.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/ray-project/ray.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.