language
string
code-snippit
string
instruction
string
flaws
list
flaw_count
int64
python
headers.update({ 'x-twitter-auth-type': 'OAuth2Session', 'x-twitter-client-language': 'en', 'x-twitter-active-user': 'yes', }) for first_attempt in (True, False): if not self.is_logged_in: if not self._token: ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n if first_attempt and not self.is_logged_in and any('bad guest token' in error.lower() for error in errors):\r\n```\r\ncorrect? Otherwise it may unnecessarily try twice when logged in.", "severity": "minor", "line": 26 } ]
1
python
from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.regex_helper import _lazy_re_compile from django.utils.text import compress_sequence, compress_string re_accepts_gzip = _lazy_re_compile(r"\bgzip\b") class GZipMiddleware(MiddlewareMixin): """...
Review this code and list any quality issues.
[ { "issue": "We should document `max_random_bytes` in the `GZipMiddleware` docs.", "severity": "minor", "line": 16 } ]
1
python
# Compute bezier point and tangent at the chosen value of t mid = bezier([a0, h0, h1, a1])(t_mid) Tm = bezier([h0 - a0, h1 - h0, a1 - h1])(t_mid) # Intersection between tangent lines at end points # and tangent in the middle i0 = find_intersection(a0, T0, mid, Tm) i1 = find_intersection(a1, T1,...
Review this code and list any quality issues.
[ { "issue": "I find the shortening of `bezier` to `bez` confusing and without any added value\r\n```suggestion\r\ndef bezier_params_from_point(\r\n```", "severity": "minor", "line": 26 } ]
1
python
.. versionchanged:: 2.0 This function will now raise :exc:`TypeError` instead of ``InvalidArgument``. .. versionadded:: 2.6 The ``secondary_color``, ``tertiary_color``, ``secondary_colour``, and ``tertiary_colour`` keyword-only parameters were added. .. versionchang...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n secondary_colour: Optional[Union[:class:`Colour`, :class:`int`]]\n The secondary colour for the role.\n\n .. versionadded:: 2.6\n tertiary_colour: Optional[Union[:class:`Colour`, :class:`int`]]\n The tertiary colour for the role. Can onl...
1
python
) -> None: assert self.graph is None # run kernel once to cache the kernel, avoid stream capture error hidden_states_origin_model = self.model( input_tokens_ids, output_tensor, inputmetadata, k_caches, v_caches, ) torch...
Review this code and list any quality issues.
[]
0
python
self._current_run = run logger.debug('Starting the pool') self._autoscale_task.start() self._log_system_status_task.start() orchestrator = asyncio.create_task( self._worker_task_orchestrator(run), name='autoscaled pool worker task orchestrator' ) try: ...
Review this code and list any quality issues.
[]
0
python
import subprocess import common_function_for_servo_test import common_function_for_mossel def operator(): WEBDRIVER_WAIT_TIME = 10 PAGE_URL = "https://m.huaweimossel.com" driver = common_function_for_servo_test.create_driver() driver.get(PAGE_URL) print("Page loaded.") # This is used to wai...
Review this code and list any quality issues.
[ { "issue": "Another improvement point: we are relying on fixed timeout after click.\n\nWe should check if page is fully loaded instead.", "severity": "minor", "line": 26 } ]
1
python
"dictionary<values=large_string, indices=int64, ordered=0>[pyarrow]", "dictionary<values=large_string, indices=int64, ordered=0>[pyarrow]", ] assert pd_pa_dtypes_names == pd_pa_dtypes_names_expected @pytest.mark.parametrize("dtype", [pl.Categorical, pl.Enum(["best", "test"])]) def test_cat_to_pandas(d...
Review this code and list any quality issues.
[]
0
python
[page](../../userman/scenario_features/task-orchestration/scenario-config.md#from-task-configurations) for more details). If *validity_period* is set to None, the data node is always up-to-date. **properties (dict[str, any]): A keyworded variable length list of additional arg...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n\r\n return cls.__configure(id, DataNodeConfig._STORAGE_TYPE_VALUE_S3_OBJECT, scope, validity_period, **properties)\r\n```\r\n\r\nThere should not be a tab here", "severity": "minor", "line": 26 } ]
1
python
ExtractorError, traverse_obj, ) class AmadeusTVIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?amadeus\.tv/library/(?P<id>[\da-f]+)' _TESTS = [{ 'url': 'http://www.amadeus.tv/library/65091a87ff85af59d9fc54c3', 'info_dict': { 'id': '5576678021301411311', 'ext': ...
Review this code and list any quality issues.
[ { "issue": "I would change this to be `display_id` and `video_id`\r\n```suggestion\r\n display_id = self._match_id(url)\r\n webpage = self._download_webpage(url, display_id)\r\n\r\n nuxt_data = self._search_nuxt_data(webpage, display_id, traverse=('fetch', '0'))\r\n video_id = traver...
1
python
def main(fd): '''Run resource tracker.''' # protect the process from ^C and "killall python" etc signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN) if _HAVE_SIGMASK: signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) for f in (sys.stdin,...
Review this code and list any quality issues.
[ { "issue": "```suggestion\n except Exception as exc:\n raise ValueError(\"malformed resource_tracker message: %r\" % (line,)) from exc\n```\n\nSame suggestion for the similar try/except below.", "severity": "minor", "line": 26 } ]
1
python
if config.get("development", False): # If debug mode, we will set up the schedule to run the next minute after the job starts time_to_start = datetime.utcnow() + timedelta(minutes=1) dev_schedule = crontab(hour=time_to_start.hour, minute=time_to_start.minute) schedule_30_minute = dev_schedule schedu...
Review this code and list any quality issues.
[ { "issue": "What if this raises an exception because the ConsoleMe role isn't set up in one of the accounts that Swag returns? With this current code, it would raise an exception and the task would fail. Is this what we want? Or perhaps we can skip the account and write try/except with : log_data[\"message\"] =...
1
python
The constructor can take multiple dicts, in which keys in the latter are prioritised. """ def __init__(self, *args, **kwargs): super().__init__() for dct in args: if dct is not None: self.update(dct) self.update(kwargs) def __setitem__(self, key, value):...
Review this code and list any quality issues.
[ { "issue": "I think we should put this into the extractor file, since its only a temporary workaround until we make `HTTPHeaderDict` store sensitive keys and the handler extension will select pre-normalization of headers", "severity": "critical", "line": 26 } ]
1
python
if page: self.add_page(name=Gui.__root_page_name, page=page) if pages is not None: self.add_pages(pages) if env_filename is not None: self.__env_filename = env_filename if libraries is not None: for library in libraries: Gui.add_lib...
Review this code and list any quality issues.
[ { "issue": "could use `_is_function(self.on_invalid_data)`", "severity": "minor", "line": 26 } ]
1
python
STRING_PRIORITY = 12 COMPARATOR_PRIORITY = 10 MATH_PRIORITIES = { token.VBAR: 9, token.CIRCUMFLEX: 8, token.AMPER: 7, token.LEFTSHIFT: 6, token.RIGHTSHIFT: 6, token.PLUS: 5, token.MINUS: 5, token.STAR: 4, token.SLASH: 4, token.DOUBLESLASH: 4, token.PERCENT: 4, token.AT: 4...
Review this code and list any quality issues.
[ { "issue": "_Maybe_ it makes sense to define a helper:\r\n```python\r\ndef Factory(fn):\r\n return field(default_factory=fn)\r\n```\r\nto minimize the size of the diff? Not sure however what looks better.", "severity": "major", "line": 26 } ]
1
python
'https://asobichannel-api.asobistore.jp/api/v1/vspf/token', video_id, note='Retrieving API token') return {'Authorization': f'Bearer {request_token}'} def _process_vod(self, video_id, metadata): content_id = metadata['contents']['video_id'] vod_data = self._download_json( ...
Review this code and list any quality issues.
[ { "issue": "This seems odd. Could we maybe use the `Player_type` to determine if a stream is upcoming? i.e. `\"poster\"` = upcoming?\r\n\r\nUpcoming streams currently also seem to error due to a 404 response from the streaming endpoint.", "severity": "minor", "line": 26 } ]
1
python
NotGivenOr, get_job_context, utils, ) from livekit.agents.voice.avatar import DataStreamAudioOutput from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF from .log import logger _BASE_API_URL = "https://api.trugen.ai" _AVATAR_AGENT_IDENTITY = "trugen-avatar" _AVATAR_AGENT_NAME = "Trugen Avatar"...
Review this code and list any quality issues.
[ { "issue": "could you set a default for `avatar_id`? maybe a variable `DEFAULT_AVATAR_ID`", "severity": "minor", "line": 26 } ]
1
python
import genesis as gs import numpy as np def test_suction_cup(): gs.init() show_viewer = True # create and build the scene scene = gs.Scene( sim_options=gs.options.SimOptions( dt=0.01, ), rigid_options=gs.options.RigidOptions( box_box_detection=True, ...
Review this code and list any quality issues.
[ { "issue": "Could you use the usual argparse approach with backend and viewer mode ? So that all examples work the same", "severity": "minor", "line": 5 } ]
1
python
result.index.names = values.names # error: Incompatible types in assignment (expression has type # "ndarray[Any, Any] | DatetimeArray | TimedeltaArray | PeriodArray | Any", # variable has type "ndarray[tuple[int, ...], dtype[Any]]") counts = result._values # type: ignore...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Preserve freq of original index\r\n```", "severity": "minor", "line": 26 } ]
1
python
from .common import InfoExtractor from ..utils import ( ExtractorError, smuggle_url, str_or_none, traverse_obj, ) class TVerIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?tver\.jp/(?:(?P<type>lp|corner|series|episodes?|feature|tokyo2020/video)/)+(?P<id>[a-zA-Z0-9]+)' _TESTS = [{ ...
Review this code and list any quality issues.
[ { "issue": "The description values seem to be unstable. I'm getting an extra \\U3000 (ideographic space) in this bit `る! テ` giving `md5:4029cc5f4b1e8090dfc5b7bd2bc5cd0b`, but not reliably. Also `u'md5:66985373a66fed8ad3cd595a3cfebb13` in the 1st test.", "severity": "minor", "line": 26 } ]
1
python
g = x._Greenlet() g.cancel() class test_TaskPool: def setup_method(self): self.patching.modules(*gevent_modules) self.spawn_raw = self.patching('gevent.spawn_raw') self.Pool = self.patching('gevent.pool.Pool') def test_pool(self): x = TaskPool() x.on_start() ...
Review this code and list any quality issues.
[]
0
python
assert res.has_next_page is True assert res.current_page == 2 assert res.per_page == 2 assert res.total_count == 42 assert len(res.branches) == 2 assert res.branches[0] == Branch( name='main', commit_sha='abc', protected=True, last_...
Review this code and list any quality issues.
[]
0
python
}, { 'url': 'https://kinder.wdr.de/tv/die-sendung-mit-dem-elefanten/av/video-folge---astronaut-100.html', 'only_matching': True, }, ] def _real_extract(self, url): mobj = self._match_valid_url(url) display_id = dict_get(mobj.groupdict(), ('display_id', 'm...
Review this code and list any quality issues.
[ { "issue": "no harm in also matching the old pattern, just in case, yeah?\r\n```suggestion\r\n )data-extension(?:-ard)?=([\"\\'])(?P<data>(?:(?!\\3).)+)\\3\r\n```", "severity": "minor", "line": 26 } ]
1
python
for tx in txs: self.scan_tx(tx) def sign_tx(self, tx, fixed_length=True): if self._mode == MiniWalletMode.RAW_P2PK: # for exact fee calculation, create only signatures with fixed size by default (>49.89% probability): # 65 bytes: high-R val (33 bytes) + low-S val (32 byt...
Review this code and list any quality issues.
[ { "issue": "Would love to see the corresponding cpp reference code, share if you know?", "severity": "minor", "line": 26 } ]
1
python
wheel_install: Path, coverage_install: Path, ) -> Iterator[VirtualEnvironment]: venv_type: VirtualEnvironmentType if request.config.getoption("--use-venv"): venv_type = "venv" else: venv_type = "virtualenv" # Create the virtual environment tmpdir = tmpdir_factory.mktemp("virtual...
Review this code and list any quality issues.
[ { "issue": "Would this work?\r\n\r\n```suggestion\r\n shutil.copy(pth, venv.site)\r\n shutil.copytree(dist_info, venv.site / dist_info.name, dirs_exist_ok=True, symlinks=True)\r\n venv.site.joinpath(\"easy-install.pth\").touch()\r\n```", "severity": "minor", "line": 26 } ]
1
python
context = args[0] # The set of "Make" functions in dump.cpp. id_types = { "class": "MakeClassId", "constant": "MakeConstantId", "symbolic_constant": "MakeSymbolicConstantId", "entity_name": "MakeEntityNameId", "facet_type": "MakeFacetTypeId", "function": "MakeFun...
Review this code and list any quality issues.
[ { "issue": "Minor typo\r\n```suggestion\r\n # Try finding a type + id from the input args. If not, the id will be passed\r\n```", "severity": "minor", "line": 26 } ]
1
python
time.sleep(2) # ensure that spawned processes go through teardown before joining trainer._call_teardown_hook() def model_to_device(self) -> None: self.model = self.wrapped_model.to(self.root_device) def barrier(self, name: Optional[str] = None) -> None: if self.is_distributed:...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n# We use `local_rank` here as separate filesystems are used for each VM for TPU Pod Training\r\n```", "severity": "minor", "line": 26 } ]
1
python
## Test the Player's calculate_score method with Ace card def test_player_calculate_score_with_ace(self): deck = Deck() player = Player("Test Player") player.hand.append(Card('A', 'Hearts', 11)) player.hand.append(Card('K', 'Hearts', 10)) player.calculate_score() self...
Review this code and list any quality issues.
[ { "issue": "@pytest.fixture(scope=\"session\", autouse=True)", "severity": "minor", "line": 26 } ]
1
python
finite_variance = sigma >= xp.finfo(sigma.dtype).smallest_normal logvar = xpx.apply_where(finite_variance, (sigma,), xp.log, fill_value=-xp.inf) loglike = (-n / 2 * logvar + (lmb - 1) * xp.sum(xp.sign(data) * xp.log1p(xp.abs(data)), axis=axis)) return loglike @xp_capabilities(np_only=...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n nan_policy : {'propagate', 'omit', 'raise'}\r\n```", "severity": "minor", "line": 26 } ]
1
python
# rename data keys for existing cache based on new TemporaryExploreState model if isinstance(cache, dict): cache = { ("datasource_id" if key == "dataset_id" else key): value for (key, value) in cache.items() } # add default datasource_type if i...
Review this code and list any quality issues.
[ { "issue": "If I got this correctly, users need to have a `HASH_ALGORITHM` defined in `superset_config.py` or else this will raise, right? \n\nI'm thinking we either need to add a mention to `UPDATING.md` that users need to define a value, or even better you could add `HASH_ALGORITHM` to the `config.py` with th...
1
python
# Table / Events / Select # Register the `select` #event to emit Wave event on each #table row selection. # #table #events #select # --- from h2o_wave import main, app, Q, ui @app('/demo') async def serve(q: Q): q.page['meta'] = ui.meta_card( box='', layouts=[ ui.layout(breakpoint='xs', zones=[ ...
Review this code and list any quality issues.
[ { "issue": "This should be q.events instead of q.args since we want to showcase clicking the selection, not row submission.", "severity": "minor", "line": 20 } ]
1
python
for i in map(read_metric_file, metrics_path.glob('*')) } class PatchedTextReader(RealPeriodicExportingMetricReader): def __init__(self, *args, **kwargs) -> None: self.exporter = DirMetricExporter(metrics_path) self.tick_counter = 0 super().__init__( ...
Review this code and list any quality issues.
[ { "issue": "Would putting a yield here and switching the PeriodicExportingMetricReader back to the Real implementation work? Seems like it would be better just in case code tries to access the PeriodicExportingMetricReader without this fixtures in later tests.", "severity": "minor", "line": 26 } ]
1
python
def main(args: argparse.Namespace): print(args) # Process all the requests in a single batch if possible. # NOTE(woosuk): If the request cannot be processed in a single batch, # the engine will automatically process the request in multiple batches. llm = LLM( model=args.model, token...
Review this code and list any quality issues.
[ { "issue": "remove this or give it a better print format.", "severity": "major", "line": 26 } ]
1
python
size=(0.5, 0.5, 0.5), pos=(0.0, 0.0, 1.0), contype=2, conaffinity=2, ) ) box3 = scene.add_entity( gs.morphs.Box( size=(0.5, 0.5, 0.5), pos=(0.0, 0.0, 1.5), contype=1, conaffinity=1, ) ) scene.buil...
Review this code and list any quality issues.
[ { "issue": "I would prefer a procedurally generated XML model for something this simple.", "severity": "minor", "line": 26 } ]
1
python
ExtractorError, decode_base_n, encode_base_n, filter_dict, float_or_none, format_field, get_element_by_attribute, int_or_none, lowercase_escape, str_or_none, str_to_int, traverse_obj, url_or_none, urlencode_postdata, ) _ENCODING_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabc...
Review this code and list any quality issues.
[ { "issue": "Pretty sure `_id_to_pk` actually needs to be this or else it will convert incorrectly for private shortcodes from years ago\r\n```diff\r\n def _id_to_pk(shortcode):\r\n- \"\"\"Covert a shortcode to a numeric value\"\"\"\r\n+ \"\"\"Convert a shortcode to a numeric value\"\"\"\r\n+ if len(sho...
1
python
"To wait for the assistant’s spoken response prior to running this tool, use `RunContext.wait_for_playout()` instead." ) await asyncio.shield(self._done_fut) def __await__(self) -> Generator[None, None, SpeechHandle]: async def _await_impl() -> SpeechHandle: await self....
Review this code and list any quality issues.
[ { "issue": "I think we should let the caller to manage the awaitables instead of cancelling them whenever the speech is interrupted?", "severity": "minor", "line": 26 } ]
1
python
from pathlib import Path from typing import Any, Callable, Dict, Optional, Union from promptflow._constants import FlowType from promptflow._utils.logger_utils import logger from promptflow.contracts.flow import PromptyFlow from promptflow.contracts.tool import InputDefinition from promptflow.core._flow import Prompty...
Review this code and list any quality issues.
[ { "issue": "maybe rename this param, flow_file is confusing to accept Callable", "severity": "minor", "line": 23 } ]
1
python
] if partitions and dataset.metadata: # Dont use dataset.metadata for partitioned datasets, unless # the column-chunk metadata includes the `"file_path"`. # The order of dataset.metadata.row_group items is often # different than the order of `d...
Review this code and list any quality issues.
[ { "issue": "Might be worth to add a short comment here why this is done. My understanding is that this checks if the file paths are correctly set in the `_metadata` file (so which was not the case with dask+pyarrow right now)", "severity": "minor", "line": 26 } ]
1
python
return self._parse_json(js_data, video_id, transform_source=js_to_json) def _real_extract(self, url): video_id = self._match_id(url) # need to pass cookie webpage = self._download_webpage(url, video_id, headers=self.HEADER) json_data = self._get_json_data(webpage, video_id) ...
Review this code and list any quality issues.
[ { "issue": "bruh wtf\r\ny not use the one in url?\r\nID is supposed to be unique, this looks like it can change", "severity": "minor", "line": 26 } ]
1
python
'Organization Inventory Admin': 'inventory_admin_role', 'Inventory Use': 'use_role', 'Inventory Adhoc': 'adhoc_role', 'Inventory Update': 'update_role', # 'NotificationTemplate Admin': 'admin_role', 'Organization NotificationTemplate Admin': 'notification_admin_role', 'Credential Admin': 'admin_...
Review this code and list any quality issues.
[ { "issue": "Maybe a debug-level log here might be good to have around. This is a perfectly normal thing to happen, but for new upgrades this is probably the exception, not the norm. So it would be good to track.", "severity": "critical", "line": 26 } ]
1
python
'expected_warnings': ['No authenticators for vimeo'] }, { 'url': 'https://app.cybrary.it/immersive/12747143/activity/52686', 'md5': '62f26547dccc59c44363e2a13d4ad08d', 'info_dict': { 'id': '445638073', 'ext': 'mp4', 'title': 'Azure Virtual Network IP Addre...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n activity = traverse_obj(course, ('learning_modules', ..., 'activities', lambda _, v: int(activity_id) == v['id']), get_all=False)\r\n```", "severity": "minor", "line": 26 } ]
1
python
""" Module for building a complete dataset from local directory with csv files. """ import os import logbook from numpy import empty from pandas import DataFrame, read_csv, Index, Timedelta, NaT from zipline.utils.calendars import register_calendar_alias from zipline.utils.cli import maybe_show_progress from . impor...
Review this code and list any quality issues.
[ { "issue": "I think we can make the output from the logger a little cleaner by removing the timestamp and log level. We can do this with a CustomHandler\r\n\r\n```\r\nhandler = StreamHandler(sys.stdout, format_string=\" | {record.message}\")\r\nlogger = Logger(__name__)\r\nlogger.handlers.append(handler)\r\n```...
1
python
return text, csam_flagged def add_text(state, model_selector, chat_input, request: gr.Request): text, images = chat_input["text"], chat_input["files"] ip = get_ip(request) logger.info(f"add_text. ip: {ip}. len: {len(text)}") if state is None: state = State(model_selector, is_vision=True) ...
Review this code and list any quality issues.
[]
0
python
import json from .common import InfoExtractor from ..networking.exceptions import HTTPError from ..utils import ExtractorError, RegexNotFoundError, clean_html, traverse_obj, unified_timestamp class TVWIE(InfoExtractor): BACKUP_API_KEY = '7WhiEBzijpritypp8bqcU7pfU9uicDR' _VALID_URL = r'https?://(?:www\.)?tvw...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\nclass TvwIE(InfoExtractor):\r\n```", "severity": "major", "line": 8 } ]
1
python
def test_mcp_sse_transport(test_mcp_app): _, url, _ = test_mcp_app.launch(mcp_server=True, prevent_thread_lock=True) with httpx.Client(timeout=5) as client: config_url = f"{url}config" config_response = client.get(config_url) assert config_response.is_success assert config_respo...
Review this code and list any quality issues.
[]
0
python
@pytest.fixture def mock_client_error() -> ClientError: return ClientError( code=400, response_json=mock.MagicMock(), response=mock.MagicMock(), ) class TestGenAIGenerateEmbeddingsOperator: @mock.patch(GEN_AI_PATH.format("GenAIGenerativeModelHook")) def test_execute(self, mock_...
Review this code and list any quality issues.
[ { "issue": "Looks like there might be overlap here with PR #61262. The tests in that PR look slightly different but I would just leave this out if they are testing the same operator. But I would check with @shahar1 first.", "severity": "minor", "line": 26 } ]
1
python
Returns None if no preferred language set. """ preferred_lang = self._configuration_arg('lang', ie_key='Youtube', casesense=True, default=[''])[0] if not preferred_lang: return if preferred_lang not in self._SUPPORTED_LANG_CODES: raise ExtractorError( ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n pref_cookie = self._youtube_cookies.get('PREF')\r\n```", "severity": "minor", "line": 26 } ]
1
python
""" is_playlist = bool(traverse_obj( data, ('metadata', 'playlistMetadataRenderer'), ('header', 'playlistHeaderRenderer'))) if not is_playlist: return headers = self.generate_api_headers( ytcfg=ytcfg, account_syncid=self._extract_account_syncid(ytcfg, data), ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n webpage = self._download_webpage(url, item_id, note='Downloading webpage', headers=self._webpage_headers)\r\n```", "severity": "minor", "line": 26 } ]
1
python
""" return await self.client_tracking( True, clientid, prefix, bcast, optin, optout, noloop, target_nodes=target_nodes, ) @deprecated_function( version="7.2.0", reason="Use client-side ca...
Review this code and list any quality issues.
[ { "issue": "The return type annotation should be `ResponseT`, not `Awaitable[ResponseT]`. Since this is an `async def` function, it already returns a coroutine (awaitable). The `Awaitable[ResponseT]` annotation suggests this function returns an awaitable that, when awaited, returns another awaitable, which is i...
1
python
return optimizer def _build_lr_scheduler(self): from verl.utils.megatron.optimizer import get_megatron_optimizer_param_scheduler optimizer_scheduler = get_megatron_optimizer_param_scheduler( optimizer=self.optimizer, config=self.optimizer_config ) return optimizer_sched...
Review this code and list any quality issues.
[ { "issue": "I advise to move this function to another place to keep the model engine implementation clean", "severity": "major", "line": 26 } ]
1
python
"tokenizer.model", "tokenizer.json", "vocab.json", "merges.txt", "added_tokens.json", "tokenizer_config.json", ]: shutil.copy( os.path.join(args.model_path, filename), os.path.join(args.artifact_path, "params...
Review this code and list any quality issues.
[]
0
python
cleaned_parts.append(reserved.upper()) return "".join(cleaned_parts) def _ensure_quoted_url(url: str) -> str: """ Make sure a link is fully quoted. For example, if ' ' occurs in the URL, it will be replaced with "%20", and without double-quoting other characters. """ # Split the URL into ...
Review this code and list any quality issues.
[ { "issue": "Are we sure we don't need to support other schemes here? What about `file://`?", "severity": "minor", "line": 26 } ]
1
python
... on Image { crops { name renditions { name width height url } } } } renditions { type width height url bitrate } summary } } }'...
Review this code and list any quality issues.
[ { "issue": "imo it's more clear to just call them `media_ids`\r\n```suggestion\r\n def _build_playlist(self, media_ids):\r\n for media_id in media_ids:\r\n```", "severity": "minor", "line": 26 } ]
1
python
async def get_instructions(run_context: RunContext[AgentDepsT]) -> str | None: parts = [ instructions_literal, *[await func.run(run_context) for func in instructions_functions], ] parts = [p for p in parts if p] if not parts: ...
Review this code and list any quality issues.
[ { "issue": "Can you please add a test that shows that the retries count passed to the agent is now respected?", "severity": "minor", "line": 26 } ]
1
python
import logging from pathlib import Path from private_gpt.di import global_injector from private_gpt.server.ingest.ingest_service import IngestService from private_gpt.server.ingest.ingest_watcher import IngestWatcher from private_gpt.settings.settings import Settings logger = logging.getLogger(__name__) class Local...
Review this code and list any quality issues.
[ { "issue": "We could point to how to enable it", "severity": "minor", "line": 26 } ]
1
python
self.templates_path_or_url = templates_path_or_url if input is None and os.path.isfile(self.data_src_cfg_name): input = self.data_src_cfg_name logger.info(f"Input config is not provided, using the default {input}") if isinstance(input, dict): self.data_src_cfg = inp...
Review this code and list any quality issues.
[ { "issue": "We may enhance the logics by comparing the absolute paths.", "severity": "minor", "line": 26 } ]
1
python
class _ProjectLogging(UserDict): def __init__(self) -> None: """Initialise project logging. The path to logging configuration is given in environment variable KEDRO_LOGGING_CONFIG (defaults to conf/logging.yml).""" # Check if a user path is set in the environment variable user_loggi...
Review this code and list any quality issues.
[ { "issue": "@SajidAlamQB I suspect the windows test is failing because on windows this path is not being resolved properly, it happens on GHA. try absolute path - `(project_path / Path(\"conf/logging.yml\")).resolve()`", "severity": "critical", "line": 26 } ]
1
python
assert method_handlers.response_serializer is None assert method_handlers.unary_unary() == f"unary call from {service_method}".encode() assert ( method_handlers.unary_stream() == f"stream call from {service_method}".encode() ) def test_ray_serve_grpc_context_serializable(): """RayServegRPCCont...
Review this code and list any quality issues.
[]
0
python
shared_chat_ctx = self.chat_ctx.copy() await self._current_task.update_chat_ctx(shared_chat_ctx) if out_of_scope_tool := self._build_out_of_scope_tool(active_task_id=task_id): current_tools = self._current_task.tools current_tools.append(out_of_scope_tool) ...
Review this code and list any quality issues.
[ { "issue": "@tinalenguyen Very interesting.. just curious: what is the benefit of tracking the exception per task in the group? How does that affect the task group's function within the agent?", "severity": "minor", "line": 26 } ]
1
python
'id': 'bjhh-nbcja', 'title': 'アイドルマスター ミリオンライブ! 765プロch 原っぱ通信', }, 'playlist_mincount': 16, }, { 'url': 'https://asobichannel.asobistore.jp/tag/hvm5qw3c6od', 'info_dict': { 'id': 'hvm5qw3c6od', 'title': 'アイマスMOIW2023ラジオ', }, 'playli...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n 'url': f'https://asobichannel.asobistore.jp/watch/{metadata[\"id\"]}',\r\n 'ie_key': AsobiChannelIE.ie_key(),\r\n```", "severity": "minor", "line": 26 } ]
1
python
component_id = self.triggered_prop_ids[prop_id] return component_id @property @has_context def args_grouping(self): """ args_grouping is a dict of the inputs used with flexible callback signatures. The keys are the variable names and the values are dictionaries containing: ...
Review this code and list any quality issues.
[]
0
python
item_desc = '\n\n'.join(summary) item_time = None for meta in try_get(media, lambda x: x['metadata']['items'], list) or []: if try_get(meta, lambda x: x['label']) == 'Published': item_time = unified_timestamp(meta.get('timestamp...
Review this code and list any quality issues.
[ { "issue": "Support SIMORGH_DATA:\r\n```suggestion\r\n\r\n # extract from SIMORGH_DATA hydration JSON \r\n simorgh_data = self._search_json(\r\n r'window\\s*\\.\\s*SIMORGH_DATA\\s*=', webpage,\r\n 'simorgh data', playlist_id, default={})\r\n if simorgh_data:\r\n ...
1
python
raise AirflowRescheduleException( reschedule_date=datetime.now(tz=timezone.utc) + timedelta(seconds=reschedule_delay) ) log.error( "Startup reschedule limit exceeded", reschedule_count=reschedule_count, max_reschedules=max_reschedules, ) def parse(what: StartupDeta...
Review this code and list any quality issues.
[ { "issue": "Where do we store or track this count?", "severity": "minor", "line": 26 } ]
1
python
config.NUM_CLASSES, 4), dtype=np.float32) pos_ids = np.where(roi_gt_class_ids > 0)[0] bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement( rois[pos_ids], roi_gt_boxes[pos_ids, :4]) # Normalize bbox refinements bboxes /= config.BBOX_STD_DEV # Generate class-specific target mask...
Review this code and list any quality issues.
[]
0
python
DatetimeArray, ExtensionArray, FloatingArray, IntegerArray, NumpyExtensionArray, TimedeltaArray, ) from pandas.core.arrays.string_ import StringDtype if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg)...
Review this code and list any quality issues.
[ { "issue": "The `type` (in the Python sense) is `ndarray`. Some values of this type will raise, and some values will not. Thus this should be a `ValueError` as Series raises currently.\r\n\r\nCan you also match the Series message:\r\n\r\n> Cannot construct an array from an ndarray with compound dtype. Use Data...
1
python
X = LogUniform(a=np.exp(1), b=np.exp(3)) Y = stats.exp(Uniform(a=1., b=3.)) x = X.sample(shape=10, rng=rng) p = X.cdf(x) assert_allclose(X.support(), Y.support()) assert_allclose(X.entropy(), Y.entropy()) assert_allclose(X.median(), Y.median()) assert_allclose(X....
Review this code and list any quality issues.
[ { "issue": "Does this run reasonably fast locally?", "severity": "minor", "line": 26 } ]
1
python
"info": "可训练模型层的数量。", }, }, "name_module_trainable": { "en": { "label": "Trainable modules", "info": "The name of trainable modules. Use commas to separate multiple modules.", }, "ru": { "label": "Обучаемые модули", "info": "Названи...
Review this code and list any quality issues.
[]
0
python
def data_gen_for_token_classification(): # token classification data gen # `labels` is the type not the token id for token classification, 0 or 1 data = data_gen() data['labels'] = torch.tensor([[0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int64) return data def data_gen_for_sequence_classification(): ...
Review this code and list any quality issues.
[]
0
python
for dataset in datasets ], ) else: # This is for maintaining backwards compatibility if backend_access_control_enabled(): return_value = [] for search_result in search_results: prepared_search_results = await prepare_search_result(search_re...
Review this code and list any quality issues.
[ { "issue": "@borisarzentar We only need graphs from search results for the visualization in the platform notebook?", "severity": "minor", "line": 26 } ]
1
python
mode = Mode( target_versions=versions, line_length=line_length, is_pyi=pyi, string_normalization=not skip_string_normalization, magic_trailing_comma=not skip_magic_trailing_comma, experimental_string_processing=experimental_string_processing, ) if config and verbo...
Review this code and list any quality issues.
[ { "issue": "Also technically misleading but I can't think of anything better.", "severity": "minor", "line": 26 } ]
1
python
} }, { # api/v6 v2 'url': 'https://beeg.com/1941093077?t=911-1391', 'only_matching': True, }, { # api/v6 v2 w/o t 'url': 'https://beeg.com/1277207756', 'only_matching': True, }] def _real_extract(self, url): video_id = self._match_id(url) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n first_fact = {}\r\n for fact in fc_facts:\r\n if not first_fact or try_get(fact, lambda x: x['id'] < first_fact['id']):\r\n```", "severity": "minor", "line": 26 } ]
1
python
Parameters ---------- data : pyarrow.Table or Arrow-compatible table Any tabular object implementing the Arrow PyCapsule Protocol (i.e. has an ``__arrow_c_array__`` or ``__arrow_c_stream__`` method). Returns ------- DataFrame """ ...
Review this code and list any quality issues.
[ { "issue": "Does this actually work for things that only expose `__arrow_c_array__`? \r\n\r\n```python\r\nIn [28]: arr = pa.array([1, 2, 3])\r\n\r\nIn [29]: hasattr(arr, \"__arrow_c_array__\")\r\nOut[29]: True\r\n\r\nIn [30]: pa.table(arr)\r\n---------------------------------------------------------------------...
1
python
Returns: dict[str, Any]: Dictionary containing: - aborted_count: Number of requests aborted - request_ids: List of aborted request IDs """ try: # Take an atomic snapshot to avoid race conditions with the vLLM engine thread request_state...
Review this code and list any quality issues.
[ { "issue": "We should always reset_prefix_cache when abort request?", "severity": "major", "line": 26 } ]
1
python
self.assertEqual(self.image.focal_point_y, 250) self.assertEqual(self.image.focal_point_width, 100) self.assertEqual(self.image.focal_point_height, 200) self.image.set_focal_point(None) self.assertIsNone(self.image.focal_point_x) self.assertIsNone(self.image.focal_point_y) ...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n # Simulate the case is which the storage is set dynamically\r\n```", "severity": "minor", "line": 26 } ]
1
python
model=self._model_name, instructions=instructions, parallel_tool_calls=model_settings.get('parallel_tool_calls', OMIT), tools=tools or OMIT, tool_choice=tool_choice or OMIT, max_output_tokens=model_settings.get('max_tokens', OMIT), ...
Review this code and list any quality issues.
[ { "issue": "As I'm sure you also noticed when you wrote this, we're kind of abusing the `ModelHTTPError` class now because this is not actually an HTTP response with status code 0.\r\n\r\nI suggest we add a new superclass of `ModelHTTPError` like `ModelAPIError` without a `status_code` field, and raise that ins...
1
python
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_str from ..utils import ( ExtractorError, js_to_json, qualities, try_get, url_or_none, urljoin, ) class MxplayerIE(InfoExtractor): _VALID_URL = r'(?:https?://)(?:www\.)?mxplaye...
Review this code and list any quality issues.
[ { "issue": "```suggestion\r\n _VALID_URL = r'https?://(?:www\\.)?mxplayer\\.in/(?:movie|show/[-\\w]+/[-\\w]+)/(?P<display_id>[-\\w]+)-(?P<id>\\w+)'\r\n```\r\nmay be easier to read. Or even better, split it into multiple lines using `(?x)`", "severity": "minor", "line": 18 } ]
1
python
op.get_next() gc.collect() # `InputDataBuffer` should still hold a reference to the input block even after # `get_next` is called. assert len(gc.get_referrers(block_ref)) > 0 def test_union_operator_throttling_disabled(ray_start_regular_shared): """Test that UnionOperator has throttling disabled....
Review this code and list any quality issues.
[ { "issue": "Rather than adding a `try-catch`, use the `restore_data_context` fixture: https://docs.ray.io/en/master/data/contributing/how-to-write-tests.html#use-fixtures-skip-try-finally", "severity": "minor", "line": 26 } ]
1
python
def get_embeddings(self, params): raise NotImplementedError def release_worker_semaphore(): worker.semaphore.release() def acquire_worker_semaphore(): if worker.semaphore is None: worker.semaphore = asyncio.Semaphore(worker.limit_worker_concurrency) return worker.semaphore.acquire() de...
Review this code and list any quality issues.
[ { "issue": "Some of these functions are worker-specific.\r\nFor example, these functions are different for the model worker, vllm model worker, and huggginface_api model worker.\r\nIs it better to put these functions under`base_model_worker.py` or `model_worker.py`?", "severity": "minor", "line": 26 ...
1
python
'url': 'https://commons.wikimedia.org/wiki/File:Die_Temperaturkurve_der_Erde_(ZDF,_Terra_X)_720p_HD_50FPS.webm', 'info_dict': { 'description': 'md5:7cd84f76e7081f1be033d0b155b4a460', 'ext': 'webm', 'id': 'Die_Temperaturkurve_der_Erde_(ZDF,_Terra_X)_720p_HD_50FPS', 'title': 'D...
Review this code and list any quality issues.
[ { "issue": "Does it have to be this strict? What do you get with just `licensetpl`?", "severity": "minor", "line": 26 } ]
1
python
y[sup] = _cdf_cvm_inf(x[sup]) * (1 + 1./(12*n)) + _psi1_mod(x[sup]) / n y[x >= n/3] = 1 if y.ndim == 0: return y[()] return y def _cvm_result_to_tuple(res, _): return res.statistic, res.pvalue @xp_capabilities(np_only=True) @_axis_nan_policy_factory(CramerVonMisesResult, n_samples=1, to...
Review this code and list any quality issues.
[ { "issue": "Single backticks (without explicit [role](https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#roles)) can be used for parameters, functions, and classes; double backticks are for (other, general) code. I think this is supposed to be math, so you need to specify the `:math:` role:\...
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
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing p...
Review this code and list any quality issues.
[ { "issue": "[optional] could add a comment above:\r\n```\r\n# using lazy_gettext since initialization happens prior to the request scope and confuses flask-babel\r\n```", "severity": "minor", "line": 26 } ]
1
python
) projection_time = time.time() - start_time node_count = len(memory_fragment.nodes) edge_count = len(memory_fragment.edges) logger.info(f"Memory fragment projection completed in {projection_time:.2f} seconds") logger.info(f"Memory fragment contains {node_count} nodes and {edge...
Review this code and list any quality issues.
[ { "issue": "Again I think we log this twice, once in cogneeGraph, the other time here.", "severity": "minor", "line": 26 } ]
1
python
except ImportError: import sys import select import termios import tty class KeyPoller: def __enter__(self): if isWindows: self.read_handle = GetStdHandle(STD_INPUT_HANDLE) self.read_handle.SetConsoleMode(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPU...
Review this code and list any quality issues.
[ { "issue": "use \r\n\r\n```\r\nif not something:\r\n # do something \r\n```\r\n\r\ninstead of \r\n\r\n```\r\nif something:\r\n pass\r\nelse:\r\n # do something\r\n```", "severity": "minor", "line": 26 } ]
1
python
self._links = self.links self._joints = self.joints self._equalities = self.equalities base_links_idx = {link.idx for link in self.links if link.is_fixed} for joint in tuple(chain.from_iterable(self.joints)): if joint.type == gs.JOINT_TYPE.FREE: base_links_id...
Review this code and list any quality issues.
[ { "issue": "At least, move this on top before the definition of the class, in upper case.", "severity": "major", "line": 26 } ]
1
python
"Found orphaned Shelly entity: %s, unique id: %s", entity.entity_id, entity.unique_id, ) orphaned_entities.append(entity.unique_id.split("-", 1)[1]) if orphaned_entities: async_remove_shelly_rpc_entities(hass, platform, mac, orphaned_entities) def _...
Review this code and list any quality issues.
[ { "issue": "The `gethostbyname` function is a blocking socket operation that should not be called directly from the event loop. This function is called from both `@callback` decorated functions (line 186 in repairs.py) and async functions (line 278 in repairs.py), which means it will block the event loop.\n\nAc...
1
python
def save(self, data: _DI) -> None: """Saves data by delegation to the provided save method. Args: data: the value to be saved by provided save method. Raises: DatasetError: when underlying save method raises error. FileNotFoundError: when save method got fil...
Review this code and list any quality issues.
[ { "issue": "IIUC, we're removing the `__str__` format right? Shouldn't we keep it around for backwards compatibility?", "severity": "minor", "line": 26 } ]
1
python
if not self._session: self._session = utils.http_context.http_session() return self._session def update_options( self, *, model: NotGivenOr[str] = NOT_GIVEN, ) -> None: """ Args: model (str): TTS model to use. """ if is_giv...
Review this code and list any quality issues.
[]
0
python
) -> AwaitMount: """Mount widgets from an iterable. Args: widgets: An iterable of widgets. before: Optional location to mount before. An `int` is the index of the child to mount before, a `str` is a `query_one` query to find the widget to mount be...
Review this code and list any quality issues.
[]
0
python
input_items_data: list[OpenAIResponseInput] = [] if isinstance(input, str): input_content = OpenAIResponseInputMessageContentText(text=input) input_content_item = OpenAIResponseMessage( role="user", content=[input_content], id=new_input_id...
Review this code and list any quality issues.
[]
0
python
def forward_runner(model): return forward_runner_helper(model, train_dataloader, device) # example: prune different layers with different sparsity attention_name_groups = list(zip(["bert.encoder.layer.{}.attention.self.query".format(i) for i in range(12)], ["bert.en...
Review this code and list any quality issues.
[ { "issue": "https://nni.readthedocs.io/en/latest/Compression/Pruner.html#transformer-head-pruner \r\nI mean the example in the documentation here has the wrong indent", "severity": "critical", "line": 26 } ]
1
python
assert _parse_yes_no_to_bool(None) is None class TestValidateSelection: def test_validate_selection_valid(self): tools = ["1", "2", "3", "4"] assert _validate_selection(tools) is None def test_validate_selection_invalid_single_tool(self): tools = ["8"] with pytest.raises(Syste...
Review this code and list any quality issues.
[ { "issue": "Could we move the tests for `parse_tools_input` into their own class as well? For consistency", "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
returncode = 0 finally: sys.stdout = orig_stdout return InMemoryPipResult(returncode, stdout.getvalue()) class ScriptFactory(Protocol): def __call__( self, tmpdir: pathlib.Path, virtualenv: Optional[VirtualEnvironment] = None, environ: Optional[Dict[AnyS...
Review this code and list any quality issues.
[ { "issue": "Instead of trying to check versions, would it be better if we just try to parse one URL to determine the version?", "severity": "minor", "line": 26 } ]
1
python
tokenizer: "PreTrainedTokenizer", processor: "ProcessorMixin", expected_mm_messages: Sequence[Dict[str, str]] = MM_MESSAGES, expected_input_ids: List[int] = INPUT_IDS, expected_labels: List[int] = LABELS, expected_mm_inputs: Dict[str, Any] = {}, expected_no_mm_inputs: Dict[str, Any] = {}, ) -> N...
Review this code and list any quality issues.
[]
0
python
def _extract_episode(self, podcast, episode): return { 'id': str(episode.get('id')), 'title': episode.get('title'), 'description': episode.get('description'), 'url': episode.get('audio_url'), 'thumbnail': episode.get('image_url'), 'duration...
Review this code and list any quality issues.
[ { "issue": "Regarding the errors, would this be a good fix?\r\n`r'(?P<id>\\d+).+[^\\d]$'`", "severity": "minor", "line": 26 } ]
1
python
'Clips': '''query ($page: Int!, $user: String!, $game: Int) { videos: clips(search: createdDate, page: $page, user: $user, mobile: false, game: $game) { data { %s %s } } }''' % (_FIELDS, _EXTRA_FIELDS), 'Montages': '''query ($page: Int!, $user: String!) { videos: montages(sea...
Review this code and list any quality issues.
[ { "issue": "No need for `str_or_none` here. `urljoin` already checks for that.\r\n```suggestion\r\n return urljoin('https://media.allstar.gg/', path)\r\n\r\n def _profile_url_or_none(path):\r\n return urljoin('https:/allstar.gg/u/', path)\r\n```", "severity": "minor", "line"...
1
python
if err: raise e @read_only.setter @invalid_view_op def read_only(self, value: bool): self._set_read_only(value, True) def pytorch( self, transform: Optional[Callable] = None, tensors: Optional[Sequence[str]] = None, num_workers: int = 1, ...
Review this code and list any quality issues.
[ { "issue": "I am curious, how did we came up with this cache size? did we do a benchmarking or is it a known constant that proved to work best?", "severity": "major", "line": 26 } ]
1
python
'only_matching': True, }, { # FMT (TOKYO FM) station does not provide <desc> 'url': 'https://radiko.jp/#!/ts/FMT/20210810150000', 'only_matching': True, }, { 'url': 'https://radiko.jp/#!/ts/JOAK-FM/20210509090000', 'only_matching': True, }] def _real_extract(self...
Review this code and list any quality issues.
[ { "issue": "this is fatal, `unified_timestamp` can return `None`. wrap in `try_call`", "severity": "minor", "line": 26 } ]
1
python
def get_device_and_memory_breakdown() -> tuple[torch.device, int, int, int]: if torch.cuda.is_available(): device = torch.device("cuda") torch.cuda.empty_cache() torch.cuda.synchronize() total_memory = torch.cuda.get_device_properties(device).total_memory reserved_memory = to...
Review this code and list any quality issues.
[ { "issue": "Could you move this import to the top of the file? And use the `is_psutil_available` check before trying to import it. If it's not available, we can keep 0s everywhere.", "severity": "major", "line": 26 } ]
1