language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
[1.0, 2, "different"], [ "", r" comparison failed. Mismatched elements: 2 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", ...
Review this code and list any quality issues.
[ { "issue": "While at it, let's add an assert that works:\r\n\r\n```suggestion\r\n )\r\n assert [1.1, 2, \"word\"] == pytest.approx([1.1, 2, \"word\"])\r\n```", "severity": "minor", "line": 26 } ]
1
python
if kv_sharing_target_layer_name is not None: validate_kv_sharing_target( prefix, kv_sharing_target_layer_name, compilation_config.static_forward_context, ) self.kv_sharing_target_layer_name = kv_sharing_target_layer_name # use a pl...
Review this code and list any quality issues.
[]
0
python
from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, parse_iso8601, ) class MaveBaseIE(InfoExtractor): _API_BASE_URL = 'https://api.mave.digital/v1/website' _API_BASE_STORAGE_URL = 'https://store.cloud.mts.ru/mave/' def _load_channel_meta(self, channel_id): ...
Review this code and list any quality issues.
[ { "issue": "same here\r\n```suggestion\r\n return self._download_json(\r\n f'{self._API_BASE_URL}/{channel_id}/episodes/{episode_code}',\r\n episode_code, note='Downloading episode metadata')\r\n```", "severity": "minor", "line": 21 } ]
1
python
option( "--custom_folders", is_flag=True, help="Use the folders defined in the [custom_folders] section of the " "config file to define the output folder structure.", ), option( "--disable_caching", is_flag=True, help="Disable the use of the cache...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n help=\"Display warnings for outdated installation.\",\r\n```", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor class VocarooIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?(?:vocaroo\.com|voca\.ro)/(?:embed/)?(?P<id>[a-zA-Z0-9]{11,12})' _TESTS = [ { 'url': 'https://vocaroo.com/1de8yA3LNe77', 'md5': 'c557841d5e50261777a6585648adf439', 'i...
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
from .rtsp import RtspFD from .websocket import WebSocketFragmentFD from .youtube_live_chat import YoutubeLiveChatFD from .bunnycdn import BunnyCdnFD from .afreecatv import AfreecaTVFD PROTOCOL_MAP = { 'rtmp': RtmpFD, 'rtmpe': RtmpFD, 'rtmp_ffmpeg': FFmpegFD, 'm3u8_native': HlsFD, 'm3u8': FFmpegFD,...
Review this code and list any quality issues.
[ { "issue": "per suggestion above\r\n```suggestion\r\n 'soopvod': SoopVodFD,\r\n```", "severity": "minor", "line": 26 } ]
1
python
'tags': list, 'thumbnail': 're:^https?://media.livr.jp/vod/img/.*$', }, 'skip': 'Premium channel subscribers only', }, { # Accessible only in the VR SQUARE app 'url': 'https://livr.jp/contents/P126481458', 'only_matching': True, }] def _real_initialize(se...
Review this code and list any quality issues.
[ { "issue": "snake_case is preferred\r\n```suggestion\r\n web_api = self._download_json(\r\n```", "severity": "minor", "line": 26 } ]
1
python
try: figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi) if fmt == formats[0][0] and config.plot_srcset: # save a 2x, 3x etc version of the default... srcset = _parse_srcset(config.plot_srcset) for mult,...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n env = document.settings.env\r\n config = env.config\r\n```", "severity": "minor", "line": 26 } ]
1
python
from .brightcove import BrightcoveNewIE from .common import InfoExtractor class NowCanalIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?nowcanal\.pt/[\w\-/]+/detalhe/(?P<id>[\w\-]+)' _TESTS = [{ 'url': 'https://www.nowcanal.pt/ultimas/detalhe/pedro-sousa-hjulmand-pode-ter-uma-saida-limpa-do-sport...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nfrom .brightcove import BrightcoveNewIE\r\nfrom .common import InfoExtractor\r\n```", "severity": "major", "line": 3 } ]
1
python
conf_rpcport = "rpcport=" + str(node_rpc_port) self.nodes[0].replace_in_config([(conf_rpcport, "#" + conf_rpcport)]) # prefer rpcport over rpcconnect assert_raises_process_error(1, "Could not connect to the server 127.0.0.1:1", self.nodes[0].cli(f"-rpcconnect=127.0.0.1:{node_rpc_port}", "-rpcpor...
Review this code and list any quality issues.
[ { "issue": "nit: we might as well use f-strings here:\r\n```suggestion\r\n assert_equal(BLOCKS, self.nodes[0].cli('-norpccookiefile', f'-rpcuser={user}', f'-rpcpassword={password}').getblockcount())\r\n```", "severity": "minor", "line": 26 } ]
1
python
import sys from consoleme.config import config from consoleme.handlers.base import BaseMtlsHandler from consoleme.lib.cloud_credential_authorization_mapping import ( CredentialAuthorizationMapping, ) from consoleme.lib.plugins import get_plugin_by_name from consoleme.models import Status2, WebResponse log = confi...
Review this code and list any quality issues.
[ { "issue": "Does this need to be `int(total / page_size)` ? thinking of a situation like `_get_last_page(10, 999)`", "severity": "minor", "line": 17 } ]
1
python
- **scores** (`List[float]`): the retrieval scores (`IndexFlatL2` score by default) of the retrieved examples - **examples** (`dict`): the retrieved examples """ self._check_index_is_initialized(index_name) scores, indices = self.search(index_name, query, k, **kwargs) top...
Review this code and list any quality issues.
[ { "issue": "Is this supposed to be `total_samples` (see [line 770](https://github.com/huggingface/datasets/blob/b8067c0262073891180869f700ebef5ac3dc5cce/src/datasets/search.py#L770)) instead of `total_examples`?", "severity": "minor", "line": 26 } ]
1
python
@pytest.mark.parametrize("replace_undefined_by", [0.0, np.nan]) def test_cohen_kappa_zero_division(test_case, replace_undefined_by): """Test that cohen_kappa_score handles divisions by 0 correctly by returning the `replace_undefined_by` param. (The fist two test cases cover the first possible location in th...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n y1, y2, labels, weights = test_case\n y1, y2 = np.array(y1), np.array(y2)\n\n score = cohen_kappa_score(\n y1,\n y2,\n labels=labels,\n weights=weights,\n replace_undefined_by=replace_undefined_by,\n )\n assert_all...
1
python
""" alpha = self._internal_space[3] black = self.from_rgb((0.0, 0.0, 0.0)) return self.interpolate(black, factor).opacity(alpha) def lighter(self, factor: float = 0.2) -> Self: """Returns a new color that is lighter than the current color, i.e. interpolated with white. The o...
Review this code and list any quality issues.
[ { "issue": "Analogously to above, we should use the available color constant:\r\n\r\n```\r\n from manim.utils.color.manim_colors import WHITE\r\n```", "severity": "minor", "line": 26 } ]
1
python
or format_id == 'HLS' or ext == 'm3u8'): formats.extend(self._extract_m3u8_formats( format_url, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)) elif (format_type == 'application/dash+x...
Review this code and list any quality issues.
[ { "issue": "Can these patterns be simplified at all? Are you able to share webpage source where these patterns are needed?\r\n\r\nI would think at least the first `(?:replacePlaceholders|processAdTagModifier).*?:\\s*)?` could be removed", "severity": "minor", "line": 26 } ]
1
python
'view': 'all', 'page': page_num + 1, 'sort': 'newest', 'format': 'all', }, note=f'Downloading page {page_num + 1}') for ep in traverse_obj(page_data, ('episodes', ..., {dict})): yield self._create_entry(channel_id, channel_meta, episode_met...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n math.ceil(channel_meta['podcast']['episodes_count'] / self._PAGE_SIZE), self._PAGE_SIZE),\r\n```", "severity": "minor", "line": 26 } ]
1
python
self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion) return self def set_start_and_end_attrs(self, start, end): # If either start or end are Mobjects, this # gives their centers rough_start = self.pointify(start) rough_end = self.pointify(end) ve...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n \"\"\"Sets starts and end coordinates of a line.\r\n```", "severity": "minor", "line": 26 } ]
1
python
yield Ok(non_string_line) # Else the target string was the last leaf... else: last_line.append(rest_leaf) last_line.comments = line.comments.copy() yield Ok(last_line) def _get_nameescape_slices(self, string: str) -> List[Tuple[int, int]]: """ Ret...
Review this code and list any quality issues.
[ { "issue": "If I'm not mistaken, with escaped backslashes this would function incorrectly: `\\\\N{something}` would result in `count = 2` and still finding a slice. So how about something like:\r\n\r\n```python\r\nprevious_was_backslash = False\r\nfor idx, c in it:\r\n if c == \"\\\\\":\r\n if not pre...
1
python
"""Remove an entity managed by one of the platforms.""" found = None for platform in self._platforms.values(): if entity_id in platform.entities: found = platform break if found: await found.async_remove_entity(entity_id) async def a...
Review this code and list any quality issues.
[ { "issue": "We can consider translating the error messages, in a follow up PR.", "severity": "minor", "line": 26 } ]
1
python
""" if hashes is None: return False return hashes.is_hash_allowed(self.name, hex_digest=self.value) @dataclass(frozen=True) class MetadataFile: """Information about a core metadata file associated with a distribution.""" hashes: Optional[Dict[str, str]] def __post_init__(self...
Review this code and list any quality issues.
[ { "issue": "nit:\r\n\r\n```suggestion\r\n if not hashes:\r\n return None\r\n return hashes\r\n```\r\n\r\nSightly less C-like, and easier to read. :)", "severity": "minor", "line": 26 } ]
1
python
): execute_function_in_subprocess( self.assert_otel_traces_with_embedding, dev_connections, func, inputs, expected_span_length ) def assert_otel_traces_with_embedding(self, dev_connections, func, inputs, expected_span_length): inject_openai_api() memory_exporter = prepar...
Review this code and list any quality issues.
[ { "issue": "Should we use subprocess to run the test to avoid side effect?", "severity": "minor", "line": 26 } ]
1
python
assert np.issubdtype(imp.dtype, np.floating) imp = waveforms.unit_impulse(5, 3, dtype=int) assert np.issubdtype(imp.dtype, np.integer) imp = waveforms.unit_impulse((5, 2), (3, 1), dtype=complex) assert np.issubdtype(imp.dtype, np.complexfloating) class TestSawtoothWaveform: def t...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n unique = xp.unique(y)\r\n```", "severity": "minor", "line": 26 } ]
1
python
"""Mixin for button specific attributes.""" entity_description: RenaultButtonEntityDescription async def async_press(self) -> None: """Process the button press.""" await self.entity_description.async_press(self) BUTTON_TYPES: tuple[RenaultButtonEntityDescription, ...] = ( RenaultButtonEn...
Review this code and list any quality issues.
[ { "issue": "This should also check `vehicle.details.supports_endpoint`\r\n```suggestion\r\n is_supported=lambda vehicle: (\r\n vehicle.details.supports_endpoint(\"actions/charge-stop\")\r\n and vehicle.details.uses_electricity()\r\n ),\r\n```", "severity": "minor", "l...
1
python
def __init__( self, decimal_mob: DecimalNumber, number_update_func: typing.Callable[[float], float], suspend_mobject_updating: bool = False, **kwargs: Any, ) -> None: self.check_validity_of_input(decimal_mob) self.number_update_func = number_update_func ...
Review this code and list any quality issues.
[ { "issue": "It should not be necessary to add a docstring to this method, since the overriden `Animation.interpolate_mobject()` already has a docstring.\r\n```suggestion\r\n```", "severity": "minor", "line": 26 } ]
1
python
'count': self._PER_PAGE }) data = self._download_json(api, song_id)['data'] return self._entries(data.get('items')) def _real_extract(self, url): song_id, type_url = self._match_valid_url(url).group('id', 'type') entries = OnDemandPagedList(functools.partial(self._fetch_page...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nsame everywhere", "severity": "minor", "line": 26 } ]
1
python
if prev and prev.type == token.DOT: return NO elif p.type == syms.sliceop: return NO return SPACE def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]: """Return the first leaf that precedes `node`, if any.""" while node: res = node.prev_sibling if res: ...
Review this code and list any quality issues.
[]
0
python
""" Example showing async caching for model responses. Run this cookbook twice to see the difference in response time. The first time should take a while to run. The second time should be instant. You can also see in the console about the cache hit/miss status """ import asyncio from agno.agent import Agent from ag...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Should take a while to run the first time, then reply from cache\r\n```", "severity": "major", "line": 22 } ]
1
python
# Create a dummy csv with open(data_dir / "data.csv", "w") as f: f.write("col1,col2\n1,2\n") def time_sequential_runner(self): catalog = create_data_catalog() test_pipeline = create_compute_bound_pipeline() runner_obj = SequentialRunner() runner_obj.run(test_pipe...
Review this code and list any quality issues.
[ { "issue": "Is the main part needed here? I think the tests work without it, the params thing is handled by asv", "severity": "minor", "line": 26 } ]
1
python
audio_input("Record audio", help="Click to start recording"), UploadedFile | None, ) assert_type(audio_input("Record audio", help=None), UploadedFile | None) # ===================================================================== # Test disabled parameter # =================================...
Review this code and list any quality issues.
[]
0
python
} renditions { type width height url bitrate } summary } } }''' def _build_playlist(self, media_items): entries = [] for media_id in media_items: json_obj = traverse_obj(self._json_from_graphql(media_id) or {}, ('data', 'vi...
Review this code and list any quality issues.
[ { "issue": "if applying my `_extract_media_from_json` suggestion\r\n```suggestion\r\n formats, subtitles = self._extract_media_from_json(media_id, json_obj)\r\n```", "severity": "major", "line": 26 } ]
1
python
blocks.reverse() return blocks async def autofarm_transaction(self, spend_name: bytes32) -> None: if self.auto_farm: self.log.info(f"Autofarm triggered by tx-id: {spend_name.hex()}") new_block = FarmNewBlockProtocol(self.bt.farmer_ph) await self.farm_new_transact...
Review this code and list any quality issues.
[ { "issue": "Having this method in `CoinStoreProtocol` is a bad idea. We use an equivalent algorithm, also a bad idea, but at least contained to the simulator, limiting its potential damage.", "severity": "minor", "line": 26 } ]
1
python
"""Test that auto mode detects reasoning from field and sends back in field.""" c = completion_message( ChatCompletionMessage.model_construct(content='response', reasoning_content='reasoning', role='assistant') ) m = OpenAIChatModel( 'foobar', provider=OpenAIProvider(openai_client=Mo...
Review this code and list any quality issues.
[ { "issue": "No inline imports please, only at the top", "severity": "minor", "line": 26 } ]
1
python
# ---------------------------- # POST-Training CLEAN UP # ---------------------------- # hook if self.state.fn == TrainerFn.FITTING: self.call_hook('on_fit_end') # teardown self._call_teardown_hook(model) if self.state.status != TrainerStatus.INTERRU...
Review this code and list any quality issues.
[ { "issue": "Not sure if having the `merge_hparams` is useful considering how simple it is to merge two dictionaries in python", "severity": "minor", "line": 26 } ]
1
python
if "tip_shape_end" in kwargs: kwargs["tip_shape"] = kwargs.pop("tip_shape_end") tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip) CurvedArrow.__init__(self, start_point, end_point, **kwargs) self.add_tip(at_start=True, tip_shape=tip_shape_start) class Circle(A...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n```\r\nNo, it is not necessary.", "severity": "minor", "line": 26 } ]
1
python
"description": "Very clear question that needs to be answered to have good bug report.", }, }, "required": ["question"], "additionalProperties": False }, } }, "...
Review this code and list any quality issues.
[ { "issue": "maybe it should be `relative path` instead of just `path`?\r\n\r\nSince it was tested like this, I suggest we keep it this way but have this in mind as potential problem if some users experience issues", "severity": "minor", "line": 26 } ]
1
python
self._wheel_texture: rl.Texture = gui_app.texture('icons/chffr_wheel.png', UI_CONFIG.wheel_icon_size, UI_CONFIG.wheel_icon_size) self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) self._font_medium: rl.Font = gui_app.font(FontWeight.ME...
Review this code and list any quality issues.
[]
0
python
from typing import Annotated, cast try: import inquirer import typer from cookiecutter.main import cookiecutter from inquirer.render.console import ConsoleRender from rich.progress import Progress, SpinnerColumn, TextColumn except ModuleNotFoundError as exc: raise ImportError( "Missing ...
Review this code and list any quality issues.
[ { "issue": "[nitpick] The `default_install_project` variable is defined but not used as the default for the CLI option. Consider using it in `typer.Option(default=default_install_project…)` to centralize default values.", "severity": "minor", "line": 26 } ]
1
python
class Span: name: str = None context: dict = None kind: str = None parent_id: str = None start_time: str = None end_time: str = None status: dict = None attributes: dict = None events: list = None links: list = None resource: dict = None id: str = None partition_key: ...
Review this code and list any quality issues.
[ { "issue": "Also make similar change for Summary.py?\r\nhttps://github.com/microsoft/promptflow/blob/main/src/promptflow-azure/promptflow/azure/_storage/cosmosdb/summary.py#L176", "severity": "minor", "line": 26 } ]
1
python
"""Support for vacuum cleaner robots (botvacs).""" from __future__ import annotations from enum import StrEnum from functools import partial from homeassistant.helpers.deprecation import ( DeprecatedConstantEnum, all_with_deprecated_constants, check_if_deprecated_constant, dir_with_deprecated_constan...
Review this code and list any quality issues.
[ { "issue": "The `EntityComponent` import should be moved under the `TYPE_CHECKING` block to be consistent with other components in the codebase (e.g., calendar, assist_satellite) and to avoid unnecessary runtime imports. Since `EntityComponent` is only used in the type annotation for `DATA_COMPONENT`, it doesn'...
1
python
The model response will have been added to messages by now by `StreamedRunResult._marked_completed`. """ nonlocal final_result final_result = FinalResult( a...
Review this code and list any quality issues.
[ { "issue": "I wonder if we could just go straight into the `CallToolsNode` here. I suppose that'd cause some unnecessary duplicate validation of the output etc.", "severity": "major", "line": 26 } ]
1
python
import anyio from loguru import logger from exo.shared.types.memory import Memory from exo.shared.types.profiling import ( MemoryPerformanceProfile, NodePerformanceProfile, SystemPerformanceProfile, ) from .macmon import ( MacMonError, Metrics, ) from .macmon import ( get_metrics_async as macm...
Review this code and list any quality issues.
[ { "issue": "can we move this over to the start_profiling function instead of a global?", "severity": "major", "line": 26 } ]
1
python
def test_get_previous_completed_not_found(self): task = DateHourTaskOk(datetime.datetime(2000, 3, 1, 2)) prev = get_previous_completed(task, 3) self.assertEqual(None, prev) class DateMinuteTaskOk(luigi.Task): minute = luigi.DateMinuteParameter() def complete(self): # test agai...
Review this code and list any quality issues.
[]
0
python
NetverseSearchIE, ) from .netzkino import NetzkinoIE from .newgrounds import ( NewgroundsIE, NewgroundsPlaylistIE, NewgroundsUserIE, ) from .newspicks import NewsPicksIE from .newsy import NewsyIE from .nextmedia import ( AppleDailyIE, NextMediaActionNewsIE, NextMediaIE, NextTVIE, ) from .ne...
Review this code and list any quality issues.
[]
0
python
def json2srt(self, json, ep_id): def sec2time(sec): h = int(sec) // 3600 m = int(sec) // 60 % 60 s = sec % 60 f = int(sec * 1000) % 1000 return "%02d:%02d:%02d,%03d" % (h, m, int(s), f) if json is str: json = self._parse_json(json, ...
Review this code and list any quality issues.
[ { "issue": "add a note, make non-fatal and add something like `if not sub_data: continue`", "severity": "minor", "line": 26 } ]
1
python
This class is thread-safe. The GPU object store is meant to be read and written by the following threads: 1. The main thread, which is executing user code. This thread may get, put, and pop objects. 2. The background _ray_system thread, which executes data transfers. This thread may get and put obje...
Review this code and list any quality issues.
[]
0
python
_logger.debug('Metric reported: %s', data) if data['type'] == MetricType.REQUEST_PARAMETER: raise ValueError('Request parameter not supported') elif data['type'] == MetricType.PERIODICAL: self.invoke_callback('intermediate_metric', data['parameter_id'], self._process_value(data['...
Review this code and list any quality issues.
[ { "issue": "Is it possible that `handld_add_customized_trial` is never called and `_advisor_initialized` is never set to true?", "severity": "minor", "line": 26 } ]
1
python
from oumi.core.datasets import BaseSftDataset from oumi.core.registry import register_dataset from oumi.core.types.conversation import Conversation, Message, Role @register_dataset("HuggingFaceDataset") class HuggingFaceDataset(BaseSftDataset): """Converts HuggingFace Datasets with messages to Oumi Message format...
Review this code and list any quality issues.
[]
0
python
}, { 'url': 'https://www.thisoldhouse.com/tv-episode/ask-toh-shelf-rough-electric', 'only_matching': True, }, { 'url': 'https://www.thisoldhouse.com/furniture/21017078/how-to-build-a-storage-bench', 'only_matching': True, }, { 'url': 'https://www.thisoldhouse.com/21113884...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n return self.url_result(self._request_webpage(HEADRequest(video_url), display_id).geturl(), 'Zype', display_id)\r\n```\r\n\r\nor \r\n```suggestion\r\n return self.url_result(video_url, 'Generic', display_id)\r\n```\r\nshould work too", "severity": "minor", ...
1
python
for image_name, image in self.images.items(): detections = self.annotations[image_name] if images_directory_path: cv2.imwrite(str(images_path / image_name), image) if annotations_directory_path: annotation_name = Path(image_name).stem ...
Review this code and list any quality issues.
[ { "issue": "Let's add `force_masks` into the docstring below.", "severity": "minor", "line": 26 } ]
1
python
def set(self, field, value): self.METRICS[field].set(value) self.metrics_have_changed = True if self.auto_pipe_execute is True and self.should_pipe_execute() is True: self.pipe_execute() def observe(self, field, value): self.METRICS[field].observe(value) self.met...
Review this code and list any quality issues.
[ { "issue": "I don't love using a timeout as a solution to reduce the number of metrics request to redis. We can have no loss in performance if we piggyback with pipelining onto the redis callback receiver pop()", "severity": "major", "line": 26 } ]
1
python
cycle (Cycle^): The cycle for which to retrieve the primary scenario. Returns: The primary scenario of the given _cycle_. If the cycle has no primary scenario, this method returns None. """ return _ScenarioManagerFactory._build_manager()._get_primary(cycle) def get_primary_scenarios( ...
Review this code and list any quality issues.
[ { "issue": "W291 Trailing whitespace\r\n```suggestion\r\n The sorting is in increasing order for dates, in alphabetical order for name and\r\n```", "severity": "minor", "line": 26 } ]
1
python
super().__init__(**kwargs) if processor is not None: # avoid wrong loss under gradient accumulation # https://github.com/huggingface/transformers/pull/36044#issuecomment-2746657112 self.model_accepts_loss_kwargs = False self.finetuning_args = finetuning_args ...
Review this code and list any quality issues.
[ { "issue": "can we shard the model using deepspeed or fsdp instead of put it on the first device? https://github.com/hiyouga/LlamaFactory/blob/92fa3df4c4e4e338ecc1cbdc6530b118337286e3/src/llamafactory/train/dpo/trainer.py#L94-L109", "severity": "minor", "line": 26 } ]
1
python
# Test not batched input encoded_images = image_processor( image_inputs[0], return_tensors="pt", input_data_format="channels_last", image_mean=(0.0, 0.0, 0.0, 0.0), image_std=(1.0, 1.0, 1.0, 1.0), ).pixel_values ...
Review this code and list any quality issues.
[ { "issue": "nit: not needed, we have decorated the class with `require_torch/vision`", "severity": "minor", "line": 26 } ]
1
python
'dv5': AverageDollarVolume(window_length=5), 'dv1_nan': AverageDollarVolume( window_length=1, inputs=[USEquityPricing.open, USEquityPricing.volume], ), 'dv5_nan': AverageDollarVolume( wind...
Review this code and list any quality issues.
[ { "issue": "You can still just do `(self.raw_data_with_nans ** 2) * 2` here. Multiplying by `self.raw_data` will just fill with NaNs in the same places.", "severity": "minor", "line": 26 } ]
1
python
# following line must be outside _run_event_loop # because _wait() might be executed before first line of the child thread _event_loop = asyncio.new_event_loop() thread = Thread(target=_run_event_loop, name='NNI-WebSocketEventLoop', daemon=True) thread.sta...
Review this code and list any quality issues.
[ { "issue": "So if I forgot to disconnect, and the program exits / crashes for reason, is it possible that the event loop run forever? Will the program hang in this case?", "severity": "critical", "line": 26 } ]
1
python
responses: Generator[GenerationResponse], tokenizer: TokenizerWrapper, ) -> Generator[GenerationResponse]: """ For models that inject thinking tags in the prompt (like GLM-4.7), prepend the thinking tag to the output stream so the frontend can properly parse thinking content. """ first = Tru...
Review this code and list any quality issues.
[ { "issue": "I think we should just fall through instead of failing. I'm sure some models will mess this up, in which case this is too extreme.", "severity": "critical", "line": 26 } ]
1
python
} if abr: fd['abr'] = abr formats.append(fd) subtitles = {} for sub in jsond.get('subtitles', []): scode, sdesc, surl = sub lang = sdesc.split(' ')[0] lang = lang[:-1] if lang.endswith(':') else lang subtitles[lang]...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n return {\r\n 'id': video_id,\r\n 'title': title,\r\n 'description': description,\r\n 'thumbnail': thumbnail,\r\n 'timestamp': timestamp,\r\n 'formats': formats,\r\n 'duration': duration,\r\n ...
1
python
delta_reader.collect_and_return_from_merkle_blobs, jobs, missing_hashes, ) async with self.db_wrapper.writer() as writer: await writer.executemany( """ INSERT OR IGNORE INTO nodes(store_id...
Review this code and list any quality issues.
[ { "issue": "is there a reason for this to move from below up to here?", "severity": "minor", "line": 26 } ]
1
python
except FileNotFoundError as e: raise configargparse.ArgumentTypeError(str(e)) def setup_parser_arguments(parser): """ Setup command-line options Takes a configargparse.ArgumentParser as argument and calls it's add_argument for each of the supported arguments """ parser._optionals.titl...
Review this code and list any quality issues.
[]
0
python
"coin_parent, amount, timestamp, coin_name FROM coin_record WHERE confirmed_index>?", (block_index,), ) for row in rows: coin = self.row_to_coin(row) spent_index = uint32(0) if row[1] <= 0 else row[1] record = CoinRecord(coin, uint3...
Review this code and list any quality issues.
[ { "issue": "did you see sqlite selecting a different index?", "severity": "minor", "line": 26 } ]
1
python
config = [ cls._resolve_dataset_config(ds_name, pattern, value) for value in config ] elif isinstance(config, str) and "}" in config: config = config.format_map(resolved_vars.named) return config def list_patterns(self) -> list[str]: """List al patter...
Review this code and list any quality issues.
[ { "issue": "[Nit] It would be nice to separate `match_default_pattern` and `match_runtime_pattern` too ?", "severity": "minor", "line": 26 } ]
1
python
""" return await self._streamer.process_single_data(request, context) @staticmethod def get_streamer(): """ Return a streamer object based on the current environment context. The streamer object is contructed using runtime arguments stored in the `JINA_STREAMER_ARGS` environment...
Review this code and list any quality issues.
[ { "issue": "This is not a good name, unless the `request_size` is something you consider", "severity": "minor", "line": 26 } ]
1
python
import copy import datetime import platform import traceback from contextlib import contextmanager from unittest import mock from unittest.mock import Mock, call, patch from zoneinfo import ZoneInfo import pytest from celery import states, uuid from celery.app.task import Context from celery.backends.base import Back...
Review this code and list any quality issues.
[ { "issue": "https://docs.python.org/3/library/zoneinfo.html was added to the Standard Library in Python 3.9.\r\n\r\nhttps://pypi.org/project/backports.zoneinfo could be installed ___conditionally___ on Python < v3.9.", "severity": "minor", "line": 8 } ]
1
python
def test_multiple_exclude_and_normalization( script: PipTestEnvironment, tmpdir: Path ) -> None: req_path = wheel.make_wheel(name="Normalizable_Name", version="1.0").save_to_dir( tmpdir ) script.pip("install", "--no-index", req_path) result = script.pip("list") print(result.stdout) a...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n assert {\"name\": \"simplewheel\", \"version\": \"1.0\"} not in json.loads(result.stdout)\r\n```", "severity": "minor", "line": 26 } ]
1
python
'uploader_id': 'UC0intLFzLaudFG-xAvUEO-A', 'channel_id': 'UC0intLFzLaudFG-xAvUEO-A', 'uploader_url': 'https://www.youtube.com/channel/UC0intLFzLaudFG-xAvUEO-A', 'channel': 'Not Just Bikes', }, 'playlist_mincount': 10, }, { # Streams/live tab 'url':...
Review this code and list any quality issues.
[ { "issue": "There is no standard way to test this. If you want, a test can be added to `test_youtube_lists`", "severity": "minor", "line": 26 } ]
1
python
Keyword arguments for `function` """ __tracebackhide__ = True # Hide traceback for py.test # reset the log self.log[:] = [] if exceptions is np._NoValue: exceptions = (self.warning_cls,) try: function(*args, **kwargs) except (Exception ...
Review this code and list any quality issues.
[ { "issue": "This doesn't look nice to me. We already have `message =` on the class, and that works just fine, it is used as `message=self.message` below.\r\n\r\nIt's fair that passing a pattern is maybe nicer (especially with `pytest.warns` existing now). But we should avoid unnecessary duplication.\r\n(And s...
1
python
'channel_is_verified': True, 'heatmap': 'count:100', 'section_end': 15, 'uploader': 'Blender', 'timestamp': 1415628355, 'uploader_url': 'https://www.youtube.com/@BlenderOfficial', 'age_limit': 0, 'section_start': 10, 'availa...
Review this code and list any quality issues.
[ { "issue": "I saw a few empty string descriptions in the tests; would be better to `filter` to get the resolving extractor's description instead IMO\r\n```suggestion\r\n 'description': ('description', {clean_html}, filter),\r\n```", "severity": "major", "line": 26 } ]
1
python
"""Test config flow for Swing2Sleep Smarla integration.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from homeassistant.components.smarla.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow ...
Review this code and list any quality issues.
[ { "issue": "Sorry, but these are not improvements; as a matter of fact some are even annotated as `Required` in the dict. As a matter of fact, by using `get()` you'll loose typing information.\r\n\r\nI'm not sure which problem you try to solve here.\r\n\r\nCould you clarify?\r\n\r\n../Frenck", "severity": "...
1
python
] def purge_page_from_cache(page, backend_settings=None, backends=None, *, request=None): urls = _get_page_cached_urls(page, request=request) purge_urls_from_cache(urls, backend_settings, backends) def purge_pages_from_cache( pages, backend_settings=None, backends=None, *, request=None ): batch = Pu...
Review this code and list any quality issues.
[ { "issue": "Question: Because `get_full_url` is used, could using this request result in the wrong site being used to resolve the URLs hostname?", "severity": "critical", "line": 26 } ]
1
python
'type': 'artist', 'page': page, 'count': self._PER_PAGE }) data = self._download_json(api, user_id, query={'sort': 'new', 'sectionId': 'aSong'})['data'] return self._entries(data.get('items')) def _real_extract(self, url): user_alias, type_url = self._match_v...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n entries = [\r\n self.url_result(urljoin(self._DOMAIN, link))\r\n for link in traverse_obj(user_info, (\r\n 'sections', lambda _, v: v['link'] == f'/{user_alias}/{type_url}', 'items', 'link'))]\r\n```\r\nuntested", "sev...
1
python
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, video_id, smuggled_data): content_type = program_info.get('content_type') return self._extract_pla...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n error_msg = traverse_obj(error, ('message', {str}))\r\n```", "severity": "minor", "line": 26 } ]
1
python
# (This static crawl is performed only to evaluate rendering type detection.) kvs = await context.get_key_value_store() default_value = dict[str, JsonSerializable]() old_state: dict[str, JsonSerializable] = await kvs.get_value(self._CRAWLEE_STATE_KEY, default_value) old_s...
Review this code and list any quality issues.
[ { "issue": "I think that we should make the changes made to the context part of the `RequestHandlerResult` data structure at some point. What do you think @Mantisus @Pijukatel?\n\nNo need to stall this PR because of that, it can be done later.", "severity": "minor", "line": 26 } ]
1
python
async def _handle_token(self, token: str) -> str | None: """Handle the token input.""" try: conn = Connection(url=HOST, token_b64=token) except ValueError: self.errors["base"] = "malformed_token" return None try: await conn.refresh_token()...
Review this code and list any quality issues.
[ { "issue": "I think we should never be in this state, if we trigger the validate_input, only once we trigger the validate_input, once the form has received input... :)", "severity": "minor", "line": 26 } ]
1
python
text_input_size = text_input.tell() text_input.seek(0, os.SEEK_SET) if self.echo_stdin: # Force unbuffered reads, otherwise TextIOWrapper reads a # large chunk which is echoed early. text_input._CHUNK_SIZE = 1 # type: ignore sys.stdout = _NamedTextIOWrapper...
Review this code and list any quality issues.
[ { "issue": "I would suggest simply moving the logic in `_NamedTextIOWrapper.__next__` to here:\r\n```\r\ntry:\r\n val = next(text_input).rstrip(\"\\r\\n\")\r\nexcept StopIteration as e:\r\n raise EOFError() from e\r\n```\r\n\r\nThis will do the same without having to check the input size. When I changed t...
1
python
alert('BEWARE - the script tag is scripting'); </script> <strong> This is a strong tag </strong> """ ) # Test that style tags are applied st.html( """ <style> #corgi { color:blue; } </style> <div id="corgi">This text should be blue</div> """ ) # Test that non-...
Review this code and list any quality issues.
[]
0
python
if remaining_time > 60: remaining_time = "{0:.2f}m".format(remaining_time / 60.0) else: remaining_time = "{0:.2f}s".format(remaining_time) print( self.verbose_fmt.format( iter=j + 1, train_score=est.train_sco...
Review this code and list any quality issues.
[ { "issue": "`\"friedman_mse\"` could also be `Hidden`", "severity": "minor", "line": 26 } ]
1
python
def _get_or_create_db(self): """Get or create the database.""" return self.client def _get_or_create_collection(self, name): """ Get or create a named collection. :param name: Name of the collection :type name: str """ if utility.has_collection(name)...
Review this code and list any quality issues.
[ { "issue": "Can you please make sure that this metric type comes from the self.config.metric_type?", "severity": "minor", "line": 26 } ]
1
python
return method def _create_unary_propagating_op(name: str): def method(self): return pd_NA method.__name__ = name return method class NAType: def __repr__(self) -> str: return "<NA>" def __format__(self, format_spec) -> str: try: return self.__repr__().__form...
Review this code and list any quality issues.
[ { "issue": "What the heck is `is_32bit`? I cannot find it anywhere in Numpy or Python.", "severity": "minor", "line": 26 } ]
1
python
__typename } }'''}) meta = data['medium'] storage_url = 'https://storage.murrtube.net/murrtube/' format_url = storage_url + meta.get('key', '') thumbnail = storage_url + meta.get('thumbnailKey', '') formats = [] if determine_ext(format_url) == 'm3u8': form...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'duration': int_or_none(meta.get('duration')),\r\n```", "severity": "minor", "line": 26 } ]
1
python
) if self.contains_expressions and not ( connection.features.supports_expression_indexes or "supports_expression_indexes" in required_db_features ): errors.append( checks.Warning( f"{connection.display_name} does not support unique ...
Review this code and list any quality issues.
[ { "issue": "I would maybe have:\r\n```python\r\n f\"{connection.display_name} does not support the \"\r\n \"'nulls_distinct' parameter for unique constraints.\",\r\n```\r\nAs I think we want to emphasizing that having values for `nulls_distinct` set is not supported (rather...
1
python
return -1 try: sig_paths = capa.main.get_signatures(args.signatures) except IOError as e: logger.error("%s", str(e)) return -1 if (args.format == "freeze") or ( args.format == capa.features.common.FORMAT_AUTO and capa.features.freeze.is_freeze(taste) ): extracto...
Review this code and list any quality issues.
[ { "issue": "could also use `collections.Counter` here", "severity": "minor", "line": 26 } ]
1
python
'Accept': "application/json", 'Authorization': self.opts['api_key'] } res = self.sf.fetchUrl( queryString, headers=headers, timeout=15, useragent=self.opts['_useragent'] ) if res['content'] is None: return None ...
Review this code and list any quality issues.
[ { "issue": "Remember to check for error codes.", "severity": "minor", "line": 26 } ]
1
python
OpenAIEmbeddingsRequestWithExtraBody, OpenAIEmbeddingsResponse, ) from llama_stack.core.telemetry.tracing import get_current_span from llama_stack.log import get_logger from llama_stack.providers.utils.inference.openai_mixin import OpenAIMixin from .config import BedrockConfig logger = get_logger(name=__name__, c...
Review this code and list any quality issues.
[ { "issue": "you don't need to override `get_api_key`", "severity": "minor", "line": 26 } ]
1
python
executor = MigrationExecutor(connection) migrating = bool(executor.migration_plan(executor.loader.graph.leaf_nodes())) connection.close() # Because of async nature, main loop will use new connection, so close this except Exception as exc: time.sleep(10) # Prevent supervisor...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n my_hostname = Instance.objects.my_hostname() # This relies on settings.CLUSTER_HOST_ID which requires database connection\r\n```", "severity": "minor", "line": 26 } ]
1
python
check_errors will not raise, unless NEW JS errors have been reported in the meantime. """ exc = None if len(self._page_errors) == 1: # if there is a single error, wrap it exc = JsError(self._page_errors[0]) elif len(self._page_errors) >= 2: exc...
Review this code and list any quality issues.
[ { "issue": "[suggestion/fix]\r\nas you have noticed, `self.tmpdir` is an instance of `py.path.local` (which is a predecessor and inspiration for `pathlib`), which makes it very easy to deal with files, paths and directory. It is a standard feature of `pytest` so I strongly suggest to become familiar with it bec...
1
python
assert len(keys) == 0 for i in range(2001): await key_value_store.set_value(str(i).zfill(4), i) index = 0 async for item in key_value_store.iterate_keys(): assert item.key == str(index).zfill(4) index += 1 assert index == 2001 async def test_static_get_set_value(key_value_stor...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n with open(path, mode='r') as f:\r\n content = await asyncio.to_thread(f.read)\r\n assert content == 'static'\r\n```", "severity": "minor", "line": 26 } ]
1
python
response_modalities=modalities, ) return contents, config def _process_response(self, response: GenerateContentResponse) -> ModelResponse: if not response.candidates: raise UnexpectedModelBehavior('Expected at least one candidate in Gemini response') # pragma: no cover ...
Review this code and list any quality issues.
[ { "issue": "Note that we could get here if `candidate.content is None`", "severity": "minor", "line": 26 } ]
1
python
# Meta / Notification # Show notification. # --- from telesync import site, ui page = site['/demo'] page['meta'] = ui.meta_card(box='') page['example'] = ui.markdown_card( box='1 1 2 2', title='Notification', content='Allow browser notifcations in order to see them.', ) page['meta'].notification = 'Proce...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n# Display a desktop notification.\r\n```", "severity": "minor", "line": 2 } ]
1
python
chat_memory_instance.add(app_id, session_id, chat_message) assert chat_memory_instance.count(app_id, session_id) == 1 chat_memory_instance.delete(app_id, session_id) def test_get(chat_memory_instance): app_id = "test_app" session_id = "test_session" for i in range(1, 7): human_message = ...
Review this code and list any quality issues.
[]
0
python
"""Iterate through all Entity nodes and fetch their edges and neighbor nodes.""" graph_engine = await get_graph_engine() entity_nodes, _ = await graph_engine.get_filtered_graph_data([{"type": ["Entity"]}]) async def fetch_one(node_id, props): edges, neighbors = await asyncio.gather( gra...
Review this code and list any quality issues.
[ { "issue": "The text that we send to the LLM for consolidation is too noisy. Could you please review the flow of what gets extracted and what gets sent, to make sure that we are only sending natural language relevant for summarization.", "severity": "major", "line": 26 } ]
1
python
*, image_width: int, image_height: int, image_processor: BaseImageProcessor, mm_kwargs: Mapping[str, object], ) -> int: hf_config = self.get_hf_config() vision_config = hf_config.vision_config patch_size = vision_config.patch_size merge_size = vision_c...
Review this code and list any quality issues.
[ { "issue": "Based on the logic above, the keys in the `size` dictionary are updated as `shortest_edge` and `longest_edge`. So we should access them accordingly here:\n```\nmin_pixels=size[\"shortest_edge\"],\nmax_pixels=size[\"longest_edge\"],\n```", "severity": "minor", "line": 26 } ]
1
python
from __future__ import annotations import os import sys from ruff import find_ruff_bin def _run() -> None: ruff = os.fsdecode(find_ruff_bin()) if sys.platform == "win32": import subprocess # Avoid emitting a traceback on interrupt try: completed_process = subprocess.run...
Review this code and list any quality issues.
[ { "issue": "I think this is fine either way, but we did have a previous PR removing the `os.fsdecode` call: #18551.", "severity": "minor", "line": 10 } ]
1
python
if message in webpage: self.raise_geo_restricted() player_config = self._search_json(r'window\.MDSTRM\.OPTIONS\s*=', webpage, 'metadata', video_id) formats, subtitles = [], {} for video_format in player_config['src']: if video_format == 'hls': params...
Review this code and list any quality issues.
[ { "issue": "How about we write this as:\r\n```suggestion\r\n params = {'at': 'web-app'}\r\n\r\n for name, key in [('MDSTRMUID', 'uid'), ('MDSTRMSID', 'sid'), ('MDSTRMPID', 'pid'), ('VERSION', 'av')]:\r\n if val := self._search_regex(rf'window\\.{name}\\s*=\\s*[\"...
1
python
``` """ st.expander("With code block:\n" + code_block) # ============================================================================ # Dynamic Expander Tests (on_change="rerun") # ============================================================================ if "lazy_exec_count" not in st.session_state: st.sessio...
Review this code and list any quality issues.
[]
0
python
:save_last_frame: polarplane_pi = PolarPlane(azimuth_units="PI radians", size=6, azimuth_label_scale=0.75, radius_config={'number_scale_value': 0.75}).add_coordinates() class PolarPlaneExample(Scene): def construct(self): self.add(polarplane_pi) """ def __init__( ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n faded_line_ratio: int = 1,\r\n make_smooth_after_applying_functions: bool = True,\r\n```", "severity": "minor", "line": 26 } ]
1
python
def _real_extract(self, url): mobj = self._match_valid_url(url) video_id = mobj.group('id') video_type = mobj.group('embed_type') or mobj.group('site_type') if video_type == 'music': video_type = 'musique' IFRAME_MD_ID = '01836272' # Static ID for Ultimedia iframes...
Review this code and list any quality issues.
[ { "issue": "Do you have an example where this is required? If yes, add a test case", "severity": "minor", "line": 26 } ]
1
python
Allows apps to delete a role """ allowed_methods = ["DELETE"] def check_xsrf_cookie(self): pass async def delete(self, account_id, role_name): """ DELETE /api/v2/mtls/roles/{account_id}/{role_name} """ log_data = { "function": f"{__name__}.{self.__c...
Review this code and list any quality issues.
[ { "issue": "Nice, I don't think I've ever had a chance to use a `406` before", "severity": "minor", "line": 26 } ]
1
python
return self._session._user_input_transcribed( UserInputTranscribedEvent( language=ev.alternatives[0].language, transcript=ev.alternatives[0].text, is_final=True, speaker_id=ev.alternatives[0].speaker_id, ), ) ...
Review this code and list any quality issues.
[]
0
python
'url': 'https://radiocomercial.pt/podcasts/convenca-me-num-minuto/t3/convenca-me-num-minuto-que-os-lobisomens-existem', 'md5': '47e96c273aef96a8eb160cd6cf46d782', 'info_dict': { 'id': 'convenca-me-num-minuto-que-os-lobisomens-existem', 'ext': 'mp3', 'title': 'Convença...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'season': 2,\r\n },\r\n }]\r\n```", "severity": "minor", "line": 26 } ]
1
python
@pytest.mark.usefixtures("location_info") async def test_integration_services( hass: HomeAssistant, cfupdate: MagicMock, caplog: pytest.LogCaptureFixture ) -> None: """Test integration services.""" instance = cfupdate.return_value entry = await init_integration(hass) assert entry.state is ConfigEnt...
Review this code and list any quality issues.
[ { "issue": "It is not needed, as we have mock for `LOCATION_PATCH_TARGET` in test code.", "severity": "minor", "line": 26 } ]
1