language string | code-snippit string | instruction string | flaws list | flaw_count int64 |
|---|---|---|---|---|
python | (b"YWJj\n", b"abc", b'\n'),
(b'YWJj\nYWI=', b'abcab', b'\n'),
(b'YW\nJj', b'abc', b'\n'),
(b'YW\nJj', b'abc', bytearray(b'\n')),
(b'YW\nJj', b'abc', memoryview(b'\n')),
)
funcs = (
base64.b64decode,
base64.standa... | Review this code and list any quality issues. | [
{
"issue": "Maybe split this into two? (the alignment looks weird though)",
"severity": "major",
"line": 26
}
] | 1 |
python | if is_explicit_error:
raise HttpStatusCodeError('Error status code (user-configured) returned.', status_code)
if is_status_code_client_error(status_code) and not is_ignored_status:
raise HttpClientStatusCodeError('Client error status code returned', status_code)
if is_status_co... | Review this code and list any quality issues. | [
{
"issue": "I'd prefer to call this `check_request_collision` or something like that. Now the name sounds like it's always going to raise an error, which is not the case.",
"severity": "minor",
"line": 26
}
] | 1 |
python | DOMAIN,
data={CONF_HOST: config[CONF_HOST]},
context={"source": SOURCE_IMPORT},
)
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add sensors for passed config_entry in ... | Review this code and list any quality issues. | [
{
"issue": "we can keep importing the charger here, we don't need the full entry",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
"""A module containing build_steps method definition."""
from datashaper import DEFAULT_INPUT_NAME
from graphrag.index.config import PipelineWorkflowConfig, PipelineWorkflowStep
workflow_name = "create_base_text_units"
def build_steps(
... | Review this code and list any quality issues. | [] | 0 |
python | def test_filtered_examples_iterable_input_columns(n, func, batched, batch_size, input_columns):
base_ex_iterable = ExamplesIterable(generate_examples_fn, {"n": n})
ex_iterable = FilteredExamplesIterable(
base_ex_iterable, func, batched=batched, batch_size=batch_size, input_columns=input_columns
)
... | Review this code and list any quality issues. | [] | 0 |
python | @staticmethod
async def llm_node(
agent: Agent,
chat_ctx: llm.ChatContext,
tools: list[llm.Tool],
model_settings: ModelSettings,
) -> AsyncGenerator[llm.ChatChunk | str | FlushSentinel, None]:
"""Default implementation for `Agent.llm_node`"""
... | Review this code and list any quality issues. | [] | 0 |
python | "automatic-speech-recognition": {**MODEL_FOR_CTC_MAPPING_NAMES, **MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES},
"zero-shot-image-classification": MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES,
"image-text-to-text": MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES,
}
logger = logging.get_logger(__name__)
AUTO... | Review this code and list any quality issues. | [
{
"issue": "Is `text2text-generation` still a supported pipeline task?\nit in the current `pipeline(task=...)` supported task list.",
"severity": "minor",
"line": 26
}
] | 1 |
python | def get_rules_path():
return os.path.join(CD, "..", "rules")
def get_rule_path():
return os.path.join(get_rules_path(), "lib", "allocate-memory.yml")
@pytest.mark.parametrize(
# test detect_duplicate_features.py script for 3 cases
# - New rule isn't a valid rule
# - New rule file name doesn't en... | Review this code and list any quality issues. | [
{
"issue": "I'm afraid this could change when we update rules, so I'd say we better create a test rule set and rule like we do in the test_rules and test that here. We don't have to parametrize it and can just add it verbatim inline.",
"severity": "minor",
"line": 26
}
] | 1 |
python | if capital_change['type'] == 'target':
# Get an updated portfolio value as of this dt, but do it in a way
# so that the performance is not recalculated. This is done so
# that `process_capital_change` can find the performance values
# for the end of the subperiod, which i... | Review this code and list any quality issues. | [
{
"issue": "What's your thinking on ignoring errors here? This seems pretty serious to me.\n\nOr alternatively, what do you think of moving this validation of the given capital changes earlier in the algorithm's lifecycle so the error condition is recognized before any simulation processing?",
"severity": "... | 1 |
python | from datashaper.table_store.types import VerbResult, create_verb_result
from graphrag.index.verbs.genid import genid_df
from graphrag.index.verbs.overrides.aggregate import aggregate_df
from graphrag.index.verbs.text.chunk.text_chunk import chunk_df
@verb(name="create_base_text_units", treats_input_tables_as_immutab... | Review this code and list any quality issues. | [
{
"issue": "also this has no effect on sort, when using reset_index() if you don't assign the result or add the inplace keyword, then reset_index call will reset the index but it won't store the result anywhere",
"severity": "minor",
"line": 26
}
] | 1 |
python | self.edges = {
(u, v): edge_type(
self[u].get_center(),
self[v].get_center(),
z_index=-1,
**self._edge_config[(u, v)],
)
for (u, v) in edges
}
self.add(*self.vertices.values())
self.add(*self.edg... | Review this code and list any quality issues. | [
{
"issue": "I like these changes to `Graph` vertex creation, regardless of the changed overridden animation. I do have to admit: I don't like the amount of bending of the Animation framework that needs to be done to make custom overrides of vertex creation work. Maybe it is not worth keeping the `@override_anim... | 1 |
python | average_coef, average_offset = asgd_oneclass(klass, X3, eta, nu)
assert_allclose(clf.coef_, average_coef)
assert_allclose(clf.offset_, average_offset)
def test_sgd_oneclass():
# Test fit, decision_function, predict and score_samples on a toy
# dataset
X_train = np.array([[-2, -1], [-1, -1], [1, 1... | Review this code and list any quality issues. | [
{
"issue": "Same here, why those numbers in assert?",
"severity": "minor",
"line": 26
}
] | 1 |
python | """Feature name."""
required: bool = False
"""Whether the feature must be always present (vs optional)."""
variable_shape: bool = False
"""Whether the feature can be of variable shape.
For example, `input_ids` is normally of variable length.
"""
first_dim_action: InternalFeatureFirstDimA... | Review this code and list any quality issues. | [
{
"issue": "we don't use the term `key` for in other cases. How about we name new fields:\r\n1. `primary_image_feature` or `main_image_feature` \r\n2. `ignore_features`, `features_to_ignore`\r\n?",
"severity": "minor",
"line": 26
}
] | 1 |
python | _VALID_URL = r'https?://space\.bilibili\.com/(?P<id>\d+)(?P<video>/video)?/?(?:[?#]|$)'
_TESTS = [{
'url': 'https://space.bilibili.com/3985676/video',
'info_dict': {
'id': '3985676',
},
'playlist_mincount': 178,
}]
def _real_extract(self, url):
playlist_i... | Review this code and list any quality issues. | [
{
"issue": "Dont print whole response. Put the relevent parts into the error message",
"severity": "minor",
"line": 26
}
] | 1 |
python | """Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this
function will catch it and raise a :exc:`Abort` exception.
:param text: the question to ask.
:param default: The default value to use when no input is given. If
``None``, repeat until... | Review this code and list any quality issues. | [
{
"issue": "Don't translate these, they're related to the literal characters that need to be input.",
"severity": "minor",
"line": 26
}
] | 1 |
python | }
]
def _get_video_thumbnails(self, image_data):
thumb_data = []
for image in image_data.get('16:9') or []:
thumb_data.append({
'url': traverse_obj(image, ('url', ...), get_all=False),
'width': image.get('width'),
'height': image.get('... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'thumbnails': [{\r\n 'url': traverse_obj(image, ('url', ...), get_all=False),\r\n 'width': image.get('width'),\r\n 'height': image.get('height')\r\n } for image in traverse_ob... | 1 |
python | # Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n\"\"\"Package for the Taipy Rest API.\"\"\"\r\n```",
"severity": "minor",
"line": 11
}
] | 1 |
python | "status_display": workflow_state.get_status_display,
}
if workflow_state.status == "needs_changes":
return _("Changes requested %(finished_at)s") % translation_context
if workflow_state.status == "in_progress":
return _("Sent to %(task_name)s %(started_at)s") % translation_context
ret... | Review this code and list any quality issues. | [
{
"issue": "The mac wording for this label is \"Paste and Match Style\".\r\n\r\nNot sure how close we want to stay to OS style icons/wording.",
"severity": "minor",
"line": 26
}
] | 1 |
python | webpage, default=None) or self._html_search_meta(
'description', webpage, default=None))
upload_date = unified_strdate(self._search_regex(
r'<input type="hidden" id="air_date_[0-9]+" value="([^"]+)"',
webpage, 'upload date', default=None))
# tabbe... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n r'\\\\\"videoTPMediaId\\\\\":\\\\\\\"(\\d+)\\\\\"', # Next.js v13, e.g. https://www.pbs.org/video/caregiving\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | def __init__(self, *arguments, **kwargs):
super().__init__(*arguments, directory=self.static_directory, **kwargs)
def end_headers(self):
if hasattr(self, "_extra_headers"):
for key, value in self._extra_headers.items():
self.send_header(key, value)
del self._... | Review this code and list any quality issues. | [
{
"issue": "How does this handle `.headers` files that have multiple headers with the same name (for example: `content-security-policy/generic/no-default-src.sub.html.sub.headers`)?",
"severity": "critical",
"line": 26
}
] | 1 |
python | from cognee.modules.pipelines.layers.check_pipeline_run_qualification import (
check_pipeline_run_qualification,
)
logger = get_logger("cognee.pipeline")
update_status_lock = asyncio.Lock()
async def run_pipeline(
tasks: list[Task],
data=None,
datasets: Union[str, list[str], list[UUID]] = None,
... | Review this code and list any quality issues. | [] | 0 |
python | @pytest.mark.parametrize(
"mode, expected_output, expectation",
[
pytest.param(
JUPYTER_MODE,
"%%custom_python_magic -n1 -n2\nx=2",
pytest.raises(NothingChanged),
id="No change when cell magic not registered",
),
pytest.param(
r... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n mode: Mode, expected_output: str, expectation: ContextManager[object]\r\n```\r\nAvoid Any if possible. `object` makes sense if you don't want to do anything with the object.",
"severity": "minor",
"line": 26
}
] | 1 |
python | video_id = self._match_id(url)
json_data = self._call_api(f'match/{video_id}', video_id)
formats = []
for video in traverse_obj(json_data, ('videos', 0, 'qualities', lambda _, v: v['cloud_front_path'])):
formats.append(traverse_obj(video, {
'url': ('cloud_front_path',... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n data['title'] = join_nonempty(\r\n join_nonempty(*teams, delim='-'),\r\n strftime_or_none(data.get('timestamp'), '%Y-%m-%d'),\r\n delim=' ')\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | if stopped_speaking_at and started_speaking_at:
assistant_metrics["started_speaking_at"] = started_speaking_at
assistant_metrics["stopped_speaking_at"] = stopped_speaking_at
msg = llm.ChatMessage(
role="assistant",
content=[forwarded_text],
... | Review this code and list any quality issues. | [
{
"issue": "we can probably remove this line",
"severity": "major",
"line": 26
}
] | 1 |
python | clf = LogisticRegression().fit(X, y)
disp = DecisionBoundaryDisplay.from_estimator(
clf,
X,
response_method=response_method,
plot_method=plot_method,
multiclass_colors=multiclass_colors,
)
if multiclass_colors is None:
if len(clf.classes_) <= 10:
... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n # Part of a non-regression test for issue #32866 to make sure the colormap \r\n # used has enough distinct colors.\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | audio_track = fmt_stream.get('audioTrack') or {}
display_name = audio_track.get('displayName') or ''
language_code = audio_track.get('id', '').split('.')[0] or None
if 'descriptive' in display_name.lower():
return join_nonempty(language_code, 'desc'), -10
... | Review this code and list any quality issues. | [
{
"issue": "I would be in favor of just removing this extractor-arg",
"severity": "major",
"line": 26
}
] | 1 |
python | """
hostname = urlparse(url).hostname
if not hostname:
# Unable find hostname in url
return True
ip = socket.gethostbyname(hostname)
return ipaddress.ip_address(ip).is_private
def clear_filename(filename: str) -> str:
"""
Removes path symbols from filename which could be used ... | Review this code and list any quality issues. | [
{
"issue": "I would name it 'get_url_origin'\r\nAlso it can return f'{scheme}://{netloc}', the behavior will be the same",
"severity": "minor",
"line": 26
}
] | 1 |
python | return result
def create_all_state(
increment: int,
total_number: int,
level: int,
current_list: list[int],
total_list: list[list[int]],
) -> None:
if level == 0:
total_list.append(current_list[:])
return
for i in range(increment, total_number - level + 2):
current... | Review this code and list any quality issues. | [
{
"issue": "I personally don't like how this helper function modifies an input argument rather than returning a new list, but that's not an issue with this PR and should be left for future work.",
"severity": "major",
"line": 26
}
] | 1 |
python | def _set_oauth_info(self, token_response, profile):
YoutubeBaseInfoExtractor._OAUTH_ACCESS_TOKEN_CACHE.setdefault(profile, {}).update({
'access_token': token_response['access_token'],
'token_type': token_response['token_type'],
'expiry': time_seconds(
seconds=... | Review this code and list any quality issues. | [
{
"issue": "I like the cmd.exe error correction here for sanity reasons, maybe we could condense though\r\n```suggestion\r\n # Allow refresh token passed to initialize cache\r\n if refresh_token and refresh_token.strip('\\''):\r\n```",
"severity": "major",
"line": 26
}
] | 1 |
python | if stream_type == 'dash':
dash_formats = self._extract_mpd_formats(
format_url, video_id, mpd_id='dash-%s' % quality, headers={'Referer': url})
for frmt in dash_formats:
frmt['quality'] = get_quality(quality)
formats.extend(dash_for... | Review this code and list any quality issues. | [
{
"issue": "If `display_id` is never being used, don't capture it",
"severity": "minor",
"line": 26
}
] | 1 |
python | self._sponsor_chapter(70, 90, 'sponsor', remove=True),
self._chapter(80, 100, remove=True),
self._chapter(90, 110, remove=True),
self._sponsor_chapter(120, 140, 'sponsor', remove=True),
self._sponsor_chapter(130, 160, 'selfpromo', remove=True),
self._chapter(1... | Review this code and list any quality issues. | [] | 0 |
python | bf.seek(b2_start)
bf.write(b[b3_start:b4_start])
bf.write(b[b2_start:b3_start])
# The reindexing code should detect and accommodate out of order blocks.
with self.nodes[0].assert_debug_log([
'LoadExternalBlockFile: Out of order block',
'LoadExternalBlockF... | Review this code and list any quality issues. | [
{
"issue": "Any reason to put the stop under the busy loop here?",
"severity": "minor",
"line": 26
}
] | 1 |
python | tm.assert_series_equal(left.eq(np_a), left == np_a)
pd_s = pd.Series(py_l)
tm.assert_series_equal(left.eq(pd_s), left == pd_s)
left_non_scalar = pd.Series([[1, 2], [3, 4]])
with pytest.raises(AssertionError):
tm.assert_series_equal(left_non_scalar.eq([1, 2]), pd.Series([True, False]))
def te... | Review this code and list any quality issues. | [
{
"issue": "This test does not belong here and is already tested for elsewhere; can you remove.",
"severity": "minor",
"line": 26
}
] | 1 |
python | @staticmethod
def _extract_url(webpage):
mobj = re.search(
r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//out\.pladform\.ru/player\?.+?)\1', webpage)
if mobj:
return mobj.group('url')
def _real_extract(self, url):
video_id = self._match_id(url)
qs = pars... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n targetUrl = self._request_webpage(HEADRequest(url), video_id, note='Resolving final URL').geturl()\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | gs.morphs.Box(
size=(0.5, 0.5, 0.5),
pos=(0.0, 0.0, 1.5),
contype=1,
conaffinity=1,
)
)
scene.build()
for _ in range(100):
scene.step()
assert_allclose(box2.get_pos(), box3.get_pos(), atol=1e-3)
assert_allclose(box1.get_pos(), np.arra... | Review this code and list any quality issues. | [
{
"issue": "Yes, that would be great to find out what is happening here.",
"severity": "minor",
"line": 26
}
] | 1 |
python | expr = pl.element().struct.field("b")
# select
q = ldf.select(x=pl.col("a").list.eval(expr))
expected = pl.Series("x", [[5, 5], [5]])
assert_series_equal(q.collect().to_series(), expected)
assert q.collect_schema() == q.collect().schema
# group_by
q = ldf.group_by("id").agg(x=pl.col("a").l... | Review this code and list any quality issues. | [] | 0 |
python | misc.check_externally_managed = check_externally_managed
"""
)
@pytest.mark.parametrize(
"arguments",
[
pytest.param(["install"], id="install"),
pytest.param(["install", "--user"], id="install-user"),
pytest.param(["install", "--dry-run"], id="install-dry-run"),
pyt... | Review this code and list any quality issues. | [
{
"issue": "This case should be dropped from the test, I think.",
"severity": "minor",
"line": 26
}
] | 1 |
python | [
(MINUTELY, 15),
(MINUTELY, 120),
(MINUTELY, 60 * 24 * 3),
(HOURLY, 7),
(HOURLY, 24 * 3),
],
)
def test_fast_forward_date(freq, interval):
'''
Assert that the resulting fast forwarded date is included in the original rrule
occurrence list
'''
dtstart = no... | Review this code and list any quality issues. | [
{
"issue": "Any reason it's not\r\n```suggestion\r\n assert new_datetime in gen\r\n```\r\n?",
"severity": "minor",
"line": 26
}
] | 1 |
python | >>> b = a.copy()
>>> a.real = np.nan
>>> b.imag = np.nan
>>> np.array_equal(a, b, equal_nan=True)
True
"""
try:
a1, a2 = asarray(a1), asarray(a2)
except Exception:
return False
if a1.shape != a2.shape:
return False
if not equal_nan:
return builtins.boo... | Review this code and list any quality issues. | [
{
"issue": "No need for a comment about previous code versions",
"severity": "minor",
"line": 26
}
] | 1 |
python | pad_value: the filled value for padding. We need to pad the input before filtering to keep the output with the same size as input. Usually use default value and not changed.
Return:
dilated mask, [N,C,M,N] or [N,C,M,N,P] torch tensor or ndarray.
Example:
.. code-block:: python
# ... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n Apply a morphological filter to a 2D/3D binary mask tensor.\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | def _ParseKeywordArgs(args, fn_args, fn_keywords):
"""Parses the supplied arguments for keyword arguments.
Given a list of arguments, finds occurences of --name value, and uses 'name'
as the keyword and 'value' as the value. Constructs and returns a dictionary
of these keyword arguments, and returns a list of ... | Review this code and list any quality issues. | [
{
"issue": "- Please update the Returns: section of the docstring.\r\n- Also how about \"remaining_kwargs\" instead of unconsumed_named_args for consistency with the existing terminology?",
"severity": "minor",
"line": 26
}
] | 1 |
python | import copy
import csv
import os
from typing import Dict, List
import json
from colossalai.logging import DistributedLogger
from .base import BaseDataset
lang2files = {'Chinese': ["dev_zh.json", "test_zh.json"],
'English': ["dev_en.json", "test_en.json"]}
lang2inst = {'English': 'The following are mul... | Review this code and list any quality issues. | [
{
"issue": "Please refer to `applications/ColossalEval/colossal_eval/dataset/safetybench_en.py` for comments.",
"severity": "minor",
"line": 5
}
] | 1 |
python | def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.ndarray:
"""Generate a mask from a polygon.
Args:
polygon (np.ndarray): The polygon for which the mask should be generated,
given as a list of vertices.
resolution_wh (Tuple[int, int]): The width and heig... | Review this code and list any quality issues. | [
{
"issue": "After addressing https://github.com/roboflow/supervision/pull/1874/files#r2202860137, please ensure to update the args description as well.",
"severity": "minor",
"line": 26
}
] | 1 |
python | pl.Series("OR", [0x7D], dtype),
pl.Series("XOR", [0x6D], dtype),
]
),
)
@pytest.mark.parametrize("dtype", INTEGER_DTYPES)
def test_bit_aggregations_lazy_no_nulls(dtype: pl.DataType) -> None:
s = pl.Series("a", [0x74, 0x1C, 0x05], dtype)
lf = s.to_frame().lazy()
ou... | Review this code and list any quality issues. | [] | 0 |
python | 'getcomments': True,
'skip_download': True,
'ignore_no_formats_error': True,
},
},
]
def _extract_vars(self, variable, html):
return self._search_regex(
rf'(?:var|const)\s+{variable}\s*=\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
htm... | Review this code and list any quality issues. | [
{
"issue": "That appended date is just for cache busting. Imo. we don't need to extract the exact date the website uses from the HTML.\r\n\r\nActually, since the APIKEY has been unchanged [since 2022](https://web.archive.org/web/20221208024332id_/https://player.pia-live.jp/statics/js/s_prod?202211082), I'd just... | 1 |
python | import uuid
import pytest
import requests
from pathlib import Path
from e2e_tests.conftest import QdrantContainerConfig
from e2e_tests.client_utils import ClientUtils
from e2e_tests.utils import extract_archive
class TestStorageCompatibility:
"""Test storage and snapshot compatibility with defined previous Qdra... | Review this code and list any quality issues. | [
{
"issue": "```\nUsing existing Docker image qdrant/qdrant:e2e-tests\nDownloading compatibility data for v1.15.0...\nExtracted /home/agourlay/Workspace/qdrant/tests/e2e_tests/test_storage_compatibility[v1.15.0]/storage/compatibility_v1.15.0_52880638.tar to /home/agourlay/Workspace/qdrant/tests/e2e_tests/test_st... | 1 |
python | else:
errors = str(exc)
response_content = {
"message": f"Invalid data for {request.method} {request.url.path}",
"detail": errors,
"hint": "Ensure the request matches the API schema.",
}
content_json = json.dumps(response_content)
return fastapi.responses.Response(
... | Review this code and list any quality issues. | [
{
"issue": "@majdyz I'm not sure we want to do this. What do you think?",
"severity": "minor",
"line": 26
}
] | 1 |
python | self.assertEqual(res, TIER2_THRESHOLD * 3)
self.assertIsNotNone(ex)
uops_and_operands = [(opcode, operand) for opcode, _, _, operand in ex]
uop_names = [uop[0] for uop in uops_and_operands]
self.assertEqual(uop_names.count("_PUSH_FRAME"), 15)
self.assertEqual(uop_names.count("_R... | Review this code and list any quality issues. | [
{
"issue": "Is it still necessary to retain these tests? I thinks these tests primarily test the logic on converting multiple `_CHECK_STACK_SPACEs` into a single `_CHECK_STACK_SPACE_OPERAND`.",
"severity": "minor",
"line": 26
}
] | 1 |
python | """All data required for testing examples"""
import pytest
from .support import Logger
@pytest.fixture(scope="session")
def logger():
return Logger() | Review this code and list any quality issues. | [] | 0 |
python | if changed is not Changed.CACHED and format_file_in_place(
src, fast=fast, write_back=write_back, mode=mode
):
changed = Changed.YES
if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
write_back is WriteBack.CHECK and changed i... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n worker_count: int = os.cpu_count(),\r\n```\r\n\r\nThis way we could just explicitly send in the worker_count as an argument.\r\n\r\nOnly worry is potentially people using the API could break - so a default argument helps there ...",
"severity": "minor",
"line": 26
}
] | 1 |
python | log_error(f"Error getting component: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.patch(
"/components/{component_id}",
response_model=ComponentResponse,
response_model_exclude_none=True,
status_code=200,
operation_id="update_... | Review this code and list any quality issues. | [] | 0 |
python | # Test the IPv6 address.
res = self.nodes[0].getnodeaddresses(0, "ipv6")
assert_equal(len(res), 1)
assert_equal(res[0]["address"], ipv6_addr)
assert_equal(res[0]["network"], "ipv6")
assert_equal(res[0]["port"], 8333)
assert_equal(res[0]["services"], P2P_SERVICES)
... | Review this code and list any quality issues. | [
{
"issue": "these init params are added here, but are only relevant until a couple subtests later in `test_getaddrmaninfo`. having unrelated init params can lead to unexpected behaviors, like in this recent [example](https://github.com/bitcoin/bitcoin/pull/28538#discussion_r1423241016). implicit dependencies be... | 1 |
python | result = await transport.handle_async_request(request)
assert result is mock_response_success
assert mock_transport.handle_async_request.call_count == 2
# Verify that the request was set on the failed response before raise_for_status was called
assert mock_response_fail.request is reque... | Review this code and list any quality issues. | [] | 0 |
python | self._kernel_rrt_step1(
q_limit_lower=self._entity.q_limit[0],
q_limit_upper=self._entity.q_limit[1],
envs_idx=envs_idx,
)
if is_plan_with_obj:
self.update_object(ee_link_idx, obj_link_idx, _pos, _quat, envs_... | Review this code and list any quality issues. | [] | 0 |
python | 'upload_date': '20101020',
'thumbnail': 'https://s1.dmcdn.net/v/SaMes1WfAm1d6maq_/x720',
'uploader': 'Moviepilot',
'like_count': int,
'view_count': int,
'tags': ['Alle Trailer', 'Movie', 'Verleih'],
'uploader_id': 'x6nd9k',
},
}]
d... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n duration = try_get(\r\n re.match(r'P(?P<hours>\\d+)H(?P<mins>\\d+)M(?P<secs>\\d+)S',\r\n self._html_search_meta('duration', webpage, fatal=False) or ''),\r\n lambda mobj: sum(float(x) * y for x, y in zip(mobj.groups(), (3600, 60, 1))... | 1 |
python | if config["preview"]:
self.window = Window(self)
self.context = self.window.ctx
self.frame_buffer_object = self.context.detect_framebuffer()
else:
self.window = None
self.context = moderngl.create_standalone_context()
... | Review this code and list any quality issues. | [] | 0 |
python | display_id = enc_id(program)
date_str = self._search_regex(
rf'{program_id}0?(\d{{6}})', m3u8_url, 'date string', default=None)
return {
'display_id': display_id,
'formats': self._extract_m3u8_formats(m3u8_url, raw_id, headers=self._HEADERS),
'http_header... | Review this code and list any quality issues. | [
{
"issue": "same\r\n```suggestion\r\n 'tags': ('hashtag_list', ..., {str}, filter),\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | """
return self._get_catalog()
@property
def params(self) -> dict[str, Any]:
"""Read-only property referring to Kedro's parameters for this context.
Returns:
Parameters defined in `parameters.yml` with the addition of any
extra parameters passed at initializ... | Review this code and list any quality issues. | [
{
"issue": "Is there a reason why this needs to be converted to an OmegaConf object? I think `OmegaConf.merge()` also works on plain dicts? I also don't think `resolve=True` is necessary, the `extra_params` shouldn't have any interpolation and `params` will already be resolved.",
"severity": "minor",
"l... | 1 |
python | except AssertionError:
llevel = left.get_level_values(level)
rlevel = right.get_level_values(level)
assert_index_equal(
llevel,
rlevel,
exact=exact,
check_names=check_names,
... | Review this code and list any quality issues. | [
{
"issue": "Can you use `isinstance` checks to call `_internal_get_values` if the object is a `CategoricalIndex`?",
"severity": "minor",
"line": 26
}
] | 1 |
python | from uuid import UUID
from typing import Optional
from cognee.infrastructure.databases.vector.create_vector_engine import create_vector_engine
from cognee.modules.users.models import User
from cognee.modules.users.models import DatasetDatabase
from cognee.infrastructure.databases.vector import get_vectordb_config
from... | Review this code and list any quality issues. | [
{
"issue": "This is not enough, this will only remove tables and data from a database in PostgreSQL we should remove the whole database here",
"severity": "minor",
"line": 26
}
] | 1 |
python | # ROCm
# ============================================================
elif has_working_rocm() and has_amd_gpu_pci():
version = ''
msg = ''
if os.name == 'posix':
for p in (
'/opt/rocm/.info/version',
... | Review this code and list any quality issues. | [] | 0 |
python | async def test_none_map_select(
hass: HomeAssistant,
mock_roborock_entry: MockConfigEntry,
fake_vacuum: FakeDevice,
) -> None:
"""Test that the select entity correctly handles not having a current map."""
# Set map status to None so that current map is never set
fake_vacuum.v1_properties.home.cu... | Review this code and list any quality issues. | [] | 0 |
python | from .common import InfoExtractor
from ..utils import (
ExtractorError,
UserNotLive,
int_or_none,
traverse_obj,
unified_strdate,
url_or_none,
urlencode_postdata,
)
class PandatvLiveIE(InfoExtractor):
_VALID_URL = r'(?P<base_url>https?://(?:www\.|m\.)?pandalive\.co\.kr)/play/(?P<id>[\da... | Review this code and list any quality issues. | [
{
"issue": "- is the site called \"PandaTV\"? or \"PandaLive\"? Calling the extractor \"PandatvLive\" seems confusing\r\n\r\n- Since we never actually request the webpage, matching the origin from the input URL is pointless, we can just hardcode `https://www.pandalive.co.kr` below\r\n\r\n- Are you sure there's... | 1 |
python | 'info_dict': {
'id': 'as-minhas-coisas-favoritas',
'title': 'As Minhas Coisas Favoritas',
},
'playlist_mincount': 131
}, {
'url': 'https://radiocomercial.pt/podcasts/tnt-todos-no-top/t2023',
'info_dict': {
'id': 'tnt-todos-no-top_t2023',
... | Review this code and list any quality issues. | [
{
"issue": "on second look, doing this is simpler and safer\r\n```suggestion\r\n webpage = self._download_webpage(\r\n f'{url}/{page}', playlist_id, f'Downloading page {page}')\r\n except ExtractorError as e:\r\n if isinstance(e.cause, HTTPError) and e... | 1 |
python | return self.view(
type=ndarray,
dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),
)
def as_string_array(self):
"""
Convert self back into an array of strings.
This is an O(N) operation.
"""
return self.categories[self.as_int_array()... | Review this code and list any quality issues. | [] | 0 |
python | # STORM is a LM system so different components can be powered by different models.
# For a good balance between cost and quality, you can choose a cheaper/faster model for conv_simulator_lm
# which is used to split queries, synthesize answers in the conversation. We recommend using stronger models
# for out... | Review this code and list any quality issues. | [] | 0 |
python | f"'{op_name}' operations between boolean dtype and {self.dtype} are "
"deprecated and will raise in a future version. Explicitly "
"cast the strings to a boolean dtype before operating instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)... | Review this code and list any quality issues. | [
{
"issue": "Can you change this example to show string data?",
"severity": "minor",
"line": 26
}
] | 1 |
python | import platform
from distutils.version import LooseVersion
from importlib.util import find_spec
import pkg_resources
import torch
def _module_available(module_path: str) -> bool:
"""
Check if a path is available in your environment
>>> _module_available('os')
True
>>> _module_available('bla.bla'... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n\r\n\r\ndef _get_version(package: str) -> LooseVersion:\r\n return LooseVersion(pkg_resources.get_distribution(package).version)\r\n\r\n\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | 'info_dict': {
'id': 'gy35PKLHe-5K29RYHga2bw',
'ext': 'mp4',
'title': 'Ett starkare samhälle - en snabbguide om Sveriges folkhögskolor',
'thumbnail': r're:^https?://.+\.jpg',
},
},
{
'url': 'https://play.su.se/media/... | Review this code and list any quality issues. | [
{
"issue": "```py\r\n video_id, ext=...)\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | import contextlib
from collections import namedtuple, deque
import datetime
from decimal import Decimal
from functools import partial
import gc
import inspect
import io
from itertools import product
import platform
import sys
from types import SimpleNamespace
import dateutil.tz
import numpy as np
from numpy import ma... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\nfrom types import SimpleNamespace\nimport unittest.mock\n```",
"severity": "minor",
"line": 12
}
] | 1 |
python | webpage = self._download_webpage(url, None, note='Getting video ID')
url = self._search_regex(self._VALID_URL, webpage, 'redirection url', group='url')
url = self._request_webpage(url, None, note='Resolving final URL').geturl()
mobj = self._match_valid_url(url)
subdomain = mobj.group... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n if password:\r\n raise ExtractorError('Wrong password', expected=True)\r\n raise ExtractorError(\r\n 'This video is protected by a password, use the --video-password option', expected=True)\r\n```",
"severity":... | 1 |
python | """Add session_api_key_hash to v1_remote_sandbox table
Revision ID: 097
Revises: 096
Create Date: 2025-02-24 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = '097'
down_revision: Union[str, None] = '096'
b... | Review this code and list any quality issues. | [] | 0 |
python | Kwargs:
wait_for_connect: if True, block until the nodes are verified as connected. You might
want to disable this when using -stopatheight with one of the connected nodes,
since there will be a race between the actual connection and performing
the assertions ... | Review this code and list any quality issues. | [
{
"issue": "Looking at the sample output of `subversion` - `\"subversion\": \"\\/Satoshi:25.1.0\\/\"`, it doesn't seem unique enough because multiple nodes can be running the same version. Won't this cause issues in `find_conn` later?\r\n\r\nhttps://chainquery.com/bitcoin-cli/getnetworkinfo",
"severity": "m... | 1 |
python | coin_hints: dict[bytes32, bytes32] = {
coin_id: bytes32(hint) for coin_id, hint in ppp_result.hints if len(hint) == 32
}
peak = Peak(
state_change_summary.peak.header_hash, state_change_summary.peak.height, state_change_summary.peak.weight
)
# Looks up coin reco... | Review this code and list any quality issues. | [
{
"issue": "I would have thought we'd want this early in this function, to minimize the reordering of these things",
"severity": "minor",
"line": 26
}
] | 1 |
python | dataset_kwargs = copy.deepcopy(dataset_kwargs) if dataset_kwargs is not None else {}
if processor_name:
dataset_kwargs["processor_name"] = processor_name
dataset = dataset_class(
dataset_name=dataset_name,
dataset_path=dataset_path,
split=dataset_split,
subset=dataset_su... | Review this code and list any quality issues. | [
{
"issue": "Food for thought here: should you add a check for an empty input? I think `_split_message_list_on_user([])` should return `[]` not `[ [] ]`",
"severity": "minor",
"line": 26
}
] | 1 |
python | metric=metric,
metric_kwargs=metric_kwargs,
strategy="auto",
return_distance=False,
)
indices = indices.flatten()
else:
# Joblib-based backend, which is used when user-defined callable
# are passed for metric.
# This won't be used in the f... | Review this code and list any quality issues. | [
{
"issue": "Is it safe to assume that any array namespace will have the `concat` method? If so, it makes the fallback unnecessary and I'll remove it. Requesting confirmation from a reviewer",
"severity": "minor",
"line": 26
}
] | 1 |
python | def test_empty_checkpoints_macro(self):
empty_checkpoints = pd.DataFrame({
'value': [],
'asof_date': [],
'timestamp': [],
})
self._test_checkpoints_macro(empty_checkpoints)
def test_checkpoints_out_of_bounds_macro(self):
# provide two checkpoints... | Review this code and list any quality issues. | [
{
"issue": "It's not clear to me how these values are connected to the description in the comment above. What's enforcing that this is the leading data query cutoff time of the query we're going to make? Are these just the values that `test_checkpoints_*` uses by default? If so, it might help clarify to lift th... | 1 |
python | tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
num_experts_per_tok (`int`, *optional*, defaults to 1):
Number ... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\n attention_dropout (`float`, *optional*, defaults to 0.0):\n Dropout rate on vision attention probabilities. Higher value adds more regularization.\n num_experts_per_tok (`int`, *optional*, defaults to 1):\n Top-k experts routed per token. Higher va... | 1 |
python | shape: (2, 2)
┌─────┬─────┐
│ b ┆ a │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 3 │
│ 2 ┆ 4 │
└─────┴─────┘
>>> lf.pipe(lambda lf: lf.select(sorted(lf.collect_schema()))).collect()
shape: (2, 2)
┌─────┬─────┐
... | Review this code and list any quality issues. | [
{
"issue": "I think it is important that we provide some kind of `*args` or `**kwargs` but I am a bit worried about doing it this way because we cannot ever add any parameters to it.\r\n\r\nE.g. if we want to add a `metadata` argument that we can pass in to the function (for #5117), we would now no longer be ab... | 1 |
python | expect_code(run_verify('--min-good-sigs 20', "pub", "22.0"), 9, "--min-good-sigs 20 should fail")
print("- testing verification (22.0-x86_64-linux-gnu.tar.gz)", flush=True)
_220_x86_64_linux_gnu = run_verify("--json", "pub", "22.0-x86_64-linux-gnu.tar.gz")
try:
result = json.loads(_220_x86_64_linux... | Review this code and list any quality issues. | [] | 0 |
python | parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars,
help="Whitelist given cars from the test (e.g. HONDA)")
parser.add_argument("--blacklist-procs", type=str, nargs="*", default=[],
help="Blacklist given processes from the test (e.g. controlsd)")
... | Review this code and list any quality issues. | [
{
"issue": "same, won't it always hit except? if it's for you to manually test against a commit, should be an argument not file",
"severity": "minor",
"line": 26
}
] | 1 |
python | js.console.log("config name:", config.name)
</py-script>
"""
)
assert self.console.log.lines[-1] == "config name: app with external config"
# The default pyodide version is 0.21.2 as of writing
# this test which is newer than the one we are loading below
# (after downloading... | Review this code and list any quality issues. | [
{
"issue": "@tedpatrick IMO, we shouldn't remove this test. The reason is that we want to check if passing a runtime from a local path works instead of a hosted one. This is useful when you have the pyodide distribution downloaded and are without an internet access.\r\n\r\nHere, we check for `0.20` as another s... | 1 |
python | "isArmed": False,
}
assert trt.can_execute(trait.COMMAND_ARM_DISARM, {"arm": False})
calls = async_mock_service(
hass, alarm_control_panel.DOMAIN, alarm_control_panel.SERVICE_ALARM_DISARM
)
# Test without secure_pin configured
trt = trait.ArmDisArmTrait(
hass,
State(
... | Review this code and list any quality issues. | [] | 0 |
python | import redis.asyncio as redis
from oasst_inference_server.settings import settings
class RedisQueue:
def __init__(
self,
redis_client: redis.Redis,
queue_id: str,
expire: int | None = None,
with_counter: bool = False,
counter_pos_expire: int = 1,
) -> None:
... | Review this code and list any quality issues. | [
{
"issue": "This is type hinted to return `None` but may not",
"severity": "minor",
"line": 20
}
] | 1 |
python | file="meshes/duck.obj",
scale=second_scale,
pos=(1.0, 0, 1.0),
quat=(1, 0, 0, 0),
),
)
scene.build()
assert len(seen_paths) == 2, "Expected 2 cache paths, got %d" % len(seen_paths)
assert len(seen_results) == 2, "Expected 2 convex decomposition results, got %... | Review this code and list any quality issues. | [
{
"issue": "You have `assert_array_equal` for this but no big deal.",
"severity": "minor",
"line": 26
}
] | 1 |
python | return TakeExamplesIterable(
self.ex_iterable.shard_data_sources(worker_id, num_workers),
n=self.split_number(self.n, num_workers)[worker_id],
block_sources_order_when_shuffling=self.block_sources_order_when_shuffling,
split_when_sharding=self.split_when_s... | Review this code and list any quality issues. | [] | 0 |
python | exclude=exclude,
extend_exclude=extend_exclude,
force_exclude=force_exclude,
report=report,
stdin_filename=stdin_filename,
)
path_empty(
sources,
"No Python files are present to be formatted. Nothing to do 😴",
quiet,
... | Review this code and list any quality issues. | [
{
"issue": "This is a bit unrelated but noticed that styling isn't used here, so I changed it.",
"severity": "minor",
"line": 26
}
] | 1 |
python | def test_norm():
# Maximum "n" which is tested:
n_max = 2 # it works, but is slow, for n_max > 2
for n in range(n_max + 1):
for l in range(n):
assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1
def test_psi_nlm():
r=S('r')
phi=S('phi')
theta=S('theta')
assert (P... | Review this code and list any quality issues. | [] | 0 |
python | ---
import useBaseUrl from '@docusaurus/useBaseUrl';
''' + '\n' + '\n\n'.join([make_gallery_thumbnail(e) for e in examples])
def main():
filenames = [line.strip() for line in read_lines(os.path.join(example_dir, 'tour.conf')) if
not line.strip().startswith('#')]
examples = [load_example(fil... | Review this code and list any quality issues. | [
{
"issue": "It would be good to preserve the gallery page as-is, and add a new page for the ToC.",
"severity": "minor",
"line": 26
}
] | 1 |
python | yield self.url_result(f'https://www.bilibili.com/video/{bvid}', BiliBiliIE, bvid)
def _get_uploader(self, uid, playlist_id):
webpage = self._download_webpage(f'https://space.bilibili.com/{uid}', playlist_id, fatal=False)
return self._search_regex(r'(?s)<title\b[^>]*>([^<]+)的个人空间-', webpage, 'upload... | Review this code and list any quality issues. | [
{
"issue": "```suggestion\r\n 'thumbnail': 'https://archive.biliimg.com/bfs/archive/e0e543ae35ad3df863ea7dea526bc32e70f4c091.jpg',\r\n```",
"severity": "minor",
"line": 26
}
] | 1 |
python | # Drop the node -datadir= argument during this test, because if it is
# specified it would take precedence over the datadir setting in the
# config file.
node_args = node.args
node.args = [arg for arg in node.args if not arg.startswith("-datadir=")]
# Check that correct configur... | Review this code and list any quality issues. | [
{
"issue": "In commit \"init: fix fatal error on '-wallet' negated option value\" (0df52e24363f729210887ca20a47824ba8073617)\r\n\r\nI think this should be extended to test `-nowallet=0`. Maybe consider making this a loop to test both `-nowallet=0` `-nowallet=not_a_boolean`.\r\n\r\nReason: the simplest and most ... | 1 |
python | from pydantic_settings import BaseSettings
class GroqHandlerConfig(BaseSettings):
"""
Configuration for Groq handler.
Attributes
----------
BASE_URL : str
Base URL for the Groq API.
DEFAULT_MODEL : str
Default model to use for Groq API.
DEFAULT_MODE : str
Default ... | Review this code and list any quality issues. | [] | 0 |
python | class RunJobTests(test_utils.GenericTestBase):
def test_working_sync_job(self) -> None:
run = jobs_manager.run_job(WorkingJob, True, namespace=self.namespace)
self.assertEqual(run.latest_job_state, 'DONE')
run_model = beam_job_models.BeamJobRunModel.get(run.id)
self.assertEqual(ru... | Review this code and list any quality issues. | [] | 0 |
python | "This caused the following error: "
"TypeError(\"unhashable type: 'dict'\",)."
)
self.assertEqual(errmsg, expected)
@parameter_space(
__fail_fast=True,
labelarray_dtype=(categorical_dtype, bytes_dtype, unicode_dtype),
relabel_func=[
lambda s: s[0],
... | Review this code and list any quality issues. | [
{
"issue": "this doesn't test the f(missing) -> missing",
"severity": "minor",
"line": 26
}
] | 1 |
python | os.close(fd1)
fd2, filepng = tempfile.mkstemp(prefix="svg_marker", suffix=".png")
os.close(fd2)
try:
basedir = os.path.abspath(os.path.dirname(__file__))
pm = gen_pattern.PatternMaker(cols, rows, filesvg, "px", square_size, 0, boar... | Review this code and list any quality issues. | [] | 0 |
python | dependencies = [
("tests", "0060_eventpagespeakeraward_certificate"),
]
operations = [
migrations.CreateModel(
name="RevisableCluster",
fields=[
(
"id",
models.AutoField(
auto_created=True,
... | Review this code and list any quality issues. | [] | 0 |
python | mock_create_pod,
mock_await_pod_completion,
mock_fetch_requested_container_logs,
data_file,
):
"""
Verifies that find_spark_job picks a Running Spark driver pod over a non-Running pod.
"""
task_name = "test_find_spark_job_prefers_running_pod"
job_spec... | Review this code and list any quality issues. | [
{
"issue": "I would advise changing this to: `\"spark-driver\"`. This is because the name is being used as a tie-breaker in the selection logic. Also, rename `pending_pod` to `non_terminating_pod`.",
"severity": "minor",
"line": 26
}
] | 1 |
python | ]
SSE_CONTENT_TYPE: Final[str] = 'text/event-stream'
"""Content type header value for Server-Sent Events (SSE)."""
AgentRunCallback = Callable[[AgentRun[Any, Any]], None | Awaitable[None]]
"""Callback function type that receives the completed AgentRun. Can be sync or async."""
class AGUIApp(Generic[AgentDepsT, Outp... | Review this code and list any quality issues. | [
{
"issue": "Please remove this from `AGUIApp` and `Agent.to_ag_ui` as those are really meant to only be used for cases where you want to serve the agent quickly and not do any pre or post processing.",
"severity": "major",
"line": 26
}
] | 1 |
python | base = self.interaction.permissions
if self.channel.type in (ChannelType.voice, ChannelType.stage_voice):
if not base.connect:
# voice channels cannot be edited by people who can't connect to them
# It also implicitly denies all other voice perms
denie... | Review this code and list any quality issues. | [
{
"issue": "This will actually no longer be true in a month.",
"severity": "minor",
"line": 26
}
] | 1 |
python | import math
import pytest
import torch
from einops import rearrange
from colossalai.kernel.cuda_native.mha.flash_attn_2 import HAS_FLASH_ATTN
from colossalai.kernel.cuda_native.mha.mem_eff_attn import HAS_MEM_EFF_ATTN
from colossalai.kernel.cuda_native.mha.utils import Repad, SeqLenInfo, Unpad
from colossalai.testing... | Review this code and list any quality issues. | [
{
"issue": "Could you make this baseline function have the same parameters as `ColoAttention`'s `forward`",
"severity": "minor",
"line": 20
}
] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.