language string | code-snippit string | instruction string | flaws list | flaw_count int64 |
|---|---|---|---|---|
python | }
entries = []
media_path = ((None, 'quoted_status'), 'extended_entities', 'media', ...)
medias = traverse_obj(status, media_path, expected_type=dict, default=[])
for media in medias:
if not media or media.get('type') == 'photo':
continue
data = ... | Review this code and list any quality issues. | [
{
"issue": "are you sure this should be transparent? Does this generally get passed to generic? If it's being passed to another extractor, this probably shouldn't be transparent",
"severity": "major",
"line": 26
}
] | 1 |
python | if display_id.startswith('$/'):
display_id = display_id.split('/', 2)[-1].replace('/', ':')
else:
display_id = display_id.replace(':', '#')
display_id = compat_urllib_parse_unquote(display_id)
uri = 'lbry://' + display_id
result = self._resolve_url(uri, display_id... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n streaming_url = final_url = live_data.get('VideoURL')\r\n # Upcoming videos may still give VideoURL\r\n if not live_data.get('Live'):\r\n streaming_url = final_url = None\r\n self.raise_no_formats('This stream is not li... | 1 |
python | class ECSTaskCustomRunTaskKwargsWithCollidingCommand(ECSTaskNoOutput):
@property
def command(self):
return [
{'name': 'hello-world', 'command': ['/bin/sleep', '10']},
{'name': 'hello-world-2', 'command': ['/bin/sleep', '10']},
]
@property
def run_task_kwargs(sel... | Review this code and list any quality issues. | [] | 0 |
python | *to_build
)
# We also need any missing datasets that are required to run the
# `to_rerun` pipeline, including any chains of missing datasets.
unregistered_ds = pipeline.datasets() - set(catalog.list())
output_to_unregistered = pipeline.only_nodes_with_outputs(*unregistered_ds)
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n catalog: An implemented instance of ``CatalogProtocol`` from which to fetch data.\r\n```\r\n\r\nCan you rephrase all docstrings in a similar fashion? I think it's useful to have a reference to the protocol in the docstrings.",
"severity": "minor",
"line": 26
}
... | 1 |
python | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | Review this code and list any quality issues. | [
{
"issue": "Could you add some examples in a comment? Currently, it's not very clear what this function is trying to do.",
"severity": "minor",
"line": 26
}
] | 1 |
python | mimetype = ext2mimetype(given_ext)
if mimetype != 'image/gif' and mimetype.partition('/')[0] != 'video':
continue
entries.append({
**parent,
'id': compat_str(item.get('id')),
'url': vid_url,
'thumbnail': item.get('po... | Review this code and list any quality issues. | [
{
"issue": "Are you sure about this? If a new entry gets added to the URL, it shouldn't cause the id of the existing entry to change\r\n\r\nPS: Also, this is wrong. Should be `entries[0]['id'] = ...`",
"severity": "critical",
"line": 26
}
] | 1 |
python | from docstring_parser import parse
class DocstringParser:
@staticmethod
def parse_description(docstring: str):
parsed = parse(docstring)
description = (
(short + " " + long if (long := parsed.long_description) is not None else short)
if (short := parsed.short_descripti... | Review this code and list any quality issues. | [
{
"issue": "Should we use `parsed.description` directly?",
"severity": "minor",
"line": 9
}
] | 1 |
python | 'info_dict': {
'id': '1915774',
'display_id': 'misfits-magic-holiday-special',
'ext': 'mp4',
'title': 'Misfits & Magic Holiday Special',
'description': 'The magical misfits spend Christmas break at Gowpenny, with an unwelcome visitor.',
'release_da... | Review this code and list any quality issues. | [
{
"issue": "remove all these unnecessary comments. The code is self-explainatory here",
"severity": "minor",
"line": 26
}
] | 1 |
python | )
for k, v in result.items():
chunks[k] = v if v else 0
return tuple(chunks)
else:
# Check if dtype.itemsize is greater than 0
if dtype.itemsize == 0:
raise ValueError(
"auto-chunking with dtype.itemsize == 0 is not supported, please pass in ... | Review this code and list any quality issues. | [
{
"issue": "nit: I've been thinking about the directional `left` here\n```suggestion\n if multiplier_remaining:\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | async def download_file_with_retry(
model_id: ModelId,
revision: str,
path: str,
target_dir: Path,
on_progress: Callable[[int, int, bool], None] = lambda _, __, ___: None,
) -> Path:
n_attempts = 30
for attempt in range(n_attempts):
try:
return await _download_file(
... | Review this code and list any quality issues. | [] | 0 |
python | result = self.invoke(inputs=kwargs)
return result.output
def invoke(self, inputs: dict) -> "LineResult":
"""Invoke a flow and get a LineResult object."""
from promptflow._sdk._submitter import TestSubmitter
from promptflow._sdk.operations._flow_context_resolver import FlowContextRes... | Review this code and list any quality issues. | [
{
"issue": "async_args -> args? \r\nwhy need to emphasize the async here?",
"severity": "minor",
"line": 26
}
] | 1 |
python | return []
search_results = self._build_search_results(results)
# Filter results based on metadata if filters are provided
if filters and search_results:
filtered_results = []
for doc in search_results:
if doc.meta_data is None:
contin... | Review this code and list any quality issues. | [] | 0 |
python | assert_eq_df_lf(
"b",
"a",
pl.col.a == 2,
[
pl.Series("a", [2, 2], dtype=pl.Int64),
pl.Series("variable", ["b", "b"], dtype=pl.String),
pl.Series("value", [33, 44], dtype=pl.Int64),
],
)
assert_eq_df_lf(
"b",
["b", "a"]... | Review this code and list any quality issues. | [
{
"issue": "Test was wrong but never ran due to lacking `test_` prefix",
"severity": "critical",
"line": 26
}
] | 1 |
python | #
# Copyright 2016 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | Review this code and list any quality issues. | [
{
"issue": "We can also put `root_symbol=str` here I think?",
"severity": "minor",
"line": null
}
] | 1 |
python | Currently, allocations and updates are done at granularity of a single sequence.
That is, the block table should be a 1D tensor of shape [max_blocks_per_sequence].
And it's possible to have a batch of sequences with different lengths of block tables.
"""
def __init__(self, config: InferenceConf... | Review this code and list any quality issues. | [
{
"issue": "Branching can be skipped: `self.kv_cache_dtype = config.kv_cache_dtype`, as the following comment indicates",
"severity": "major",
"line": 26
}
] | 1 |
python | if mobj:
uploader_id, uploader = mobj.groups()
breadcrumb = get_element_by_attribute('typeof', 'BreadcrumbList', webpage)
categories = []
if breadcrumb:
for _, name in re.findall(r'<span[^>]+property=(["\'])name\1[^>]*>([^<]+)', breadcrumb):
categories.ap... | Review this code and list any quality issues. | [
{
"issue": "these could just be in the info dict root instead of a formats dict, but either way works. core code will also determine acodec from ext, but explicitly returning it is fine too",
"severity": "minor",
"line": 26
}
] | 1 |
python | ds = local_ds_generator()
ds.create_tensor("abc")
ds.abc.append(1)
a = ds.commit("first")
ds.checkout(a)
ds.create_tensor("a/b/c/d")
assert list(ds.tensors) == ["abc", "a/b/c/d"]
@pytest.mark.skipif(
os.name == "nt" and sys.version_info < (3, 7), reason="requires python 3.7 or above"
)
def... | Review this code and list any quality issues. | [] | 0 |
python | 'Foundation', # base layer functionality for apps/frameworks
'ImageIO', # read and write image file formats.
'IOKit', # user-space access to hardware devices and drivers.
'IOSurface', # cross process image/drawing buffers
'libobjc.A.dylib', # Objective-C runtime library
'Metal', # 3D graphics
'QuartzCore', # animation
... | Review this code and list any quality issues. | [] | 0 |
python | from __future__ import annotations
import types
from typing import Callable
from numpy import piecewise
from manim.utils.simple_functions import get_parameters
from ..animation.animation import Animation, Wait, prepare_animation
from ..animation.composition import AnimationGroup
from ..mobject.mobject import Mobjec... | Review this code and list any quality issues. | [
{
"issue": "Just to be in line with our general docstring format.\r\n\r\n```suggestion\r\n \"\"\"Modifies the speed of passed animation. :class:`AnimationGroup` with\r\n```",
"severity": "minor",
"line": 18
}
] | 1 |
python | if expr.is_number:
return _PrimePredicate_number(expr, assumptions)
for arg in expr.args:
if not ask(Q.integer(arg), assumptions):
return None
for arg in expr.args:
if arg.is_number and arg.is_composite:
return False
@PrimePredicate.register(Pow)
def _(expr, assu... | Review this code and list any quality issues. | [
{
"issue": "It would be logically equivalent if you checked `ask(Q.eq(expr.exp, 1), assumptions)` and adjusted the logic accordingly. I think that would be a bit more readable.",
"severity": "minor",
"line": 26
}
] | 1 |
python | default_path: Optional[str] = None,
engine: Optional[str] = None,
compression: Optional[str] = None,
read_kwargs: Optional[Dict] = None,
write_kwargs: Optional[Dict] = None,
exposed_type: Optional[str] = None,
scope: Optional[Scope] = None,
validity_period: Option... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n The parameters in *read_kwargs* and *write_kwargs* have a **higher precedence** \r\n than the top-level parameters which are also passed to Pandas.\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | ) -> None:
"""Enable or pause charging.
The NRGkick API uses a pause flag (pause=True means charging is paused).
"""
await async_api_call(coordinator.api.set_charge_pause(not is_on))
await coordinator.async_refresh()
SWITCHES: tuple[NRGkickSwitchEntityDescription, ...] = (
NRGkickSwitchEntity... | Review this code and list any quality issues. | [
{
"issue": "no need to overwrite the type, it's already typed",
"severity": "minor",
"line": 26
}
] | 1 |
python | def _parse_vue_element_attr(self, name, string, video_id):
page_elem = self._search_regex(rf'(<{name}[^>]+>)', string, name)
attrs = {}
for key, value in extract_attributes(page_elem).items():
if key.startswith(':'):
attrs[key[1:]] = self._parse_json(
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'formats': formats,\r\n 'live_status': live_status,\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | conversation.AssistantContent(
agent_id="conversation.openai_conversation",
content="12:00 PM",
)
)
mock_create_stream.return_value = [
# Initial conversation
(
# Wait for the model to think
*create_reasoning_item(
id="rs_A... | Review this code and list any quality issues. | [] | 0 |
python | )
dev_reg = dr.async_get(hass)
async def async_mount_reload(service: ServiceCall) -> None:
"""Handle service calls for Hass.io."""
if (device := dev_reg.async_get(service.data[ATTR_DEVICE_ID])) and device.name:
await supervisor_client.mounts.reload_mount(device.name)
hass.serv... | Review this code and list any quality issues. | [
{
"issue": "Does this call need error handling?",
"severity": "minor",
"line": 26
}
] | 1 |
python | """Get pipeline layers for current stage."""
stage_manager = self.pipeline_stage_manager
held_layers = super().get_held_layers()
if stage_manager.is_last_stage():
held_layers.append(self.model.score)
return held_layers
def get_shared_params(self) -> List[Dict[int, Tensor... | Review this code and list any quality issues. | [
{
"issue": "what is this function used for?",
"severity": "minor",
"line": 26
}
] | 1 |
python | """Test the generation of unique ids."""
state_entity_ids = hass.states.async_entity_ids()
for entity_id, unique_id in EXPECTED_ENTITY_IDS.items():
assert entity_id in state_entity_ids
state = hass.states.get(entity_id)
assert state
assert state.state == "100"
entity = e... | Review this code and list any quality issues. | [
{
"issue": "Instead of this, use the `entity_registry_enabled_by_default` fixture in a test which checks the sensor state when they are enabled.\n\nYou can check that they are not enabled by default in a separate test (check that they exist in the entity registry but are disabled and don't have a state).\n\nEx... | 1 |
python | def setup(self) -> None:
cc.init_collective_group(1 + self.num_consumer_procs, 0, group_name=f"sync_data_{self.producer_idx}")
if self.consumer_pp_size > 1:
for i in range(self.consumer_pp_size):
cc.init_collective_group(self.num_producers + 1, self.producer_idx, group_name=f... | Review this code and list any quality issues. | [] | 0 |
python | return out
def training_epoch_end(self, outputs):
self.training_epoch_end_called = True
self.log('c', outputs[0]['loss'], on_epoch=True, prog_bar=True, logger=True)
self.log('d/e/f', 2)
model = TestModel()
model.val_dataloader = None
trainer = Trainer(
... | Review this code and list any quality issues. | [] | 0 |
python | X_test,
y_test,
display_labels=class_names,
cmap=plt.cm.Blues,
normalize=normalize,
)
disp.ax_.set_title(title)
print(title)
print(disp.confusion_matrix)
plt.show()
# %%
# Binary Classification
# =====================
#
# For binary problems, :func:`sklearn.metrics.con... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\n# metrics like :func:`~sklearn.metrics.roc_auc_score` and\n# :func:`~sklearn.metrics.det_curve`.\n```\nnit",
"severity": "minor",
"line": 26
}
] | 1 |
python | Parameters
----------
kwargs
Passing any keyword argument will update the default
values of the keyword arguments of the initialization
function of this class.
Examples
--------
.. manim:: ChangeDefaultAnimation
class ChangeDefa... | Review this code and list any quality issues. | [
{
"issue": "Thanks for writing an example (especially one that renders fast)!",
"severity": "minor",
"line": 26
}
] | 1 |
python | }).encode(), headers=self._HEADERS)
obj = resp['data'][object_type]
if not obj:
raise ExtractorError(resp['errors'][0]['message'], expected=True)
return obj
class DailymotionIE(DailymotionBaseInfoExtractor):
_VALID_URL = r'''(?ix)
https?://
... | Review this code and list any quality issues. | [
{
"issue": "`[5:]` is a bit obscure?\r\n\r\nMaybe s/5/len('(?ix)')/ but constructing `_VALID_URL = f'(?ix){VALID_URL_TAIL}'` with the obvious definition of `_VALID_URL_TAIL` would be clearer. Or `re.sub(r'^\\(\\?[^)]*\\)\\s*', '', _VALID_URL)` would cater for any or no flag group (probably put that RE in utils ... | 1 |
python | __all__ = ["TrueDot", "DotCloud"]
import numpy as np
from ...constants import ORIGIN, RIGHT, UP
from ...utils.color import YELLOW
from .opengl_point_cloud_mobject import OpenGLPMObject
class DotCloud(OpenGLPMObject):
def __init__(
self, color=YELLOW, stroke_width=2.0, radius=2.0, density=10, **kwargs
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n self.points = np.array(self.generate_points(), dtype=np.float32)\r\n```",
"severity": "minor",
"line": 22
}
] | 1 |
python | import pytest
from pandas.core.indexers import (
is_scalar_indexer,
length_of_indexer,
validate_indices,
)
def test_length_of_indexer():
arr = np.zeros(4, dtype=bool)
arr[0] = 1
result = length_of_indexer(arr)
assert result == 1
@pytest.mark.parametrize(
"start,stop,step",
[
... | Review this code and list any quality issues. | [
{
"issue": "Can you add a comment referring to this PR.\n\n\n```suggestion\n # https://github.com/pandas-dev/pandas/pull/63872\n indexer = range(start, stop, step)\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | class Policy(ABC):
r"""
The base class for all the policies. For each different model, it should have a different policy class,
like BertPolicy for Bert Model or OPTPolicy for OPT model.
Shardformer has provided many built-in sharding policies for the mainstream models. You can use the
built-in pol... | Review this code and list any quality issues. | [] | 0 |
python | return cls._instance
def _reload(self, manager: str, obj):
if self._no_reload_context:
return obj
entity = _get_manager(manager)._get(obj, obj)
if obj._is_in_context and hasattr(entity, "_properties"):
if obj._properties._pending_changes:
entity._pro... | Review this code and list any quality issues. | [
{
"issue": "[nitpick] Referencing a class-level lock via the class (e.g., `type(self)._lock`) can improve clarity that `_lock` is not an instance attribute.\n```suggestion\n with type(self)._lock:\n self._context_depth += 1\n self._no_reload_context = True\n return self\n\n ... | 1 |
python | }, {
'note': 'Movie',
'url': 'https://duoplay.ee/4325/naljamangud',
'md5': '2b0bcac4159a08b1844c2bfde06b1199',
'info_dict': {
'id': '4325',
'ext': 'mp4',
'title': 'Näljamängud',
'thumbnail': r're:https://.+\.jpg(?:\?c=\d+)?$',
'... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'cast': 'count:9',\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | )
class NhkBaseIE(InfoExtractor):
_API_URL_TEMPLATE = 'https://nwapi.nhk.jp/nhkworld/%sod%slist/v7b/%s/%s/%s/all%s.json'
_BASE_URL_REGEX = r'https?://www3\.nhk\.or\.jp/nhkworld/(?P<lang>[a-z]{2})/ondemand'
_TYPE_REGEX = r'/(?P<type>video|audio)/'
def _call_api(self, m_id, lang, is_video, is_episode, ... | Review this code and list any quality issues. | [
{
"issue": "Since this si requesting \"static\" parameters, this should imo not be tied to `vod_id` and instead be using a video_id of `None`. Also perhaps it should be cached so we wouldnt download it more than once? How long before the api url and api token expire?",
"severity": "major",
"line": 26
... | 1 |
python | import capa.features.common
import capa.features.address
import capa.features.basicblock
import capa.features.extractors.base_extractor
from capa.helpers import assert_never
from capa.features.freeze.features import Feature, feature_from_capa
logger = logging.getLogger(__name__)
class HashableModel(BaseModel):
m... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n value: Union[int, Tuple[int, int], None] = None # None default value to support deserialization of NO_ADDRESS\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | valid_num_frames = len(valid_frame_indices)
if recovered_map:
logger.info(
"Frame recovery: %d frames recovered using forward scan.",
len(recovered_map),
)
else:
frame_indices_set = set(frame_indices_list)
... | Review this code and list any quality issues. | [] | 0 |
python | _LOGGING_INTERVAL = timedelta(minutes=1)
"""Interval at which the autoscaled pool logs its current state."""
_DESIRED_CONCURRENCY_RATIO = 0.9
"""Minimum ratio of desired concurrency that must be reached before allowing further scale-up."""
_SCALE_UP_STEP_RATIO = 0.05
"""Fraction of desired concurr... | Review this code and list any quality issues. | [
{
"issue": "`__init__` is not a constructor, it does not create the instance, it initializes it :slightly_smiling_face: Also, I'd prefer to just leave this blank, but I guess it's not possible to just have the `Args` section in a docblock.",
"severity": "minor",
"line": 26
}
] | 1 |
python | ).total_seconds()
return (datetime.now() - self._status_change_records[Status.PENDING.name]).total_seconds()
@property
@_self_reload(_MANAGER_NAME)
def blocked_duration(self) -> Optional[float]:
"""Get the duration of the job in the blocked state in seconds.
Returns:
O... | Review this code and list any quality issues. | [
{
"issue": "Is it correct?\r\n\r\nWhat if the job got blocked, unblocked(pending), running, and completed?\r\nYour method returns the difference between the completion time and the blocked time. while we expect to return PENDING - BLOCKED.\r\n\r\nLet me propose something like the following:\r\n```suggestion\r\n... | 1 |
python | else:
self._attr_extra_state_attributes = {}
class Pet(SurePetcareBinarySensor):
"""Sure Petcare Pet."""
_attr_device_class = BinarySensorDeviceClass.PRESENCE
@callback
def _update_attr(self, surepy_entity: SurepyEntity) -> None:
"""Get the latest data and update the state."""
... | Review this code and list any quality issues. | [
{
"issue": "Would it make sense to name it something like `flap_device_id` ?",
"severity": "minor",
"line": 26
}
] | 1 |
python | 0,
self._ckpt[ckpt_name]["pos"],
self._ckpt[ckpt_name]["vel"],
self._ckpt[ckpt_name]["active"],
)
for entity in self._entities:
entity.load_ckpt(ckpt_name=ckpt_name)
# ----------------------------------------------------------... | Review this code and list any quality issues. | [
{
"issue": "Just enforce return uvs systematically now. This is private API. No backward compatibility concerns.",
"severity": "minor",
"line": 26
}
] | 1 |
python | # from getMixinKey() in the vendor js
mixin_key_enc_tab = [
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57... | Review this code and list any quality issues. | [
{
"issue": "let's not change the order of the args just in case\r\n```suggestion\r\n def _download_playinfo(self, bvid, cid, headers=None, qn=None, fatal=True):\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | global FACE_MASK_PADDING_GROUP
FACE_MASK_TYPES_CHECKBOX_GROUP = gradio.CheckboxGroup(
label = wording.get('face_mask_types_checkbox_group_label'),
choices = facefusion.choices.face_mask_types,
value = facefusion.globals.face_mask_types
)
FACE_MASK_BLUR_SLIDER = gradio.Slider(
label = wording.get('face_mask... | Review this code and list any quality issues. | [] | 0 |
python | " text text (1000, 1) str None \n"
)
assert output in captured.out
assert len(vector_store) == number_of_data
assert list(vector_store.dataset.tensors) == [
"embedding",
"id",
"metadata",
"text",
]
assert list(vector_store.tensors()) == [
... | Review this code and list any quality issues. | [] | 0 |
python | if not task.collective:
task.done = True
self.db.add(task)
logger.debug(f"inserting TextLabels for {message_id=}, {text_labels_id=}")
model = TextLabels(
id=text_labels_id,
api_client_id=self.api_client.id,
message_id=message_id,
... | Review this code and list any quality issues. | [
{
"issue": "send message_id inside send_new_report_message, this would be easier for the mod team to search the DB",
"severity": "minor",
"line": 26
}
] | 1 |
python | import os
from pathlib import Path
from typing import Any, Callable, Sequence, Mapping, Iterable, Protocol, ClassVar, runtime_checkable
try:
from sentencepiece import SentencePieceProcessor
except ImportError:
SentencePieceProcessor = None
try:
from mistral_common.tokens.tokenizers.mistral import MistralT... | Review this code and list any quality issues. | [
{
"issue": "Actually, while waiting, perhaps move this below so that we don't have nested try/except.",
"severity": "major",
"line": 26
}
] | 1 |
python | import torch
import pytorch_lightning
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning.utilities import _OMEGACONF_AVAILABLE, DeviceType, rank_zero_info, rank_zero_warn
from pytorch_lightning.utilities.cloud_io import atomic_save, get_filesystem
from pytorch_lightning.utilities.cloud... | Review this code and list any quality issues. | [
{
"issue": "reviewers: this is temporary. I don't know otherwise how to break down the complex PR in #7652",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'continuation': continuation,
}
# TODO: Inconsistency with clickTrackingParams.
# Currently we have a fixed ctp contained within context (from ytcfg)
# and a ctp in root query for continuation.
if ctp:
query['clickTracking'] = {'clickTrackingParams': ctp}
retu... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n continuation_commands = traverse_obj(\r\n continuation_ep, ('commandExecutorCommand', 'commands', ..., {dict}))\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | )
assert_numpy_array_equal(left.codes[level], right.codes[level])
except AssertionError:
llevel = left.get_level_values(level)
rlevel = right.get_level_values(level)
assert_index_equal(
llevel,
rlevel,
... | Review this code and list any quality issues. | [
{
"issue": "If the `TypeError` is hit, we should be comparing the materialized version of the `CategoricalIndex` e.g. `left._internal_get_values() != right._internal_get_values()`",
"severity": "minor",
"line": 26
}
] | 1 |
python | - name: Export a job template named "My Template" and all Credentials
export:
job_templates: "My Template"
credentials: 'all'
- name: Export a list of inventories
export:
inventory: ['My Inventory 1', 'My Inventory 2']
'''
import logging
from ansible.module_utils.six.moves import StringIO
from ..modul... | Review this code and list any quality issues. | [
{
"issue": "This is confusing, how did this work before?",
"severity": "minor",
"line": 26
}
] | 1 |
python | Normal Cache Timeout Logic
'''
timeout_seconds = timedelta(seconds=latest_project_update.project.scm_update_cache_timeout)
if (latest_project_update.finished + timeout_seconds) < now:
return True
return False
def gen_dep_for_job(self, task):
created_dependencies ... | Review this code and list any quality issues. | [
{
"issue": "I'd turn this list comprehension into a generator expression (square brackets into parentheses)",
"severity": "minor",
"line": 26
}
] | 1 |
python | #!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | Review this code and list any quality issues. | [
{
"issue": "Perhaps we could make the argument mandatory.",
"severity": "minor",
"line": 25
}
] | 1 |
python | self.viewer_lock = None
self._renderer = None
def add_camera(self, res, pos, lookat, up, model, fov, aperture, focus_dist, GUI, spp, denoise, env_idx, debug):
cam_idx = len(self._cameras) if not debug else len(self._debug_cameras)
camera = Camera(
self,
cam_idx,
... | Review this code and list any quality issues. | [
{
"issue": "I'm not a great fan of managing cameras and \"debug cameras\" separately. They are inherently the same things. Just the debug camera are not considered real sensors but only used to monitor the progress of the agent / debugging. Having `camera` getting hiding debug camera by default, and keeping the... | 1 |
python | for page_num in itertools.count(2):
for a_entry, entry_id in re.findall(
r'(?s)<article[^>]+>.*?(<a[^>]+href=["\']/\d+/\d+/Artykul/(\d+)[^>]+>).*?</article>',
content):
entry = extract_attributes(a_entry)
href = entry.get('href')
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n webpage, urlh = self._download_webpage_handle(url, category_id)\r\n if PolskieRadioAuditionIE.suitable(urlh.url):\r\n return self.url_result(urlh.url, PolskieRadioAuditionIE, category_id)\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
class LpNormalization(Base):
@staticmethod
def export_l2normalizatio... | Review this code and list any quality issues. | [
{
"issue": "Would it be a good idea to also test 1d input?",
"severity": "minor",
"line": 19
}
] | 1 |
python | beam_width: int = 1
# TODO: beam search is not support for now
ratio: Optional[float] = 1.2
# the ratio of prefill sequences to decoding sequences, we do prefill step once the actual value exceeds ratio
def __init_batch_size__(self):
"""
MAX_BATCH_SIZE is set to acurately utilize the me... | Review this code and list any quality issues. | [
{
"issue": "Shouldn't `max_batch_size` be passed in the by the user?",
"severity": "major",
"line": 26
}
] | 1 |
python | If `fit_intercept` is set to False, the intercept is set to zero.
`intercept_` is of shape (1,) when the given problem is binary.
In particular, when `multi_class='multinomial'`, `intercept_`
corresponds to outcome 1 (True) and `-intercept_` corresponds to
outcome 0 (False).
n_featu... | Review this code and list any quality issues. | [
{
"issue": "same comment, no need to modify this in this PR",
"severity": "minor",
"line": 26
}
] | 1 |
python | (
(?P<type_playlist>playlists(?:/(?P<playlist_id>\d+))?) # We have a playlist
|
(?P<type_series>series) # We have a series
|
(?P<type_talk>talks) # We have a simple talk
)
(/lang/(.*?))? # The url may contain the language
/(?P<name>[\w-... | Review this code and list any quality issues. | [
{
"issue": "is this URL stable? use a regex if not",
"severity": "minor",
"line": 26
}
] | 1 |
python | self.base_costs = base_costs or []
self.supported_auth_types = supported_auth_types or set()
self._api_client_factory = api_client_factory
self._error_handler = error_handler
# Store any additional configuration
self._extra_config = kwargs
self.test_credentials_uuid = uu... | Review this code and list any quality issues. | [
{
"issue": "Why not just:\r\n```suggestion\r\n else []\r\n```\r\n?\r\n\r\nThen we don't need a separate check and also don't have to treat `\"not_configured\"` as if it's an auth type",
"severity": "critical",
"line": 26
}
] | 1 |
python | else:
self.nVersion = header.nVersion
self.hashPrevBlock = header.hashPrevBlock
self.hashMerkleRoot = header.hashMerkleRoot
self.nTime = header.nTime
self.nBits = header.nBits
self.nNonce = header.nNonce
self.sha256 = header.sha256
... | Review this code and list any quality issues. | [
{
"issue": "this sets the entire `nVersion` to `n`, not just the base? I assume the \"base\" is `nVersion & 0x000000ff`?",
"severity": "minor",
"line": 26
}
] | 1 |
python | outs, errs = await self.run_text(code=self.context.code)
logger.info(f"{outs=}")
logger.info(f"{errs=}")
context = CONTEXT.format(
code=self.context.code,
code_file_name=self.context.code_filename,
test_code=self.context.test_code,
test_file_name... | Review this code and list any quality issues. | [
{
"issue": "@staticmethod will ignore this self. is it a bug?",
"severity": "critical",
"line": 26
}
] | 1 |
python | def test_run_query(self):
task = TestRunQueryTask(table=self.table.table_id,
dataset=self.table.dataset.dataset_id)
task._BIGQUERY_CLIENT = self.bq_client
task.run()
self.assertTrue(self.bq_client.table_exists(self.table))
@attr('gcloud')
class BigQuery... | Review this code and list any quality issues. | [] | 0 |
python | uploader_id, video_id = self._match_valid_url(url).groups()
video_password = self.get_param('videopassword')
request_data = None
if video_password:
request_data = urlencode_postdata({
'password': video_password,
})
webpage = self._download_webpage... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n thumbnail = traverse_obj(video_js_data, (0, 'thumbnailUrl')) or self._og_search_thumbnail(webpage)\r\n```\r\nwhy try_get?",
"severity": "minor",
"line": 26
}
] | 1 |
python | logger.info("runner created")
event_sender.send(
RunnerStatusUpdated(runner_id=runner_id, runner_status=current_status)
)
with task_receiver as tasks:
for task in tasks:
cancelled_tasks.discard(TaskId("CANCEL_CURRENT_TASK"))
event_sender.send(
TaskStat... | Review this code and list any quality issues. | [
{
"issue": "Nice, I think it's definitely good to split these up. Not sure if we should call it inference_model, but whatever.",
"severity": "minor",
"line": 26
}
] | 1 |
python | message = traverse_obj(response, ('Value', 'Error', 'Message'), expected_type=compat_str)
if not message:
message = 'There was a error in the response: %d' % response['Status']
raise ExtractorError(message, expected=False)
return response['Value']
class VoicyIE(VoicyBas... | Review this code and list any quality issues. | [
{
"issue": "no need to match twice. you can just use `re.match(self.VALID_URL, ...)`",
"severity": "minor",
"line": 26
}
] | 1 |
python | async with self.blockchain.priority_mutex.acquire(priority=BlockchainMutexPriority.low):
if self.mempool_manager.get_spendbundle(spend_name) is not None:
self.mempool_manager.remove_seen(spend_name)
return MempoolInclusionStatus.SUCCESS, None
if self.mempool_manag... | Review this code and list any quality issues. | [
{
"issue": "I think we should be specific.\n```suggestion\n # The 2.4.3 full node, and earlier, computed the cost slightly differently.\n # They did not include byte-cost or execution cost of the quote for the puzzle.\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | raise AppUnavailableError()
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description)
except QuotaExceededError:
raise ProviderQuotaExceededError()
except ModelCurrentlyNotSupportError:
raise ProviderModelCurrentlyNotSupportError... | Review this code and list any quality issues. | [
{
"issue": "Using truthiness here skips UUID validation when the client sends an empty string (e.g., `\\\"conversation_id\\\": \\\"\\\"`), which previously would have been rejected by `reqparse` + `uuid_value`. Consider checking `is not None` (or better, modeling these fields as `UUID | None` in Pydantic so val... | 1 |
python | "qwen-7b-chat": {"prompt": 0.00084, "completion": 0.00084},
"qwen-1.8b-chat": {"prompt": 0.0, "completion": 0.0},
"baichuan2-13b-chat-v1": {"prompt": 0.0011, "completion": 0.0011},
"baichuan2-7b-chat-v1": {"prompt": 0.00084, "completion": 0.00084},
"baichuan-7b-v1": {"prompt": 0.0, "completion": 0.0},
... | Review this code and list any quality issues. | [
{
"issue": "There also doubao-xx related token cost under `TOKEN_COSTS`, you can delete it.",
"severity": "minor",
"line": 26
}
] | 1 |
python | cumulative_perf = \
[r['cumulative_perf'] for r in results if 'cumulative_perf' in r]
daily_perf = [r['daily_perf'] for r in results if 'daily_perf' in r]
capital_change_packets = \
[r['capital_change'] for r in results if 'capital_change' in r]
self.assertEqual(len(capi... | Review this code and list any quality issues. | [] | 0 |
python | def encodeArgument(s):
# Legacy code that uses byte strings
# Uncomment the following line after fixing all post processors
# assert isinstance(s, str), 'Internal error: %r should be of type %r, is %r' % (s, str, type(s))
return s if isinstance(s, str) else s.decode('ascii')
_timetuple = collections.n... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n return f'{ret}.{time.milliseconds:03.0f}' if msec else ret\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | if num_red_flag is not None and num_red_flag >= self.cfg.auto_mod_red_flags:
if m.parent_id is None:
logger.warning(
f"[AUTO MOD] Halting tree {m.message_tree_id}, initial prompt got too many red flags ({m.emojis})."
)
s... | Review this code and list any quality issues. | [
{
"issue": "Could you move this to the [TreeManagerConfiguration](https://github.com/LAION-AI/Open-Assistant/blob/main/backend/oasst_backend/config.py)? The setting then still can be set via env-variable and this setting would be handled in the same way all other TreeManager settings are handled.",
"severit... | 1 |
python | Unspecialize a column to its generic form.
This is equivalent to ``column.specialize(GENERIC)``.
"""
return self.specialize(GENERIC)
@coerce_types(currency=(str, Currency))
def fx(self, currency):
"""
Construct a currency-converted version of this column.
Param... | Review this code and list any quality issues. | [
{
"issue": "This can just be `if not self._currency_aware`. The reason I'm binding `conversion` as a local variable here is because the if-statement below exceeds 80 chars if we use `self._currency_conversion` twice.",
"severity": "minor",
"line": 26
}
] | 1 |
python | break
if self._tags:
from jina.helper import colored
req_msg = colored('fallback to default behavior', color='yellow')
if self._required:
req_msg = colored('and it is required', color='red')
err_msg = f'''Python package "{... | Review this code and list any quality issues. | [] | 0 |
python | from .niconico import (
NiconicoIE,
NiconicoPlaylistIE,
NiconicoUserIE,
NicovideoSearchDateIE,
NicovideoSearchIE,
NicovideoSearchURLIE,
)
from .ninecninemedia import NineCNineMediaIE
from .ninegag import NineGagIE
from .ninenow import NineNowIE
from .nintendo import NintendoIE
from .nitter impor... | Review this code and list any quality issues. | [] | 0 |
python | # download badge and replace url with local file
text = _parse_README_for_badge(text)
return text
# https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras
# Define package extras. These are only installed if you specify them.
# From remote, use like `pip install pytorch-lightning[dev, do... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n name=\"pytorch-lightning\",\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'url': 'https://www.eltrecetv.com.ar/el-galpon/capitulos/temporada-2023/programa-del-160923-invitado-raul-lavie/',
'only_matching': True,
}
]
def _real_extract(self, url):
slug = self._match_id(url)
webpage = self._download_webpage(url, slug)
json_all = self._search... | Review this code and list any quality issues. | [
{
"issue": "We shouldn't discard/replace the m3u8 formats, especially since 1080p is only available as an m3u8 format; we should extract the direct http mp4 formats in addition to them.\r\n\r\nAlso, it's worth trying to extract subtitles here just in case\r\n```suggestion\r\n formats, subtitles = self._e... | 1 |
python | update_modified_at=True,
update_accessed_at=True,
new_pending_request_count=0,
)
# Invalidate is_empty cache.
self._is_empty_cache = None
@override
async def add_batch_of_requests(
self,
requests: Sequence[Request],
*,... | Review this code and list any quality issues. | [
{
"issue": "Could we rename this please?\r\n\r\n```suggestion\r\n requests_to_enqueue = {}\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | Whether to show the base plane or not.
v_range
The azimuthal angle to start and end at.
u_min
The radius at the apex.
checkerboard_colors
Show checkerboard grid texture on the cone.
Examples
--------
.. manim:: ExampleCone
:save_last_frame:
class Example... | Review this code and list any quality issues. | [
{
"issue": "I suggest the following, making sure to convert it to a NumPy array later:\n```suggestion\n direction: Vector3DLike = Z_AXIS,\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | # See the License for the specific language governing permissions and
# limitations under the License.
import string
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
from oumi.core.configs.params.base_params import BaseParams
def resolve_placeholders(
text: str,
val... | Review this code and list any quality issues. | [
{
"issue": "I don't think the string library is needed here. Instead do the following:\r\n```suggestion\r\n return text.format_map(SafeDict(values_dict))\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | translation_domain = DOMAIN
translation_key = "communication_error"
class NRGkickApiClientAuthenticationError(NRGkickApiClientError):
"""Exception for NRGkick API client authentication errors."""
translation_domain = DOMAIN
translation_key = "authentication_error"
class NRGkickApiClientApiDisabledE... | Review this code and list any quality issues. | [
{
"issue": "By the way, did we talk about why not a decorator here? You can just that on every `async_turn_on` and `async_turn_off` and you'd be set",
"severity": "minor",
"line": 26
}
] | 1 |
python | if error_code == 2204:
self._verify_video_password(event_id, path='event')
continue
if error_code == 3200:
raise ExtractorError(self._REFERER_HINT, expected=True)
if error_msg := response.get('error'):
raise ... | Review this code and list any quality issues. | [
{
"issue": "missed this when refactoring; if we have `release_timestamp` then we know we have `start_time` too\r\n```suggestion\r\n self.raise_no_formats(f'This live event is scheduled for {start_time}', expected=True)\r\n```",
"severity": "major",
"line": 26
}
] | 1 |
python | @override
def idle_time(self) -> timedelta:
return datetime.now(timezone.utc) - self._last_page_opened_at
@property
@override
def has_free_capacity(self) -> bool:
return self.pages_count < self._max_open_pages_per_browser
@property
@override
def is_browser_connected(self) -... | Review this code and list any quality issues. | [
{
"issue": "We have multiple libraries that can compose URLs for us, why not use one of them? :slightly_smiling_face:",
"severity": "minor",
"line": 26
}
] | 1 |
python | logger.debug(f"chktok: {chktok}")
logger.debug(f"chkhsh: {chkhsh}")
res = None
# NOTE: if you get an error here, you need to update the convert_hf_to_gguf_update.py script
# or pull the latest version of the model from Huggingface
# don't edit the hashes manually!
... | Review this code and list any quality issues. | [
{
"issue": "Just checking; is it using the same pre-tokenizer regex as the MoE?",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'subtitles': subtitles,
**traverse_obj(video_data, ('video', {
'id': ('id', {str}),
'title': ('title', {str}),
'description': ('description', {str}),
'thumbnail': ('media', 'thumbnail', {url_or_none}),
'channel': ('channel', 'na... | Review this code and list any quality issues. | [
{
"issue": "unless there is `smuggled_data`, this will always trigger the `--no-playlist` message even if `_entries()` only yields a single entry, which is not ideal... but I don't see a better way to handle it",
"severity": "minor",
"line": 26
}
] | 1 |
python | summarized (i.e., multiple elements replaced with ``...``).
If set to ``'2.2'``, the transition to use scientific notation for
printing ``np.float16`` and ``np.float32`` types may happen later or
not at all for larger values.
If set to `False`, disables legacy mode.
Unrecogniz... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n * ``formatter`` is always reset with a call to `set_printoptions`.\r\n```\r\n\r\nThis is a preexisting issue but let's just fix it.",
"severity": "minor",
"line": 26
}
] | 1 |
python | if not traverse_obj(stream_server_data, 'llfmp4') and is_live:
self.raise_login_required(method='cookies')
def find_dmu(x):
data_movie_url = self._search_regex(
r'data-movie-url=(["\'])(?P<url>(?:(?!\1).)+)\1',
x, 'm3u8 url', group='url', default=None)
... | Review this code and list any quality issues. | [
{
"issue": "isn't this present by default? 🤔",
"severity": "minor",
"line": 26
}
] | 1 |
python | cmd_action_2 = CmdRunAction(command='ls')
state.history.append(cmd_action_2)
cmd_observation_2 = CmdOutputObservation(
command='ls', content='file1.txt\nfile2.txt'
)
# cmd_observation_2._cause = cmd_action_2._id
state.history.append(cmd_observation_2)
read_ac... | Review this code and list any quality issues. | [] | 0 |
python | if np.isnan(res) and np.isnan(exp):
return True
return res == exp
y1, y2, labels, weights = test_case
y1, y2 = np.array(y1), np.array(y2)
assert _check_equal(
cohen_kappa_score(
y1,
y2,
labels=labels,
weights=weights,
... | Review this code and list any quality issues. | [
{
"issue": "Not sure this comment is necessary\n```suggestion\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | def _validate_transcoded_datasets(catalog: DataCatalog):
"""Validates transcoded datasets are correctly named
Args:
catalog (DataCatalog): The catalog object containing the
datasets to be validated.
Raises:
ValueError: If a dataset name does not conform to the expected
tran... | Review this code and list any quality issues. | [
{
"issue": "Is this still needed now we're not freezing anything?",
"severity": "minor",
"line": 26
}
] | 1 |
python | instances of :class:`zipline.pipeline.term.Term`.
For each date between ``start_date`` and ``end_date``, ``result``
will contain a row for each asset that passed `pipeline.screen`.
A screen of ``None`` indicates that a row should be returned for
each asset that existed e... | Review this code and list any quality issues. | [
{
"issue": "If a user is going to explicitly pass None, they should probably just use `run_pipeline`.",
"severity": "minor",
"line": 26
}
] | 1 |
python | def pytest_addoption(parser: Parser) -> None:
parser.addini(
"norecursedirs",
"Directory patterns to avoid for recursion",
type="args",
default=[
"*.egg",
".*",
"_darcs",
"build",
"CVS",
"dist",
"node... | Review this code and list any quality issues. | [
{
"issue": "Is the idea that `discover_imports` is really only active if 'testpaths' is also defined in `pytest.ini`?",
"severity": "minor",
"line": 26
}
] | 1 |
python | debug_mode: Optional[bool] = None,
**kwargs: Any,
) -> Union[RunOutput, Iterator[Union[RunOutputEvent, RunOutput]]]:
"""Run the Agent and return the response."""
if self._has_async_db():
raise RuntimeError(
"`run` method is not supported with an async database. Pl... | Review this code and list any quality issues. | [
{
"issue": "Let's move it up now that we are here. Should happen before the warnings, just after the initial checks that can raise (those runs we don't want to register)",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Login
self.login(username="test2", password="password")
def test_delete_permitted(self):
response = self.client.get("/admin/tests/eventpage/delete/4/")
self.assertRedirects(response, "/admin/")
class TestModeratorAccess(TestCase, WagtailTestUtils):
fixtures = ["test_specific.json"]
... | Review this code and list any quality issues. | [
{
"issue": "Please add a new test in both test files that the back link exists and goes to the right location.",
"severity": "minor",
"line": 26
}
] | 1 |
python | satisfied.
Returns:
Any node outputs that cannot be processed by the
catalog. These are returned in a dictionary, where
the keys are defined by the node outputs.
"""
free_outputs = pipeline.outputs() - set(catalog.list())
missing = {ds for ds in cata... | Review this code and list any quality issues. | [
{
"issue": "Could we make this less specific and just return `Executor`? Both executors have the same interface and it would be nice if we just program against the interface rather than the concretes. That applies to all other places where for type hints we could just set the type as `Executor` and not the conc... | 1 |
python | from colossalai.testing import clear_cache_before_run, parameterize, rerun_if_address_is_in_use, spawn
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true"
TPSIZE = 1
BATCH_SIZE = 8
MAX_INPUT_LEN = 12
MAX_OUTPUT_LEN = 100
CUDA_SUPPORT = version.parse(torch.version.cuda) > version.parse("11.5")
@parameterize(
... | Review this code and list any quality issues. | [] | 0 |
python | with pytest.raises(TypeError):
await client.get(auth="not a tuple, not a callable") # type: ignore
with pytest.raises(TypeError):
client.auth = "not a tuple, not a callable" # type: ignore
@pytest.mark.asyncio
async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:... | Review this code and list any quality issues. | [
{
"issue": "CI is failing, I guess this should be `httpx.Client`?",
"severity": "critical",
"line": 26
}
] | 1 |
python | """Build a minimal .core_files.yaml dict."""
return {
"base_platforms": [f"homeassistant/components/{p}/**" for p in base_platforms],
}
def test_skip_specific_integrations() -> None:
"""Test that validation is skipped for specific integrations."""
config = Config(
root=Path(".").absolu... | Review this code and list any quality issues. | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.