language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
import atexit import tempfile tempfile.tempdir = tempdir = tempfile.mkdtemp() @atexit.register def cleanup_tempdir(): import shutil shutil.rmtree(tempdir) _() del _ # This is *not* a place to dump arbitrary classes/modules for convenience, # it is a pl...
Review this code and list any quality issues.
[ { "issue": "why did this move before the other imports", "severity": "minor", "line": 26 } ]
1
python
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the notification entity platform.""" json_path = hass.config.path(REGISTRATIONS_FILE) registrations = await hass.async_add_executor_job(_load_con...
Review this code and list any quality issues.
[ { "issue": "entity description doesn't add much as it's just setting translation key and name", "severity": "minor", "line": 26 } ]
1
python
if not algorithm: raise UnableToAuthenticate( "ID Token header does not specify a signing algorithm." ) pub_key = oidc_config["jwt_keys"][key_id] # This will raises errors if the audience isn't right or if the token is expired or has other erro...
Review this code and list any quality issues.
[ { "issue": "We should also raise this exception on `algorithm.lower() == \"none\"` (although the lib should™ protect us from this anyway)", "severity": "minor", "line": 26 } ]
1
python
self.vertices[vertex] = vertex_type(**vertex_config) else: self.vertices[vertex] = vertex_mobject self.vertices[vertex].move_to(position) self.add(self.vertices[vertex]) return self.vertices[vertex] def add_vertices( self: "Graph", *vertices: Hashable, ...
Review this code and list any quality issues.
[ { "issue": "I think it is best to avoid using the word list to avoid confusion if it doesn't accept a list, and \"comma separated\" is already implicit in varargs, so maybe just \"hashable vertex identifiers\" is enough ?", "severity": "minor", "line": 26 } ]
1
python
'youtube_include_hls_manifest': opts.youtube_include_hls_manifest, 'encoding': opts.encoding, 'extract_flat': opts.extract_flat, 'live_from_start': opts.live_from_start, 'wait_for_video': opts.wait_for_video, 'mark_watched': opts.mark_watched, 'merge_output_format': opts....
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\n\r\nas this is not a `YoutubeDL` opt", "severity": "minor", "line": 26 } ]
1
python
from pathlib import Path from kedro.templates.project.hooks.utils import ( setup_template_tools, sort_requirements, ) def main(): current_dir = Path.cwd() requirements_file_path = current_dir / "requirements.txt" pyproject_file_path = current_dir / "pyproject.toml" python_package_name = '{{ ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Get the selected tools from cookiecutter\r\n```", "severity": "minor", "line": 16 } ]
1
python
from .newstube import NewstubeIE from .newsy import NewsyIE from .nextmedia import ( NextMediaIE, NextMediaActionNewsIE, AppleDailyIE, NextTVIE, ) from .nexx import ( NexxIE, NexxEmbedIE, ) from .nfb import NFBIE from .nfhsnetwork import NFHSNetworkIE from .nfl import ( NFLIE, NFLArticle...
Review this code and list any quality issues.
[]
0
python
def parse_count(s): if s is None: return None s = s.strip() if re.match(r'^[\d,.]+$', s): return str_to_int(s) _UNIT_TABLE = { 'k': 1000, 'K': 1000, 'm': 1000 ** 2, 'M': 1000 ** 2, 'kk': 1000 ** 2, 'KK': 1000 ** 2, } return look...
Review this code and list any quality issues.
[ { "issue": "Have you tested that these changes won't break an existing extractor?", "severity": "major", "line": 26 } ]
1
python
result = pytester.runpytest("--collect-only", "--pyargs", "pkg.subpkg_regular") result.stdout.fnmatch_lines( [ "collected 1 item", "<Dir pkg>", " <Package subpkg_regular>", " <Module module3.py>", " <Function test_module3>", ] ...
Review this code and list any quality issues.
[ { "issue": "Could we use another parametrized argument here *without* duplicates to ensure the message handles it correctly?", "severity": "major", "line": 26 } ]
1
python
class L1ChannelPruner(DependencyAwarePruner): def __init__(self, model, config_list, optimizer=None, dependency_aware=False, dummy_input=None): super().__init__(model, config_list, pruning_algorithm='l1', optimizer=optimizer, dependency_aware=dependency_aware, dummy_input=dummy_inpu...
Review this code and list any quality issues.
[ { "issue": "this is not unit test, more like integration test", "severity": "minor", "line": 26 } ]
1
python
HfFolder.delete_token() @pytest.fixture(scope="session") def hf_api(): return HfApi(endpoint=CI_HUB_ENDPOINT) @pytest.fixture(scope="session") def hf_token(): yield CI_HUB_USER_TOKEN @pytest.fixture def cleanup_repo(hf_api): def _cleanup_repo(repo_id): hf_api.delete_repo(repo_id, token=CI_HUB_...
Review this code and list any quality issues.
[ { "issue": "Maybe instead of modifying the precision, we can use something like [this](https://github.com/huggingface/huggingface_hub/blob/89cc69105074f1d071e0471144605f3cdfe1dab3/tests/testing_utils.py#L54) to be aligned with `huggingface_hub`", "severity": "minor", "line": 26 } ]
1
python
from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema from backend.data.model import ( APIKeyCredentials, CredentialsField, CredentialsMetaInput, NodeExecutionStats, SchemaField, ) from backend.integrations.providers import ProviderName from backend.util import json from back...
Review this code and list any quality issues.
[ { "issue": "please insert this in the right alphabetical location, so at the very top", "severity": "minor", "line": 26 } ]
1
python
def begin(self) -> None: pass def finish(self) -> None: pass def clean_up_from_scene(self, scene: Scene) -> None: pass def update_mobjects(self, dt: float) -> None: pass def interpolate(self, alpha: float) -> None: pass class Add(Animation): """Add Mobje...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n One :class:`.Mobject` or more to add to a scene.\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf" # Importing necessary libraries import numpy as np from PIL import Image import matplotlib.pyplot as plt def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray: """ Performs image segmentation based on intensity thresho...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image\r\n```", "severity": "minor", "line": 6 } ]
1
python
"MASTER_ADDR": master_addr, "MASTER_PORT": master_port, "TORCHELASTIC_USE_AGENT_STORE": "False", } if env is not None: env.update(env_vars) remote_config = { "scheduling_strategy": PlacementGroupSchedulingStrategy( placement_group=placement_group, pla...
Review this code and list any quality issues.
[ { "issue": "Is this function to find an available port? If so, call the `find_available_port` function in `llamafactory/extras/misc.py` without implementing it yourself.", "severity": "minor", "line": 26 } ]
1
python
) if "backend" in wanted: parser.add_argument( "-b", "--backend", type=str, help="select the backend to use", choices=(BACKEND_VIV,), default=BACKEND_VIV, ) if "os" in wanted: ...
Review this code and list any quality issues.
[ { "issue": "this is clever and concise but also hard to read. i think its ok, just mentioning it, though.", "severity": "minor", "line": 26 } ]
1
python
) dataset_id = dataset.id if not data: data: list[Data] = await get_dataset_data(dataset_id=dataset_id) # async with update_status_lock: TODO: Add UI lock to prevent multiple backend requests if isinstance(dataset, Dataset): task_status = await get_pipeline_status([dataset_id], pipeli...
Review this code and list any quality issues.
[ { "issue": "You will need that `return` here as we discsussed.", "severity": "minor", "line": 26 } ]
1
python
}, 'contentCheckOk': True, 'racyCheckOk': True } @staticmethod def _is_agegated(player_response): if traverse_obj(player_response, ('playabilityStatus', 'desktopLegacyAgeGateReason')): return True reasons = traverse_obj(player_response, ('playability...
Review this code and list any quality issues.
[ { "issue": "Is there really a need for `require_js_player`? Can't we just check if `player_url is None`? I also noticed `fatal=true` is never used for `_extract_signature_timestamp`", "severity": "major", "line": 26 } ]
1
python
x = x + self.attn(self.ln_1(x), attention_bias=attention_bias) x = x + self.mlp(self.ln_2(x)) return x class DolmaGPTOutput(NamedTuple): logits: torch.FloatTensor """ A tensor of shape `(batch_size, seq_len, vocab_size)` representing the log probabilities for the next token *before* no...
Review this code and list any quality issues.
[]
0
python
is_npu_available = is_torch_npu_available() def get_visible_devices_keyword() -> str: """Function that gets visible devices keyword name. Returns: 'CUDA_VISIBLE_DEVICES' or `ASCEND_RT_VISIBLE_DEVICES` """ return "CUDA_VISIBLE_DEVICES" if is_cuda_available else "ASCEND_RT_VISIBLE_DEVICES" def...
Review this code and list any quality issues.
[]
0
python
For backward compatibility, if ``data`` is a dictionary, it returns the dictionary with updated ``data[key]``. Otherwise, this function returns a MetaObj with updated transform metadata. """ data_t = data[key] if key is not None else data # compatible with the dict data representation ...
Review this code and list any quality issues.
[]
0
python
df[id_col] = df[content_col].apply(gen_hash) else: # generate for empty for i in range(len(df)): if pd.isna(df.loc[i, id_col]): df.loc[i, id_col] = gen_hash(df.loc[i, content_col]) # remove duplicated ids df = df.drop_duplicates([Table...
Review this code and list any quality issues.
[ { "issue": "1. it is postgres specific syntax\r\nI think it should filter by metadata key name: \r\nFilterCondition( column='original_row_id', ...)\r\n\r\n2. maybe it should be original_row_id - it is id of the source", "severity": "minor", "line": 26 } ]
1
python
# Sometimes wat serves the whole file with the --test option 'skip_download': True, }, }, { 'url': 'https://www.tf1.fr/tmc/burger-quiz/videos/burger-quiz-du-19-aout-2023-s03-episode-21-85585666.html', 'info_dict': { 'id': '14010600', 'ext': 'mp4', ...
Review this code and list any quality issues.
[]
0
python
def __init__( self, *, build_dir: str, download_dir: str | None, src_dir: str, build_isolation: bool, build_isolation_installer: BuildEnvironmentInstaller, check_build_deps: bool, build_tracker: BuildTracker, session: PipSession, pr...
Review this code and list any quality issues.
[ { "issue": "Is there a reason this doesn't go a step further and remove the resume_retries parameter from the Downloader and take the value from the session object?", "severity": "minor", "line": 26 } ]
1
python
'id': '63756df1c638b008a5659dec', 'title': 'Facundo González sufrió fuerte golpe durante competencia frente a Hugo García en EEG', 'description': 'md5:9490c034264afd756eef7b2c3adee69e', 'thumbnail': 're:^https?://[^?#]+63756df1c638b008a5659dec', 'ext': 'mp4', }, ...
Review this code and list any quality issues.
[]
0
python
CNNIE, CNNIndonesiaIE, ) from .comedycentral import ComedyCentralIE from .commonmistakes import ( BlobIE, CommonMistakesIE, UnicodeBOMIE, ) from .commonprotocols import ( MmsIE, RtmpIE, ViewSourceIE, ) from .condenast import CondeNastIE from .contv import CONtvIE from .corus import CorusIE f...
Review this code and list any quality issues.
[ { "issue": "The name of the site is \"croatian.film\"\r\n```suggestion\r\nfrom .croatianfilm import CroatianFilmIE\r\n```", "severity": "minor", "line": 26 } ]
1
python
{ 'url': 'https://image.cnbcfm.com/api/v1/image/107345486-Screenshot_2023-12-08_at_70339_PM.png?v=1702080248' } ], 'timestamp': 1702080535, 'title': 'The epicenter of AI is in Seattle, says Jim Cramer', 'upload_d...
Review this code and list any quality issues.
[ { "issue": "Just inline this along with other data below\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
webpage = self._download_webpage(url, video_id) config = self._search_json( r'window\.__NUXT__\.config\s*=', webpage, 'config', video_id, transform_source=js_to_json) api_key = traverse_obj(config, ('public', 'streaksVodPlaybackApiKey', {str}, {require('api key')})) return { ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = [\r\n fr'https?://locipo\\.jp/(?P<type>playlist)/(?P<id>{LocipoBaseIE._UUID_RE})',\r\n fr'https?://locipo\\.jp/(?P<type>series)/(?P<id>\\d+)',\r\n ]\r\n```", "severity": "minor", "line": 26 } ]
1
python
'thumbnail': 'https://video.jixie.media/1003/28210/28210_1280x720.jpg', 'description': 'md5:2a5e18d98eef9b39d7895029cac96c63', 'title': 'Paris Van Java Episode 16', } } ] def _real_extract(self, url): display_id = self._match_id(url) webpage =...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n fmt, sub = self._extract_m3u8_formats_and_subtitles(stream.get('url'), display_id, ext='mp4')\r\n if json_data.get('drm'):\r\n for f in fmt:\r\n f['has_drm'] = True\r\n```", "severity": "major", "line":...
1
python
point_2: Optional[Sequence[float]], direction: Optional[Sequence[float]] = ORIGIN, **kwargs ): if all(direction == ORIGIN): line_vector = np.array(point_2) - np.array(point_1) direction = np.array([line_vector[1], -line_vector[0], 0]) Brace.__init__(self, Line...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n .. warning::\r\n The ArcBraces are smaller for Arcs with smaller radii.\r\n \r\n .. note::\r\n The ArcBrace is initially a vertical Brace that takes the dimensions of a line\r\n with the length of the Arc but scaled down to match the start and end angl...
1
python
}, 'skip': 'Requires login', }] def _perform_login(self, username, password): login = self._download_json( 'https://api.laxarxames.cat/Authorization/SignIn', None, note='Logging in', headers={ 'X-Tenantorigin': 'https://laxarxames.cat', 'Content-Type'...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n self.raise_login_required()\r\n```", "severity": "minor", "line": 26 } ]
1
python
'thumbnail': r're:^https?://.+\.jpg', 'comment_count': int, 'duration': 18014, 'play_count': int, 'view_count': int, 'timestamp': 1611694774, 'like_count': int, 'uploader': 'Fernanda Rivas🎶', 'uploader_id': 'fernanda_rivasg...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n self._search_regex(r'window\\.data\\s=\\s({.+?});', webpage, 'video info'),\r\n```", "severity": "minor", "line": 26 } ]
1
python
@hash_df.register((pd.DataFrame, pd.Series, pd.Index)) def hash_df_pandas(dfs): return hash_pandas_object(dfs, index=False) # --------------------------------- # group_split # --------------------------------- group_split = Dispatch("group_split") @group_split.register((pd.DataFrame, pd.Series, pd.Index)) def...
Review this code and list any quality issues.
[ { "issue": "We probably don't need separate comments like these for each function. Maybe one larger header for \"shuffling/merging/sorting\" or something like that?", "severity": "minor", "line": 26 } ]
1
python
import re from .common import InfoExtractor from .archiveorg import ArchiveOrgIE from ..utils import ( int_or_none, str_to_int, orderedSet, urljoin, InAdvancePagedList, ) class AltCensoredIE(InfoExtractor): IE_NAME = 'altcensored' _VALID_URL = r'https?://(?:www\.)?altcensored\.com/(?:watc...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n InAdvancePagedList,\r\n int_or_none,\r\n orderedSet,\r\n str_to_int,\r\n urljoin,\r\n```", "severity": "minor", "line": 10 } ]
1
python
if str(Role.RefPolicy) in all_wg: self.ref_policy_wg = all_wg[str(Role.RefPolicy)] self.ref_policy_wg.init_model() else: # Model engine: ActorRolloutRefWorker assert str(Role.ActorRolloutRef) in all_wg, f"{all_wg.keys()=}" self....
Review this code and list any quality issues.
[ { "issue": "Please move this to a util function", "severity": "major", "line": 26 } ]
1
python
"pico_set_printf_implementation", "pico_expand_pico_platform", ]) all_functions = {} # Supported commands: # \brief\ <brief description, which should be included in the main description> # \brief_nodesc\ <brief description, which should be excluded from the main description> # \param\ <parameter_name> <parameter ...
Review this code and list any quality issues.
[ { "issue": "You've got `line.split('\\\\')[2].strip()` appearing multiple times, so perhaps it's better to do something like:\r\n```python3\r\n_, command, remainder = line.split('\\\\', 2)\r\nremainder = remainder.strip()\r\n```", "severity": "minor", "line": 26 } ]
1
python
if version_check and version_check(sys.version_info): pytest.skip(f'Python {sys.version} version does not have the required validation for this test.') with handler() as rh: with pytest.raises(RequestError, match=match) as exc_info: validate_and_send(rh, req) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n (lambda: urllib3.exceptions.HTTPError(), TransportError),\r\n (lambda: requests.exceptions.RequestException(), RequestError),\r\n # Needs a response object\r\n # (lambda: requests.exceptions.TooManyRedirects(), HTTPError),\r\n # ruff: enable[PLW01...
1
python
async def subscribe_graph_execs( self, *, user_id: str, graph_id: str, websocket: WebSocket ) -> str: return await self._subscribe( _graph_execs_channel_key(user_id, graph_id=graph_id), websocket ) async def unsubscribe_graph_exec( self, *, user_id: str, graph_exec_i...
Review this code and list any quality issues.
[]
0
python
("last week : ", True), ("next 12 months : ", True), ("next 12 months : ", True), ("next 12 months : ", True), ("last7days : ", False), # no space after scope - invalid ("last 7days : ", True), # \s{0,5} allows 0 spaces after number - valid ("lastweek : ",...
Review this code and list any quality issues.
[ { "issue": "Let's not add conditionals inside unit tests", "severity": "minor", "line": 26 } ]
1
python
import os import math import numpy as np import pickle import trimesh import genesis as gs from genesis.ext import fast_simplification from genesis.ext.isaacgym import terrain_utils as isaacgym_terrain_utils from genesis.options.morphs import Terrain from .misc import get_assets_dir def parse_terrain(morph: Terrain...
Review this code and list any quality issues.
[ { "issue": "Keep system deps seperated from common deps:\r\n```\r\nimport os\r\nimport math\r\nimport pickle\r\n\r\nimport numpy as np\r\nimport trimesh\r\n```", "severity": "minor", "line": 6 } ]
1
python
# check known value if scalar < 1: assert_array_equal(w, np.array([])) elif scalar == 1: assert_array_equal(w, np.ones(1)) else: assert_almost_equal(np.sum(w, axis=0), 10, 15) class TestTrapezoid: def test_simple(self): x = np.arange(-10, 10, .1...
Review this code and list any quality issues.
[]
0
python
def _map_chunk_engines(self, tensors: Sequence[str]) -> Dict[str, ChunkEngine]: return { name: self._create_chunk_engine(name, self.dataset.version_state) for name in tensors } def _create_chunk_engine(self, tensor_name, version_state): tensor_key = version_state["te...
Review this code and list any quality issues.
[ { "issue": "why do we compare it with 0? is it related to case when tensor_meta.max_chunk_size is None?", "severity": "minor", "line": 26 } ]
1
python
sampling_params = request.sampling_params assert sampling_params is not None if request.num_output_tokens < sampling_params.min_tokens: return False last_token_id = request.output_token_ids[-1] if last_token_id == sampling_params.eos_token_id: request.status = RequestStatus.FINISHED_ST...
Review this code and list any quality issues.
[ { "issue": "If you make `check_sequence_repetition` accept `Sequence[int]`, then we don't need the list conversion", "severity": "minor", "line": 26 } ]
1
python
for data in tensor_data ] return tensor_data def convert_tensor_data_to_list(tensor_data, tensors, ids_tensor): if tensor_data is None: tensor_data = [None] * len(tensors[ids_tensor]) elif not isinstance(tensor_data, list): tensor_data = list(tensor_data) return tensor_data d...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\ndef populate_id_tensor_if_needed(ids_tensor, tensors, not_none_tensors, num_items):\r\n```", "severity": "minor", "line": 26 } ]
1
python
# flake8: noqa: F401 from .add_config import AddConfig, ChunkerConfig from .apps.app_config import AppConfig from .apps.custom_app_config import CustomAppConfig from .apps.open_source_app_config import OpenSourceAppConfig from .base_config import BaseConfig from .embedder.base import BaseEmbedderConfig from .embedder....
Review this code and list any quality issues.
[]
0
python
def init_page(self, page): self.page = page # cache to store data via sha256(url) cache = {} # router to cache with fail 2x on requests def router(route): # hash of url hash = hashlib.sha256(route.request.url.encode("utf-8")).hexdigest() # ca...
Review this code and list any quality issues.
[ { "issue": "In my opinion, the snippets under try and catch are exactly the same, so it makes sense to make a function out of this and put it inside a retry decorator.\r\n\r\nSo, for example:\r\n\r\n```\r\n@retry(times=2, exceptions=(Exception,))\r\ndef fetch_and_put_in_cache():\r\n response = page.request.f...
1
python
dataset name, value from [qlib_data, qlib_data_simple], by default qlib_data version: str data version, value from [v0, v1, ..., latest], by default latest interval: str data freq, value from [1d], by default 1d region: str data region, value from [cn, us], by...
Review this code and list any quality issues.
[ { "issue": "Did you consider the situation that the qlib version changes but the data version remains the same?", "severity": "minor", "line": 26 } ]
1
python
'title': 'K1, J2: Pouchit | Modernit miehet', 'thumbnail': r're:^https?://.*\.jpg$', 'uploader_id': 'ovp@yle.fi', 'duration': 1435, 'view_count': int, 'upload_date': '20181204', 'timestamp': 1543916210, } }] def _real_extract(self,...
Review this code and list any quality issues.
[ { "issue": "shouldnt this be:\r\n```suggestion\r\n 'thumbnails': traverse_obj(info, ('thumbnails', ..., {'url': 'url'})),\r\n```\r\nThis will extract all available thumbnails", "severity": "major", "line": 26 } ]
1
python
# day after its start date). dates = pd.date_range('2013-01-01', freq='2D', periods=5, tz='UTC') sids = list(range(5)) df = pd.DataFrame.from_records( [ { 'sid': sid, 'symbol': str(sid), 'start_date': date.v...
Review this code and list any quality issues.
[ { "issue": "Out of paranoia, should we give each (or at least one of) the assets a different exchange to make sure that we're correctly deduplicating only within each asset?", "severity": "minor", "line": 26 } ]
1
python
for mob in self.family_members_with_points(): mob.points -= about_point mob.points = func(mob.points) mob.points += about_point return self @deprecated( since="v0.11.0", until="v0.12.0", ) def rotate_in_place(self, angle, axis=OUT): # redu...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n @deprecated(\r\n since=\"v0.11.0\",\r\n until=\"v0.12.0\",\r\n replacement=\"scale\"\r\n )\r\n```", "severity": "minor", "line": 26 } ]
1
python
angle = Angle(line1, line2, radius=0.4) value = DecimalNumber(angle.get_value(degrees=True), unit="^{\\circ}") value.next_to(angle, UR) self.add(line1, line2, angle, value) """ if degrees: return self.angle_value / DEGREES ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n A\r\n The endpoint of the first angle leg\r\n B\r\n The vertex of the angle\r\n C\r\n The endpoint of the second angle leg\r\n```\r\n\r\nThe formatting in my comment was not meant to be used verbatim in ReST", "severity": "m...
1
python
time.sleep(1) if res['code'] == '429': self.error("You are being rate-limited by ThreatJammer.com") self.errorState = True return None if res['code'] != "200": self.error("Error retrieving search results from ThreatJammer.com") self.errorStat...
Review this code and list any quality issues.
[ { "issue": "Does the server reply with an error when the provided API key is invalid (401 / 403) or quota exceeded ? If so, this function should handle the appropriate code explicitly and set `errorState` with an appropriate error, prior to presuming all non-200 codes are fatal.", "severity": "minor", "...
1
python
"error_message": f"'{input}' is an invalid value for project tools. Please select valid options for tools using comma-separated values, ranges, or 'all/none'.", }, } if not re.match(VALIDATION_PATTERNS[pattern_name]["regex"], input, flags=re.X): click.secho( VALIDATION_PATTERNS[patt...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"Kedro Viz is automatically included in the project. Please remove 'viz' from your tool selection.\",\r\n```\r\nSomething like this?", "severity": "minor", "line": 26 } ]
1
python
import torch import transformers from ..registry import ModelAttribute, model_zoo # =============================== # Register single-sentence OPT # =============================== BATCH_SIZE = 2 SEQ_LENGTH = 16 def data_gen(): input_ids = torch.zeros((BATCH_SIZE, SEQ_LENGTH), dtype=torch.int64) attention_m...
Review this code and list any quality issues.
[ { "issue": "The old `data_gen` will produce data where all elements are 0. Please refer to the llama file to generate real data.", "severity": "minor", "line": 25 } ]
1
python
'format_id': name, 'url': url, 'vcodec': 'none', **traverse_obj(match, { 'acodec': 'codec', 'abr': ('bitrate', {int_or_none}), 'ext': 'ext', }), } for name, url in share_data....
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n for name, url in share_data.items():\r\n if not isinstance(name, str) or not url_or_none(url):\r\n continue\r\n\r\n elif name.startswith('audio'):\r\n match = re.search(self._SHARE_AUDIO_REGEX, url)\r\n yield...
1
python
if args.quiet: logging.basicConfig(level=logging.WARNING) logging.getLogger().setLevel(logging.WARNING) elif args.debug: logging.basicConfig(level=logging.DEBUG) logging.getLogger().setLevel(logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.getL...
Review this code and list any quality issues.
[]
0
python
model = model.eval() if args.dtype == "fp16": model = model.half() elif args.dtype == "bf16": model = model.to(torch.bfloat16) if args.continous_batching: mbsz = args.mbsz else: mbsz = args.batch_size if args.mode == "caiinference...
Review this code and list any quality issues.
[ { "issue": "Replace this actual path with the `args.model_path`", "severity": "minor", "line": 26 } ]
1
python
# SPDX-License-Identifier: Apache-2.0 # Standard from dataclasses import dataclass from enum import IntEnum, auto import struct MAX_KEY_LENGTH = 150 class Constants(IntEnum): CLIENT_PUT = auto() CLIENT_GET = auto() CLIENT_EXIST = auto() CLIENT_LIST = auto() SERVER_SUCCESS = 200 SERVER_FAIL =...
Review this code and list any quality issues.
[ { "issue": "I know this isn't part of this PR but do you mind breaking this out into 2 enums:\r\n\r\n- ClientCommands\r\n- ServerReturnCodes\r\n\r\nAs it currently stands, the enum is just a catchall for constants which is not good practice.", "severity": "minor", "line": 17 } ]
1
python
self.assertEqual(clone_settings_dict["NAME"], expected_clone_name) @mock.patch.object(multiprocessing, "get_start_method", return_value="unsupported") def test_get_test_db_clone_settings_not_supported(self, *mocked_objects): msg = "Cloning with start method 'unsupported' is not supported." with...
Review this code and list any quality issues.
[ { "issue": "Not sure if we want this committed, but I thought this might clear up any confusion in case someone raised the question of \"why does this test modify the `[\"NAME\"]` directly instead of `[\"TEST\"][\"NAME\"]`?\"\n\nIt's pretty much equivalent to the comment in this method:\n\nhttps://github.com/dj...
1
python
from typing import Annotated, Any, Literal, Optional, TypedDict from uuid import uuid4 from pydantic import BaseModel, Field, SecretStr, field_serializer class _BaseCredentials(BaseModel): id: str = Field(default_factory=lambda: str(uuid4())) provider: str title: Optional[str] hidden: Optional[bool] ...
Review this code and list any quality issues.
[ { "issue": "Putting this here will also persist it in the DB, which I think should be avoided if possible.\r\n\r\nIMO there should be minimal involvement of the credentials system when a user wants to use credits to run a block. Right now we're injecting credentials into the credential system in a way it defini...
1
python
'ext': 'mp4', 'title': 'Welcome to 3-4 Philosophy @ DECV!', 'thumbnail': r're:^https?://.*\.jpg$', 'description': 'as the title says! also: some general info re 1) VCE philosophy and 2) distance learning.', 'duration': 369, 'upload_date': '20141216', }...
Review this code and list any quality issues.
[ { "issue": "```py\r\npassword = self.get_param('videopassword')\r\nif not pasword:\r\n raise ExtractorError(...)\r\n...\r\n```", "severity": "major", "line": 26 } ]
1
python
import importlib.resources import json import sys from typing import Any def get_schema(tool_name: str = "cibuildwheel") -> Any: "Get the stored complete schema for black's settings." assert tool_name == "black", "Only black is supported." loc = "resources/black.schema.json" if sys.version_info < (3...
Review this code and list any quality issues.
[ { "issue": "Then why is the default `cibuildwheel`?", "severity": "minor", "line": 9 } ]
1
python
SensorEntityDescriptionWithValueAccessor( key=ATTR_API_TOTAL_CONSUMPTION, translation_key=ATTR_API_TOTAL_CONSUMPTION, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL, native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, value_accessor=lambda d...
Review this code and list any quality issues.
[ { "issue": "The new DeviceInfo enrichment isn’t covered by the current test suite: `test_sensor` snapshots validate entity/state, but don’t assert the device registry entry gets `manufacturer`, `serial_number`, and `sw_version` populated (or preserved when a fetch returns `None`). Add a test that reads the devi...
1
python
from model_training.custom_datasets.rank_datasets import AnthropicRLHF, HFDataset def load_anthroopic_rlhf(): train = AnthropicRLHF(split="train") validation = AnthropicRLHF(split="test") print(f"AnthropicRLHF extra dataset size: {len(train)}, {len(validation)}") return train, validation def load_...
Review this code and list any quality issues.
[ { "issue": "typo:\r\n```suggestion\r\ndef load_anthropic_rlhf():\r\n```", "severity": "minor", "line": 4 } ]
1
python
def allocate_slots_to_shards( rules_grouped_by_time: List[Tuple[float, List[BazelRule]]], count: int, ) -> Tuple[List[dict], float]: """ Allocate test slots to shards using least-loaded strategy. This only determines how many tests of each size go to each shard, without assigning specific tests...
Review this code and list any quality issues.
[ { "issue": "we do not need this right? you are just always putting tests into the shard that has the min sum?\n\ncan we just remove the optimum concept now? this algorithm does not have anything to do with the expected optimum.", "severity": "minor", "line": 26 } ]
1
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
if not text_parts: return ( "Error: PDF appears to be empty or contains only images.\n\n" "**Tip**: For image-based or complex PDFs, try vision-based reading:\n" "1. Use `screenshot_url()` to capture pages as images\n" "2. Use the vision tool t...
Review this code and list any quality issues.
[ { "issue": "We keep repeating this hint in various forms, extract it to a variable so we can refine it in a single place.", "severity": "major", "line": 26 } ]
1
python
For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_v1_1_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path = '<fill_in>' >>> t5_model = t5.models.MtfModel(model_d...
Review this code and list any quality issues.
[ { "issue": "Let's try to use more `Expectation` class.\r\n\r\nBTW, do you know why such difference?", "severity": "minor", "line": 26 } ]
1
python
""" Shared docstrings for parameters that should be documented identically across different functions. """ import re from six import iteritems from textwrap import dedent PIPELINE_DOWNSAMPLING_FREQUENCY_DOC = dedent( """\ frequency : {'year_start', 'quarter_start', 'month_start', 'week_start'} A string...
Review this code and list any quality issues.
[ { "issue": "actually, are those not the same? the prefix isn't added to the first line in the join case.\n\n```\nIn [14]: '\\n '.join(['a', 'b', 'c'])\nOut[14]: 'a\\n b\\n c'\n```", "severity": "minor", "line": null } ]
1
python
def masked_outside(x, v1, v2, copy=...): ... def masked_object(x, value, copy=..., shrink=...): ... def masked_values(x, value, rtol=..., atol=..., copy=..., shrink=...): ... def masked_invalid(a, copy=...): ... class _MaskedPrintOption: def __init__(self, display): ... def display(self): ... def set_displ...
Review this code and list any quality issues.
[ { "issue": "maybe I'm wrong here, but I thought integer masks also worked", "severity": "critical", "line": 26 } ]
1
python
or '正在观看预览,大会员免费看全片' in webpage or '开通大会员观看' in webpage): self.raise_login_required('This video is for premium members only') play_info = self._download_json('https://api.bilibili.com/pgc/player/web/v2/playurl', video_id, 'Extracting episode', ...
Review this code and list any quality issues.
[ { "issue": "use `traverse_obj` like the old code did\r\n```suggestion\r\n traverse_obj(bangumi_info, ('seasons', ...)))\r\n```", "severity": "minor", "line": 26 } ]
1
python
'playable_in_embed': True, 'availability': 'public', 'live_status': 'not_live', }, }, { # data-plyr-embed-id="B1TZV8rNZoc" data-plyr-provider="youtube" 'url': 'https://www.vnis.edu.vn', 'info_dict': { 'id': 'vnis.edu', 'title': 'VNIS Ed...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n plyr_embeds = re.finditer(r'''(?x)\r\n <div[^>]+(?:\r\n data-plyr-embed-id=\"(?P<id1>[^\"]+)\"[^>]+data-plyr-provider=\"(?P<provider1>[^\"]+)\"|\r\n data-plyr-provider=\"(?P<provider2>[^\"]+)\"[^>]+data-plyr-embed-id=\"(?P<id2>[^\"]+)...
1
python
vod_data, ('props', 'pageProps', 'programInformation'), default={}, expected_type=dict) series_id = program_info.get('series_id') playlist_data = traverse_obj(vod_data, ('props', 'pageProps', 'seriesTree')) if playlist_data is not None and self._yes_playlist(series_id, vi...
Review this code and list any quality issues.
[ { "issue": "inline the payload in the request call\r\n```suggestion\r\n video_data = self._download_json(\r\n f'https://www.litv.tv/api/{endpoint}', video_id,\r\n data=json.dumps({'AssetId': asset_id, 'MediaType': media_type, 'puid': puid}).encode(),\r\n headers={'Content...
1
python
logger.debug( f"The {cls.__name__} animation has been is overridden for " f"{type(mobject).__name__} mobjects. use_override = False can " f" be used as keyword argument to prevent animation overriding.", ) return anim re...
Review this code and list any quality issues.
[ { "issue": "Do we really need to set the actual attribute and the property here?", "severity": "minor", "line": 26 } ]
1
python
#!/usr/bin/env -S uv run print("hello world") #!/usr/bin/env uv --offline run print("offline") #!/usr/bin/env uv --color=auto run print("color") #!/usr/bin/env uv --quiet run --script print("quiet run script") #!/usr/bin/env uv tool run print("uv tool") #!/usr/bin/env uvx print("uvx") #!/usr/bin/env uvx --quiet p...
Review this code and list any quality issues.
[]
0
python
norm=norm) # === Inset histogram as colorbar === cax = inset_axes(ax, width="20%", height="95%", loc='center left', bbox_to_anchor=(1.18, 0.025, 1, 1), bbox_transform=ax.transAxes, borderpad=0) # Histogram values and...
Review this code and list any quality issues.
[ { "issue": "If you use the ax.inset_axes from the original than you won't need to use this", "severity": "minor", "line": 26 } ]
1
python
) f.post( f'/bar', inputs=DocumentArray.empty(size=5) ) # process 5 documents on bar assert not ( f'jina_document_processed_total{{executor="DummyExecutor",executor_endpoint="/bar",runtime_name="executor0/rep-0"}} 5.0' # check that we count 5 documents on foo ...
Review this code and list any quality issues.
[]
0
python
unwrapped = [] for wrapped in checks: try: pred = wrapped.predicate except AttributeError: raise TypeError(f'{wrapped!r} must be wrapped by commands.check decorator') from None else: unwrapped.append(pred) async def predicate(ctx: Context[BotT]) -> bo...
Review this code and list any quality issues.
[ { "issue": "For `--verifytypes` these need to have their generics passed, something like `Check[Any]` works fine to silence it.", "severity": "minor", "line": 26 } ]
1
python
"-W", "ignore::DeprecationWarning", "-W", "ignore::PendingDeprecationWarning", ) assert WARNINGS_SUMMARY_HEADER not in result.stdout.str() def test_hidden_by_system(self, pytester: Pytester, monkeypatch) -> None: self.create_file(pytester) monkeyp...
Review this code and list any quality issues.
[ { "issue": "I think it would be more thorough to test on the whole \"while parsing ...\" output?", "severity": "minor", "line": 26 } ]
1
python
try: return subprocess.run(cmd, check=True, **kwargs) except Exception as e: sys.exit(e) def main(): print("Running test-one-commit on ...") run(["git", "log", "-1"]) num_procs = int(run(["nproc"], stdout=subprocess.PIPE).stdout) # Use clang++, because it is a bit faster and uses...
Review this code and list any quality issues.
[ { "issue": "Is `-03` chosen here to try and counteract the slow-down from `Debug` as opposed to using `-02`?\r\n\r\nIIRC I did some tests of `-02` vs `-03` and didn't find much/any speedup, so just curious if that was the reason. If it's been chosen to expose new classes of bugs not found by `-03`, then seems f...
1
python
} # If column parameters are not specified for a column, use the sanitized column name self.column_params = column_params def _get_most_frequent_image_extension(self, fn_iterator): # TODO: Make this generic and work for any htype that requires compression supported_image_extensions = tup...
Review this code and list any quality issues.
[ { "issue": "Couple of issues: `endswith` check should include the period (`.`) otherwise a file named `abcdjpg` for example would be counted as a jpeg. Second, creating `pathlib.Path` object in a for loop for basic string operations is not good. Consider refactoring:\r\n\r\n```suggestion\r\n\r\n def _get_mos...
1
python
processor: Optional["ProcessorMixin"], template: "Template", generating_args: Dict[str, Any], messages: Sequence[Dict[str, str]], system: Optional[str] = None, tools: Optional[str] = None, images: Optional[Sequence["ImageInput"]] = None, videos: Optional[Sequence[...
Review this code and list any quality issues.
[ { "issue": "can we don't use any if-else here? we recommend to move all the logic to process args.", "severity": "minor", "line": 26 } ]
1
python
has_theory_preds = any(is_supported_predicate(pred) for pred in expr.encoding.keys()) if has_theory_preds: return True if model: return model return True def z3_model_to_sympy_model(z3_model, enc_cnf): rev_enc = {value: key for key, value in enc_cnf.encodi...
Review this code and list any quality issues.
[ { "issue": "See https://peps.python.org/pep-0257/ for proper docstring formatting", "severity": "minor", "line": 26 } ]
1
python
logger.debug("Created temporary directory: %s", path) return path def cleanup(self) -> None: """Remove the temporary directory created and reset state""" self._deleted = True if not os.path.exists(self._path): return errors: List[BaseException] = [] def...
Review this code and list any quality issues.
[ { "issue": "This is the only annoying false positive", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor from ..utils import ( ExtractorError, js_to_json, parse_duration, traverse_obj, urljoin, ) class RottenTomatoesIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?rottentomatoes\.com/m/[^/]+/trailers/(?P<id>[\da-zA-Z]+)' _TESTS = [{ 'url': 'http:...
Review this code and list any quality issues.
[ { "issue": "This test is dead. When the URL is opened in browser, it redirects to an arbitrary video from the `/toy_story_3/trailers/` page, which is the \"Best Tom Hanks Movies\" video. That video's actual URL is https://www.rottentomatoes.com/m/toy_story_3/trailers/8FSKloB_r38Z\r\n\r\nEither update the `url` ...
1
python
def __init__(self): super().__init__() self.global_features: List[Tuple[Feature, Address]] = [] self.global_features.extend(capa.features.extractors.ghidra.file.extract_file_format()) self.global_features.extend(capa.features.extractors.ghidra.global_.extract_os()) self.global_fe...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n func = getFunctionContaining(toAddr(addr)) # type: ignore [name-defined] # noqa: F821\r\n return FunctionHandle(address=AbsoluteVirtualAddress(func.getAddress().getOffset()), inner=func)\r\n```", "severity": "minor", "line": 26 } ]
1
python
class GraySwanAnalyzer(SecurityAnalyzer): """Security analyzer using GraySwan's Cygnal API for AI safety monitoring.""" def __init__( self, history_limit: int = 20, max_message_chars: int = 30000, timeout: int = 30, session: Optional[aiohttp.ClientSession] = None, ) ...
Review this code and list any quality issues.
[ { "issue": "Any particular reason to keep these as environment variables instead of some config-level arg like `history_limit`?", "severity": "minor", "line": 26 } ]
1
python
class PandaTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|m\.)?pandalive\.co\.kr/play/(?P<id>[\da-z]+)' _TESTS = [{ 'url': 'https://www.pandalive.co.kr/play/bebenim', 'info_dict': { 'id': 'bebenim', 'ext': 'mp4', 'channel': '릴리ෆ', 'title': r...
Review this code and list any quality issues.
[ { "issue": "if we're not using the headers in the api call then let's just inline them in the return\r\n```suggestion\r\n channel_id = self._match_id(url)\r\n video_meta = self._download_json(\r\n```", "severity": "minor", "line": 26 } ]
1
python
# start a fastapi server with uvicorn import uvicorn from private_gpt.main import app from private_gpt.settings.settings import settings if __name__ == "__main__": # Set log_config=None to do not use the uvicorn logging configuration, and # use ours instead. For reference, see below: # https://github.com...
Review this code and list any quality issues.
[ { "issue": "Why is this necessary or a better practice?", "severity": "minor", "line": 8 } ]
1
python
if not sigs_path.exists(): logger.error( "Using default signature path, but it doesn't exist. " # noqa: G003 [logging statement uses +] + "Please install the signatures first: " + "https://github.com/mandiant/capa/blob/master/doc/installation....
Review this code and list any quality issues.
[ { "issue": "use argparse parsed data, like `if args.debug: ...`", "severity": "critical", "line": 26 } ]
1
python
<br> {config.get('ses.support_reference', '')} <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </body> </html>""" await send_email(to_addresses, subject, body, sending_app=sending_app) async def send_request_to_secondary_approvers( secondary_approvers, group, reques...
Review this code and list any quality issues.
[]
0
python
methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN). Operations between Series (+, -, /, \\*, \\*\\*) align values based on their associated index values-- they need not be the ...
Review this code and list any quality issues.
[ { "issue": "Related to https://github.com/pandas-dev/pandas/issues/63144, the question is what to put here in the docstring ..\r\n\r\n`copy=None` is closest to what is in the signature, but is not really meaningful by itself. Of course, the behaviour also depends on the intput, so writing that it defaults to ei...
1
python
import subprocess import glob import sys import os.path as path import os import argparse BAT_OPTIONS = [ "--no-config", "--style=plain", "--color=always", "--theme='1337'", "--italic-text=always", ] BINARY_OPTIONS = [ "--show-all", "--no-config", "--style=plain", "--color=always"...
Review this code and list any quality issues.
[ { "issue": "To make this more generally useful, what do you think about the following approach:\r\n\r\nWhen reading one of the `source` folders, we check if a `tests/syntax-tests/source/…/bat_options` file exists. If it does, we read the file and expect each line to be an additional command-line option for `bat...
1
python
############## # Pipeline API ############## @api_method @require_not_initialized(AttachPipelineAfterInitialize()) @expect_types( pipeline=Pipeline, name=string_types, chunks=(int, Iterable, type(None)), ) def attach_pipeline(self, pipeline, name, chunks=None, eager=T...
Review this code and list any quality issues.
[ { "issue": "We can be more precise here and say \"prior to\" rather than \"outside of\".", "severity": "minor", "line": 26 } ]
1
python
#!/opt/venv/bin/python # SPDX-License-Identifier: Apache-2.0 """Example plugin for LMCache system This plugin runs continuously and exits when parent process terminates""" # Standard import json import os import signal import time # First Party from lmcache.integration.vllm.utils import lmcache_get_config from lmcach...
Review this code and list any quality issues.
[]
0
python
image = Image.fromarray(frame_or_renderer) else: image = ( frame_or_renderer.get_image() if config.renderer == RendererType.OPENGL else Image.fromarray(frame_or_renderer) ) target_dir = self.image_file_pa...
Review this code and list any quality issues.
[ { "issue": "`image` should be a `PIL.Image.Image`, because `PixelArray` is a NumPy array and those don't have a `save` method (there is a `numpy.save()` function, but it's used differently). Around the source code, the argument which is passed to this method is effectively a `PIL.Image Image`.\n```suggestion\n ...
1
python
_VALID_URL = r'https?://(?:\w+\.)?ixigua\.com/(?:video/)?(?P<id>[0-9]+).+' _TEST = { 'url': 'https://www.ixigua.com/6996881461559165471', 'info_dict': { 'id': '6996881461559165471', 'ext': 'mp4', 'title': '盲目涉水风险大,亲身示范高水位行车注意事项', 'description': '本期《懂车帝...
Review this code and list any quality issues.
[ { "issue": "`39:25: W291 trailing whitespace`", "severity": "minor", "line": 26 } ]
1
python
) server = uvicorn.Server( uvicorn.Config( self.fastapi_app, host=api_host, port=self.get_port(), log_config=None, # Explicitly None to avoid uvicorn replacing the logger. log_level=self.log_level, ) ...
Review this code and list any quality issues.
[ { "issue": "Does service shutting down always means it's not healthy? or is this only for database manager?", "severity": "minor", "line": 26 } ]
1
python
== ApplicationStatus.RUNNING ) except (KeyError, AttributeError): return False @pytest.fixture(scope="module") def sglang_client(): """Start an SGLang server once for all tests in this module.""" llm_config = LLMConfig( model_loading_config={ "model_id": RAY_MODEL_ID, ...
Review this code and list any quality issues.
[ { "issue": "Please create a separate client for is_embedding, local to the embedding test", "severity": "minor", "line": 26 } ]
1
python
self.max_pool2 = torch.nn.MaxPool2d(2, 2) def forward(self, x): x = self.relu1(self.conv1(x)) x = self.max_pool1(x) x = self.relu2(self.conv2(x)) x = self.max_pool2(x) x = x.view(-1, x.size()[1:].numel()) x = self.relu3(self.fc1(x)) x = self.fc2(x) re...
Review this code and list any quality issues.
[]
0