language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\nfrom verl.utils.import_utils import is_torch_npu_available\n```", "severity": "minor", "line": 21 } ]
1
python
def _refresh_component(self, button: ButtonComponent) -> None: self._underlying = button def button( *, label: Optional[str] = None, custom_id: Optional[str] = None, disabled: bool = False, style: ButtonStyle = ButtonStyle.secondary, emoji: Optional[Union[str, Emoji, PartialEmoji]] = N...
Review this code and list any quality issues.
[ { "issue": "This should probably be:\r\n\r\n```\r\n .. note::\r\n\r\n Buttons with a URL or an SKU cannot be created with this function.\r\n Consider creating a :class:`Button` manually instead.\r\n This is because these buttons cannot have a callback\r\n associated with them sinc...
1
python
): return field raise else: return field @cached_property def related_field(self): # The field stored on the reference index can be a related field or a # reverse related field, depending on whether the reference was extracted # direct...
Review this code and list any quality issues.
[ { "issue": "I don't think it's worth extracting into a method. We could instead collect the model names into a list and do a `.join()`. Also, we'll likely replace the right arrow with something more proper that works for RTL languages too, e.g. an icon, a translatable string, or some other trick.", "severit...
1
python
] expected_output_buffer_novel_deltas = [ 0, 1, 2, np.nan, 11, 12, 13, np.nan ] else: expected_output_buffer_all_deltas = [ 10, 11, 12, 11, 12, 13 ] expected_output_buffer_novel_deltas = [ 0, 1, 2, 11, 12...
Review this code and list any quality issues.
[ { "issue": "why do we get this delta but not the other one?", "severity": "minor", "line": 26 } ]
1
python
# Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.messages import ( tx_from_hex, ) from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert...
Review this code and list any quality issues.
[ { "issue": "nit: There is just one node here, so no need for such a loop", "severity": "minor", "line": 26 } ]
1
python
from typing import List, Optional import subprocess import facefusion.globals from facefusion import logger from facefusion.typing import OutputVideoPreset, Fps from facefusion.filesystem import get_temp_frames_pattern, get_temp_output_video_path def run_ffmpeg(args : List[str]) -> bool: commands = [ 'ffmpeg', '...
Review this code and list any quality issues.
[ { "issue": "Undo replacing tabs with spaces", "severity": "minor", "line": 11 } ]
1
python
"""Convert to original configuration format""" return orig_config.LMCacheEngineConfig( chunk_size=self.chunk_size, local_device="cpu" if self.local_cpu else "cuda", max_local_cache_size=int(self.max_local_cpu_size), remote_url=None, remote_serde=None, pipelined_backen...
Review this code and list any quality issues.
[ { "issue": "Same here, prefer `if not self.lmcache_worker_ids`", "severity": "major", "line": 26 } ]
1
python
def _refresh_state(self, interaction: Interaction, data: SelectMessageComponentInteractionData) -> None: values = selected_values.get({}) payload: List[PossibleValue] try: resolved = Namespace._get_resolved_items(interaction, data['resolved']) payload = list(resolved.valu...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n defaults: Sequence[ValidDefaultValues], value_type: Optional[SelectDefaultValueType] = None\r\n```", "severity": "minor", "line": 26 } ]
1
python
get_redis_connection, read_bin, parse_field, remove_fields_space, normalize_cache_fields, normalize_cache_instruments, ) from ..log import get_module_logger from .base import Feature from .ops import * class QlibCacheException(RuntimeError): pass class MemCacheUnit(abc.ABC): """Memory ...
Review this code and list any quality issues.
[ { "issue": "If we have two subclasses, `limit_type` is not requried anymore.", "severity": "minor", "line": 26 } ]
1
python
https://doc-popover2.streamlit.app/ height: 400px """ if label is None: raise StreamlitAPIException("A label is required for a popover") if use_container_width is not None: width = "stretch" if use_container_width else "content" # Checks whether the...
Review this code and list any quality issues.
[ { "issue": "Same as in the other PR, I think it's better not to throw this error (see other PR)", "severity": "minor", "line": 26 } ]
1
python
file=f"{asset_path}/meshes/cube8.obj", scale=0.1, pos=np.array([0.0, 0.0, 0.6], dtype=np.float32), ), material=fem_material_linear_corotated, ) verts_idx = [0] initial_target_poss = cube.init_positions[verts_idx] scene.build() if show_viewer: sphere...
Review this code and list any quality issues.
[ { "issue": "`gs.tensor` instead of `torch.tensor`?", "severity": "minor", "line": 26 } ]
1
python
register_model_group( models={ "MiniCPM3-4B-Chat": { DownloadSource.DEFAULT: "openbmb/MiniCPM3-4B", DownloadSource.MODELSCOPE: "OpenBMB/MiniCPM3-4B", DownloadSource.OPENMIND: "LlamaFactory/MiniCPM3-4B", }, }, template="cpm3", ) register_model_group( m...
Review this code and list any quality issues.
[ { "issue": "where is the 4B model? I cannot find it on huggingface", "severity": "minor", "line": 26 } ]
1
python
expression[0, 15, 0] += map_float(face_editor_eye_gaze_horizontal, -1, 1, -0.020, 0.020) else: expression[0, 11, 0] += map_float(face_editor_eye_gaze_horizontal, -1, 1, -0.020, 0.020) expression[0, 15, 0] += map_float(face_editor_eye_gaze_horizontal, -1, 1, -0.015, 0.015) expression[0, 1, 1] += map_float(face_edi...
Review this code and list any quality issues.
[ { "issue": "do the concatenate outside of the semaphore block: potential better performance (I had similar issues before) but for sure better readability", "severity": "major", "line": 26 } ]
1
python
'title': 'cherokee - Mobile Clips', }, 'playlist_mincount': 1 }] def _get_page(self, user_id, game, query_id, page_num): page_num += 1 for video_data in self._send_query( _QUERIES.get(query_id), { 'user': user_id, 'page': ...
Review this code and list any quality issues.
[ { "issue": "This is fatal right now in case either of them is renamed, while only `user_id` is required.\r\nI would also suggest keeping the original id as the `display_id`.", "severity": "minor", "line": 26 } ]
1
python
import json from urllib.parse import quote from .common import InfoExtractor from ..utils import ( ExtractorError, make_archive_id, remove_start, unified_timestamp, urljoin, ) from ..utils.traversal import traverse_obj class NintendoIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?nintend...
Review this code and list any quality issues.
[ { "issue": "I think it fits better as `tags` but mayhaps `categories`?", "severity": "minor", "line": 26 } ]
1
python
""" test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]).astype(float), np.eye(4)) with tempfile.TemporaryDirectory() as tempdir: nib.save(test_image, os.path.join(tempdir, "test_image.nii.gz")) test_data = [{"image": os.path.join(tempdir, "test_image.nii.gz...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n\n cm = self.assertRaises(ValueError) if expected_error else contextlib.nullcontext()\n with cm:\n test_dataset = PersistentDataset(\n data=test_data,\n transform=transform,\n cache_dir=cache...
1
python
return # The multiple context managers grammar has a different pattern, thus this is # separate from the for-loop below. This possibly wraps them in invisible parens, # and later will be removed in remove_with_parens when needed. if node.type == syms.with_stmt: _maybe_wrap_cms_in_parens(node, m...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Add parentheses around if guards in case blocks\r\n```", "severity": "minor", "line": 26 } ]
1
python
BadClean Raised when ``before`` and or ``after`` are passed with ``keep_last``. This is a subclass of ``ValueError``. """ try: all_runs = sorted( filter( complement(pth.hidden), os.listdir(pth.data_path([name], e...
Review this code and list any quality issues.
[ { "issue": "@llllllllll What is the intended way to clean out all the ingestions for a bundle? I tried with no args, but nothing happened. However, my change looks to fail the relevant test...", "severity": "critical", "line": 26 } ]
1
python
self, keys: KeysCollection, axcodes: str | None = None, as_closest_canonical: bool = False, labels: Sequence[tuple[str, str]] | None = None, allow_missing_keys: bool = False, lazy: bool = False, ) -> None: """ Args: axcodes: N elements sequ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n metadata item (if any) of the input is ignored.\n```", "severity": "minor", "line": 26 } ]
1
python
return x def forward(self, x, normalize=True): x0 = self.patch_embed(x) x0 = self.pos_drop(x0) x0_out = self.proj_out(x0, normalize) if self.use_v2: x0 = self.layers1c[0](x0.contiguous()) x1 = self.layers1[0](x0.contiguous()) x1_out = self.proj_out(x1, no...
Review this code and list any quality issues.
[ { "issue": "We should have tests with this function. If possible a code example of using this with a default network would help as well since just mentioning `copy_model_state` doesn't really say enough about use case.", "severity": "minor", "line": 26 } ]
1
python
return False batch = selected_files[i:i + batch_size] txt = os.path.join(worker_dir, f'chunk_{i:04d}.txt') out = os.path.join(worker_dir, f'chunk_{i:04d}.{default_audio_proc_format}') with open(txt, 'w') as f: for file in batch: ...
Review this code and list any quality issues.
[ { "issue": "Potential bug: The code attempts to clear the progress_queue, but if progress_queue is None (when session_id is not found in context.progress_queues), this will raise an AttributeError when calling .empty() on None. Consider adding a None check before attempting to clear the queue.", "severity":...
1
python
}, { 'url': 'http://motherless.com/g/sex_must_be_funny', 'info_dict': { 'id': 'sex_must_be_funny', 'title': 'Sex must be funny', }, 'playlist_count': 0, }, { 'url': 'https://motherless.com/gv/beautiful_cock', 'info_dict': { 'id': 'b...
Review this code and list any quality issues.
[ { "issue": "same as above, instead of redefining `suitable`, I think this would work:\r\n```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?motherless\\.com/G[VIG]?(?P<id>[A-F0-9]+)/?(?:$|[#?])'\r\n```", "severity": "minor", "line": 26 } ]
1
python
def _compute_exports(self): assert self.sample_file_static_data is not None if self.sample_file_static_data.pe: for export in self.sample_file_static_data.pe.exports: self.exports[export.address] = export.api.name def _compute_imports(self): assert self.sample_fi...
Review this code and list any quality issues.
[ { "issue": "don't need `.keys()` here and in similar lines below", "severity": "minor", "line": 26 } ]
1
python
def test_concat_multiple_parquet_inmem() -> None: f = io.BytesIO() g = io.BytesIO() df1 = pl.DataFrame( { "a": [1, 2, 3], "b": ["xyz", "abc", "wow"], } ) df2 = pl.DataFrame( { "a": [5, 6, 7], "b": ["a", "few", "entries"], ...
Review this code and list any quality issues.
[]
0
python
@pytest.fixture def hass_fixture_setup() -> list[bool]: """Fixture which is truthy if the hass fixture has been setup.""" return [] @pytest.fixture def hass_tmp_config_dir(tmp_path: pathlib.Path) -> Generator[str]: """Fixture to provide a temporary config directory. Use this fixture in a fixture over...
Review this code and list any quality issues.
[ { "issue": "`hass_tmp_config_dir` never returns or yields the temporary directory path. As written, the fixture returns `None`, so any override like `def hass_config_dir(hass_tmp_config_dir: str) -> str: ...` will receive `None` and `async_test_home_assistant(..., config_dir=...)` will fall back to the shared `...
1
python
Read more in the :ref:`User Guide <sparse_inverse_covariance>`. .. versionchanged:: v0.20 GraphLassoCV has been renamed to GraphicalLassoCV Parameters ---------- alphas : int or array-like of shape (n_alphas,), dtype=float, default=4 If an integer is given, it fixes the number of point...
Review this code and list any quality issues.
[ { "issue": "If we're being picky, this (and all other occurrences below) also has to start with a lowercase `an`", "severity": "minor", "line": 26 } ]
1
python
@dataclass class SampleAnalyzeConfig: """Configuration for a single sample analyzer plugin.""" id: str = MISSING """Unique identifier for the analyzer.""" enabled: bool = True """Whether this analyzer is enabled.""" config: dict[str, Any] = field(default_factory=dict) """Analyzer-specific...
Review this code and list any quality issues.
[ { "issue": "question: what is the behavior when this is None? use the full dataset?", "severity": "minor", "line": 26 } ]
1
python
def unpublish_hook(self, pages, action): assert action == "unpublish" assert isinstance(pages, list) def missing_hook_action(self, pages, action): assert action == "" assert isinstance(pages, list) @override_settings(WAGTAILSIMPLETRANSLATION_SYNC_PAGE_TREE=True) def test_pa...
Review this code and list any quality issues.
[ { "issue": "so.. this is fine, but best to add a note and another assertion\r\n\r\n```\r\ndefined_hooks = hooks.get_hooks(\"construct_synced_page_tree_list\")\r\nfor fn in defined_hooks:\r\n # We should have two implementations. \r\n # One in simple_tranalation.wagtail_hook and the other registered above\...
1
python
Note that Polars' `floordiv` is subtly different from Python's floor division. For example, consider 6.0 floor-divided by 0.1. Python gives: >>> 6.0 // 0.1 59.0 because `0.1` is not represented internally as that exact value, but a slightly larger value. So the ...
Review this code and list any quality issues.
[]
0
python
'graphql_is_translatable_rweb_tweet_is_translatable_enabled': False, 'interactive_text_enabled': True, 'responsive_web_edit_tweet_api_enabled': True, 'responsive_web_enhance_cards_enabled': True, 'responsive_web_graphql_timeline_navigation_enabled': False,...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if self.is_logged_in or self._configuration_arg('force_graphql'):\r\n self.write_debug(f'Using GraphQL API (Auth = {self.logged_in}')\r\n```", "severity": "critical", "line": 26 } ]
1
python
log_warning(f"Failed to convert memory_search response to MemorySearchResponse: {e}") return [] memories_to_return = [] if memory_search: for memory_id in memory_search.memory_ids: for memory in user_memories: if memory.memory_id == memory...
Review this code and list any quality issues.
[]
0
python
if not self.is_logged_in: self.raise_login_required('Twitter Spaces require authentication') space_data = self._call_graphql_api('HPEisOmj1epUNLCWTYhUWw/AudioSpaceById', space_id)['audioSpace'] if not space_data: raise ExtractorError('Twitter Space not found', expected=True) ...
Review this code and list any quality issues.
[ { "issue": "Add this anyway, since user can force native with `--downloader native`. Afair, fixup code will not run when ffmpeg is used", "severity": "minor", "line": 26 } ]
1
python
from re import finditer from urllib.parse import urljoin from .common import InfoExtractor from ..utils import join_nonempty, unified_timestamp class CamFMBaseIE(InfoExtractor): def _absolute_url(self, path, root='https://camfm.co.uk'): return urljoin(root, path) class CamFMShowIE(CamFMBaseIE): _VA...
Review this code and list any quality issues.
[ { "issue": "It's pointless to make a class for this. Just hardcode the urljoin", "severity": "minor", "line": 10 } ]
1
python
known_speakers (list[DiarizationKnownSpeaker]): List of known speaker labels and identifiers. If you supply a list of labels and identifiers for speakers, then the STT engine will use them to attribute any spoken words to that speaker. This is useful when you want to attr...
Review this code and list any quality issues.
[ { "issue": "`enable_diarization` is missing?", "severity": "minor", "line": 26 } ]
1
python
# Users may modify `model.config` to control generation. This is a legacy behavior and is not supported anymore if len(self.config._get_generation_parameters()) > 0: raise ValueError( "You have modified the pretrained model configuration to control generation " ...
Review this code and list any quality issues.
[ { "issue": "thanks @vasqu 👍 \r\n\r\nThis is indeed what works for me with VibeVoice (see [here](https://github.com/pengzhiliang/transformers/blob/1204d12f7a04370b17212103d2713d4e266e33c7/src/transformers/generation/utils.py#L1800) from VibeVoice PR)", "severity": "minor", "line": 26 } ]
1
python
If this argument is passed by position or `random_state` is passed by keyword into the initializer, or if the `random_state` attribute is used directly, legacy behavior for `random_state` applies: - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState` singleto...
Review this code and list any quality issues.
[ { "issue": "This is a little complicated because we're trying to preserve all the niceties of a dataclass (e.g. automatic `__repr__`). Solution draws from https://florimond.dev/en/posts/2018/10/reconciling-dataclasses-and-properties-in-python.", "severity": "minor", "line": 26 } ]
1
python
), # Implications of zero = False: (('zero', False), set( ( ) ), ), ] ) # full_implications prereq = { # facts that could determine the value of algebraic 'algebraic': { 'commutative', 'complex', 'composite', 'even', 'finite', 'infinite', ...
Review this code and list any quality issues.
[]
0
python
self.enable_blending = config.enable_blending self.token_database: TokenDatabase if self.enable_blending: self.token_database = SegmentTokenDatabase(config, metadata) else: self.token_database = ChunkedTokenDatabase(config, metadata) def lookup( self, ...
Review this code and list any quality issues.
[ { "issue": "Can it works if the `mla_lookup_server_worker_ids` configured to `0,8,16,24`? @chunxiaozheng", "severity": "minor", "line": 26 } ]
1
python
# If not enough objects in pool, create new ones if to_get < n: objs.extend([self.object_creator() for _ in range(n - to_get)]) self._num_checked_out += len(objs) return objs def put(self, objs: T | List[T]) -> None: """ Return an object or object...
Review this code and list any quality issues.
[ { "issue": "When returning objects, `_num_checked_out` is only decremented if the pool is not full; if the pool is full, the checked-out count remains too high. You should decrement `_num_checked_out` for every returned object and only skip the `put_nowait` call when the pool is at capacity.\n```suggestion\n ...
1
python
line_to_number_buff : :class:`float` The distance between the line and the number mobject. decimal_number_config : :class:`dict` Arguments that can be passed to :class:`~.numbers.DecimalNumber` to influence number mobjects. numbers_to_exclude : Union[:class:`list`, :class:`numpy.ndarray`] ...
Review this code and list any quality issues.
[ { "issue": "`length` technically overrides `unit_size` when they're used together. So you should probably chose only one for this line.", "severity": "minor", "line": 26 } ]
1
python
) async for data, _ in resp.content.iter_chunks(): output_emitter.push(data) output_emitter.flush() except asyncio.TimeoutError: raise APITimeoutError() from None except aiohttp.ClientResponseError as e: raise APIStatusError(...
Review this code and list any quality issues.
[ { "issue": "Few Suggestions:\r\n\r\n1) Correct control message (TTS):\r\n`await ws.send_str(json.dumps({\"type\": \"Close\"})) # not \"CloseStream\"`\r\n\r\n2) Flush before close (if any text was streamed):\r\n```\r\nawait ws.send_str(json.dumps({\"type\": \"Flush\"}))\r\nawait ws.send_str(json.dumps({\"type\"...
1
python
max_autotune = False, shape_padding = True, cudagraphs = False, debug = False, fullgraph = fullgraph, import_from_cache = False, disable ...
Review this code and list any quality issues.
[ { "issue": "Best to use `if auto_model is None`", "severity": "minor", "line": 26 } ]
1
python
We patch some functions in the module to use `fsspec` to support data streaming: - We use `fsspec.open` to open and read remote files. We patch the module function: - `open` - We use the "::" hop separator to join paths and navigate remote compressed/archive files. We patch the module functions: ...
Review this code and list any quality issues.
[]
0
python
except subprocess.TimeoutExpired: return False, "Timeout checking Node.js/npm installation" except FileNotFoundError: return False, "Node.js/npm not found. Please install Node.js from https://nodejs.org/" except Exception as e: return False, f"Error checking Node.js/npm: {str(e)}" def ...
Review this code and list any quality issues.
[]
0
python
import json from typing import TYPE_CHECKING import pytest from crawlee.fingerprint_suite._browserforge_adapter import get_available_header_values from crawlee.fingerprint_suite._consts import COMMON_ACCEPT_LANGUAGE from crawlee.http_clients import HttpxHttpClient if TYPE_CHECKING: from collections.abc import As...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Test that the relevant headers use header values from header generator instead of default Httpx headers.\r\n```", "severity": "minor", "line": 26 } ]
1
python
if ind is None: ind = concat([df.index for df in dfs2]) return pd.Series(union_categoricals(dfs2), index=ind, name=dfs2[0].name) with warnings.catch_warnings(): if filter_warning: warnings.simplefilter("ignore", FutureWarning) out = pd.concat(d...
Review this code and list any quality issues.
[ { "issue": "I think that this function may not be necessary, the `hash_df_dispatch` object above should do this. You might remove this function and rename the dispatch object above.\r\n\r\nWe had to do tricky dispatch stuff with `concat` (where I expect you're copying things from) because `concat` takes in a l...
1
python
loss_functions = {"hinge": (Hinge, 1.0)} _parameter_constraints: dict = { **BaseSGD._parameter_constraints, "nu": [Interval(Real, 0.0, 1.0, closed="right")], "learning_rate": [ StrOptions({"constant", "optimal", "invscaling", "adaptive"}), Hidden(StrOptions({"pa1", "...
Review this code and list any quality issues.
[ { "issue": "I'm not sure why these changes are necessary", "severity": "minor", "line": 26 } ]
1
python
stop_targets = batch[6] item_idx = batch[7] d_vectors = batch[8] speaker_ids = batch[9] attn_mask = batch[10] max_text_length = torch.max(text_lengths.float()) max_spec_length = torch.max(mel_lengths.float()) # compute durations from attention masks durat...
Review this code and list any quality issues.
[]
0
python
timeout: The maximum time in seconds to wait for the object to be present in the GPU object store. If not specified, wait indefinitely. Returns: The GPU object. """ with self._lock: self._wait_object(obj_id, timeout) return sel...
Review this code and list any quality issues.
[ { "issue": "Oh I guess there must be a potential bug here if you combine this with #60509. @Sparks0219, can you add a test to #60509 that checks that if two views of the same tensor are added, calling `wait_tensor_free` only waits until that specific view is freed?", "severity": "critical", "line": 26 ...
1
python
import random import itertools import urllib.parse from .common import InfoExtractor from ..utils import ( int_or_none, make_archive_id, mimetype2ext, parse_resolution, str_or_none, strip_jsonp, traverse_obj, url_or_none, urlencode_postdata, urljoin, ) class WeiboBaseIE(InfoEx...
Review this code and list any quality issues.
[ { "issue": "the `User-Agent` key will always exist in `params['http_headers']`\r\n```suggestion\r\n r'Chrome/(\\d+)', self.get_param('http_headers')['User-Agent'], 'user agent version', default='90')\r\n```", "severity": "minor", "line": 24 } ]
1
python
for hook in self._pre_navigation_hooks: await hook(pre_navigation_context) yield pre_navigation_context async def _navigate( self, context: PlaywrightPreNavigationContext, ) -> AsyncGenerator[PlaywrightCrawlingContext, None]: """Executes an HTTP request utilizing th...
Review this code and list any quality issues.
[ { "issue": "The comment belongs to the next line.\r\n\r\n```suggestion\r\n if context.request.headers:\r\n await context.page.set_extra_http_headers(context.request.headers.model_dump())\r\n # Navigate to the URL and get response.\r\n```", "severity": "minor", "line"...
1
python
Returns: - Solution vector. Raises: - ValueError: If the matrix is not correct (i.e., singular). https://courses.engr.illinois.edu/cs357/su2013/lect.htm Lecture 7 Example: >>> A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]], dtype=float) >>> B = np.array([8, -11, -3], dtype=float) ...
Review this code and list any quality issues.
[ { "issue": "Instead of an `assert`, let's just have the function raise a `ValueError` instead.", "severity": "minor", "line": 26 } ]
1
python
logger.error(f"Failed to fetch content from {url} after {self.max_retries} attempts") return None def _create_document_from_url(self, url: str, content: str, search_result: Dict[str, str]) -> Document: """Create a Document object from URL content and search result metadata""" # Use the URL ...
Review this code and list any quality issues.
[ { "issue": "Consistency: ensures reusing a reader instance works correctly.", "severity": "minor", "line": 26 } ]
1
python
on_action = on_action_name else: _warn("download() on_action is invalid.") content_str = self._get_content("Gui.download", content, False) self.__send_ws_download(content_str, str(name), str(on_action) if on_action is not None else "") def _notify( self, ...
Review this code and list any quality issues.
[ { "issue": "should check for non empty also ie `if notification_id:` should be enough", "severity": "minor", "line": 26 } ]
1
python
logger.info(f"Downloaded TOS file to {destination_file}") return local_path except (TosClientError, TosServerError) as e: logger.error(f"TOS download error: {e}") status_code = getattr(e, "status_code", None) if status_code == 404 or "404" in str(e): ...
Review this code and list any quality issues.
[ { "issue": "seems response has `is_truncated`? seems it doesn't handle the pagination. this is ok since the model weights won't be that large but let's leave a comment here", "severity": "minor", "line": 26 } ]
1
python
# Dictionary containing new label numbers new_label_names = {} label = np.zeros(d[key].shape) # Sort label names to ensure deterministic ordering (exclude background) sorted_labels = sorted( [(k, v) for k, v in self.label_names.items() if k != "background...
Review this code and list any quality issues.
[ { "issue": "We should definitely mark the old name as deprecated but we should instead use the [deprecated](https://github.com/Project-MONAI/MONAI/blob/01711cf7e3af991aabc92cc3fdf4c0b65949e65e/monai/utils/deprecate_utils.py#L41) decorator for this. The deprecation is also since version 1.6.0 and will be removed...
1
python
state = hass.states.get(entity_id) assert state is not None assert state.state == "on" async def test_device_status_off( recorder_mock: Recorder, hass: HomeAssistant, config_entry: MockConfigEntry, data_api_client_mock: AsyncMock, setup_credentials: None, entity_registry: er.EntityRegi...
Review this code and list any quality issues.
[ { "issue": "This can be parametrized. I also think that we can skip the entity regsitry lookup part, as _in theory_ the entity_id stays the same", "severity": "minor", "line": 26 } ]
1
python
from pydantic import BaseModel from pydantic_settings import BaseSettings from backend.util.settings import Settings logger = logging.getLogger(__name__) settings = Settings() class VirusScanResult(BaseModel): is_clean: bool scan_time_ms: int file_size: int threat_name: Optional[str] = None class ...
Review this code and list any quality issues.
[ { "issue": "Should the initial value be determined based on number of CPU cores (`os.cpu_count()`)?", "severity": "minor", "line": 26 } ]
1
python
import json from filelock import FileLock count = sum(completed_run_metrics) with FileLock(str(COUNTER_FILE) + ".lock"): is_non_zero_file = os.path.isfile(COUNTER_FILE) and os.path.getsize(COUNTER_FILE) > 0 if is_non_zero_file: with open(COUNTER_FILE, "r...
Review this code and list any quality issues.
[ { "issue": "how about recording each run in each line? and we can apply aggregation in our collection pipeline?", "severity": "minor", "line": 26 } ]
1
python
video_id)['page']['items'][0] if info['state'] == 'DESPU': raise ExtractorError('The video is no longer available', expected=True) title = info['title'].strip() formats = self._extract_png_formats(video_id) sbt_file = f'https://api2.rtve.es/api/videos/{video_id}/subtitulos.j...
Review this code and list any quality issues.
[ { "issue": "Can you please change this to not be fatal.", "severity": "minor", "line": 26 } ]
1
python
# rule was: DTSTART;TZID=America/New_York:20200601T120000 RRULE:...;UNTIL=20200601T170000 # rule is now: DTSTART;TZID=America/New_York:20200601T120000 RRULE:...;UNTIL=20200601T220000Z rules[index] = rule.replace(naive_until, utc_until) return " ".join(rules) @clas...
Review this code and list any quality issues.
[ { "issue": "Comment says \"> 30 days old\" and then \"> 30 hours\". This doesn't look intentional.", "severity": "minor", "line": 26 } ]
1
python
for attempt in range(self.max_retries + 1): try: if self._executor_type == "function": if _is_generator_function(self.active_executor) or _is_async_generator_function( self.active_executor ): content = ""...
Review this code and list any quality issues.
[]
0
python
else: return ['-O3', '-std=c++17', '-g', '-Wno-reorder'] def nvcc_args(self): if self.build_for_cpu: return [] args = ['-O3'] if self.is_rocm_pytorch(): ROCM_MAJOR, ROCM_MINOR = self.installed_rocm_version() args += [ '-std=c++...
Review this code and list any quality issues.
[ { "issue": "If this is a breaking change going forward, should this be `cuda_minor >= 5`", "severity": "minor", "line": 26 } ]
1
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n def update_learning_rates(self, interval: str, monitor_metrics: Optional[Dict[str, Any]]=None, opt_indices: List[int]=[]):\r\n```\r\nshould this be an empty list by default?", "severity": "minor", "line": 26 } ]
1
python
send_path: str, done_event: threading.Event, ): """ Upload a file to S3. """ headers = HttpHeaders() headers.add("Host", self.s3_endpoint) req = HttpRequest("PUT", self._format_safe_path(key_str), headers) done = {"err": None, "status": None} ...
Review this code and list any quality issues.
[ { "issue": "Why do we have a `_put` and another `put`?", "severity": "minor", "line": 26 } ]
1
python
"GPT-JT": TokenizerConfig(special_tokens=SpecialTokens(sep_token="<|extratoken_100|>")), "codegen": TokenizerConfig(special_tokens=SpecialTokens("<|endoftext|>", sep_token="<|endoftext|>")), "pythia": TokenizerConfig(special_tokens=SpecialTokens("<|padding|>", "<|endoftext|>", "<|endoftext|>")), } def match_t...
Review this code and list any quality issues.
[ { "issue": "This should be Digits instead of Digit", "severity": "minor", "line": 26 } ]
1
python
'ext': 'm4a', } }, { 'url': 'https://m.qtfm.cn/vchannels/378005/programs/23023573/', 'md5': '2703120b6abe63b5fa90b975a58f4c0e', 'info_dict': { 'id': '23023573', 'title': '【睡前消息488】重庆山火之后,有图≠真相', 'channel_id': '378005', 'channel_name': '...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'channel': traverse_obj(info, ('ProgramStore', 'channelInfo', 'title')),\r\n 'uploader': traverse_obj(info, ('ProgramStore', 'podcasterInfo', 'podcaster', 'nickname')),\r\n```", "severity": "minor", "line": 26 } ]
1
python
if thumbnail.endswith('/404_processing_{width}x{height}.png'): is_live, thumbnail = True, None else: is_live = False for p in ('width', 'height'): thumbnail = thumbnail.replace('{%s}' % p, '0') return { 'id': vod_id, ...
Review this code and list any quality issues.
[ { "issue": "No need to sort. Core code should handle it", "severity": "minor", "line": 26 } ]
1
python
self._app = web.Application() self._runner: web.AppRunner | None = None self._site: web.TCPSite | None = None @property def app(self) -> web.Application: return self._app @property def host(self) -> str: return self._host @property def port(self) -> int: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n addresses = self._runner.addresses\n if addresses:\n self._port = addresses[0][1]\n```\n\nthen maybe we don't need to store `self._site`", "severity": "minor", "line": 26 } ]
1
python
True if the arrays are containers that implement the Array API spec. Always False when array_api_dispatch=False. device : device `device` object (see the "Device Support" section of the array API spec). """ skip_remove_kwargs = dict(remove_none=False, remove_types=[]) array_list = _remo...
Review this code and list any quality issues.
[ { "issue": "How about calling the arguments `xp` and `device` instead? Or `reference_xp` - I don't love abbreviations, if it is important to have it in the name we should spell it out or if that feels like too much then let's not have it\r\n\r\nI prefer the \"plain\" name (`xp`).", "severity": "minor", ...
1
python
@property def commands(self) -> Set[Command[CogT, ..., Any]]: """Set[:class:`.Command`]: A unique set of commands without aliases that are registered.""" return set(self.all_commands.values()) def recursively_remove_all_commands(self) -> None: for command in self.all_commands.copy().val...
Review this code and list any quality issues.
[]
0
python
if not video_id: video_id = traverse_obj(query, ('id', 0, {int_or_none})) webpage = self._download_webpage(url, video_id) player_data, media_data = self._html_search_regex( r'LR\.audio\.Player\s*\([^{]*(?P<player>\{.*?\}),(?P<media>\{.*\})\);', webpage, 'player json...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n media_json, ('audio', lambda _, v: v['id'][1:] == id_[1:], 'title',\r\n```", "severity": "minor", "line": 26 } ]
1
python
[ 0.5 0.25 2.5 1.0 ] """ def reinterpret( self, *, dtype: PolarsDataType, endianness: Endianness = "little" ) -> Series: r""" Interpret a buffer as a numerical polars type. Parameters ---------- dty...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n Note that rows of the binary array where the length does not match the width of the output array will become NULL.\r\n```", "severity": "minor", "line": 26 } ]
1
python
""" logging_first_step: bool = field( default=False, metadata={"help": "Whether to log and evaluate the first global_step or not."}, ) """Whether to log and evaluate the first global step. If True, metrics will be logged and evaluation will be performed at the very beginning of tra...
Review this code and list any quality issues.
[ { "issue": "Instead of logging_steps I think we should set this to match the default save_steps", "severity": "minor", "line": 26 } ]
1
python
# Postcard # Create a postcard displaying persona, image, caption and optional buttons. # --- from h2o_wave import site, ui page = site['/demo'] image = 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&h=750&w=1260' page['example'] = ui.postcard_card( box='1 1 3 5', persona=ui.p...
Review this code and list any quality issues.
[ { "issue": "nit\r\n```suggestion\r\n commands=[\r\n ui.command(name='new', label='New', icon='Add', items=[\r\n ui.command(name='email', label='Email Message', icon='Mail'),\r\n ui.command(name='calendar', label='Calendar Event', icon='Calendar'),\r\n ]),\r\n ui.com...
1
python
# Ex. 'communication/named-pipe/create' -> capa::communication::named-pipe::create namespace_str = Namespace.DELIMITER.join(meta["namespace"].split("/")) this_namespace = "capa" + Namespace.DELIMITER + namespace_str # lib rules via the official rules repo will not contain data ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n logger.error(\"unsupported Ghidra execution mode\")\r\n```", "severity": "minor", "line": 26 } ]
1
python
Detects the available accelerator and returns the corresponding PyTorch device type string. Currently supports CUDA, Ascend NPU, and CPU. Returns: str: Device type string ('cuda', 'npu', or 'cpu'). """ if is_cuda_available: device = "cuda" elif is_npu_available: device = "np...
Review this code and list any quality issues.
[]
0
python
fcompute=lambda *idx: tir.sum( tir.if_then_else( idx[axis] * self.num_elem_per_storage + r < k, scaled_weight( *idx[:axis], idx[axis] * self.num_elem_per_storage + r, *idx[axis + 1 :] ) << (r * quanti...
Review this code and list any quality issues.
[]
0
python
import numpy as np import random import string from typing import Optional, List, Dict, Callable EXEC_OPTION_TO_RUNTIME: Dict[str, Optional[Dict]] = { "compute_engine": None, "python": None, "tensor_db": {"db_engine": True}, } def parse_tensor_return(tensor): return tensor.data(aslist=True)["value"]...
Review this code and list any quality issues.
[ { "issue": "Not sure why in case of `DeepLakeCloudDataset` by default it should be either `tensor_db` or `compute_engine`. Shouldn't by default it be `tensor_db` or `python`? Or is it our final decision to do it like that?", "severity": "minor", "line": 26 } ]
1
python
video_id = self._match_id(url) src_iframe = self._search_regex( r'\<iframe[^>]+src="([^"]+)"', self._download_webpage(url, video_id), 'src iframe') webpage_iframe = self._download_webpage( src_iframe.replace('player.php', 'config2.php'), video_id, headers={'Referer': src_iframe}...
Review this code and list any quality issues.
[ { "issue": "did u mean this?\r\n```suggestion\r\n 'thumbnail': self._search_regex(r'image:\\s*\"([^\"]+)', webpage_iframe, 'thumbnail'),\r\n```", "severity": "minor", "line": 26 } ]
1
python
detection_idx=detection_idx, color_lookup=( self.color_lookup if custom_color_lookup is None else custom_color_lookup ), ) # Convert Color type to numpy list in BGRA format, and color icon with it ...
Review this code and list any quality issues.
[ { "issue": "I think we can remove most of those comments and replace them with more descriptive variable names.", "severity": "minor", "line": 26 } ]
1
python
version: str config: Optional[str] = None def get_pypi_download_url(package: str, version: Optional[str]) -> str: with urlopen(PYPI_INSTANCE + f"/{package}/json") as page: metadata = json.load(page) if version is None: sources = metadata["urls"] else: if version in metadata["r...
Review this code and list any quality issues.
[ { "issue": "This is clever. Any idea if this is better than `pip download --no-binary --no-deps`?", "severity": "minor", "line": 26 } ]
1
python
self._statistics, self._session_pool if self._use_session_pool else None, self._http_client, *self._additional_context_managers, ) if cm and getattr(cm, 'active', False) is False ] async with AsyncExitStack() as exit_stack: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n event_manager.emit(\r\n event=Event.PERSIST_STATE,\r\n event_data=EventPersistStateData(is_migrating=False),\r\n )\r\n```", "severity": "minor", "line": 26 } ]
1
python
3.5: clr[3], masked_value: bad}), ('neither', -2, {-2: no_color, -1: clr[0], 2: clr[1], 2.25: clr[1], 3: no_color, 3.5: no_color, ...
Review this code and list any quality issues.
[]
0
python
video, ('creation_story', 'short_form_video_context', 'playback_video', {dict})) if reel_info: video = video['creation_story'] video['owner'] = traverse_obj(video, ('short_form_video_context', 'video_owner')) video.update(reel_i...
Review this code and list any quality issues.
[ { "issue": "`get_first(x, y)` is just `traverse_obj(x, (..., y), get_all=False)`\r\n```suggestion\r\n is_video_broadcast = traverse_obj(video, ('is_video_broadcast', {bool}))\r\n```", "severity": "minor", "line": 26 } ]
1
python
'only_matching': True, }, ] def _real_extract(self, url): course_id, hostname, year, term, slug = self._match_valid_url(url).group('id', 'hostname', 'year', 'term', 'slug') json = f'{hostname}/api/courses/{slug}/?year={year}&term={term}' try: meta = self._download_json(json...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n meta = self._download_json(\r\n f'https://{hostname}/api/courses/{slug}/', course_id, fatal=False,\r\n query={'year': year, 'term': term}) or {}\r\n lecture_series_title = meta.get('Name')\r\n lectures = [self.url_result(f'https://{hostnam...
1
python
# Add multi-modal related parameters. # details at https://github.com/EleutherAI/lm-evaluation-harness/releases/tag/v0.4.5 if is_multimodal: # FIXME OPE-355 To remove `max_images=1` limit model_args_dict |= {"max_images": 1, "interleave": True} # Only applicable to hf-multimodal (NOT vl...
Review this code and list any quality issues.
[ { "issue": "nit: `relevant_for_lm` is only referenced once. Can it be inlined for clarity? Otherwise I'm looking for its other non-existent usages", "severity": "minor", "line": 26 } ]
1
python
assert_raises_rpc_error, sha256sum_file, ) from test_framework.wallet_util import ( get_generate_key, ) class WalletMigrationTest(BitcoinTestFramework): def add_options(self, parser): self.add_wallet_options(parser) def set_test_params(self): self.setup_clean_chain = True self...
Review this code and list any quality issues.
[ { "issue": "Would be nice to have the commit message mention this instead of `use previous releases`, which gives an impression multiple previous releases are being used. Couple suggestions:\r\n\r\n```diff\r\n- test: Rework migratewallet to use previous releases\r\n+ test: Rework migratewallet to use previous r...
1
python
# The config requires (open and close scripts) or a set position script, # therefore the base supported features will always include them. self._attr_supported_features: CoverEntityFeature = ( CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE ) for action_id, supported_featu...
Review this code and list any quality issues.
[ { "issue": "I think the method name is misleading because the method doesn't just update the opening and closing attributes.", "severity": "minor", "line": 26 } ]
1
python
import os import cognee.modules.ingestion as ingestion import asyncio from uuid import UUID from typing import Any from functools import wraps from sqlalchemy import select from cognee.infrastructure.databases.graph import get_graph_engine from cognee.infrastructure.databases.relational import get_relational_engine f...
Review this code and list any quality issues.
[ { "issue": "Let's move it down with other cognee imports.", "severity": "minor", "line": 2 } ]
1
python
output_path = os.path.join(get_tests_output_path(), "train_outputs") config = AlignTTSConfig( batch_size=8, eval_batch_size=8, num_loader_workers=0, num_eval_loader_workers=0, text_cleaner="english_cleaners", use_phonemes=False, phoneme_language="en-us", phoneme_cache_path=os.path.join...
Review this code and list any quality issues.
[]
0
python
"--root", default="numpy", type=str, help="Root directory to scan (default: numpy)" ) ap.add_argument( "--ext", action="append", default=None, help="File extension(s) to include (repeatable). Defaults to .c,.h,.c.src,.cpp", ) ap.add_argument( ...
Review this code and list any quality issues.
[ { "issue": "these `DEFAULT_..` vars are already `set`s, right?", "severity": "minor", "line": 26 } ]
1
python
await create_db_and_tables() counter = ExecutionCounter() user = await get_default_user() tasks = [Task(create_counting_task, counter=counter)] # First run pipeline_results_1 = [] async for result in run_pipeline( tasks=tasks, datasets="test_dat...
Review this code and list any quality issues.
[]
0
python
from .neteasemusic import ( NetEaseMusicAlbumIE, NetEaseMusicDjRadioIE, NetEaseMusicIE, NetEaseMusicListIE, NetEaseMusicMvIE, NetEaseMusicProgramIE, NetEaseMusicSingerIE, ) from .netverse import ( NetverseIE, NetversePlaylistIE, NetverseSearchIE, ) from .netzkino import NetzkinoI...
Review this code and list any quality issues.
[]
0
python
_MISS_QUANT_DEFAULT = 'fbgemm' not in torch.backends.quantized.supported_engines def create_skipif( min_gpus: int = 0, min_torch: Optional[str] = None, pt_quant: bool = False, ) -> dict: """ Creating aggregated arguments for standatd pytest skipif, sot the usecase is:: @pytest.mark.skipif(**c...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n conditions.append(torch.cuda.device_count() < min_gpus)\r\n```", "severity": "minor", "line": 26 } ]
1
python
for subclass in _get_all_subclasses(DataLoader): _enable_class(subclass) yield for subclass in _get_all_subclasses(DataLoader): _disable_class(subclass) class _LiteDataLoader: def __init__(self, dataloader: DataLoader, device: Optional[torch.device] = None) -> None: """The LiteData...
Review this code and list any quality issues.
[ { "issue": "returning inf here is a strong assumption. LiteDataLoader should wrap the underlying dataloader and there is currently no reason why we would change the behavior of ``len``.", "severity": "minor", "line": 26 } ]
1
python
log = logging.getLogger(__name__) JOB_NAME_PREFIX = "job-" class KubernetesJobOperator(KubernetesPodOperator): """ Executes a Kubernetes Job. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:KubernetesJobOperator` .. note:...
Review this code and list any quality issues.
[ { "issue": "Docstring should be updated to reflect that the default value (`None`), as well as falsy value (`0`), are the same as `1`", "severity": "minor", "line": 26 } ]
1
python
check_val_every_n_epoch: Check val every n train epochs. default_root_dir: Default path for logs and weights when no logger/ckpt_callback passed. Default: ``os.getcwd()``. Can be remote file paths such as `s3://mybucket/path` or 'hdfs://path/' deterministic: If ...
Review this code and list any quality issues.
[ { "issue": "the defaults are already in the signature :)", "severity": "minor", "line": 26 } ]
1
python
elif v < 50: return 'invite' elif v < 60: return 'webhook' elif v < 70: return 'emoji' elif v == 73: return 'channel' elif v < 80: return 'message' elif v < 83: return 'integration' elif v < 90: ...
Review this code and list any quality issues.
[ { "issue": "This feels a bit weird. What's the reason for that?", "severity": "minor", "line": 26 } ]
1
python
Attributes ----------- id: :class:`int` The interaction ID. type: :class:`InteractionType` The interaction type. user: :class:`User` The user that invoked the interaction. original_response_message_id: Optional[:class:`int`] The ID of the original response message if ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n '_state',\r\n '_guild',\r\n```\r\n\r\nPlease rename these.", "severity": "minor", "line": 26 } ]
1