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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | test_kivy_log_mode_marker_on | def test_kivy_log_mode_marker_on():
from kivy.logger import previous_stderr
assert sys.stderr == previous_stderr, "Kivy.logging override stderr"
assert logging.root.parent is None, "Kivy.logging override root logger"
| 2d9755ad8a82ba0777299cbc1666bed25278db94 | 8 | test_logger.py | 50 | Support KivyLogMode environment variable for logging testing (#7971)
* Support KivyLogMode for logging testing
Also:
Remove unused imports.
Remove Python 2 only code
Run through Black to canonicalize formatting
* Undo formatting changes
Undo black. | 47,024 | 0 | 33 | 29 | 18 | 194,668 | 21 | kivy | 9 | kivy/tests/test_logger.py | Python | 4 | {
"docstring": "\n This is a test of the pytest marker \"logmodetest\".\n This should only be invoked if the environment variable is properly set\n (before pytest is run).\n\n Also, tests that kivy.logger paid attention to the environment variable\n ",
"language": "en",
"n_whitespaces": 51,
"n_wo... | https://github.com/kivy/kivy.git | |
3 | _get_checkfiles_linux | def _get_checkfiles_linux(self):
chk = os.popen("ldconfig -p | grep -P \"libcudnn.so.\\d+\" | head -n 1").read()
chk = chk.strip().replace("libcudnn.so.", "")
if not chk:
return []
cudnn_vers = chk[0]
header_files = [f"cudnn_v{cudnn_vers}.h"] + self._cudnn_h... | c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf | 14 | setup.py | 202 | 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 -... | 19,893 | 0 | 133 | 114 | 40 | 100,410 | 52 | faceswap | 18 | setup.py | Python | 11 | {
"docstring": " Return the the files to check for cuDNN locations for Linux by querying\n the dynamic link loader.\n\n Returns\n -------\n list\n List of header file locations to scan for cuDNN versions\n ",
"language": "en",
"n_whitespaces": 77,
"n_words": 30,
"... | https://github.com/deepfakes/faceswap.git | |
1 | set_default_options | def set_default_options(self) -> None:
default = self.cli_opts.get_option_values()
logger.debug(default)
self._gui_objects.default_options = default
self.project.set_default_options()
| dc18c74eea0c7837a820d27628cb12b0824fa30e | 9 | utils.py | 64 | Bugfix: Preview for extract in batch mode | 20,926 | 0 | 47 | 37 | 10 | 101,515 | 12 | faceswap | 10 | lib/gui/utils.py | Python | 12 | {
"docstring": " Set the default options for :mod:`lib.gui.projects`\n\n The Default GUI options are stored on Faceswap startup.\n\n Exposed as the :attr:`_default_opts` for a project cannot be set until after the main\n Command Tabs have been loaded.\n ",
"language": "en",
"n_whitespa... | https://github.com/deepfakes/faceswap.git | |
5 | do_lint | def do_lint() -> Set[str]:
failures = set()
with monkeypatch_pydantic():
logger.debug("Importing synapse")
try:
# TODO: make "synapse" an argument so we can target this script at
# a subpackage
module = importlib.import_module("synapse")
except M... | ba8938b090c7e1908cfa4feac75f08f3bc1183e8 | 17 | check_pydantic_models.py | 285 | Reject non-strict types in Pydantic models (#13502) | 72,885 | 0 | 406 | 152 | 61 | 249,389 | 93 | synapse | 24 | scripts-dev/check_pydantic_models.py | Python | 30 | {
"docstring": "Try to import all of Synapse and see if we spot any Pydantic type coercions.",
"language": "en",
"n_whitespaces": 14,
"n_words": 15,
"vocab_size": 15
} | https://github.com/matrix-org/synapse.git | |
17 | kernS | def kernS(s):
hit = False
quoted = '"' in s or "'" in s
if '(' in s and not quoted:
if s.count('(') != s.count(")"):
raise SympifyError('unmatched left parenthesis')
# strip all space from s
s = ''.join(s.split())
olds = s
# now use space to represen... | 65be461082dda54c8748922f9c29a19af1279fe1 | 16 | sympify.py | 535 | Remove abbreviations in documentation | 48,459 | 0 | 868 | 307 | 166 | 197,316 | 288 | sympy | 29 | sympy/core/sympify.py | Python | 53 | {
"docstring": "Use a hack to try keep autosimplification from distributing a\n a number into an Add; this modification does not\n prevent the 2-arg Mul from becoming an Add, however.\n\n Examples\n ========\n\n >>> from sympy.core.sympify import kernS\n >>> from sympy.abc import x, y\n\n The 2-a... | https://github.com/sympy/sympy.git | |
1 | test_install_fail_dnf_try_fileset | def test_install_fail_dnf_try_fileset():
bos_net_fake_error =
dnf_installp_call = MagicMock(
side_effect=[
{"retcode": 1, "stdout": "", "stderr": bos_net_fake_error},
{"retcode": 0, "stdout": ""},
]
)
fileset_pkg_name = "/cecc/repos/aix72/TL3/BASE/installp... | f1c37893caf90738288e789c3233ab934630254f | 16 | test_aixpkg.py | 331 | Working tests for install | 53,810 | 0 | 453 | 184 | 67 | 215,093 | 89 | salt | 23 | tests/pytests/unit/modules/test_aixpkg.py | Python | 43 | {
"docstring": "\n Test install of non-recognized extension, first dnf then fileset\n AIX generic repository ... | https://github.com/saltstack/salt.git | |
10 | plot_resources | def plot_resources(results, palette="Viridis", **kwargs):
bp = import_required("bokeh.plotting", _BOKEH_MISSING_MSG)
from bokeh import palettes
from bokeh.models import LinearAxis, Range1d
defaults = dict(
title="Profile Results",
tools="save,reset,xwheel_zoom,xpan",
toolba... | 6193b9de78798fc9b2d934e3317debc9bb5d8af5 | 16 | profile_visualize.py | 615 | Handle plot_width / plot_height deprecations (#8544)
Bokeh 3.0 will finally deprecates `plot_width` and `plot_height` and expose only `width` and `height` (consistent with every other layout-able). | 36,429 | 0 | 541 | 378 | 124 | 155,568 | 190 | dask | 51 | dask/diagnostics/profile_visualize.py | Python | 59 | {
"docstring": "Plot resource usage in a bokeh plot.\n\n Parameters\n ----------\n results : sequence\n Output of ResourceProfiler.results\n palette : string, optional\n Name of the bokeh palette to use, must be a member of\n bokeh.palettes.all_palettes.\n **kwargs\n Other k... | https://github.com/dask/dask.git | |
9 | get_mode_of_payment_details | def get_mode_of_payment_details(filters):
mode_of_payment_details = {}
invoice_list = get_invoices(filters)
invoice_list_names = ",".join('"' + invoice['name'] + '"' for invoice in invoice_list)
if invoice_list:
inv_mop_detail = frappe.db.sql(.format(invoice_list_names=invoice_list_names), as_dict=1)
inv_chang... | 3eb5440aa968960528379930cc3c2ba4a4ee544a | 18 | sales_payment_summary.py | 299 | fix: linters erros on report sales payments summary (#30345)
* fix: wrong values for report and get change amout based on payment TYPE.
* charcase for select field.
* fix: linter check erros
* fix: linters errors
Co-authored-by: Ankush Menat <ankush@frappe.io> | 13,689 | 0 | 50 | 177 | 41 | 64,660 | 65 | erpnext | 22 | erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py | Python | 55 | {
"docstring": "\n\t\t\tselect t.owner,\n\t\t\t t.posting_date,\n\t\t\t\t t.mode_of_payment,\n\t\t\t\t sum(t.paid_amount) as paid_amount\n\t\t\tfrom (\n\t\t\t\tselect a.owner, a.posting_date,\n\t\t\t\tifnull(b.mode_of_payment, '') as mode_of_payment, sum(b.base_amount) as paid_amount\n\t\t\t\tfrom `tabSales... | https://github.com/frappe/erpnext.git | |
3 | adv_search_text | def adv_search_text(q, include_inputs, exclude_inputs, data_value):
for inp in include_inputs:
q = q.filter(db.Books.data.any(data_value == inp))
for excl in exclude_inputs:
q = q.filter(not_(db.Books.data.any(data_value == excl)))
return q
| 4545f4a20d9ff90b99bbd4e3e34b6de4441d6367 | ''' | 17 | web.py | 206 | Better epub cover parsing with multiple cover-image items
Code cosmetics
renamed variables
refactored xml page generation
refactored prepare author | 40,820 | 1 | 47 | 64 | 19 | 172,806 | 25 | calibre-web | 19 | cps/web.py | Python | 6 | {
"docstring": "def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs):\n for extension in include_extension_inputs:\n q = q.filter(db.Books.data.any(db.Data.format == extension))\n for extension in exclude_extension_inputs:\n q = q.filter(not_(db.Books.data.any(db.Data.fo... | https://github.com/janeczku/calibre-web.git |
1 | test_api_create_invalid_storage_path | def test_api_create_invalid_storage_path(self):
response = self.client.post(
self.ENDPOINT,
json.dumps(
{
"name": "Another storage path",
"path": "Somewhere/{correspdent}",
},
),
cont... | d7f7d839f8a6b7d0378dda1e0744739748d71b9c | 13 | test_api.py | 108 | Adds invalid storage path format test | 117,006 | 0 | 169 | 64 | 22 | 319,842 | 22 | paperless-ngx | 14 | src/documents/tests/test_api.py | Python | 13 | {
"docstring": "\n GIVEN:\n - API request to create a storage paths\n - Storage path format is incorrect\n WHEN:\n - API is called\n THEN:\n - Correct HTTP 400 response\n - No storage path is created\n ",
"language": "en",
"n_white... | https://github.com/paperless-ngx/paperless-ngx.git | |
14 | resolve_template_files | def resolve_template_files(self) -> None:
if self.template_ext:
for field in self.template_fields:
content = getattr(self, field, None)
if content is None:
continue
elif isinstance(content, str) and any(content.endswith(ext... | ff3bbc3db24f9f3f4f88033d48859fb08fc3237b | 23 | base.py | 298 | Implement enough interface for MappedOperator to be baggable (#20945) | 8,182 | 0 | 476 | 189 | 54 | 44,163 | 83 | airflow | 26 | airflow/models/base.py | Python | 22 | {
"docstring": "Getting the content of files for template_field / template_ext.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/apache/airflow.git | |
1 | autocast_box_type | def autocast_box_type(dst_box_type='hbox') -> Callable:
_, box_type_cls = get_box_type(dst_box_type)
| af063a6f25ddae4de90646f86b2db824f3d00138 | 8 | box_type.py | 34 | [Refactor] Refactor pipelines with boxlist. (#8562)
* Refactor pipelines and data_preprocesser by boxlist
* Refactor browse_dataset.py
* Update
* Update
* Update
* Update
* update
* Update
* Change with_box_wrapped to with_boxlist
* Fix comments
* Fix commits
* Update UT | 70,810 | 0 | 14 | 22 | 8 | 245,504 | 8 | mmdetection | 6 | mmdet/structures/bbox/box_type.py | Python | 18 | {
"docstring": "A decorator which automatically casts results['gt_bboxes'] to the\n destination box type.\n\n It commenly used in mmdet.datasets.transforms to make the transforms up-\n compatible with the np.ndarray type of results['gt_bboxes'].\n\n The speed of processing of np.ndarray and BaseBoxes data... | https://github.com/open-mmlab/mmdetection.git | |
2 | __next__ | def __next__(self):
if self._leftover:
output = self._leftover
self._leftover = b""
else:
output = next(self._producer)
self._unget_history = []
self.position += len(output)
return output
| 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 12 | multipartparser.py | 82 | Refs #33476 -- Reformatted code with Black. | 51,343 | 0 | 101 | 48 | 16 | 206,055 | 22 | django | 9 | django/http/multipartparser.py | Python | 9 | {
"docstring": "\n Used when the exact number of bytes to read is unimportant.\n\n Return whatever chunk is conveniently returned from the iterator.\n Useful to avoid unnecessary bookkeeping if performance is an issue.\n ",
"language": "en",
"n_whitespaces": 59,
"n_words": 30,
"voc... | https://github.com/django/django.git | |
7 | get_power_utilization | def get_power_utilization(self):
powerfeeds = PowerFeed.objects.filter(rack=self)
available_power_total = sum(pf.available_power for pf in powerfeeds)
print(f'available_power_total: {available_power_total}')
if not available_power_total:
return 0
powerports ... | fcd1daaf798d62023f999c3e09e035f7b3f47c8f | 13 | racks.py | 175 | Update power utilization calculations for new cabling model | 78,027 | 0 | 190 | 103 | 39 | 265,205 | 54 | netbox | 23 | netbox/dcim/models/racks.py | Python | 16 | {
"docstring": "\n Determine the utilization rate of power in the rack and return it as a percentage.\n ",
"language": "en",
"n_whitespaces": 30,
"n_words": 15,
"vocab_size": 14
} | https://github.com/netbox-community/netbox.git | |
11 | k_edge_augmentation | def k_edge_augmentation(G, k, avail=None, weight=None, partial=False):
try:
if k <= 0:
raise ValueError(f"k must be a positive integer, not {k}")
elif G.number_of_nodes() < k + 1:
msg = f"impossible to {k} connect in graph with less than {k + 1} nodes"
raise ... | 26b7de005ac562786f72b24a73af5a59bbab6953 | 17 | edge_augmentation.py | 342 | doc: fix typos in docstring and comment (#5647) | 42,026 | 0 | 566 | 207 | 108 | 176,658 | 165 | networkx | 21 | networkx/algorithms/connectivity/edge_augmentation.py | Python | 33 | {
"docstring": "Finds set of edges to k-edge-connect G.\n\n Adding edges from the augmentation to G make it impossible to disconnect G\n unless k or more edges are removed. This function uses the most efficient\n function available (depending on the value of k and if the problem is\n weighted or unweighte... | https://github.com/networkx/networkx.git | |
16 | block_parser | def block_parser(part, rgxin, rgxout, fmtin, fmtout):
block = []
lines = part.split('\n')
N = len(lines)
i = 0
decorator = None
while 1:
if i==N:
# nothing left to parse -- the last line
break
line = lines[i]
i += 1
line_stripped = l... | a9b523c7047fe12c49373972c6b092ed5fc29e99 | 20 | ipython_directive.py | 598 | match only pseudo-decorators | 52,443 | 0 | 1,178 | 345 | 184 | 208,657 | 334 | ipython | 39 | IPython/sphinxext/ipython_directive.py | Python | 52 | {
"docstring": "\n part is a string of ipython text, comprised of at most one\n input, one output, comments, and blank lines. The block parser\n parses the text into a list of::\n\n blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]\n\n where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and\n data ... | https://github.com/ipython/ipython.git | |
6 | update_direct_sparsity | def update_direct_sparsity(self, node):
# this name is consistent with the name returned by named_modules()
module_name = node.name
_logger.info('Update mask for %s', module_name)
unique_name = node.unique_name
dummy_input, input_debugname = self._prepare_dummy_input(nod... | 97d067e614243f06ed1f8e2d389512977fff8828 | 16 | compressor.py | 411 | Speedup enhancement (#4925) | 24,873 | 0 | 806 | 256 | 164 | 113,264 | 311 | nni | 37 | nni/compression/pytorch/speedup/compressor.py | Python | 34 | {
"docstring": "\n Update the direct sparsity for the target node. Here the direct sparsity\n means that the sparsity in the output tensor that caused by the sparsity\n in the input tensors/weight tensors.\n ",
"language": "en",
"n_whitespaces": 59,
"n_words": 30,
"vocab_size": 18
... | https://github.com/microsoft/nni.git | |
4 | read_graph6 | def read_graph6(path):
glist = []
for line in path:
line = line.strip()
if not len(line):
continue
glist.append(from_graph6_bytes(line))
if len(glist) == 1:
return glist[0]
else:
return glist
@not_implemented_for("directed")
@not_implemented_for... | 9b63ca1a0d46a1f50bcc59eda52be02721a134db | @not_implemented_for("directed")
@not_implemented_for("multigraph")
@open_file(1, mode="wb") | 11 | graph6.py | 133 | Remove old Appveyor cruft (#5924)
* Remove old Appveyor cruft
* Fix Windows issue | 42,277 | 1 | 88 | 56 | 25 | 177,122 | 30 | networkx | 11 | networkx/readwrite/graph6.py | Python | 11 | {
"docstring": "Read simple undirected graphs in graph6 format from path.\n\n Parameters\n ----------\n path : file or string\n File or filename to write.\n\n Returns\n -------\n G : Graph or list of Graphs\n If the file contains multiple lines then a list of graphs is returned\n\n Ra... | https://github.com/networkx/networkx.git |
7 | split_ref_from_uri | def split_ref_from_uri(uri):
# type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]]
if not isinstance(uri, str):
raise TypeError("Expected a string, received {0!r}".format(uri))
parsed = _get_parsed_url(uri)
path = parsed.path if parsed.path else ""
scheme = parsed.scheme if parsed.scheme ... | 2f6a04b89a70879f40a42d7d2ce662468f6e87ca | 12 | utils.py | 188 | 5132 Vendor in latest requirementslib. (#5151)
* 5132 Vendor in latest requirementslib. | 3,737 | 0 | 104 | 111 | 45 | 21,253 | 60 | pipenv | 18 | pipenv/vendor/requirementslib/models/utils.py | Python | 11 | {
"docstring": "Given a path or URI, check for a ref and split it from the path if it is\n present, returning a tuple of the original input and the ref or None.\n\n :param AnyStr uri: The path or URI to split\n :returns: A 2-tuple of the path or URI and the ref\n :rtype: Tuple[AnyStr, Optional[AnyStr]]\n ... | https://github.com/pypa/pipenv.git | |
1 | mock_update_duration_fixture | def mock_update_duration_fixture(mock_update):
mock_update.return_value = {
"rows": [
{
"elements": [
{
"duration": {
"value": 1560,
"text": "26 mins",
... | beb30a1ff199596163c655e8ae745a0f1649b78a | @pytest.fixture(name="mock_update_empty") | 17 | test_sensor.py | 108 | Add google_travel_time sensor tests (#66568)
Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io> | 91,329 | 1 | 269 | 47 | 24 | 292,229 | 31 | core | 6 | tests/components/google_travel_time/test_sensor.py | Python | 17 | {
"docstring": "Mock an update to the sensor returning no duration_in_traffic.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/home-assistant/core.git |
1 | async_process_entity_map | async def async_process_entity_map(self) -> None:
# Ensure the Pairing object has access to the latest version of the entity map. This
# is especially important for BLE, as the Pairing instance relies on the entity map
# to map aid/iid to GATT characteristics. So push it to there as wel... | f23b1750e85f07091eb896a0b12b8f95e5646338 | 9 | connection.py | 76 | Migrate HomeKit Controller to use stable identifiers (#80064) | 87,991 | 0 | 167 | 39 | 60 | 288,842 | 83 | core | 9 | homeassistant/components/homekit_controller/connection.py | Python | 12 | {
"docstring": "\n Process the entity map and load any platforms or entities that need adding.\n\n This is idempotent and will be called at startup and when we detect metadata changes\n via the c# counter on the zeroconf record.\n ",
"language": "en",
"n_whitespaces": 65,
"n_words": ... | https://github.com/home-assistant/core.git | |
4 | patch_mac_app | def patch_mac_app() -> None:
dist_path = pathlib.Path('dist')
app_path = dist_path / 'qutebrowser.app'
contents_path = app_path / 'Contents'
macos_path = contents_path / 'MacOS'
resources_path = contents_path / 'Resources'
pyqt_path = macos_path / 'PyQt5'
# Replace some duplicate file... | 660e776a15c02f5577d7aca075bb0e3f8b142831 | 14 | build_release.py | 395 | build-release: Sign macOS .app properly
Based on https://github.com/pyinstaller/pyinstaller/issues/6612
Might help with #6771. | 117,462 | 0 | 265 | 221 | 81 | 320,956 | 128 | qutebrowser | 32 | scripts/dev/build_release.py | Python | 29 | {
"docstring": "Patch .app to save some space and make it signable.",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 10
} | https://github.com/qutebrowser/qutebrowser.git | |
5 | expand | def expand(image, border=0, fill=0):
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
color = _color(fill, image.mode)
if image.mode == "P" and image.palette:
palette = ImagePalette.ImagePalette(palette=image.getpalett... | 279ddf4ce6c76498ac29df2552a3023b9aaa76c1 | 13 | ImageOps.py | 230 | Use getpalette() in ImageOps | 70,030 | 0 | 133 | 149 | 45 | 243,427 | 61 | Pillow | 26 | src/PIL/ImageOps.py | Python | 16 | {
"docstring": "\n Add border to the image\n\n :param image: The image to expand.\n :param border: Border width, in pixels.\n :param fill: Pixel fill value (a color value). Default is 0 (black).\n :return: An image.\n ",
"language": "en",
"n_whitespaces": 52,
"n_words": 32,
"vocab_size": 28... | https://github.com/python-pillow/Pillow.git | |
8 | get_policy_data_from_agent_data | def get_policy_data_from_agent_data(agent_data, policy_map_fn):
policy_data = {}
for agent_id, data in agent_data.items():
policy_id = policy_map_fn(agent_id)
policy_data.setdefault(policy_id, {})
policy_data[policy_id].setdefault("agent_id", [])
if data["obs"].ndim == 1:
... | 30058267363b8de16b809c987bb1f7d7befad24d | 16 | test_torch_marl_module.py | 291 | [RLlib] MARLModule, RLModule PR 4/N (N=4) (#29449)
Signed-off-by: Kourosh Hakhamaneshi <kourosh@anyscale.com> | 30,625 | 0 | 230 | 182 | 47 | 135,458 | 67 | ray | 16 | rllib/core/rl_module/torch/tests/test_torch_marl_module.py | Python | 21 | {
"docstring": "Utility function to get policy data from agent data and policy map function.\n\n It also keeps track of agent_id for each row so that we can retreive the agent\n level information after the forward pass.\n\n Returns:\n dict of module_id to module data\n ",
"language": "en",
"n_w... | https://github.com/ray-project/ray.git | |
1 | cli | def cli():
...
option_verbose = click.option(
"--verbose",
is_flag=True,
help="Print verbose information about performed steps",
)
option_assume_yes = click.option(
"--assume-yes",
is_flag=True,
help="Assume yes answer to question",
)
option_previous_release = click.option(
"--previ... | bc1f062bdebd5a92b650e2316d4d98d2097388ca | 10 | assign_cherry_picked_prs_with_milestone.py | 358 | Add dev tool to review and classify cherry-picked commits (#21032)
Until we have Towncrier, this is a useful tool to classify commits
to one of three categories (in v*-test) branches
1) a/add - add to milestone
2) d/doc - doc-only change
3) e/excluded - change that is skipped from changelog (dev tools)
This i... | 8,197 | 0 | 285 | 5 | 116 | 44,213 | 177 | airflow | 24 | dev/assign_cherry_picked_prs_with_milestone.py | Python | 2 | {
"docstring": "\n Github token used to authenticate.\n You can set omit it if you have GITHUB_TOKEN env variable set\n Can be generated with:\n https://github.com/settings/tokens/new?description=Read%20Write%20isssues&scopes=repo",
"language": "en",
"n_whitespaces": 50,
"n_words": 2... | https://github.com/apache/airflow.git | |
4 | delete_systemd_cgroup_v1 | def delete_systemd_cgroup_v1(self) -> None:
# Privileged mode is required to remove the cgroup directories on some hosts, such as Fedora 36 and RHEL 9.0.
# The BusyBox find utility will report "Permission denied" otherwise, although it still exits with a status code of 0.
options = ['--... | cda16cc5e9aa8703fb4e1ac0a0be6b631d9076cc | 13 | host_profiles.py | 173 | ansible-test - Improve container management. (#78550)
See changelogs/fragments/ansible-test-container-management.yml for details. | 79,632 | 0 | 196 | 77 | 75 | 268,732 | 80 | ansible | 20 | test/lib/ansible_test/_internal/host_profiles.py | Python | 11 | {
"docstring": "Delete a previously created ansible-test cgroup in the v1 systemd hierarchy.",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/ansible/ansible.git | |
3 | iterate_tree_cache_items | def iterate_tree_cache_items(key, value):
if isinstance(value, TreeCacheNode):
for sub_key, sub_value in value.items():
yield from iterate_tree_cache_items((*key, sub_key), sub_value)
else:
# we've reached a leaf of the tree.
yield key, value
| 0b87eb8e0c8e2dd4a426005dce53dfdd57282475 | 14 | treecache.py | 75 | Make DictionaryCache have better expiry properties (#13292) | 72,514 | 0 | 69 | 46 | 27 | 248,927 | 28 | synapse | 8 | synapse/util/caches/treecache.py | Python | 6 | {
"docstring": "Helper function to iterate over the leaves of a tree, i.e. a dict of that\n can contain dicts.\n\n The provided key is a tuple that will get prepended to the returned keys.\n\n Example:\n\n cache = TreeCache()\n cache[(1, 1)] = \"a\"\n cache[(1, 2)] = \"b\"\n cache... | https://github.com/matrix-org/synapse.git | |
1 | deserialize | def deserialize(config, custom_objects=None):
return deserialize_keras_object(
config,
module_objects=globals(),
custom_objects=custom_objects,
printable_module_name='metric function')
@keras_export('keras.metrics.get') | b4dca51d0558e788f62a96d1009a07f773a202f4 | @keras_export('keras.metrics.get') | 10 | __init__.py | 58 | Refactor disparate metrics-related files into a single metrics folder.
Further work may be needed to split up the long file with individual metric definitions. However having a single file per metric may be too granular. TBD.
PiperOrigin-RevId: 425248502 | 79,747 | 1 | 32 | 29 | 11 | 268,880 | 11 | keras | 8 | keras/metrics/__init__.py | Python | 6 | {
"docstring": "Deserializes a serialized metric class/function instance.\n\n Args:\n config: Metric configuration.\n custom_objects: Optional dictionary mapping names (strings) to custom\n objects (classes and functions) to be considered during deserialization.\n\n Returns:\n A Keras `Metric` insta... | https://github.com/keras-team/keras.git |
4 | get_top_k_scored_items | def get_top_k_scored_items(scores, top_k, sort_top_k=False):
# ensure we're working with a dense ndarray
if isinstance(scores, sparse.spmatrix):
scores = scores.todense()
if scores.shape[1] < top_k:
logger.warning(
"Number of items is less than top_k, limiting top_k to num... | 1d7341e93d1f03387699fb3c6ae0b6c0e464296f | 11 | python_utils.py | 231 | Add new item similarity metrics for SAR (#1754)
* Add mutual information similarity in SAR
* Add lexicographers mutual information similarity for SAR
* Add cosine similarity for SAR
* Add inclusion index for SAR
* Typos
* Change SARSingleNode to SAR
* Convert item similarity matrix to np.array
* U... | 7,236 | 0 | 178 | 148 | 71 | 39,444 | 89 | recommenders | 23 | recommenders/utils/python_utils.py | Python | 16 | {
"docstring": "Extract top K items from a matrix of scores for each user-item pair, optionally sort results per user.\n\n Args:\n scores (numpy.ndarray): Score matrix (users x items).\n top_k (int): Number of top items to recommend.\n sort_top_k (bool): Flag to sort top k results.\n\n Retu... | https://github.com/microsoft/recommenders.git | |
19 | curse_add_stat | def curse_add_stat(self, key, width=None, header='', display_key=True, separator='', trailer=''):
if key not in self.stats:
return []
# Check if a shortname is defined
if key in self.fields_description and 'short_name' in self.fields_description[key]:
key_name =... | 586ebd7099fb6fca47cf04f632c8cbf7f0450500 | 22 | glances_plugin.py | 797 | Refactor comment | 15,223 | 0 | 1,104 | 475 | 116 | 69,984 | 282 | glances | 27 | glances/plugins/glances_plugin.py | Python | 65 | {
"docstring": "Return a list of dict messages with the 'key: value' result\n\n <=== width ===>\n __key : 80.5%__\n | | | | |_ trailer\n | | | |_ self.stats[key]\n | | |_ separator\n | |_ key (if display_key is True)\n |_ header\n\n In... | https://github.com/nicolargo/glances.git | |
3 | loss_labels | def loss_labels(self, outputs, targets, indices, num_boxes):
if "logits" not in outputs:
raise KeyError("No logits were found in the outputs")
src_logits = outputs["logits"]
idx = self._get_src_permutation_idx(indices)
target_classes_o = torch.cat([t["class_labels"]... | cc034f72eb6137f4c550e911fba67f8a0e1e98fa | 12 | modeling_detr.py | 213 | Replace assertion with exception (#16720)
* Updated assertions to exceptions
* updated assertions to exceptions
* bug fixes
* fix-copies
* Update modeling_ctrl.py
* Update src/transformers/models/ctrl/modeling_tf_ctrl.py
Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com>
* ... | 6,726 | 0 | 157 | 138 | 48 | 37,071 | 58 | transformers | 31 | src/transformers/models/detr/modeling_detr.py | Python | 13 | {
"docstring": "\n Classification loss (NLL) targets dicts must contain the key \"class_labels\" containing a tensor of dim\n [nb_target_boxes]\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 16,
"vocab_size": 16
} | https://github.com/huggingface/transformers.git | |
3 | get_func | def get_func(cls, key, **kwargs):
if "agg_func" in kwargs:
return cls.inplace_applyier_builder(key, kwargs["agg_func"])
elif "func_dict" in kwargs:
return cls.inplace_applyier_builder(key, kwargs["func_dict"])
else:
return cls.inplace_applyier_builder... | 1e65a4afd191cf61ba05b80545d23f9b88962f41 | 12 | groupby.py | 92 | FIX-#3197: do not pass lambdas to the backend in GroupBy (#3373)
Signed-off-by: Dmitry Chigarev <dmitry.chigarev@intel.com> | 35,257 | 0 | 82 | 54 | 16 | 153,097 | 21 | modin | 5 | modin/core/dataframe/algebra/default2pandas/groupby.py | Python | 7 | {
"docstring": "\n Extract aggregation function from groupby arguments.\n\n Parameters\n ----------\n key : callable or str\n Default aggregation function. If aggregation function is not specified\n via groupby arguments, then `key` function is used.\n **kwargs... | https://github.com/modin-project/modin.git | |
11 | check_validation_split_arg | def check_validation_split_arg(validation_split, subset, shuffle, seed):
if validation_split and not 0 < validation_split < 1:
raise ValueError(
'`validation_split` must be between 0 and 1, received: %s' %
(validation_split,))
if (validation_split or subset) and not (validation_split and subs... | c52c11968b096580577c75b169f51c5b39002106 | 12 | dataset_utils.py | 159 | Updated tests for subset="both" | 79,952 | 0 | 188 | 92 | 68 | 269,208 | 109 | keras | 6 | keras/utils/dataset_utils.py | Python | 16 | {
"docstring": "Raise errors in case of invalid argument values.\n\n Args:\n validation_split: float between 0 and 1, fraction of data to reserve for\n validation.\n subset: One of \"training\", \"validation\" or \"both\". Only used if `validation_split`\n is set.\n shuffle: Whether to shuffle the... | https://github.com/keras-team/keras.git | |
2 | prepare_test_img | def prepare_test_img(self, idx):
img_info = self.data_infos[idx]
results = dict(img_info=img_info)
if self.proposals is not None:
results['proposals'] = self.proposals[idx]
self.pre_pipeline(results)
return self.pipeline(results)
| 1516986a616fee8bb741d0ab2be40683045efccd | 10 | custom.py | 92 | [Feature] Support OpenImages Dataset (#6331)
* [Feature] support openimage group of eval
* [Feature] support openimage group of eval
* support openimage dataset
* support openimage challenge dataset
* fully support OpenImages-V6 and OpenImages Challenge 2019
* Fix some logic error
* update config fil... | 70,180 | 0 | 73 | 56 | 18 | 243,990 | 20 | mmdetection | 10 | mmdet/datasets/custom.py | Python | 7 | {
"docstring": "Get testing data after pipeline.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Testing data after pipeline with new keys introduced by \\\n pipeline.\n ",
"language": "en",
"n_whitespaces": 82,
"n_words": 24,
"vocab_size": ... | https://github.com/open-mmlab/mmdetection.git | |
2 | get_redirect_target | def get_redirect_target(self, resp):
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# If a custom mixin is used to handle this logic... | cd5a9683be69c86c8f3adcd13385a9bc5db198ec | 11 | sessions.py | 79 | Rename notpip to pip. Vendor in pip-22.2.1 and latest requirementslib and vistir. | 4,187 | 0 | 305 | 38 | 100 | 22,111 | 143 | pipenv | 8 | pipenv/patched/pip/_vendor/requests/sessions.py | Python | 6 | {
"docstring": "Receives a Response. Returns a redirect URI or ``None``",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | https://github.com/pypa/pipenv.git | |
4 | get_type_hints | def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
if hasattr(typing, "Annotated"):
hint = typing.get_type_hints(
obj, globalns=globalns, localns=localns, include_extras=True
)
else:
hint = typing.get_type_hints(obj, g... | c69d55f7c82d5ae2cce542bcfb98d043ca4836a0 | 12 | typing_extensions.py | 172 | Vendor in pip 22.1.2 | 3,948 | 0 | 172 | 88 | 54 | 21,600 | 70 | pipenv | 14 | pipenv/patched/notpip/_vendor/typing_extensions.py | Python | 10 | {
"docstring": "Return type hints for an object.\n\n This is often the same as obj.__annotations__, but it handles\n forward references encoded as string literals, adds Optional[t] if a\n default value equal to None is set and recursively replaces all\n 'Annotated[T, ...]', 'Required[T]' o... | https://github.com/pypa/pipenv.git | |
3 | color_temp_supported | def color_temp_supported(self) -> bool:
return (
self.color_capabilities is not None
and lighting.Color.ColorCapabilities.Color_temperature
in self.color_capabilities
) or self.color_temperature is not None
| df67a8cd4f8df91a153778009a74be1e3876ca53 | 12 | lighting.py | 57 | Fix ZHA light color temp support (#76305) | 102,289 | 0 | 74 | 36 | 16 | 303,469 | 20 | core | 9 | homeassistant/components/zha/core/channels/lighting.py | Python | 7 | {
"docstring": "Return True if the channel supports color temperature.",
"language": "en",
"n_whitespaces": 7,
"n_words": 8,
"vocab_size": 8
} | https://github.com/home-assistant/core.git | |
8 | partial_fit | def partial_fit(self, X, y, classes=None):
if _check_partial_fit_first_call(self, classes):
self._validate_params()
if not hasattr(self.estimator, "partial_fit"):
raise ValueError(
("Base estimator {0}, doesn't have partial_fit method").forma... | 1aa38c44f60cb729faf217ef85f5cb7d1dd30b46 | 15 | multiclass.py | 372 | MAINT Parameters validation for OneVsRest estimator (#24290)
Co-authored-by: Jérémie du Boisberranger <34657725+jeremiedbb@users.noreply.github.com> | 76,491 | 0 | 493 | 232 | 100 | 260,786 | 129 | scikit-learn | 40 | sklearn/multiclass.py | Python | 28 | {
"docstring": "Partially fit underlying estimators.\n\n Should be used when memory is inefficient to train all data.\n Chunks of data can be passed in several iteration.\n\n Parameters\n ----------\n X : (sparse) array-like of shape (n_samples, n_features)\n Data.\n\n ... | https://github.com/scikit-learn/scikit-learn.git | |
12 | _get_items | def _get_items(self):
postprocess_items = {}
# Debug Landmarks
if (hasattr(self._args, 'debug_landmarks') and self._args.debug_landmarks):
postprocess_items["DebugLandmarks"] = None
# Face Filter post processing
if ((hasattr(self._args, "filter") and self._a... | 9e503bdaa2bfe2baaea50ad2e4bf742f309d9d10 | 16 | fsmedia.py | 422 | bugfix: debug landmarks | 20,730 | 0 | 496 | 249 | 67 | 101,311 | 108 | faceswap | 23 | scripts/fsmedia.py | Python | 29 | {
"docstring": " Check the passed in command line arguments for requested actions,\n\n For any requested actions, add the item to the actions list along with\n any relevant arguments and keyword arguments.\n\n Returns\n -------\n dict\n The name of the action to be perfor... | https://github.com/deepfakes/faceswap.git | |
3 | _apply_media_retention_rules | async def _apply_media_retention_rules(self) -> None:
# Purge remote media
if self._media_retention_remote_media_lifetime_ms is not None:
# Calculate a threshold timestamp derived from the configured lifetime. Any
# media that has not been accessed since this timestamp w... | 2fc787c341ff540e5880932f116498ec0ed7a2c2 | 13 | media_repository.py | 170 | Add config options for media retention (#12732) | 72,294 | 0 | 440 | 93 | 62 | 248,466 | 105 | synapse | 14 | synapse/rest/media/v1/media_repository.py | Python | 28 | {
"docstring": "\n Purge old local and remote media according to the media retention rules\n defined in the homeserver config.\n ",
"language": "en",
"n_whitespaces": 39,
"n_words": 17,
"vocab_size": 15
} | https://github.com/matrix-org/synapse.git | |
11 | _url | def _url(self, hashed_name_func, name, force=False, hashed_files=None):
if settings.DEBUG and not force:
hashed_name, fragment = name, ""
else:
clean_name, fragment = urldefrag(name)
if urlsplit(clean_name).path.endswith("/"): # don't hash paths
... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 15 | storage.py | 261 | Refs #33476 -- Reformatted code with Black. | 50,711 | 0 | 356 | 156 | 60 | 204,364 | 94 | django | 24 | django/contrib/staticfiles/storage.py | Python | 22 | {
"docstring": "\n Return the non-hashed URL in DEBUG mode.\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | https://github.com/django/django.git | |
8 | parseString | def parseString(self, instring, parseAll=False):
ParserElement.resetCache()
if not self.streamlined:
self.streamline()
# ~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = instring.e... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 17 | pyparsing.py | 233 | upd; format | 13,288 | 0 | 359 | 141 | 64 | 63,403 | 80 | transferlearning | 25 | .venv/lib/python3.8/site-packages/pip/_vendor/pyparsing.py | Python | 23 | {
"docstring": "\n Execute the parse expression with the given string.\n This is the main interface to the client code, once the complete\n expression has been built.\n\n Returns the parsed data as a :class:`ParseResults` object, which may be\n accessed as a list, or as a dict or ob... | https://github.com/jindongwang/transferlearning.git | |
4 | show_actual_vendor_versions | def show_actual_vendor_versions(vendor_txt_versions):
# type: (Dict[str, str]) -> None
for module_name, expected_version in vendor_txt_versions.items():
extra_message = ''
actual_version = get_vendor_version_from_module(module_name)
if not actual_version:
extra_message =... | f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 15 | debug.py | 126 | upd; format | 12,219 | 0 | 189 | 71 | 45 | 60,607 | 58 | transferlearning | 12 | .venv/lib/python3.8/site-packages/pip/_internal/commands/debug.py | Python | 12 | {
"docstring": "Log the actual version and print extra info if there is\n a conflict or if the actual version could not be imported.\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 22,
"vocab_size": 18
} | https://github.com/jindongwang/transferlearning.git | |
1 | test_sends_resolution_notification | def test_sends_resolution_notification(self, record_analytics):
url = f"/api/0/issues/{self.group.id}/"
with self.tasks():
response = self.client.put(url, format="json", data={"status": "resolved"})
assert response.status_code == 200, response.content
msg = mail.out... | afbf9a3334ce9cad1a62fced372d7fcee40a3133 | 14 | test_notifications.py | 360 | chore(notification): Pass User ID into notification analytics (#38924)
We pass in the actor_id to notification analytics events but we should
also include a user_id if the recipient is a user | 18,056 | 0 | 387 | 178 | 57 | 85,881 | 89 | sentry | 34 | tests/sentry/notifications/test_notifications.py | Python | 32 | {
"docstring": "\n Test that an email AND Slack notification are sent with\n the expected values when an issue is resolved.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 17
} | https://github.com/getsentry/sentry.git | |
1 | get | def get(self):
raise NotImplementedError
@keras_export("keras.utils.OrderedEnqueuer") | 84afc5193d38057e2e2badf9c889ea87d80d8fbf | @keras_export("keras.utils.OrderedEnqueuer") | 7 | data_utils.py | 27 | Reformatting the codebase with black.
PiperOrigin-RevId: 450093126 | 81,716 | 1 | 18 | 8 | 5 | 276,742 | 5 | keras | 4 | keras/utils/data_utils.py | Python | 2 | {
"docstring": "Creates a generator to extract data from the queue.\n\n Skip the data if it is `None`.\n # Returns\n Generator yielding tuples `(inputs, targets)`\n or `(inputs, targets, sample_weights)`.\n ",
"language": "en",
"n_whitespaces": 74,
"n_words": 27,
... | https://github.com/keras-team/keras.git |
2 | _check_data | def _check_data(self, xp, rs):
xp_lines = xp.get_lines()
rs_lines = rs.get_lines()
assert len(xp_lines) == len(rs_lines)
for xpl, rsl in zip(xp_lines, rs_lines):
xpdata = xpl.get_xydata()
rsdata = rsl.get_xydata()
tm.assert_almost_equal(xpdat... | 03fef5f0e35200aa5828975b62782bcf11faa0d2 | 10 | common.py | 119 | TST: Clean tests/plotting (#45992) | 39,621 | 0 | 104 | 73 | 26 | 164,924 | 29 | pandas | 17 | pandas/tests/plotting/common.py | Python | 9 | {
"docstring": "\n Check each axes has identical lines\n\n Parameters\n ----------\n xp : matplotlib Axes object\n rs : matplotlib Axes object\n ",
"language": "en",
"n_whitespaces": 61,
"n_words": 18,
"vocab_size": 14
} | https://github.com/pandas-dev/pandas.git | |
4 | get_1x_lr_params | def get_1x_lr_params(model):
b = [model.xception_features]
for i in range(len(b)):
for k in b[i].parameters():
if k.requires_grad:
yield k
| 2e5d23ee0e7fc1fdd7ad2e615fd651655aeb0f5b | 12 | deeplab_xception.py | 71 | Graphonomy Face/Hair Segmentation added | 1,642 | 0 | 59 | 43 | 14 | 9,617 | 17 | insightface | 10 | reconstruction/ostec/external/graphonomy/FaceHairMask/deeplab_xception.py | Python | 6 | {
"docstring": "\n This generator returns all the parameters of the net except for\n the last classification layer. Note that for each batchnorm layer,\n requires_grad is set to False in deeplab_resnet.py, therefore this function does not return\n any batchnorm parameter\n ",
"language": "en",
"n_w... | https://github.com/deepinsight/insightface.git | |
2 | parse_sysconfig_var | def parse_sysconfig_var(self) -> None:
defines = apache_util.parse_define_file(self.sysconfig_filep, "OPTIONS")
for k, v in defines.items():
self.variables[k] = v
| 7d9e9a49005de7961e84d2a7c608db57dbab3046 | 10 | override_centos.py | 65 | Add typing to certbot.apache (#9071)
* Add typing to certbot.apache
Co-authored-by: Adrien Ferrand <ferrand.ad@gmail.com> | 45,572 | 0 | 48 | 39 | 14 | 186,664 | 16 | certbot | 10 | certbot-apache/certbot_apache/_internal/override_centos.py | Python | 5 | {
"docstring": " Parses Apache CLI options from CentOS configuration file ",
"language": "en",
"n_whitespaces": 9,
"n_words": 8,
"vocab_size": 8
} | https://github.com/certbot/certbot.git | |
69 | max_weight_matching | def max_weight_matching(G, maxcardinality=False, weight="weight"):
#
# The algorithm is taken from "Efficient Algorithms for Finding Maximum
# Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
# It is based on the "blossom" method for finding augmenting paths and
# the "primal-dual... | 853fb4b27b547bf11761d73c1a62648701f3679f | 6 | matching.py | 38 | Added docstring examples to matching functions (#5617)
Co-authored-by: Dan Schult <dschult@colgate.edu>
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu> | 42,021 | 0 | 151 | 1,118 | 74 | 176,653 | 109 | networkx | 4 | networkx/algorithms/matching.py | Python | 165 | {
"docstring": "Compute a maximum-weighted matching of G.\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 add more edges and still be a matching.\n The cardinality of a matching is th... | https://github.com/networkx/networkx.git | |
4 | make_action_immutable | def make_action_immutable(obj):
if isinstance(obj, np.ndarray):
obj.setflags(write=False)
return obj
elif isinstance(obj, OrderedDict):
return MappingProxyType(dict(obj))
elif isinstance(obj, dict):
return MappingProxyType(obj)
else:
return obj
| 242706922b44d4ba4e395deaf6e98b745474863b | 12 | numpy.py | 96 | [rllib] Fix linting (#24335)
#24262 broke linting. This fixes this. | 31,541 | 0 | 71 | 59 | 14 | 138,874 | 21 | ray | 10 | rllib/utils/numpy.py | Python | 10 | {
"docstring": "Flags actions immutable to notify users when trying to change\n them.\n\n Can also be used with any tree-like structure containing either\n dictionaries, numpy arrays or already immutable objects per se.\n Note, however that `tree.map_structure()` will in general not\n include the shall... | https://github.com/ray-project/ray.git | |
13 | execute_list_role | def execute_list_role(self):
path_found = False
role_found = False
warnings = []
roles_search_paths = context.CLIARGS['roles_path']
role_name = context.CLIARGS['role']
for path in roles_search_paths:
role_path = GalaxyCLI._resolve_path(path)
... | cb2e434dd2359a9fe1c00e75431f4abeff7381e8 | 17 | galaxy.py | 465 | ansible-galaxy install - fix unnecessary api check when installing a role from git repo (#79090)
* delay server api evaluation until a GalaxyRole needs to make an api call for info, list, and install | 79,564 | 0 | 742 | 278 | 97 | 268,616 | 177 | ansible | 33 | lib/ansible/cli/galaxy.py | Python | 41 | {
"docstring": "\n List all roles installed on the local system or a specific role\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 12,
"vocab_size": 12
} | https://github.com/ansible/ansible.git | |
10 | localize_input | def localize_input(value, default=None):
if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(value, bool): # Don't treat booleans as numbers.
return str(value)
elif isinstance(value, (decimal.Decimal, float, int)):
return num... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | @functools.lru_cache | 14 | formats.py | 250 | Refs #33476 -- Reformatted code with Black. | 51,614 | 1 | 174 | 152 | 40 | 206,662 | 72 | django | 20 | django/utils/formats.py | Python | 19 | {
"docstring": "\n Check if an input value is a localizable type and return it\n formatted with the appropriate formatting string of the current locale.\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 22,
"vocab_size": 21
} | https://github.com/django/django.git |
3 | _process_state | def _process_state(self, entity_observation):
entity = entity_observation.entity_id
try:
if condition.state(self.hass, entity, [STATE_UNKNOWN, STATE_UNAVAILABLE]):
return None
return condition.state(self.hass, entity, entity_observation.to_state)
... | dd1463da287f591652e47b00eee0c5b77f5f5b7c | 10 | binary_sensor.py | 84 | Refactor bayesian observations using dataclass (#79590)
* refactor
* remove some changes
* remove typehint
* improve codestyle
* move docstring to comment
* < 88 chars
* avoid short var names
* more readable
* fix rename
* Update homeassistant/components/bayesian/helpers.py
Co-authored-by... | 87,639 | 0 | 98 | 55 | 17 | 288,481 | 22 | core | 12 | homeassistant/components/bayesian/binary_sensor.py | Python | 8 | {
"docstring": "Return True if state conditions are met, return False if they are not.\n\n Returns None if the state is unavailable.\n ",
"language": "en",
"n_whitespaces": 34,
"n_words": 20,
"vocab_size": 16
} | https://github.com/home-assistant/core.git | |
3 | pi | def pi(self):
total = 0.0
label_freqs = FreqDist(x["labels"] for x in self.data)
for k, f in label_freqs.items():
total += f**2
Ae = total / ((len(self.I) * len(self.C)) ** 2)
return (self.avg_Ao() - Ae) / (1 - Ae)
| 0fac0c0f8e4618c2bdd3d2137d5fb8a80f581246 | 14 | agreement.py | 128 | Update black to 22.3.0
The most recent release of Click (8.1.0) was breaking Black. See psf/black#2964 | 7,551 | 0 | 90 | 81 | 28 | 42,462 | 37 | nltk | 15 | nltk/metrics/agreement.py | Python | 7 | {
"docstring": "Scott 1955; here, multi-pi.\n Equivalent to K from Siegel and Castellan (1988).\n\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 12,
"vocab_size": 12
} | https://github.com/nltk/nltk.git | |
1 | test_user_logout_all | def test_user_logout_all(self) -> None:
# Login in as the user
puppet_token = self._get_token()
# Test that we can successfully make a request
channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
self.assertEqual(HTTPStatus.OK, channel.code, m... | 901b264c0c88f39cbfb8b2229e0dc57968882658 | 10 | test_user.py | 255 | Add type hints to `tests/rest/admin` (#11851) | 71,059 | 0 | 226 | 159 | 51 | 246,165 | 85 | synapse | 15 | tests/rest/admin/test_user.py | Python | 17 | {
"docstring": "Tests that the target user calling `/logout/all` does *not* expire\n the token.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 12,
"vocab_size": 11
} | https://github.com/matrix-org/synapse.git | |
2 | create_vae_diffusers_config | def create_vae_diffusers_config(original_config):
vae_params = original_config.model.params.first_stage_config.params.ddconfig
_ = original_config.model.params.first_stage_config.params.embed_dim
block_out_channels = [vae_params.ch * mult for mult in vae_params.ch_mult]
down_block_types = ["DownEn... | 039958eae55ff0700cfb42a7e72739575ab341f1 | 11 | convert_original_stable_diffusion_to_diffusers.py | 193 | Stable diffusion text2img conversion script. (#154)
* begin text2img conversion script
* add fn to convert config
* create config if not provided
* update imports and use UNet2DConditionModel
* fix imports, layer names
* fix unet coversion
* add function to convert VAE
* fix vae conversion
* up... | 120,913 | 0 | 124 | 125 | 31 | 336,767 | 41 | diffusers | 28 | scripts/convert_original_stable_diffusion_to_diffusers.py | Python | 17 | {
"docstring": "\n Creates a config for the diffusers based on the config of the LDM model.\n ",
"language": "en",
"n_whitespaces": 21,
"n_words": 14,
"vocab_size": 11
} | https://github.com/huggingface/diffusers.git | |
5 | __isub__ | def __isub__(self, other):
m = getmask(other)
if self._mask is nomask:
if m is not nomask and m.any():
self._mask = make_mask_none(self.shape, self.dtype)
self._mask += m
elif m is not nomask:
self._mask += m
other_data = g... | 8fced79a8c60d86aaaaf997aa861589336f7899c | 13 | core.py | 158 | MAINT: Fortify masked in-place ops against promotion warnings
These warnings are probably optional in the future. They should
not matter much (since the following is an in-place op), but
the `np.where` could upcast currently! | 38,627 | 0 | 151 | 100 | 26 | 160,410 | 43 | numpy | 17 | numpy/ma/core.py | Python | 12 | {
"docstring": "\n Subtract other from self in-place.\n\n ",
"language": "en",
"n_whitespaces": 20,
"n_words": 5,
"vocab_size": 5
} | https://github.com/numpy/numpy.git | |
1 | mixin_head_parser | def mixin_head_parser(parser):
gp = add_arg_group(parser, title='Head')
gp.add_argument(
'--uses-before-address',
type=str,
help='The address of the uses-before runtime',
)
gp.add_argument(
'--uses-after-address',
type=str,
help='The address of the... | c7ad27e5614dfb2b1684f4718c5508840cd55de0 | 10 | head.py | 137 | refactor: add disable_reduce args (#4424) | 2,054 | 0 | 186 | 80 | 44 | 11,483 | 65 | jina | 11 | jina/parsers/orchestrate/runtimes/head.py | Python | 23 | {
"docstring": "Mixing in arguments required by head pods and runtimes into the given parser.\n :param parser: the parser instance to which we add arguments\n ",
"language": "en",
"n_whitespaces": 29,
"n_words": 23,
"vocab_size": 21
} | https://github.com/jina-ai/jina.git | |
3 | get_pe_matching_query | def get_pe_matching_query(amount_condition, account_from_to, transaction):
# get matching payment entries query
from_date = frappe.db.get_single_value('Bank Reconciliation Tool','bank_statement_from_date')
to_date = frappe.db.get_single_value('Bank Reconciliation Tool','bank_statement_to_date')
from_reference_date ... | e5a1189becad071f54c727bc6c0dba16bea2a12f | 11 | bank_reconciliation_tool.py | 222 | Update bank_reconciliation_tool.py
Applying date filter on transactions and all the bank entries and also gives the filter the bank entries as per reference date. Sorted all transactions and entries as per date in ascending order.
Also added posting date columns in all bank entries and default checkbox tick of journal... | 15,082 | 0 | 45 | 101 | 38 | 69,682 | 59 | erpnext | 15 | erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py | Python | 65 | {
"docstring": "\n\t\t\tSELECT\n\t\t\t\t(CASE WHEN reference_no=%(reference_no)s THEN 1 ELSE 0 END\n\t\t\t\t+ CASE WHEN (party_type = %(party_type)s AND party = %(party)s ) THEN 1 ELSE 0 END\n\t\t\t\t+ 1 ) AS rank,\n\t\t\t\t'Payment Entry' as doctype,\n\t\t\t\tname,\n\t\t\t\tpaid_amount,\n\t\t\t\treference_no,\n\t\t... | https://github.com/frappe/erpnext.git | |
2 | set_client_cli_parser | def set_client_cli_parser(parser=None):
if not parser:
from jina.parsers.base import set_base_parser
parser = set_base_parser()
from jina.parsers.peapods.runtimes.remote import mixin_client_gateway_parser
from jina.parsers.client import (
mixin_client_features_parser,
... | cea300655ed8be70d74c390ca12e8b09fb741665 | 10 | __init__.py | 99 | refactor: use absolute imports (#4167) | 1,853 | 0 | 83 | 64 | 23 | 10,563 | 28 | jina | 13 | jina/parsers/__init__.py | Python | 13 | {
"docstring": "Set the parser for the cli client\n\n :param parser: an optional existing parser to build upon\n :return: the parser\n ",
"language": "en",
"n_whitespaces": 28,
"n_words": 19,
"vocab_size": 15
} | https://github.com/jina-ai/jina.git | |
3 | get_delivered_items_cost | def get_delivered_items_cost():
dn_items = frappe.db.sql(
,
as_dict=1,
)
si_items = frappe.db.sql(
,
as_dict=1,
)
dn_item_map = {}
for item in dn_items:
dn_item_map.setdefault(item.project, item.amount)
for item in si_items:
dn_item_map.setdefault(item.project, item.amount)
return dn_item_map
| 494bd9ef78313436f0424b918f200dab8fc7c20b | 10 | project_wise_stock_tracking.py | 116 | style: format code with black | 14,413 | 0 | 16 | 74 | 19 | 67,035 | 31 | erpnext | 12 | erpnext/projects/report/project_wise_stock_tracking/project_wise_stock_tracking.py | Python | 22 | {
"docstring": "select dn.project, sum(dn_item.base_net_amount) as amount\n\t\tfrom `tabDelivery Note` dn, `tabDelivery Note Item` dn_item\n\t\twhere dn.name = dn_item.parent and dn.docstatus = 1 and ifnull(dn.project, '') != ''\n\t\tgroup by dn.projectselect si.project, sum(si_item.base_net_amount) as amount\n\t\tfr... | https://github.com/frappe/erpnext.git | |
5 | set_location | def set_location(self, location):
# This puts the rectangle into figure-relative coordinates.
if isinstance(location, str):
_api.check_in_list(self._locstrings, location=location)
self._pos = 1. if location in ('top', 'right') else 0.
elif isinstance(location, n... | 8387676bc049d7b3e071846730c632e6ced137ed | 15 | _secondary_axes.py | 230 | Clean up code in SecondaryAxis | 23,720 | 0 | 363 | 130 | 97 | 109,724 | 142 | matplotlib | 19 | lib/matplotlib/axes/_secondary_axes.py | Python | 17 | {
"docstring": "\n Set the vertical or horizontal location of the axes in\n parent-normalized coordinates.\n\n Parameters\n ----------\n location : {'top', 'bottom', 'left', 'right'} or float\n The position to put the secondary axis. Strings can be 'top' or\n ... | https://github.com/matplotlib/matplotlib.git | |
8 | load_and_dump | def load_and_dump(self) -> None:
with ExitStack() as stack:
# set env vars
stack.enter_context(change_env('JINA_FULL_CLI', 'true'))
# change directory to `workspace`
stack.enter_context(change_cwd(get_workspace_path(self.workspace_id)))
# lo... | 13edc16d806fb5d77a6849551178ccc75937f25f | 18 | dependencies.py | 436 | refactor: rename pod to deployment (#4230)
* refactor: rename pod to deployment
* style: fix overload and cli autocomplete
* fix: undo daemon mistake
* refactor: leftover cleanup
* fix: more test fixes
* fix: more fixes
* fix: more fixes
* fix: more fixes
* fix: more tests
* fix: fix more te... | 1,916 | 0 | 994 | 267 | 92 | 10,804 | 129 | jina | 51 | daemon/api/dependencies.py | Python | 63 | {
"docstring": "\n every Flow created inside JinaD lives inside a container. It is important to know the\n list of ports to be published with localhost before actually starting the container.\n\n 1. `load` the flow yaml here.\n - yaml is stored in `workspace` directory, so we'll `cd` t... | https://github.com/jina-ai/jina.git | |
7 | search | def search(self, content):
result = []
length = len(content)
for start in range(length):
for end in range(start + 1, length + 1):
pos = self.tree.get(content[start:end], -1)
if pos == -1:
break
if pos and (l... | 621357338437ee420eabbbf5ab19065bc85e73a5 | 16 | utils.py | 156 | Update neural search readme and Add Paddle Serving Support (#1558)
* add recall inference similarity
* update examples
* updatea readme
* update dir name
* update neural search readme
* update milvus readme
* update domain adaptive pretraining readme
* fix the mistakes
* update readme
* add ... | 118,098 | 0 | 174 | 100 | 33 | 322,216 | 45 | PaddleNLP | 13 | paddlenlp/taskflow/utils.py | Python | 11 | {
"docstring": "Backward maximum matching\n\n Args:\n content (str): string to be searched\n Returns:\n List[Tuple]: list of maximum matching words, each element represents \n the starting and ending position of the matching string.\n ",
"language": "en",
... | https://github.com/PaddlePaddle/PaddleNLP.git | |
2 | send_gstin_reminder | def send_gstin_reminder(party_type, party):
frappe.has_permission(party_type, throw=True)
email = _send_gstin_reminder(party_type, party)
if email:
frappe.msgprint(_("Reminder to update GSTIN Sent"), title="Reminder sent", indicator="green")
| 494bd9ef78313436f0424b918f200dab8fc7c20b | 12 | gst_settings.py | 78 | style: format code with black | 14,421 | 0 | 14 | 46 | 19 | 67,056 | 19 | erpnext | 12 | erpnext/regional/doctype/gst_settings/gst_settings.py | Python | 5 | {
"docstring": "Send GSTIN reminder to one party (called from Customer, Supplier form)",
"language": "en",
"n_whitespaces": 10,
"n_words": 11,
"vocab_size": 11
} | https://github.com/frappe/erpnext.git | |
7 | serialize | def serialize(items):
data = QByteArray()
stream = QDataStream(data, QIODevice.OpenModeFlag.ReadWrite)
cur_user_data = None
current_idx = None
for i, item in enumerate(items):
if item.active:
if current_idx is not None:
raise ValueError("Multiple active ite... | 0877fb0d78635692e481c8bde224fac5ad0dd430 | 17 | tabhistory.py | 246 | Run scripts/dev/rewrite_enums.py | 117,553 | 0 | 337 | 143 | 60 | 321,126 | 91 | qutebrowser | 26 | qutebrowser/browser/webengine/tabhistory.py | Python | 25 | {
"docstring": "Serialize a list of TabHistoryItems to a data stream.\n\n Args:\n items: An iterable of TabHistoryItems.\n\n Return:\n A (stream, data, user_data) tuple.\n stream: The reset QDataStream.\n data: The QByteArray with the raw data.\n cur_user_data: The... | https://github.com/qutebrowser/qutebrowser.git | |
2 | check_query_parameters | def check_query_parameters(self, queryset):
query_parameters = set(self.request.GET.keys())
# All query parameters must be either a database field or an operation
allowed_query_parameters = set(
self.get_available_fields(queryset.model, db_fields_only=True)
).union(... | d10f15e55806c6944827d801cd9c2d53f5da4186 | 14 | views.py | 117 | Reformat with black | 15,918 | 0 | 161 | 69 | 41 | 72,960 | 49 | wagtail | 18 | wagtail/api/v2/views.py | Python | 11 | {
"docstring": "\n Ensure that only valid query parameters are included in the URL.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 11,
"vocab_size": 11
} | https://github.com/wagtail/wagtail.git | |
2 | request | def request(self, method, path, data=None, params=None, **kwargs):
request_spec = self.request_hook(method, path, data, params, **kwargs)
if "headers" not in request_spec:
request_spec["headers"] = {}
# Force adherence to the GDPR compliant API conventions.
# See
... | 2fbf550ec05c8501cbc9eca62e73526e717dcbdf | 10 | client.py | 113 | ref(Jira): Split Jira Cloud and Jira Server (#37034)
* Split Jira Cloud and Jira Server | 19,008 | 0 | 107 | 68 | 35 | 93,686 | 40 | sentry | 10 | src/sentry/integrations/jira/client.py | Python | 6 | {
"docstring": "\n Use the request_hook method for our specific style of Jira to\n add authentication data and transform parameters.\n ",
"language": "en",
"n_whitespaces": 39,
"n_words": 17,
"vocab_size": 17
} | https://github.com/getsentry/sentry.git | |
1 | nullify_connected_endpoints | def nullify_connected_endpoints(instance, **kwargs):
model = instance.termination_type.model_class()
model.objects.filter(pk=instance.termination_id).update(_link_peer_type=None, _link_peer_id=None)
| 8bc6d8cb231ad45cd8b97ffb26cc3d989c60c277 | 11 | signals.py | 67 | Introduce CablePath.retrace() to handle deleted cables | 77,858 | 0 | 17 | 41 | 8 | 264,840 | 8 | netbox | 13 | netbox/dcim/signals.py | Python | 3 | {
"docstring": "\n Disassociate the Cable from the termination object.\n ",
"language": "en",
"n_whitespaces": 14,
"n_words": 7,
"vocab_size": 6
} | https://github.com/netbox-community/netbox.git | |
7 | getModuleImportableFilesHash | def getModuleImportableFilesHash(full_name):
package_name = full_name.getPackageName()
paths = getPackageSearchPath(None)
if package_name is not None:
paths += getPackageSearchPath(package_name)
all_suffixes = getAllModuleSuffixes()
result_hash = Hash()
for path in paths:
... | 840959fbec6d897aa7e51f63e1c34e46402ced8b | 14 | Caching.py | 159 | Optimization: Make experimental caching bytecode demotion work. | 42,780 | 0 | 125 | 96 | 33 | 178,646 | 43 | Nuitka | 20 | nuitka/Caching.py | Python | 14 | {
"docstring": "Calculate hash value of packages importable for a module of this name.",
"language": "en",
"n_whitespaces": 11,
"n_words": 12,
"vocab_size": 11
} | https://github.com/Nuitka/Nuitka.git | |
2 | get_summary_stats | def get_summary_stats(self) -> List[dict]:
logger.debug("Compiling sessions summary data")
self._get_time_stats()
self._get_per_session_stats()
if not self._per_session_stats:
return self._per_session_stats
total_stats = self._total_stats()
retval = ... | afec52309326304f4323029039e49bfcf928ef43 | 8 | stats.py | 122 | Bugfixes:
- Stats graph - Handle NaNs in data
- logger - de-elevate matplotlib font messages | 20,168 | 0 | 113 | 71 | 26 | 100,713 | 32 | faceswap | 13 | lib/gui/analysis/stats.py | Python | 22 | {
"docstring": " Compile the individual session statistics and calculate the total.\n\n Format the stats for display\n\n Returns\n -------\n list\n A list of summary statistics dictionaries containing the Session ID, start time, end\n time, elapsed time, rate, batch s... | https://github.com/deepfakes/faceswap.git | |
2 | zero_module | def zero_module(module):
for p in module.parameters():
p.detach().zero_()
return module
| f4d6e64cdc132ae868699a0ba442f4ab1d304a14 | 11 | nn.py | 46 | add disco_diffusion_cnclip_vitb16 module | 9,933 | 0 | 25 | 26 | 9 | 49,823 | 9 | PaddleHub | 6 | modules/image/text_to_image/disco_diffusion_cnclip_vitb16/reverse_diffusion/model/nn.py | Python | 4 | {
"docstring": "\n Zero out the parameters of a module and return it.\n ",
"language": "en",
"n_whitespaces": 17,
"n_words": 10,
"vocab_size": 10
} | https://github.com/PaddlePaddle/PaddleHub.git | |
6 | normalize_drive | def normalize_drive(path):
if os.name != "nt" or not isinstance(path, str):
return path
drive, tail = os.path.splitdrive(path)
# Only match (lower cased) local drives (e.g. 'c:'), not UNC mounts.
if drive.islower() and len(drive) == 2 and drive[1] == ":":
return f"{drive.upper()}{t... | 3387881a6d4fc2d8bdc0f05c484cb2f7222acfb8 | @contextmanager | 11 | shell.py | 123 | Code reorg utils into utils module reduces complexity (#4990)
* Split apart the massive utils.py into a utils module | 3,025 | 1 | 74 | 61 | 36 | 19,569 | 43 | pipenv | 13 | pipenv/utils/shell.py | Python | 7 | {
"docstring": "Normalize drive in path so they stay consistent.\n\n This currently only affects local drives on Windows, which can be\n identified with either upper or lower cased drive names. The case is\n always converted to uppercase because it seems to be preferred.\n\n See: <https://github.com/pypa/... | https://github.com/pypa/pipenv.git |
6 | check_models_are_tested | def check_models_are_tested(module, test_file):
# XxxPreTrainedModel are not tested
defined_models = get_models(module)
tested_models = find_tested_models(test_file)
if tested_models is None:
if test_file.replace(os.path.sep, "/") in TEST_FILES_WITH_NO_COMMON_TESTS:
return
... | 1f9e862507704774334dc22a84724e74f52232b7 | 19 | check_repo.py | 185 | Update check_models_are_tested to deal with Windows path (#16973)
* fix
* Apply suggestions from code review
Co-authored-by: ydshieh <ydshieh@users.noreply.github.com>
Co-authored-by: Sylvain Gugger <35901082+sgugger@users.noreply.github.com> | 6,780 | 0 | 299 | 89 | 74 | 37,451 | 121 | transformers | 20 | utils/check_repo.py | Python | 21 | {
"docstring": "Check models defined in module are tested in test_file.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 8
} | https://github.com/huggingface/transformers.git | |
3 | test_with_slicing | def test_with_slicing(metrics_message, setup_slicing) -> None:
org_id = metrics_message.payload.routing_header.get("org_id")
router = SlicingRouter("sliceable")
route = router.get_route_for_message(metrics_message)
if int(org_id) % SENTRY_SLICING_LOGICAL_PARTITION_COUNT < 128:
assert route.... | e1c5b9ca3bdeadcfdb328dc42740923038d6eb94 | 11 | test_slicing_router.py | 144 | feat(indexer): Allow routing of messages (#40776)
### Context
In order to support slicing in Snuba, the upstream dependency of Snuba
i.e. Sentry metrics indexer needs to route messages to different slices.
The current implementation is hardcoded to send messages on a single
destination topic.
### Implementation... | 18,423 | 0 | 85 | 83 | 30 | 88,664 | 40 | sentry | 16 | tests/sentry/sentry_metrics/consumers/test_slicing_router.py | Python | 15 | {
"docstring": "\n With partitioning settings, the SlicingRouter should route to the correct topic\n based on the org_id header.\n ",
"language": "en",
"n_whitespaces": 26,
"n_words": 16,
"vocab_size": 14
} | https://github.com/getsentry/sentry.git | |
3 | get_dependencies | def get_dependencies(dsk, key=None, task=no_default, as_list=False):
if key is not None:
arg = dsk[key]
elif task is not no_default:
arg = task
else:
raise ValueError("Provide either key or task")
return keys_in_tasks(dsk, [arg], as_list=as_list)
| cccb9d8d8e33a891396b1275c2448c352ef40c27 | 11 | core.py | 92 | absolufy-imports - No relative - PEP8 (#8796)
Conversation in https://github.com/dask/distributed/issues/5889 | 36,541 | 0 | 68 | 59 | 26 | 156,079 | 32 | dask | 9 | dask/core.py | Python | 8 | {
"docstring": "Get the immediate tasks on which this task depends\n\n Examples\n --------\n >>> inc = lambda x: x + 1\n >>> add = lambda x, y: x + y\n >>> dsk = {'x': 1,\n ... 'y': (inc, 'x'),\n ... 'z': (add, 'x', 'y'),\n ... 'w': (inc, 'z'),\n ... 'a': (add, (... | https://github.com/dask/dask.git | |
3 | start | def start(self, page, user):
state = WorkflowState(
page=page,
workflow=self,
status=WorkflowState.STATUS_IN_PROGRESS,
requested_by=user,
)
state.save()
state.update(user=user)
workflow_submitted.send(sender=state.__class__... | d10f15e55806c6944827d801cd9c2d53f5da4186 | 15 | __init__.py | 260 | Reformat with black | 16,126 | 0 | 459 | 166 | 47 | 73,815 | 57 | wagtail | 27 | wagtail/core/models/__init__.py | Python | 34 | {
"docstring": "Initiates a workflow by creating an instance of ``WorkflowState``",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/wagtail/wagtail.git | |
2 | unpack | def unpack(self, location, url):
# type: (str, HiddenText) -> None
if os.path.exists(location):
rmtree(location)
self.obtain(location, url=url)
| f638f5d0e6c8ebed0e69a6584bc7f003ec646580 | 9 | versioncontrol.py | 56 | upd; format | 12,546 | 0 | 54 | 34 | 15 | 61,400 | 15 | transferlearning | 9 | .venv/lib/python3.8/site-packages/pip/_internal/vcs/versioncontrol.py | Python | 4 | {
"docstring": "\n Clean up current location and download the url repository\n (and vcs infos) into location\n\n :param url: the repository URL starting with a vcs prefix.\n ",
"language": "en",
"n_whitespaces": 53,
"n_words": 24,
"vocab_size": 20
} | https://github.com/jindongwang/transferlearning.git | |
5 | mutual_info_score | def mutual_info_score(labels_true, labels_pred, *, contingency=None):
if contingency is None:
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
contingency = contingency_matrix(labels_true, labels_pred, sparse=True)
else:
contingency = check_array(
c... | 8256a48519b7ff0a29c46862de533cefa9ad7f48 | 14 | _supervised.py | 488 | MAINT Parameters validation for metrics.mutual_info_score (#25243) | 77,010 | 0 | 344 | 312 | 111 | 261,808 | 157 | scikit-learn | 43 | sklearn/metrics/cluster/_supervised.py | Python | 32 | {
"docstring": "Mutual Information between two clusterings.\n\n The Mutual Information is a measure of the similarity between two labels\n of the same data. Where :math:`|U_i|` is the number of the samples\n in cluster :math:`U_i` and :math:`|V_j|` is the number of the\n samples in cluster :math:`V_j`, th... | https://github.com/scikit-learn/scikit-learn.git | |
2 | _load_own_variables | def _load_own_variables(self, store):
for i, variable in enumerate(self.variables()):
variable.assign(store[str(i)])
base_optimizer_keyword_args =
@keras_export(
"keras.optimizers.Optimizer",
"keras.optimizers.experimental.Optimizer",
v1=[],
) | 2851235d5bc1c6603a97d7efffc7649b0a84b826 | @keras_export(
"keras.optimizers.Optimizer",
"keras.optimizers.experimental.Optimizer",
v1=[],
) | 12 | optimizer.py | 86 | Use a single h5 file for all numerical state in the model.
The modular design enables us to easily swap out the h5 file storage with any other form of storage (e.g. npz or tensorstore) in the future. Just implement a new IOHandler for the new storage system.
PiperOrigin-RevId: 479718541 | 83,263 | 1 | 48 | 34 | 16 | 280,118 | 16 | keras | 12 | keras/optimizers/optimizer_experimental/optimizer.py | Python | 3 | {
"docstring": "Set the state of this optimizer object.name: String. The name to use\n for momentum accumulator weights created by\n the optimizer.\n weight_decay: Float, defaults to None. If set, weight decay is applied.\n clipnorm: Float. If set, the gradient of each weight is individually\n... | https://github.com/keras-team/keras.git |
2 | test_sessions_metrics_equal_num_keys | def test_sessions_metrics_equal_num_keys(self):
empty_groupbyes = ["project", "release", "environment", "session.status"]
interval_days = "1d"
for groupby in empty_groupbyes:
with patch(
"sentry.api.endpoints.organization_sessions.release_health",
... | cfdb7fdc1fef7f8a364bbfef050cdcfc66c82371 | 14 | test_metrics_sessions_v2.py | 195 | fix(metrics): Zero-fill response when there's no data [INGEST-941] (#32157)
When there isn't any metrics data, the `groups` of the response is empty.
However, the absence of data must be represented with an appropriate value.
For example, `count_unique(user)` must return `0` when there aren't any
users, instead of ... | 19,338 | 0 | 325 | 114 | 45 | 96,684 | 58 | sentry | 20 | tests/sentry/release_health/test_metrics_sessions_v2.py | Python | 22 | {
"docstring": "\n Tests whether the number of keys in the metrics implementation of\n sessions data is the same as in the sessions implementation.\n\n Runs twice. Firstly, against sessions implementation to populate the\n cache. Then, against the metrics implementation, and compares with\... | https://github.com/getsentry/sentry.git | |
1 | get_linear_schedule_with_warmup | def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
| 71289ba06ea897270ad6de0ea7ff641f4a7b246c | 6 | optimization.py | 24 | add lr schedule utils | 120,727 | 0 | 8 | 26 | 5 | 335,246 | 5 | diffusers | 5 | src/diffusers/optimization.py | Python | 3 | {
"docstring": "\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0, after\n a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.\n\n Args:\n optimizer ([`~torch.optim.Optimizer`]):\n Th... | https://github.com/huggingface/diffusers.git | |
6 | _dedupe_indices | def _dedupe_indices(new, exclude):
exclude = set(exclude)
dums_new = set(get_dummy_indices(new))
conflicts = dums_new.intersection(exclude)
if len(conflicts) == 0:
return None
exclude.update(dums_new)
self_args_free = [(i, None) for i in ex... | 22174995eac1f437c5f4abe0232760877daf586f | 13 | tensor.py | 240 | TensMul._dedupe_indices: remove index_structure arg
_get_generator_for_dummy_indices is a staticmethod, and so I can just
call _IndexStructure._get_generator_for_dummy_indices | 49,714 | 0 | 257 | 148 | 44 | 200,579 | 66 | sympy | 25 | sympy/tensor/tensor.py | Python | 26 | {
"docstring": "\n exclude: set\n new: TensExpr\n\n If ``new`` has any dummy indices that are in ``exclude``, return a version\n of new with those indices replaced. If no replacements are needed,\n return None\n\n \n ``self_args_free`` is to be passed to ``_IndexStruct... | https://github.com/sympy/sympy.git | |
9 | tls_session_update | def tls_session_update(self, msg_str):
super(TLS13ClientHello, self).tls_session_update(msg_str)
s = self.tls_session
if self.sidlen and self.sidlen > 0:
s.sid = self.sid
s.middlebox_compatibility = True
self.random_bytes = msg_str[6:38]
s.clien... | eb1e56d676c78ccbd5a3c820b931ac50f6a5a4f8 | 18 | handshake.py | 201 | TLS1.3: wrong parsing size of random_bytes (#3539)
Co-authored-by: dim0x69 <github@3or.de> | 52,590 | 0 | 410 | 126 | 53 | 209,068 | 76 | scapy | 25 | scapy/layers/tls/handshake.py | Python | 17 | {
"docstring": "\n Either for parsing or building, we store the client_random\n along with the raw string representing this handshake message.\n ",
"language": "en",
"n_whitespaces": 40,
"n_words": 18,
"vocab_size": 17
} | https://github.com/secdev/scapy.git | |
1 | _reshape_tensor | def _reshape_tensor(self, new_len, tensor, indices):
reshaped_tensor = torch.zeros(new_len, device=tensor.device, dtype=tensor.dtype)
reshaped_tensor[indices] = tensor
return reshaped_tensor
| b1acb681207559da56a787ba96e16f0e23697d92 | 10 | director_bb2.py | 60 | Patch 8322 (#4709)
* add dafetymix teacher
* safety_mix teacher
* safety_mix teacher pos and neg teachers
* add tests for teacher
* add license info
* improvement
* add task list
* add task list and lint
* add init.py
* adding some patch to director
* seeker changes
* th
* 3
* ji... | 47,242 | 0 | 43 | 40 | 13 | 195,279 | 15 | ParlAI | 10 | projects/fits/agents/director_bb2.py | Python | 4 | {
"docstring": "\n This method reshapes the tensor back to the batch size.\n\n Args:\n batch: batch being processed in this iteration.\n tensor: vector (shape: b' X 1), where b' <= b.\n indices: indices of (either classification or generation) exs for which the loss was ... | https://github.com/facebookresearch/ParlAI.git | |
6 | getphraselist | def getphraselist(self):
plist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.FWS:
self.pos += 1
elif self.field[self.pos] == '"':
plist.append(self.getquote())
elif self.field[self.pos] == '(':
... | 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 15 | _parseaddr.py | 196 | add python 3.10.4 for windows | 57,004 | 0 | 193 | 119 | 26 | 223,611 | 35 | XX-Net | 13 | python3.10.4/Lib/email/_parseaddr.py | Python | 14 | {
"docstring": "Parse a sequence of RFC 2822 phrases.\n\n A phrase is a sequence of words, which are in turn either RFC 2822\n atoms or quoted-strings. Phrases are canonicalized by squeezing all\n runs of continuous whitespace into one space.\n ",
"language": "en",
"n_whitespaces": 66... | https://github.com/XX-net/XX-Net.git | |
1 | test_login_appservice_wrong_as | def test_login_appservice_wrong_as(self) -> None:
self.register_appservice_user(AS_USER, self.service.token)
params = {
"type": login.LoginRestServlet.APPSERVICE_TYPE,
"identifier": {"type": "m.id.user", "user": AS_USER},
}
channel = self.make_request(
... | 64c73c6ac88a740ee480a0ad1f9afc8596bccfa4 | 11 | test_login.py | 136 | Add type hints to `tests/rest/client` (#12066) | 71,281 | 0 | 110 | 83 | 27 | 246,588 | 28 | synapse | 17 | tests/rest/client/test_login.py | Python | 11 | {
"docstring": "Test that as users cannot login with wrong as token",
"language": "en",
"n_whitespaces": 9,
"n_words": 10,
"vocab_size": 9
} | https://github.com/matrix-org/synapse.git | |
19 | __exit__ | def __exit__(self, exc_type, exc_val, traceback):
if exc_type == ModuleNotFoundError:
missing_module = self._pkg_name or exc_val.name
with open(os.path.join(__resources_path__, 'extra-requirements.txt')) as fp:
for v in fp:
if (
... | cea300655ed8be70d74c390ca12e8b09fb741665 | 19 | importer.py | 565 | refactor: use absolute imports (#4167) | 1,848 | 0 | 992 | 296 | 101 | 10,555 | 143 | jina | 46 | jina/importer.py | Python | 49 | {
"docstring": "Python package \"{colored(missing_module, attrs='bold')}\" is not installed, {req_msg}.\n You are trying to use a feature not enabled by your current Jina installation.",
"language": "en",
"n_whitespaces": 40,
"n_words": 22,
"vocab_size": 21
} | https://github.com/jina-ai/jina.git | |
1 | _patch_app_session | def _patch_app_session(self):
return mock.patch(
"streamlit.server.server.AppSession",
# new_callable must return a function, not an object, or else
# there will only be a single AppSession mock. Hence the lambda.
new_callable=lambda: self._create_mock_a... | 704eab3478cf69847825b23dabf15813a8ac9fa2 | 10 | server_test_case.py | 40 | Rename and refactor `Report` machinery (#4141)
This refactor renames (almost) everything related to the outdated "report" concept with more precise concepts that we use throughout our code, primarily "script run", "session", and "app". | 26,307 | 0 | 96 | 22 | 28 | 118,584 | 31 | streamlit | 6 | lib/tests/server_test_case.py | Python | 5 | {
"docstring": "Mock the Server's AppSession import. We don't want\n actual sessions to be instantiated, or scripts to be run.\n ",
"language": "en",
"n_whitespaces": 32,
"n_words": 18,
"vocab_size": 16
} | https://github.com/streamlit/streamlit.git | |
9 | get_sales_orders | def get_sales_orders(self):
so_filter = item_filter = ""
bom_item = "bom.item = so_item.item_code"
date_field_mapper = {
"from_date": (">=", "so.transaction_date"),
"to_date": ("<=", "so.transaction_date"),
"from_delivery_date": (">=", "so_item.delivery_date"),
"to_delivery_date": ("<=", "so_item.delivery_d... | 494bd9ef78313436f0424b918f200dab8fc7c20b | @frappe.whitelist() | 13 | production_plan.py | 329 | style: format code with black | 14,183 | 1 | 67 | 158 | 59 | 66,418 | 93 | erpnext | 20 | erpnext/manufacturing/doctype/production_plan/production_plan.py | Python | 38 | {
"docstring": "\n\t\tselect distinct so.name, so.transaction_date, so.customer, so.base_grand_total\n\t\tfrom `tabSales Order` so, `tabSales Order Item` so_item\n\t\twhere so_item.parent = so.name\n\t\t\tand so.docstatus = 1 and so.status not in (\"Stopped\", \"Closed\")\n\t\t\tand so.company = %(company)s\n\t\t\tan... | https://github.com/frappe/erpnext.git |
4 | _create_examples | def _create_examples(self, lines, set_type):
examples = []
for i, line in enumerate(lines):
if i == 0:
continue
guid = f"{set_type}-{i}"
text_a = line[3]
text_b = line[4]
label = None if set_type == "test" else line[0]
... | afe5d42d8d1d80af911ed980c2936bfe887078f6 | 12 | glue.py | 137 | Black preview (#17217)
* Black preview
* Fixup too!
* Fix check copies
* Use the same version as the CI
* Bump black | 6,924 | 0 | 150 | 83 | 34 | 38,166 | 41 | transformers | 14 | src/transformers/data/processors/glue.py | Python | 11 | {
"docstring": "Creates examples for the training, dev and test sets.",
"language": "en",
"n_whitespaces": 8,
"n_words": 9,
"vocab_size": 9
} | https://github.com/huggingface/transformers.git | |
8 | _wait | async def _wait(fs, timeout, return_when, loop):
assert fs, 'Set of Futures is empty.'
waiter = loop.create_future()
timeout_handle = None
if timeout is not None:
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
counter = len(fs)
| 8198943edd73a363c266633e1aa5b2a9e9c9f526 | 10 | tasks.py | 80 | add python 3.10.4 for windows | 56,138 | 0 | 57 | 132 | 27 | 220,831 | 32 | XX-Net | 12 | python3.10.4/Lib/asyncio/tasks.py | Python | 24 | {
"docstring": "Internal helper for wait().\n\n The fs argument must be a collection of Futures.\n ",
"language": "en",
"n_whitespaces": 19,
"n_words": 13,
"vocab_size": 13
} | https://github.com/XX-net/XX-Net.git | |
5 | get_timestamps | def get_timestamps(self, session_id=None):
logger.debug("Getting timestamps: (session_id: %s, is_training: %s)",
session_id, self._is_training)
retval = {}
for idx in [session_id] if session_id else self.session_ids:
self._check_cache(idx)
d... | c1512fd41d86ef47a5d1ce618d6d755ef7cbacdf | 11 | event_reader.py | 157 | 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 -... | 19,800 | 0 | 164 | 98 | 37 | 100,303 | 43 | faceswap | 17 | lib/gui/analysis/event_reader.py | Python | 12 | {
"docstring": " Read the timestamps from the TensorBoard logs.\n\n As loss timestamps are slightly different for each loss, we collect the timestamp from the\n `batch_loss` key.\n\n Parameters\n ----------\n session_id: int, optional\n The Session ID to return the timest... | https://github.com/deepfakes/faceswap.git | |
1 | test_querysets_related_name | def test_querysets_related_name(self):
self.assertQuerysetEqual(
self.business.employees.all(),
[
"Fran Bones",
"Dan Jones",
],
str,
)
self.assertQuerysetEqual(
self.fran.business_set.all(),
... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 11 | tests.py | 93 | Refs #33476 -- Reformatted code with Black. | 50,147 | 0 | 189 | 57 | 17 | 202,528 | 21 | django | 11 | tests/custom_pk/tests.py | Python | 16 | {
"docstring": "\n Custom pk doesn't affect related_name based lookups\n ",
"language": "en",
"n_whitespaces": 22,
"n_words": 7,
"vocab_size": 7
} | https://github.com/django/django.git | |
2 | draw_bboxes | def draw_bboxes(ax, bboxes, color='g', alpha=0.8, thickness=2):
polygons = []
for i, bbox in enumerate(bboxes):
bbox_int = bbox.astype(np.int32)
poly = [[bbox_int[0], bbox_int[1]], [bbox_int[0], bbox_int[3]],
[bbox_int[2], bbox_int[3]], [bbox_int[2], bbox_int[1]]]
np... | 301d4a2d4cfe1cdb62608e2892924be3e67e3098 | 12 | image.py | 222 | [Feature] Support visualization for Panoptic Segmentation (#7041)
* First commit of v2
* split the functions
* Support to show panoptic result
* temp
* Support to show gt
* support show gt
* fix lint
* Support to browse datasets
* Fix unit tests
* Fix findContours
* fix comments
* Fix ... | 70,168 | 0 | 139 | 153 | 37 | 243,966 | 43 | mmdetection | 26 | mmdet/core/visualization/image.py | Python | 16 | {
"docstring": "Draw bounding boxes on the axes.\n\n Args:\n ax (matplotlib.Axes): The input axes.\n bboxes (ndarray): The input bounding boxes with the shape\n of (n, 4).\n color (list[tuple] | matplotlib.color): the colors for each\n bounding boxes.\n alpha (floa... | https://github.com/open-mmlab/mmdetection.git | |
19 | prepare_coco_detection | def prepare_coco_detection(self, image, target, return_segmentation_masks=False):
w, h = image.size
image_id = target["image_id"]
image_id = np.asarray([image_id], dtype=np.int64)
# get all COCO annotations for the given image
anno = target["annotations"]
anno... | 1ac698744c4dbdf1495d303246d08ffacdf4f5b8 | 14 | feature_extraction_yolos.py | 832 | 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... | 6,843 | 0 | 629 | 528 | 121 | 37,637 | 242 | transformers | 32 | src/transformers/models/yolos/feature_extraction_yolos.py | Python | 45 | {
"docstring": "\n Convert the target in COCO format into the format expected by DETR.\n ",
"language": "en",
"n_whitespaces": 27,
"n_words": 12,
"vocab_size": 10
} | https://github.com/huggingface/transformers.git | |
2 | secure_popen | def secure_popen(cmd):
ret = ''
# Split by multiple commands '&&'
for c in cmd.split('&&'):
ret += __secure_popen(c)
return ret
| 4046fbb18cf16be684ada228314c1f328779a3c1 | 10 | secure.py | 51 | Fix typos
Found via `codespell -S ./venv,./glances/outputs,*.svg -L hart,bu,te,statics` | 15,402 | 0 | 42 | 27 | 18 | 70,176 | 20 | glances | 6 | glances/secure.py | Python | 5 | {
"docstring": "A more or less secure way to execute system commands\n\n Multiple command should be separated with a &&\n\n :return: the result of the commands\n ",
"language": "en",
"n_whitespaces": 33,
"n_words": 24,
"vocab_size": 22
} | https://github.com/nicolargo/glances.git | |
1 | at | def at(self, axis=None): # noqa: PR01, RT01, D200
from .indexing import _LocIndexer
return _LocIndexer(self)
| 605efa618e7994681f57b11d04d417f353ef8d50 | 7 | base.py | 37 | DOCS-#3099: Fix `BasePandasDataSet` docstrings warnings (#4333)
Co-authored-by: Yaroslav Igoshev <Poolliver868@mail.ru>
Signed-off-by: Alexander Myskov <alexander.myskov@intel.com> | 35,484 | 0 | 36 | 20 | 14 | 153,603 | 14 | modin | 5 | modin/pandas/base.py | Python | 3 | {
"docstring": "\n Get a single value for a row/column label pair.\n ",
"language": "en",
"n_whitespaces": 24,
"n_words": 9,
"vocab_size": 8
} | https://github.com/modin-project/modin.git | |
2 | update | def update(self, **kwargs):
self._not_support_combined_queries("update")
if self.query.is_sliced:
raise TypeError("Cannot update a query once a slice has been taken.")
self._for_write = True
query = self.query.chain(sql.UpdateQuery)
query.add_update_values(kw... | 9c19aff7c7561e3a82978a272ecdaad40dda5c00 | 13 | query.py | 162 | Refs #33476 -- Reformatted code with Black. | 51,201 | 0 | 154 | 90 | 43 | 205,763 | 52 | django | 23 | django/db/models/query.py | Python | 12 | {
"docstring": "\n Update all elements in the current QuerySet, setting all the given\n fields to the appropriate values.\n ",
"language": "en",
"n_whitespaces": 38,
"n_words": 16,
"vocab_size": 13
} | https://github.com/django/django.git | |
6 | _identity_from_extracted | def _identity_from_extracted(cls, filename) -> Tuple[np.ndarray, bool]:
if os.path.splitext(filename)[-1].lower() != ".png":
logger.info("'%s' not a png. Returning empty array", filename)
return np.array([]), False
meta = read_image_meta(filename)
if "itxt" not ... | 1d1face00d9476896e7857d3976afce383585d1b | 12 | extract.py | 285 | Update Face Filter
- Remove old face filter
- plugins.extract.pipeline: Expose plugins directly
- Change `is_aligned` from plugin level to ExtractMedia level
- Allow extract pipeline to take faceswap aligned images
- Add ability for recognition plugins to accept aligned faces as input
- Add face filter to r... | 21,385 | 0 | 217 | 166 | 52 | 102,011 | 88 | faceswap | 20 | scripts/extract.py | Python | 31 | {
"docstring": " Test whether the given image is a faceswap extracted face and contains identity\n information. If so, return the identity embedding\n\n Parameters\n ----------\n filename: str\n Full path to the image file to load\n\n Returns\n -------\n :cl... | https://github.com/deepfakes/faceswap.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.