language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np from onnx.reference.ops._op import OpRunUnaryNum def sigmoid(x: np.ndarray) -> np.ndarray: result = np.empty_like(x) pos_mask = x > 0 neg_mask = ~pos_mask x_neg = x...
Review this code and list any quality issues.
[ { "issue": "You probably don't want to compute `np.exp(x_neg)` twice.", "severity": "minor", "line": 17 } ]
1
python
from cognee.infrastructure.databases.vector import get_vector_engine vector_engine = get_vector_engine() query_vector = (await vector_engine.embedding_engine.embed_text([query_text]))[0] result = await vector_engine.search( collection_name="DocumentChunk_text", query_vector=query_vector, ...
Review this code and list any quality issues.
[]
0
python
if not self._exact: return tag elif self._version_compare(tag, resolved_tag): return resolved_tag elif tag != resolved_tag: continue self._report_error( f'yt-dlp cannot be updated...
Review this code and list any quality issues.
[ { "issue": "This should describe the type, so it would be `UpdateInfo`. Same below, `Optional[UpdateInfo]` or `UpdateInfo | None`", "severity": "minor", "line": 26 } ]
1
python
TessieSensorEntityDescription( key="charge_state_ideal_battery_range", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfLength.MILES, device_class=SensorDeviceClass.DISTANCE, suggested_display_precision=1, entity_registry_enabled_default=False, ...
Review this code and list any quality issues.
[ { "issue": "The value_fn for the charge port latch sensor should use bracket notation for dictionary access like the existing TessieChargeStates sensor. Change from `TessieChargePortLatchStates.get(cast(str, value))` to `TessieChargePortLatchStates[cast(str, value)]` to maintain consistency with the existing pa...
1
python
user: User, tasks: list[Task], data=None, pipeline_name: str = "custom_pipeline", context: dict = None, pipeline_cache=False, incremental_loading=False, data_per_batch: int = 20, ): # Will only be used if ENABLE_BACKEND_ACCESS_CONTROL is set to True await set_database_global_context_...
Review this code and list any quality issues.
[ { "issue": "Won't then `PipelineRunStarted` be yielded two times? Once from here and second time from `run_tasks`.", "severity": "minor", "line": 26 } ]
1
python
# or an offset into a file (file) if loc.get("type", "") in ("absolute", "file"): yield loc.get("value"), match_dict.get("node") for child in match_dict.get("children", {}): yield from get_locations(child) def parse_json(capa_data): """Parse json produced by capa""" rules = c...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n this_attack = meta.get(\"attack\", [])\r\n```", "severity": "minor", "line": 26 } ]
1
python
# we postpone the definition of unit_of_measurement to later self._attr_native_unit_of_measurement = None else: self._attr_native_unit_of_measurement = unit_of_measurement self._unit_prefix = UNIT_PREFIXES[unit_prefix] self._unit_time = UNIT_TIME[unit_time] self....
Review this code and list any quality issues.
[ { "issue": "or just pass it, as you've already initialised it to None", "severity": "minor", "line": 26 } ]
1
python
) # Filter tools to only allowed ones if tool_choice specified an allowed list effective_tools = self.ctx.chat_tools if allowed_tool_names is not None: effective_tools = [ tool for tool in self.ctx.chat_t...
Review this code and list any quality issues.
[ { "issue": "Hey @mattf I want to get some comments from you, seems llamastack need to implmenet its own truncation logic here, so a function is needed to do some truncation for message, comments? Thanks", "severity": "minor", "line": 26 } ]
1
python
}, }, { 'url': 'http://parliamentlive.tv/event/index/3f24936f-130f-40bf-9a5d-b3d6479da6a4', 'only_matching': True, }] _DEVICE_ID = str(uuid.uuid4()) _DATA = json.dumps({'device': { 'deviceId': _DEVICE_ID, 'width': 653, 'height': 368, 'type': 'WEB', ...
Review this code and list any quality issues.
[ { "issue": "Are you sure the accept and content-type are needed? Generally, the defaults are enough", "severity": "minor", "line": 26 } ]
1
python
int(np.array(1.0, dtype=np.float64)) int(np.array("1", dtype=np.str_)) float(np.array(1.0, dtype=np.float64)) float(np.array("1", dtype=np.str_)) complex(np.array(1.0, dtype=np.float64)) operator.index(np.array(1, dtype=np.int64)) # this fails on numpy 2.2.1 # https://github.com/scipy/scipy/blob/a755ee77ec47a64849a...
Review this code and list any quality issues.
[ { "issue": "there's also `with pytest.deprecated_call()`, probably doesn't matter", "severity": "minor", "line": 26 } ]
1
python
# When prompt length is divisible by the block size and all # blocks are cached, we need to recompute the last token. # This will be removed in the future if vLLM's scheduler provides # a better support for this case. need_to_allocate = num_external_hit_tokens - num_computed_tokens ...
Review this code and list any quality issues.
[ { "issue": "this is the main logic for preemption", "severity": "minor", "line": 26 } ]
1
python
port += 1 # Node1, both -bind=... and -bind=...=onion. self.expected.append( [ [f"-bind=127.0.0.1:{port}", f"-bind=127.0.0.1:{port + 1}=onion"], [(loopback_ipv4, port), (loopback_ipv4, port + 1)] ], ) port += 2 self.extra_...
Review this code and list any quality issues.
[ { "issue": "The `self.expected` variable name really confused me since it includes command line inputs used to *steer* the test, but it was named prior to this PR. Maybe improve the situation with some slightly clearer names in the loop?\r\n```python\r\n for i, (args, expected_services) in enumerate(self...
1
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging from typing import Optional, Text, Dict, Any import re from logging import config as logging_config from time import time from contextlib import contextmanager from .config import C class MetaLogger(type): def __init__(self...
Review this code and list any quality issues.
[ { "issue": "Why not use `logging.Logger.__doc__` ?", "severity": "minor", "line": 22 } ]
1
python
get_elements_html_by_class, ) class ViouslyIE(InfoExtractor): _VALID_URL = False _API_URL = 'https://www.viously.com/video/hls/{0:}/index.m3u8' _WEBPAGE_TESTS = [{ 'url': 'http://www.turbo.fr/videos-voiture/454443-turbo-du-07-09-2014-renault-twingo-3-bentley-continental-gt-speed-ces-guide-achat-da...
Review this code and list any quality issues.
[ { "issue": "I think we can just\r\n```suggestion\r\n viously_players = re.findall(r'<div[^>]*class=\"(?:[^\"]*\\s)?v(?:iou)?sly-player(?:\\s[^\"]*)?\"[^>]*>', webpage)\r\n if not viously_players:\r\n return\r\n\r\n```", "severity": "minor", "line": 26 } ]
1
python
) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Parameters ---------- path : str .glb / .obj / … file containing the terrain mesh. spacing : float | (float, float) Desired grid spacing Δx (and Δy). Units must match the mesh. oversample : int, default 3 Number of...
Review this code and list any quality issues.
[ { "issue": "I would remove this comment entirely. `rtree` is already installed automatically as part of the requirements.", "severity": "major", "line": 26 } ]
1
python
if ((left if left is not None else self.left) >= (right if right is not None else self.right)): raise ValueError('left cannot be >= right') if ((bottom if bottom is not None else self.bottom) >= (top if top is not None else self.top)): raise ValueError('bo...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Return a copy of the subplot parameters as a dict.\"\"\"\r\n```", "severity": "minor", "line": 26 } ]
1
python
'series': 'The Tim Dillon Show', 'thumbnail': 're:.+[.](png|jpe?g|webp)', }, }, { 'url': 'https://podcasts.apple.com/podcast/207-whitney-webb-returns/id1135137367?i=1000482637777', 'only_matching': True, }, { 'url': 'https://podcasts.apple.com/podcast/207-whitney-webb...
Review this code and list any quality issues.
[ { "issue": "Let's simplify this to:\r\n```suggestion\r\n model_data = traverse_obj(server_data, (\r\n 'headerButtonItems', lambda _, v: v['$kind'] == 'bookmark' and v['modelType'] == 'EpisodeOffer',\r\n 'model', {dict}, any))\r\n```\r\nAlso, was there any reason for choosing `bookma...
1
python
"metadata": SafeJson(metadata or {}), } ) logger.info( f"Created workspace file {file.id} at path {path} " f"in workspace {workspace_id}" ) return WorkspaceFile.from_db(file) async def get_workspace_file( file_id: str, workspace_id: str, ) -> Optional[WorkspaceFile]: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n where_clause: UserWorkspaceFileWhereInput = {\n```", "severity": "minor", "line": 26 } ]
1
python
'id': 'e1shjqd', 'ext': 'mp3', 'release_date': '20221221', 'duration': 1042.008, 'season': 'Season 2', 'modified_timestamp': 1671590834, 'uploader_id': '2585461', 'modified_date': '20221221', 'description': 'md5:9e95ad9293bf...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'ext': 'mp3',\r\n 'vcodec': 'none',\r\n```", "severity": "minor", "line": 26 } ]
1
python
rolls, limit = map(int, dice.split('d')) except Exception: await ctx.send('Format has to be in NdN!') return result = ', '.join(str(random.randint(1, limit)) for r in range(rolls)) await ctx.send(result) @bot.command(description='For when you wanna settle the score some other way') async ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n await ctx.send(f'{member.name} joined {discord.utils.format_dt(member.joined_at)}')\r\n```", "severity": "minor", "line": 26 } ]
1
python
If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here. If a circular reference is found within the iterable, it will be replaced by the value of ALREADY_PROCESSED_PLACEHOLDER. Parameters ---------- it...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n def _iter_check_dict(dct: dict[Any, Any]) -> dict[Any, Any]:\r\n```", "severity": "minor", "line": 26 } ]
1
python
to a set of data set names, according to the data engineering convention. For more details, see https://docs.kedro.org/en/stable/resources/glossary.html#layers-data-engineering-convention Example: :: >>> from kedro.extras.datasets.pandas import CSVDataSet ...
Review this code and list any quality issues.
[ { "issue": "Do we really need a separate variable for this cache? Couldn't this just be `self._data_sets` and just have a `set()` of all original (non-pattern) data set names?", "severity": "major", "line": 26 } ]
1
python
if xp is None: xp, is_array_api = get_namespace(*array_list, **skip_remove_kwargs) else: xp, is_array_api = xp, True if is_array_api: return xp, is_array_api, arrays_device else: return xp, False, arrays_device def _convert_to_reference(*, reference, arrays): """Conver...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Converting to numpy is tricky, handle this via a dedicated function\r\n```", "severity": "minor", "line": 26 } ]
1
python
'info_dict': { 'id': '6376598467112', 'ext': 'mp4', 'title': 'Pedro Sousa «Hjulmand pode ter uma saída limpa do Sporting daqui a um ano»', 'description': '', 'uploader_id': '6108484330001', 'duration': 65.237, 'thumbnail': r're:^https:/...
Review this code and list any quality issues.
[ { "issue": "we don't use `video_data` for anything else, so let's get the BC `video_id` right away\r\n```suggestion\r\n video_id = self._search_json(\r\n r'videoHandler\\.addBrightcoveVideoWithJson\\(\\[',\r\n webpage, 'video data', display_id)['brightcoveVideoId']\r\n```", "sev...
1
python
entry_dir = nni_node.__path__[0] entry_file = os.path.join(entry_dir, 'nasui', 'server.js') if sys.platform == 'win32': node_command = os.path.join(entry_dir, 'node.exe') else: node_command = os.path.join(entry_dir, 'node') cmds = [node_command, '--max-old-space-s...
Review this code and list any quality issues.
[]
0
python
expected_cpu_features = DEFAULT_G3_FEATURES_V1N1 case CpuModel.ARM_NEOVERSE_V1, _, "aarch64_with_sve_and_pac": expected_cpu_features = DEFAULT_G3_FEATURES_WITH_SVE_AND_PAC_5_10 case CpuModel.ARM_NEOVERSE_V1, _, None: expected_cpu_features = DEFAULT_G3_FEATURES_5_10 _, stdout...
Review this code and list any quality issues.
[ { "issue": "We could make this test more generic and support x86_64. Maybe it belongs in a generic `test_cpu_features.py` (and move the current `test_cpu_features.py` to `test_cpu_features_x86.py`)", "severity": "minor", "line": 26 } ]
1
python
``candidates`` can be a list of modules or a ordered dict of named modules, for example, .. code-block:: python self.op_choice = LayerChoice(OrderedDict([ ("conv3x3", nn.Conv2d(3, 16, 128)), ("conv5x5", nn.Conv2d(5, 16, 128)), ("conv7x7", nn.Conv2d(7, 16, 128)) ...
Review this code and list any quality issues.
[ { "issue": "have not supported value choice, right?", "severity": "minor", "line": 26 } ]
1
python
from agno.run.team import TeamRunInput data["run_input"] = TeamRunInput.from_dict(run_input) else: from agno.run.agent import RunInput data["run_input"] = RunInput.from_dict(run_input) # Handle requirements # Handle requirements ...
Review this code and list any quality issues.
[ { "issue": "ah, i think we also need to handle for `to_dict`? can we do some tests to make sure a fix is not needed in `to_dict` because we use `asdict` there and i'm afraid if its even serializing it properly. Specially if we dynamically set the attributes for that custom event", "severity": "minor", "...
1
python
return ret def set_q_k_v(self): """ Necessary to implement for `HybridSplitQKVContainer` """ self.qw = self.policy.client_module.self_attn.q_proj.weight self.qb = None self.kw = self.policy.client_module.self_attn.k_proj.weight self.kb = None self.vw ...
Review this code and list any quality issues.
[]
0
python
f'{self._BASE_URL}/webApi/play/url/{video_id}', video_id) except ExtractorError as e: if isinstance(e.cause, HTTPError) and e.cause.status == 500: raise ExtractorError('VR SQUARE app-only videos are not supported', expected=True) return { 'id': video_id, ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n ..., {extract_attributes}, 'data-url', {str}, filter))\r\n```", "severity": "major", "line": 26 } ]
1
python
if any_string_dtype == "str": # NaN propagates as False expected = Series([False, False, False], dtype=bool) else: expected_dtype = ( "object" if is_object_or_nan_string_dtype(any_string_dtype) else "boolean" ) expected = Series([np.nan, np.nan, np.nan], dtype=exp...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nThis check will also be done by the `assert_series_equal` called on the next line", "severity": "minor", "line": 26 } ]
1
python
axis_loss = torch.mean(self.perceptual_function(input_slices, target_slices)) return axis_loss def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ Args: input: the shape should be BNHW[D]. target: the shape should be BNHW[D]. ""...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n loss = torch.mean(loss.squeeze(), dim=0)\r\n```", "severity": "minor", "line": 26 } ]
1
python
result = mempool.get_items_by_coin_ids(coin_ids) assert set(result) == set(expected) def make_test_spendbundle(coin: Coin, *, fee: int = 0, with_higher_cost: bool = False) -> SpendBundle: conditions = [] actual_fee = fee if with_higher_cost: conditions.extend([[ConditionOpcode.CREATE_COIN, IDE...
Review this code and list any quality issues.
[ { "issue": "We can still return the saved cost to maintain the test intent. I addressed this as part of an addendum (PR #19816).", "severity": "minor", "line": 26 } ]
1
python
BloodGlucoseConcentrationConverter.VALID_UNITS ), vol.Optional("carbon_monoxide"): vol.In( CarbonMonoxideConcentrationConverter.VALID_UNITS ), vol.Optional("concentration"): vol.In( MassVolumeConcentrationConverter.VALID_UNITS ), vol.Optional("cond...
Review this code and list any quality issues.
[ { "issue": "Can you please move ozone up above power (alphabetical order - let's ignore invalid voltage position 🤣 )", "severity": "minor", "line": 26 } ]
1
python
}) if thumb_asset_portrait := asset_portrait.get('thumbnailURL'): thumbnails.append({ 'id': 'portrait', 'url': thumb_asset_portrait, }) old_id = self._search_regex(r'%7C(\d+)(?:-\d+)?.mp4', formats[-1]['url'], 'old id', default=None) retu...
Review this code and list any quality issues.
[ { "issue": "I'd just unpack one big traverse_obj call for everything that you can (obviously not `formats` etc)\r\n\r\n```py\r\n**traverse_obj(clip, {\r\n 'title': ('title', {str}),\r\n 'duration': ('durationSeconds', {int_or_none}),\r\n 'view_count': ('viewCount', {int_or_none}),\r\n # etc \r\n}),"...
1
python
MISTRAL = "mistral" YI = "yi" # lingyiwanwu OPENROUTER = "openrouter" BEDROCK = "bedrock" ARK = "ark" # https://www.volcengine.com/docs/82379/1263482#python-sdk def __missing__(self, key): return self.OPENAI class LLMConfig(YamlModel): """Config for LLM OpenAI: https://github.c...
Review this code and list any quality issues.
[]
0
python
if video_format == 'hls': src = player_config['src'][video_format] params = {} uid = self._search_regex(r'window\.MDSTRMUID\s*=\s*["\']([^"\']+)["\'];', webpage, 'uid', fatal=False, default=None) if uid: params['uid'] = uid ...
Review this code and list any quality issues.
[ { "issue": "Use `parse_qs` from `..utils` instead\r\n```suggestion\r\n access_token = parse_qs(url).get('access_token', [None])[0]\r\n if access_token:\r\n params['access_token'] = access_token\r\n```", "severity": "minor", "line": 26 } ]
1
python
AutoModelForCausalLM, AutoModelForImageTextToText, AutoModelForVision2Seq, ) from verl.utils.model import get_generation_config, print_model_size, update_model_config from verl.utils.torch_dtypes import PrecisionType assert role in ["actor", "ref"] log_...
Review this code and list any quality issues.
[ { "issue": "There's 2 question here:\r\n1. `fsdp_config.get(\"model_dtype\", None)` always return fp32 here, so we never enter this branch.\r\n2. `torch_dtype` only affects `AutoModel.from_pretrained`, while FSDP mixed precision still use bf16 as param_dtype\r\nhttps://github.com/volcengine/verl/blob/main/verl/...
1
python
import sys num = 1337 def return_num() -> int: return num print(oct(num)[2:]) # FURB116 print(hex(num)[2:]) # FURB116 print(bin(num)[2:]) # FURB116 print(oct(1337)[2:]) # FURB116 print(hex(1337)[2:]) # FURB116 print(bin(1337)[2:]) # FURB116 print(bin(+1337)[2:]) # FURB116 print(bin(return_num())[2:]) #...
Review this code and list any quality issues.
[]
0
python
}] def _real_extract(self, url): content_code, channel_id = self._match_valid_url(url).group('code', 'channel') fanclub_site_id = self._find_fanclub_site_id(channel_id) data_json = self._call_api( f'video_pages/{content_code}', item_id=content_code, headers={'fc_use_device': 'n...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if live_status == 'is_upcoming':\r\n if release_timestamp_str:\r\n msg = f'This live event will begin at {release_timestamp_str} UTC'\r\n else:\r\n msg = 'This event has not started yet'\r\n self.raise_no_formats...
1
python
def normalize(df): df['scaled'] = df['signal'] * 10 return df def initialize(context): fetch_csv('https://fake.urls.com/aapl_ibm_csv_data.csv', post_func=normalize, mask=True) def handle_data(context, data): record( signal=data.current(sid(24),"signal"), scaled=...
Review this code and list any quality issues.
[]
0
python
class ActionModule(ActionBase): def save_playbook(self, proj_path, remediation, content): name = remediation.get('name', None) or 'insights-remediation' name = re.sub(r'[^\w\s-]', '', name).strip().lower() name = re.sub(r'[-\s]+', '-', name) fname = '{}-{}.yml'.format(name, remediati...
Review this code and list any quality issues.
[ { "issue": "we might prefer `oidc_endpoint = oidc_endpoint.rstrip('/')`", "severity": "minor", "line": 26 } ]
1
python
indexing_technique="high_quality", created_by=account.id, ) db_session_with_containers.add(dataset) db_session_with_containers.commit() document = Document( tenant_id=tenant.id, dataset_id=dataset.id, position=0, data_source_ty...
Review this code and list any quality issues.
[]
0
python
key: str | None @api_router.post('', response_model=ApiKeyCreateResponse) async def create_api_key(key_data: ApiKeyCreate, user_id: str = Depends(get_user_id)): """Create a new API key for the authenticated user.""" try: api_key = await api_key_store.create_api_key( user_id, key_data.name,...
Review this code and list any quality issues.
[ { "issue": "**suggestion:** It appears that we may be missing tests for this endpoint. Thank you! 🙏", "severity": "minor", "line": 26 } ]
1
python
@pytest.mark.parametrize('install_deps', [True, False]) def test_install_local(test_envs, executor_zip_file, test_executor, install_deps): assert not hubapi.exist_local(test_executor.uuid, test_executor.tag) hubapi.install_local(executor_zip_file, test_executor, install_deps=install_deps) assert hubapi.exis...
Review this code and list any quality issues.
[ { "issue": "Maybe due to these lines @floralatin", "severity": "minor", "line": 26 } ]
1
python
def _get_process_by_port(port): if platform.system() == "Windows": command = f"netstat -ano | findstr :{port}" result = subprocess.run(command, shell=True, capture_output=True, text=True) if result.returncode == 0: output = result.stdout.strip() lines = output.split("...
Review this code and list any quality issues.
[]
0
python
if live_status: info_dict['live_status'] = live_status for key in live_keys: if info_dict.get(key) is None: info_dict[key] = (live_status == key) if live_status == 'post_live': info_dict['was_live'] = True # Auto generate title fie...
Review this code and list any quality issues.
[ { "issue": "We could perhaps do (remove space):\r\n```suggestion\r\n info_dict[old_key] = ', '.join(re.replace(', +', ',', v) for v in new_value)\r\n```\r\nor maybe (unicode):\r\n```suggestion\r\n info_dict[old_key] = ', '.join(v.replace(', ', ', ') for v in new_value)\r\n```\r\n\r...
1
python
# FIXME: non-standard, but we need a way of showing that it is an estimate. '_time_text': time_text, 'timestamp': timestamp, }) info['author_url'] = urljoin( 'https://www.youtube.com', traverse_obj(comment_entity_payload, ('author...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if traverse_obj(view_model, 'pinnedText'):\r\n```", "severity": "minor", "line": 26 } ]
1
python
# Generated by Django 3.2.16 on 2023-03-03 20:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0174_ensure_org_ee_admin_roles'), ] operations = [ migrations.AddField( model_name='inventorysource', name='...
Review this code and list any quality issues.
[]
0
python
""" def __init__(self, vmobject, **kwargs): VGroup.__init__(self, **kwargs) tuples = vmobject.get_cubic_bezier_tuples() for tup in tuples: part = VMobject() part.set_points(tup) part.match_style(vmobject) self.add(part) class DashedVMobject(...
Review this code and list any quality issues.
[ { "issue": "Echoing @kolibril13's comment: spelling out what the range produces doesn't seem necessary.\r\n```suggestion\r\n for dashes in range(2, 12): \r\n```", "severity": "minor", "line": 26 } ]
1
python
f.write("goodbye") with open(os.path.join(path, "file3.txt"), "w") as f: f.write("ray\n") ds = ray.data.read_text(path) assert sorted(_to_lines(ds.take())) == ["goodbye", "hello", "ray", "world"] ds = ray.data.read_text(path, drop_empty_lines=False) assert ds.count() == 4 def test_read_tex...
Review this code and list any quality issues.
[ { "issue": "Nit: Might be worth explicitly commenting that the intent is to verify both lists of pathlib.Path and a single pathlib.Path. Intent wasn't immediately obvious to me when I skimmed the test", "severity": "minor", "line": 26 } ]
1
python
) str_keys.append(f"{arg_name}={descr}") return f"{type(self).__module__}.{type(self).__name__}({', '.join(str_keys)})" def __repr__(self) -> str: return self._pretty_repr(self._describe()) @abc.abstractmethod def _load(self) -> _DO: raise NotImplementedError( ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nAlthough, why sort the top-level key, but not subkeys?", "severity": "minor", "line": 26 } ]
1
python
engine: Optional[str] = None, compression: Optional[str] = None, read_kwargs: Optional[Dict] = None, write_kwargs: Optional[Dict] = None, exposed_type: Optional[str] = None, scope: Optional[Scope] = None, validity_period: Optional[timedelta] = None, **properties, ...
Review this code and list any quality issues.
[]
0
python
import os from sherlock_interactives import Interactives import sherlock def test_versioning() -> None: # Ensure __version__ matches version presented to the user assert sherlock.__version__ in Interactives.run_cli("--version") # Ensure __init__ is single source of truth for __version__ in package # Te...
Review this code and list any quality issues.
[]
0
python
# Copyright 2021-2024 Avaiga Private Limited # # 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 agree...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n<|menu|lov={options}|>\r\n```", "severity": "minor", "line": 22 } ]
1
python
model_request_parameters: ModelRequestParameters, ) -> GenerateContentResponse: ... @overload async def _generate_content( self, messages: list[ModelMessage], stream: Literal[True], model_settings: GoogleModelSettings, model_request_parameters: ModelRequestParameters...
Review this code and list any quality issues.
[ { "issue": "finally pass all required tests, for lint I add this ignore comment", "severity": "minor", "line": 26 } ]
1
python
coin = blocks[-1].get_included_reward_coins()[0] spend_bundle = wallet.generate_signed_transaction(uint64(42), wallet_ph, coin) sb_name = spend_bundle.name() await node_to_add_tx_to.add_transaction(spend_bundle, sb_name, ws_con) mempool_item = node_to_add_tx_to.mempool_manager.get_mempoo...
Review this code and list any quality issues.
[ { "issue": "you need an else block here, to make sure the peer is *not* banned. e.g. if the peer is *always* banned, this test would still pass right now", "severity": "minor", "line": 26 } ]
1
python
existing_host_ids = set(h.id for h in all_hosts) summaries = dict() updated_hosts_list = list() for host in hostnames: host_id = host_map.get(host) if host_id not in existing_host_ids: host_id = None constructed_hos...
Review this code and list any quality issues.
[ { "issue": "Doubts:\r\nThis goes to the log files right? Wouldn't this be too verbose? `error` tends to be captured by monitoring tools.", "severity": "minor", "line": 26 } ]
1
python
if workflow_state.status == "in_progress": return _("Sent to %(task_name)s %(started_at)s") % translation_context return _("%(status_display)s %(task_name)s %(started_at)s") % translation_context @register.inclusion_tag( "wagtailadmin/shared/keyboard_shortcuts_dialog.html", takes_context=True, ) ...
Review this code and list any quality issues.
[ { "issue": "Sorry to nitpick, but for consistency, this should be sentence case.\n\n```suggestion\n (\"text-editing\", _(\"Text editing\")): [\n```", "severity": "minor", "line": 26 } ]
1
python
chunk_size = (3, 3, 3) a = np.arange(np.prod(shape), dtype=dtype).reshape(shape) d = da.from_array(a, chunks=chunk_size) for num_axes in range(1, d.ndim): for axes in combinations_with_replacement(range(d.ndim), num_axes): cs = list(chunk_size) for i in axes: ...
Review this code and list any quality issues.
[]
0
python
rank_zero_info(f"Restoring states from the checkpoint file at {checkpoint_path}") checkpoint, load_optimizer_states = self.trainer.training_type_plugin.restore_model_state_from_ckpt_path( checkpoint_path, map_location=lambda storage, loc: storage ) self.loaded_checkpoint = checkpoint...
Review this code and list any quality issues.
[ { "issue": "Should this docstring be the same as that of `resume_start`?", "severity": "minor", "line": 26 } ]
1
python
response_cookies[context.session.id] = response_data.get('cookies') if context.request.user_data.get('retire_session'): context.session.retire() await crawler.run( [ # The first request sets the cookie in the session str(server_url.with_path('set_cookies').exten...
Review this code and list any quality issues.
[]
0
python
def run_test(self): node = self.nodes[0].add_p2p_connection(P2PIgnoreInv()) expected_services = NODE_WITNESS | NODE_NETWORK_LIMITED if self.options.v2transport: expected_services |= NODE_P2P_V2 self.log.info("Check that node has signalled expected services.") assert...
Review this code and list any quality issues.
[ { "issue": "nit: Could add a comment on why number 12 is chosen here?", "severity": "minor", "line": 26 } ]
1
python
state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": REDIRECT, }, ) client = await hass_client_no_auth() await client.get(f"/auth/external/callback?code=abcd&state={state}") aioclient_mock.post( TOKEN...
Review this code and list any quality issues.
[ { "issue": "A reconfigure_flow, as such in your case, also relies on the `async_step_user()`. We also need tests for these exceptions. And during these exceptions we need to test we can recover from it. An example can be found here: https://github.com/erwindouna/ha-core/blob/2032138b400d0b80d752f5a479ab4087cba1...
1
python
from .common import InfoExtractor from ..utils import traverse_obj class QingTingIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.|m\.)?(?:qingting\.fm|qtfm\.cn)/v?channels/(?P<channel>\d+)/programs/(?P<id>\d+)' _TESTS = { 'url': 'https://www.qingting.fm/channels/378005/programs/22257411/', ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _TESTS = [{\r\n 'url': 'https://www.qingting.fm/channels/378005/programs/22257411/',\r\n 'md5': '47e6a94f4e621ed832c316fd1888fb3c',\r\n 'info_dict': {\r\n 'id': '22257411',\r\n 'ext': 'mp3',\r\n 'title': '用了十年才修改,谁在乎教科书?-睡前消息...
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), 3.7800, 4) def test_kaiser(self, dtype: str, M: int) -> None: scalar = np.array...
Review this code and list any quality issues.
[]
0
python
train_loader = pl.DataLoader(train_dataset, 64) valid_dataset = nni.trace(MNIST)('data/mnist', download=True, train=False, transform=transform) valid_loader = pl.DataLoader(valid_dataset, 64) return pl.Classification( train_dataloader=train_loader, val_dataloaders=valid_loader, limit_train_b...
Review this code and list any quality issues.
[ { "issue": "Please put this in algo test. I'd like to keep `test_experiment` as minimal as possible.", "severity": "minor", "line": 26 } ]
1
python
log.info("DB: Creating index coin_spent_index") await conn.execute("CREATE INDEX IF NOT EXISTS coin_spent_index on coin_record(spent_index)") log.info("DB: Creating index coin_puzzle_hash") await conn.execute("CREATE INDEX IF NOT EXISTS coin_puzzle_hash on coin_record(puzzle_hash)")...
Review this code and list any quality issues.
[ { "issue": "this will make the database larger. Can you add a comment to the source code explaining why we need this index? it would be good to document why we only add it to new databases too", "severity": "minor", "line": 26 } ]
1
python
self.tp(self.BytesIO(), 1024, 1024, 1024) def test_bad_readinto_value(self): rawio = self.tp(self.BytesIO(b"12")) rawio.readinto = lambda buf: -1 bufio = self.tp(rawio) with self.assertRaises(OSError) as cm: bufio.readline() self.assertIsNone(cm.exception.__cause...
Review this code and list any quality issues.
[ { "issue": "When we have tests that looks like:\r\n```python\r\n@unittest.expectedFailure # TODO: RUSTPYTHON\r\ndef foo(self):\r\n return super().foo()\r\n```\r\n\r\nThat is a test that we are patching for that specific subclass.\r\nanyway, if there are no other decorators for those kind of tests, they can b...
1
python
if not integration_controller.get_handler_meta('dummy_ml')['import']['success']: error = integration_controller.handlers_import_status['dummy_ml']['import']['error_message'] raise Exception(f"Can not import: {str(handler_dir)}: {error}") if import_dummy_llm: test_han...
Review this code and list any quality issues.
[]
0
python
ensure_feature_valid_for_scope(scope, feature) return feature elif ( (key == "os" and d[key] not in capa.features.common.VALID_OS) or (key == "format" and d[key] not in capa.features.common.VALID_FORMAT) or (key == "arch" and d[key] not in capa.features.common.VALID_ARCH) ): ...
Review this code and list any quality issues.
[ { "issue": "please parse the description from this line as well, like we do above with `property/`", "severity": "minor", "line": 26 } ]
1
python
class_obj = None if isinstance(dataset_type, str): if len(dataset_type.strip(".")) != len(dataset_type): raise DatasetError( "'type' class path does not support relative " "paths or paths ending with a dot." ) class_paths = (prefix + dataset_ty...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"You can do so by running `pip install kedro-datasets` or `pip install kedro-datasets[polars] for a specific back-end`.\"\r\n```\r\n\r\nwdyt?", "severity": "minor", "line": 26 } ]
1
python
else _("Paste without formatting"), f"{KEYS.MOD} + {KEYS.SHIFT} + v", ), (_("Undo"), f"{KEYS.MOD} + z"), ( _("Redo"), f"{KEYS.MOD} + {KEYS.SHIFT} + z" if is_mac else f"{KEYS.MOD} + y", ), ...
Review this code and list any quality issues.
[ { "issue": "I'm good with removing this. We probably don't want to encourage underline use, anyway, since it could fool people into thinking it's a link.", "severity": "minor", "line": 26 } ]
1
python
input_schema=GetCurrentDateBlock.Input, output_schema=GetCurrentDateBlock.Output, test_input=[ {"trigger": "Hello", "offset": "7"}, {"trigger": "Hello", "offset": "7", "format": "%m/%d/%Y"}, ], test_output=[ ( ...
Review this code and list any quality issues.
[]
0
python
import random from .common import InfoExtractor from ..utils import ExtractorError, traverse_obj class CamsodaIE(InfoExtractor): _VALID_URL = r'https?://www\.camsoda\.com/(?P<id>[0-9A-Za-z-]+)' _TESTS = [{ 'url': 'https://www.camsoda.com/lizzhopf', 'info_dict': { 'id': 'lizzhopf',...
Review this code and list any quality issues.
[ { "issue": "is it worth downloading webpage just for description?", "severity": "minor", "line": 24 } ]
1
python
kwonly_defaults, takes_context, function_name, ) return SimpleBlockNode( nodelist, func, takes_context, args, kwargs, target_var ) self.tag(function_name, compile_func) return func ...
Review this code and list any quality issues.
[]
0
python
# Save initial model, that is loaded after batch size is found ckpt_path = os.path.join(trainer.default_root_dir, f".scale_batch_size_{uuid.uuid4()}.ckpt") trainer.save_checkpoint(ckpt_path) # Arguments we adjust during the batch size finder, save for restoring params = __scale_batch_dump_params(traine...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n except Exception as ex:\r\n raise ex\r\n```\r\npls not a single letter :)", "severity": "minor", "line": 26 } ]
1
python
"v0.5.0", "v0.6.0", "v0.7.0", ] colors = ["#003f5c", "#58508d", "#bc5090", "#ff6361", "#ffa600"] bar = BarChart( pull_req, max_value=max(pull_req), bar_colors=colors, ...
Review this code and list any quality issues.
[ { "issue": "Are you sure the quotes are correct? It seems to be unquoted in other typehints in the rest of the library.", "severity": "minor", "line": 26 } ]
1
python
video_id, title = video_data['bvid'], video_data.get('title') # Bilibili anthologies are similar to playlists but all videos share the same video ID as the anthology itself. page_list_json = (not is_festival and traverse_obj( self._download_json( 'https://api.bilibili.com/x/...
Review this code and list any quality issues.
[ { "issue": "this `is_logged_in` check seems redundant if we are also popping `try_look` from the query params in `_download_playinfo()`", "severity": "minor", "line": 26 } ]
1
python
def replace_cell_magics(src: str) -> tuple[str, list[Replacement]]: r"""Replace cell magic with token. Note that 'src' will already have been processed by IPython's TransformerManager().transform_cell. Example, get_ipython().run_cell_magic('t', '-n1', 'ls =!ls\n') becomes "a794....
Review this code and list any quality issues.
[]
0
python
for source in sources: header = f"{default_conversation.system}" conversation, intermediate = _add_speaker_and_signal(header, source) conversations.append(conversation) intermediates.append(intermediate) conversations_tokenized = _tokenize_fn(conversations, tokenizer, max_length) ...
Review this code and list any quality issues.
[ { "issue": "Please specify return type of the function", "severity": "minor", "line": 26 } ]
1
python
Returns ------- A dictionary (id -> recorder) of recorder information that being stored. """ raise NotImplementedError(f"Please implement the `list_recorders` method.") class MLflowExperiment(Experiment): """ Use mlflow to implement Experiment. """ def __in...
Review this code and list any quality issues.
[ { "issue": "How could user start recorder for the same name for multiple times?", "severity": "minor", "line": 26 } ]
1
python
match.group(1), match.group(2)) platform = args.platform if tag < "v23" and platform in ["x86_64-apple-darwin", "arm64-apple-darwin"]: platform = "osx64" tarball = 'bitcoin-{tag}-{platform}.tar.gz'.format( tag=tag[1:], platform=platform) tarballUrl = 'https://bitcoincore.org/{bin_path}/{...
Review this code and list any quality issues.
[]
0
python
else "\n\n".join(current_chunk_content) ) chunks.append(chunk_text.strip()) current_chunk_content = [] # Split the large paragraph by sentences or fixed size available_size = self.chunk_size - heading_size words...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # add remaining content\r\n```", "severity": "minor", "line": 26 } ]
1
python
If None, all paths are allowed (permissive-by-default). kwargs: Additional keyword arguments. """ try: aca_settings = ACASessionsSettings( env_file_path=env_file_path, pool_management_endpoint=pool_management_endpoint, token_endpoin...
Review this code and list any quality issues.
[ { "issue": "Passing an empty set or empty list for `allowed_upload_directories` will be treated as if None was passed (due to the falsy check on line 95), which disables upload functionality. This might be unexpected behavior - if a user explicitly passes an empty set/list, they might expect it to deny all uplo...
1
python
@pytest.mark.parametrize("bin", (False, True)) def test_dump(self, tmpdir, bin): path = tmpdir.join(f"dumpfile{int(bin)}") try: d = {"answer": 42} path.dump(d, bin=bin) f = path.open("rb+") import pickle dnew = pickle.load(f) a...
Review this code and list any quality issues.
[ { "issue": "This particular test needs to be excluded from timing control as it tests fs interaction", "severity": "minor", "line": 26 } ]
1
python
""" These system prompts come from: https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/system_messages.py#L54 """ SYSTEM_MESSAGE = """You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object attribution a...
Review this code and list any quality issues.
[ { "issue": "As discussed internally, this new-line character thingy messes the quality a bit. Hence, I have decided to keep these system messages one-to-one same as the original implementation linked above. \r\n\r\nIf we run `make style && make quality`, this order will be completely destroyed. We can change th...
1
python
>>> io = DataCatalog() >>> # get data sets where the substring 'raw' is present >>> raw_data = io.list(regex_search='raw') >>> # get data sets which start with 'prm' or 'feat' >>> feat_eng_data = io.list(regex_search='^(prm|feat)') >>> # get data sets which en...
Review this code and list any quality issues.
[ { "issue": "I know I named this method like this, but there's already an `exists` method in this file, so it's a bit confusing what the difference is. Especially because `exists` actually calls `_get_dataset()` but now `_get_dataset()` calls this method. Is it necessary for `_get_datasets()` to call this method...
1
python
for file in fn_iterator: if file.endswith(supported_image_extensions): ext = pathlib.Path(file).suffix[ 1: ] # Get extension without the . symbol image_extensions[ext] += 1 else: raise IngestionError(f"The follo...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"htype\" not in tensor_params\r\n```", "severity": "minor", "line": 26 } ]
1
python
parsed_value = _parse_interval_value(value) parsed_unit = _parse_interval_unit(unit) if parsed_value is not None and parsed_unit is not None: return parsed_value, parsed_unit if len(parts) == 1: raw = parts[0].value if isinstance(parts[0], ast.Constant) else parts[0] ...
Review this code and list any quality issues.
[ { "issue": "can we add just 1-2 examples of transformations that this function makes?, like\r\n DATE_ADD('2024-02-03', INTERVAL 10 DAY) -> dateadd('2024-02-03', 10);", "severity": "minor", "line": 26 } ]
1
python
log.info("Done!") def preprocess(example, tokenizer: Tokenizer, max_seq_len: int): parts = [] for msg in example["messages"]: parts.append(f"<|{msg['role']}|>") parts.append(msg["content"]) prompt = "\n".join(parts[:-1]) + "\n" completion = parts[-1] prompt_ids = tokenizer.encode...
Review this code and list any quality issues.
[ { "issue": "@hamishivi in particular this function for preprocessing/tokenizing each example.", "severity": "minor", "line": 26 } ]
1
python
fontsize = prop.get_size_in_points() dvifile = texmanager.make_dvi(s, fontsize) with dviread.Dvi(dvifile, 72) as dvi: page, = dvi if gc.get_url() is not None: self.file._annotations[-1][1].append(_get_link_annotation( gc, x, y, page.width, page.height, an...
Review this code and list any quality issues.
[ { "issue": "I think you need to use `text.index` here? (with `for text in page.text: x1, y1 dvifont, glyph, width = text; ...`) (#29868)\r\nI would even stop unpacking and just use text.x, text.y, etc.", "severity": "minor", "line": 26 } ]
1
python
'ac2': 'wifi5g', 'uoo': '1', 'carrier_region': 'US', 'op_region': 'US', 'build_number': self._APP_INFO['app_version'], 'region': 'US', 'ts': int(time.time()), 'iid': self._APP_INFO.get('iid'), 'device_id': self._DEVICE_ID, ...
Review this code and list any quality issues.
[ { "issue": "It'll still show in the verbose head. So what's the point?", "severity": "minor", "line": 26 } ]
1
python
'title': name, } def _extract_info_gql(self, info, item_id): vod_id = info.get('id') or item_id # id backward compatibility for download archives if vod_id[0] != 'v': vod_id = 'v%s' % vod_id thumbnail = url_or_none(info.get('previewThumbnailURL')) is_...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'thumbnails': self._get_thumbnails(thumbnail),\r\n```", "severity": "minor", "line": 26 } ]
1
python
y: int inaxes: Axes | None xdata: float | None ydata: float | None def __init__( self, name: str, canvas: FigureCanvasBase, x: int, y: int, guiEvent: Any | None = ..., *, modifiers: Iterable[str] | None = ..., ) -> None: ... class Mous...
Review this code and list any quality issues.
[]
0
python
from graphrag.index.typing.workflow import WorkflowFunctionOutput from graphrag.utils.storage import load_table_from_storage, write_table_to_storage logger = logging.getLogger(__name__) async def run_workflow( _config: GraphRagConfig, context: PipelineRunContext, ) -> WorkflowFunctionOutput: """All the s...
Review this code and list any quality issues.
[]
0
python
})['stream_url'] formats = self._extract_m3u8_formats( m3u8_url, video_id, ext='mp4', entry_protocol='m3u8_native', m3u8_id='hls') self._sort_formats(formats) info.update({ 'id': video_id, 'formats': formats, }) return info clas...
Review this code and list any quality issues.
[ { "issue": "why is this an empty string? If not found, it should be None", "severity": "minor", "line": 26 } ]
1
python
decoder_input_ids = torch.tensor([[1, 2, 3], [4, 5, 6]]).to(torch_device) model_inputs = model.prepare_inputs_for_generation(decoder_input_ids) self.assertTrue(torch.all(model_inputs["decoder_input_ids"] == decoder_input_ids)) # 3. If we pass the attention mask too, we will get back the attenti...
Review this code and list any quality issues.
[ { "issue": "generate is not and will not be fullgraph compilable, we compile only `model.forward`", "severity": "minor", "line": 26 } ]
1
python
# as_integer_ratio not defined in a class class A: pass a = A() a.as_integer_ratio = lambda: (9, 5) self.assertEqual((9, 5), _components(F(a))) # as_integer_ratio defined in a metaclass class M(type): def as_integer_ratio(self): re...
Review this code and list any quality issues.
[ { "issue": "Why this was replaced, not added?", "severity": "minor", "line": 26 } ]
1
python
import json import re from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, str_or_none, traverse_obj, ) class TelecincoIE(InfoExtractor): IE_DESC = 'telecinco.es, cuatro.com and mediaset.es' _VALID_URL = r'https?://(?:www\.)?(?:telecinco\.es|cuatro\.com|mediaset\.e...
Review this code and list any quality issues.
[ { "issue": "needed for other suggestions\r\n```suggestion\r\n traverse_obj,\r\n update_url,\r\n url_or_none,\r\n```", "severity": "minor", "line": 12 } ]
1