language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 1912,
"end": 2183
} | class ____(BaseModel):
model_config = ConfigDict(from_attributes={}) # type: ignore[typeddict-item]
# MYPY: error: Invalid value for "Config.from_attributes" [pydantic-config]
# MYPY: note: Error code "pydantic-config" not covered by "type: ignore" comment
| BadConfig1 |
python | weaviate__weaviate-python-client | weaviate/proto/v1/v4216/v1/weaviate_pb2_grpc.py | {
"start": 549,
"end": 2863
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Search = channel.unary_unary(
'/weaviate.v1.Weaviate/Search',
requ... | WeaviateStub |
python | doocs__leetcode | lcci/10.11.Peaks and Valleys/Solution.py | {
"start": 0,
"end": 180
} | class ____:
def wiggleSort(self, nums: List[int]) -> None:
nums.sort()
for i in range(0, len(nums), 2):
nums[i : i + 2] = nums[i : i + 2][::-1]
| Solution |
python | doocs__leetcode | solution/3000-3099/3020.Find the Maximum Number of Elements in Subset/Solution.py | {
"start": 0,
"end": 361
} | class ____:
def maximumLength(self, nums: List[int]) -> int:
cnt = Counter(nums)
ans = cnt[1] - (cnt[1] % 2 ^ 1)
del cnt[1]
for x in cnt:
t = 0
while cnt[x] > 1:
x = x * x
t += 2
t += 1 if cnt[x] else -1
... | Solution |
python | doocs__leetcode | solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/Solution.py | {
"start": 0,
"end": 446
} | class ____:
def maximumJumps(self, nums: List[int], target: int) -> int:
@cache
def dfs(i: int) -> int:
if i == n - 1:
return 0
ans = -inf
for j in range(i + 1, n):
if abs(nums[i] - nums[j]) <= target:
ans = max(... | Solution |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 71910,
"end": 72314
} | class ____:
xlLegendPositionBottom = -4107 # from enum XlLegendPosition
xlLegendPositionCorner = 2 # from enum XlLegendPosition
xlLegendPositionCustom = -4161 # from enum XlLegendPosition
xlLegendPositionLeft = -4131 # from enum XlLegendPosition
xlLegendPositionRight = -4152 # from enum XlLegen... | LegendPosition |
python | sympy__sympy | sympy/stats/joint_rv_types.py | {
"start": 12400,
"end": 15105
} | class ____(JointDistribution):
_argnames = ('mu', 'lamda', 'alpha', 'beta')
is_Continuous=True
@staticmethod
def check(mu, lamda, alpha, beta):
_value_check(mu.is_real, "Location must be real.")
_value_check(lamda > 0, "Lambda must be positive")
_value_check(alpha > 0, "alpha m... | NormalGammaDistribution |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 38717,
"end": 42312
} | class ____(fixtures.TestBase):
"""test process_result_value in conjunction with primary key columns.
Also tests that "autoincrement" checks are against
column.type._type_affinity, rather than the class of "type" itself.
"""
__sparse_driver_backend__ = True
@classmethod
def setup_test_cla... | SpecialTypePKTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 1525,
"end": 1685
} | class ____:
if ...:
...
else:
with ...:
for _ in ...:
def __eq__(self, other): ...
### OK
| MaybeEqDeeplyNested |
python | sqlalchemy__sqlalchemy | test/orm/test_assorted_eager.py | {
"start": 16477,
"end": 18660
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"departments",
metadata,
Column(
"department_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
... | EagerTest4 |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/plugins/pycodestyle_lint.py | {
"start": 2225,
"end": 4011
} | class ____(pycodestyle.BaseReport):
def __init__(self, options) -> None:
self.diagnostics = []
super().__init__(options=options)
def error(self, line_number, offset, text, check):
code = text[:4]
if self._ignore_code(code):
return
# Don't care about expected... | PyCodeStyleDiagnosticReport |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 2074,
"end": 2233
} | class ____(TypedDict):
git: GitInfo
entrypoint: List[str]
notebook: bool
build_context: Optional[str]
dockerfile: Optional[str]
| GitSourceDict |
python | realpython__materials | django-diary/source_code_final/entries/views.py | {
"start": 531,
"end": 598
} | class ____(LockedView, DetailView):
model = Entry
| EntryDetailView |
python | ray-project__ray | python/ray/dashboard/subprocesses/routes.py | {
"start": 260,
"end": 3758
} | class ____(BaseRouteTable):
"""
A route table to bind http route to SubprocessModuleHandle and SubprocessModule.
This class is used in cls object: all the decorator methods are @classmethod, and
the routes are binded to the cls object.
Note we have 2 handlers:
1. the child side handler, that i... | SubprocessRouteTable |
python | plotly__plotly.py | tests/test_core/test_figure_messages/test_batch_animate.py | {
"start": 101,
"end": 2259
} | class ____(TestCase):
def setUp(self):
# Construct initial scatter object
self.figure = go.Figure(
data=[
go.Scatter(y=[3, 2, 1], marker={"color": "green"}),
go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}),
],
layout={"xaxis": {... | TestBatchAnimateMessage |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/common_transformers/anf.py | {
"start": 1271,
"end": 1758
} | class ____:
"""A dumb gensym that suffixes a stem by sequential numbers from 1000."""
def __init__(self):
# A proper implementation needs to account for:
# * ctx.info.namespace
# * all the symbols defined in the AST
# * the symbols generated so far
self._idx = 0
def new_name(self, stem... | DummyGensym |
python | pypa__virtualenv | src/virtualenv/config/cli/parser.py | {
"start": 314,
"end": 1246
} | class ____(Namespace):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self._src = None
self._sources = {}
def set_src(self, key, value, src):
setattr(self, key, value)
if src.startswith("env var"):
src = "env var"
self._sources[key] ... | VirtualEnvOptions |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_variables.py | {
"start": 7110,
"end": 11054
} | class ____:
async def test_no_results(
self,
client: AsyncClient,
):
res = await client.post(
"/variables/filter",
)
assert res.status_code == 200
assert len(res.json()) == 0
async def test_no_filter(
self,
client: AsyncClient,
... | TestReadVariables |
python | gevent__gevent | src/gevent/tests/test__core_callback.py | {
"start": 87,
"end": 618
} | class ____(greentest.TestCase):
def test(self):
loop = get_hub().loop
called = []
def f():
called.append(1)
x = loop.run_callback(f)
assert x, x
gevent.sleep(0)
assert called == [1], called
assert not x, (x, bool(x))
x = loop.r... | Test |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_dynamodb.py | {
"start": 998,
"end": 4473
} | class ____:
def setup_method(self):
self.table_name = "test_airflow"
self.pk_name = "PK"
self.pk_value = "PKTest"
self.sk_name = "SK"
self.sk_value = "SKTest"
self.attribute_name = "Foo"
self.attribute_value = "Bar"
self.sensor_pk_sk = DynamoDBValueSe... | TestDynamoDBValueSensor |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/events.py | {
"start": 273,
"end": 390
} | class ____(BaseVoiceAgentEvent):
model_config = ConfigDict(extra="allow")
base_64_encoded_audio: str
| AudioEvent |
python | tensorflow__tensorflow | tensorflow/python/autograph/operators/control_flow_test.py | {
"start": 29407,
"end": 35936
} | class ____(testing.AutoGraphTestCase):
def test_tensor(self):
def test_fn(cond):
def body():
nonlocal i
i = constant_op.constant(1)
def orelse():
nonlocal i
i = constant_op.constant(-1)
def set_state(cond_vars):
nonlocal i
i, = cond_vars
... | IfStmtTest |
python | kamyu104__LeetCode-Solutions | Python/zigzag-grid-traversal-with-skip.py | {
"start": 41,
"end": 475
} | class ____(object):
def zigzagTraversal(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[int]
"""
result = []
for i in xrange(len(grid)):
if i%2 == 0:
result.extend(grid[i][j] for j in xrange(0, len(grid[0]), 2))
else:
... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/group_open_period_serializer.py | {
"start": 503,
"end": 629
} | class ____(TypedDict):
id: str
type: str
value: str | None
dateCreated: datetime
| GroupOpenPeriodActivityResponse |
python | urllib3__urllib3 | src/urllib3/contrib/socks.py | {
"start": 2341,
"end": 2530
} | class ____(typing.TypedDict):
socks_version: int
proxy_host: str | None
proxy_port: str | None
username: str | None
password: str | None
rdns: bool
| _TYPE_SOCKS_OPTIONS |
python | readthedocs__readthedocs.org | readthedocs/projects/views/mixins.py | {
"start": 1648,
"end": 3032
} | class ____:
"""Injects ``subprojects_and_urls`` into the context."""
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["subprojects_and_urls"] = self._get_subprojects_and_urls()
return context
def _get_subprojects_and_urls(self):
"""... | ProjectRelationListMixin |
python | django-guardian__django-guardian | guardian/testapp/tests/test_utils.py | {
"start": 921,
"end": 1065
} | class ____(TestCase):
def test(self):
anon = get_anonymous_user()
self.assertTrue(isinstance(anon, User))
| GetAnonymousUserTest |
python | facebook__pyre-check | tools/generate_taint_models/model_generator.py | {
"start": 908,
"end": 1318
} | class ____(ABC, Generic[T]):
@abstractmethod
def compute_models(
self, functions_to_model: Iterable[Callable[..., object]]
) -> Iterable[T]:
pass
@abstractmethod
def gather_functions_to_model(self) -> Iterable[Callable[..., object]]:
pass
def generate_models(self) -> It... | ModelGenerator |
python | walkccc__LeetCode | solutions/681. Next Closest Time/681.py | {
"start": 0,
"end": 640
} | class ____:
def nextClosestTime(self, time: str) -> str:
ans = list(time)
digits = sorted(ans)
def nextClosest(digit: str, limit: str) -> str:
next = bisect_right(digits, digit)
return digits[0] if next == 4 or digits[next] > limit else digits[next]
ans[4] = nextClosest(ans[4], '9')
... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ012.py | {
"start": 2333,
"end": 2705
} | class ____(models.Model):
"""Model that contains multiple out-of-order field definitions in a row."""
class Meta:
verbose_name = "test"
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
def get_absolute_url(self):
pass
middle_name = mod... | MultipleConsecutiveFields |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/events.py | {
"start": 10271,
"end": 13479
} | class ____(EventWithMetadata, IHaveNew):
asset_key: AssetKey
description: Optional[str]
metadata: Mapping[str, MetadataValue]
partition: Optional[str]
tags: Mapping[str, str]
failure_type: AssetMaterializationFailureType
reason: AssetMaterializationFailureReason
"""Event that indicates ... | AssetMaterializationFailure |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_logs.py | {
"start": 1004,
"end": 4341
} | class ____:
@pytest.mark.parametrize(
("get_log_events_response", "num_skip_events", "expected_num_events", "end_time"),
[
# 3 empty responses with different tokens
(
[
{"nextForwardToken": "1", "events": []},
{"nextForw... | TestAwsLogsHook |
python | ray-project__ray | doc/source/serve/doc_code/http_guide/http_guide.py | {
"start": 1579,
"end": 1970
} | class ____:
pass
serve.run(FastAPIWrapper.bind(), route_prefix="/")
resp = requests.get("http://localhost:8000/")
assert resp.json() == "Hello from the root!"
# __end_byo_fastapi__
# __begin_fastapi_factory_pattern__
import requests
from fastapi import FastAPI
from ray import serve
from opentelemetry.instrument... | FastAPIWrapper |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_numeric.py | {
"start": 5444,
"end": 6454
} | class ____:
def test_valid(self) -> None:
prop = bcpn.Percent()
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(0.0)
assert prop.is_valid(1.0)
assert prop.is_valid(0.5)
def test_invalid(self) -> None:
prop = bcpn.Percent()
a... | Test_Percent |
python | tensorflow__tensorflow | third_party/xla/build_tools/configure/configure.py | {
"start": 6565,
"end": 6683
} | class ____(ArgparseableEnum):
CPU = enum.auto()
CUDA = enum.auto()
ROCM = enum.auto()
SYCL = enum.auto()
| Backend |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | {
"start": 1770,
"end": 2947
} | class ____(StyleTransformation):
"""
Turn dark colors into light colors and the other way around.
This is meant to make color schemes that work on a dark background usable
on a light background (and the other way around).
Notice that this doesn't swap foreground and background like "reverse"
d... | SwapLightAndDarkStyleTransformation |
python | scrapy__scrapy | tests/test_command_runspider.py | {
"start": 8994,
"end": 9543
} | class ____(scrapy.Spider):
name = 'myspider'
async def start(self):
self.logger.debug('FEEDS: {}'.format(self.settings.getdict('FEEDS')))
return
yield
"""
args = ["-o", "-:json"]
log = self.get_log(tmp_path, spider_code, args=args)
assert "[myspider] DEBUG: FEEDS... | MySpider |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_sql.py | {
"start": 1233,
"end": 4967
} | class ____(BaseOperator):
"""
Load Data from S3 into a SQL Database.
You need to provide a parser function that takes a filename as an input
and returns an iterable of rows
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator... | S3ToSqlOperator |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 17604,
"end": 17785
} | class ____(GenericType):
"""Special generic type for heterogeneous tuples.
A tuple with length len(self.parameters), whose item type is specified at
each index.
"""
| TupleType |
python | django__django | tests/decorators/test_csrf.py | {
"start": 380,
"end": 672
} | class ____:
def get_request(self, token=CSRF_TOKEN):
request = HttpRequest()
request.method = "POST"
if token:
request.POST["csrfmiddlewaretoken"] = token
request.COOKIES[settings.CSRF_COOKIE_NAME] = token
return request
| CsrfTestMixin |
python | walkccc__LeetCode | solutions/587. Erect the Fence/587.py | {
"start": 0,
"end": 764
} | class ____:
def outerTrees(self, trees: list[list[int]]) -> list[list[int]]:
hull = []
trees.sort(key=lambda x: (x[0], x[1]))
def cross(p: list[int], q: list[int], r: list[int]) -> int:
return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
# Build the lower hull: left-to-right ... | Solution |
python | spyder-ide__spyder | spyder/widgets/browser.py | {
"start": 1745,
"end": 2455
} | class ____(QWebEnginePage):
"""
Web page subclass to manage hyperlinks for WebEngine
Note: This can't be used for WebKit because the
acceptNavigationRequest method has a different
functionality for it.
"""
linkClicked = Signal(QUrl)
def acceptNavigationRequest(self, url, navigation_typ... | WebPage |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 240587,
"end": 245578
} | class ____(Response):
"""
Response of tasks.delete_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "delete_many"
_version = "2.23"
_schema = {
"definitions": {
... | DeleteManyResponse |
python | getsentry__sentry | src/sentry/auth/providers/google/provider.py | {
"start": 672,
"end": 1430
} | class ____(OAuth2Login):
authorize_url = AUTHORIZE_URL
scope = SCOPE
def __init__(self, client_id: str, domains: list[str] | None = None) -> None:
self.domains = domains
super().__init__(client_id=client_id)
def get_authorize_params(self, state: str, redirect_uri: str) -> dict[str, str... | GoogleOAuth2Login |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py | {
"start": 2541,
"end": 6082
} | class ____(ColumnAggregateExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_aggregate_expectation_template.py docstring">
"""TODO: add a docstring here"""
# </snippet>
# These examples will be shown in the public gallery.
... | ExpectColumnAggregateToMatchSomeCriteria |
python | django__django | django/contrib/gis/gdal/geometries.py | {
"start": 24874,
"end": 24969
} | class ____(OGRGeometry):
geos_support = False
# Geometry Collection base class.
| CompoundCurve |
python | PrefectHQ__prefect | tests/test_waiters.py | {
"start": 296,
"end": 4301
} | class ____:
@pytest.fixture(autouse=True)
def teardown(self):
yield
FlowRunWaiter.instance().stop()
def test_instance_returns_singleton(self):
assert FlowRunWaiter.instance() is FlowRunWaiter.instance()
def test_instance_returns_instance_after_stop(self):
instance = Fl... | TestFlowRunWaiter |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokehjs_content.py | {
"start": 3705,
"end": 9531
} | class ____(CodeBlock):
has_content = True
optional_arguments = 1
required_arguments = 0
option_spec = CodeBlock.option_spec
option_spec.update(title=unchanged)
option_spec.update(js_file=unchanged)
option_spec.update(include_html=unchanged)
option_spec.update(disable_codepen=unchanged)... | BokehJSContent |
python | huggingface__transformers | src/transformers/models/eomt/image_processing_eomt.py | {
"start": 1553,
"end": 7676
} | class ____(ImagesKwargs, total=False):
"""
do_split_image (`bool`, *optional*, defaults to `False`):
Whether to split the input images into overlapping patches for semantic segmentation. If set to `True`, the
input images will be split into patches of size `size["shortest_edge"]` with an overlap... | EomtImageProcessorKwargs |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_util.py | {
"start": 4634,
"end": 6504
} | class ____(object):
"""Implementation of OptionsInterface."""
def __init__(self,
bytes_per_pack=0,
timeout_seconds=None,
implementation=CommunicationImplementation.AUTO):
if bytes_per_pack < 0:
raise ValueError(
f"Argument `bytes_per_pack` must be >=... | Options |
python | networkx__networkx | networkx/algorithms/bipartite/tests/test_matching.py | {
"start": 320,
"end": 7698
} | class ____:
"""Tests for bipartite matching algorithms."""
def setup_method(self):
"""Creates a bipartite graph for use in testing matching algorithms.
The bipartite graph has a maximum cardinality matching that leaves
vertex 1 and vertex 10 unmatched. The first six numbers are the lef... | TestMatching |
python | ray-project__ray | rllib/utils/filter.py | {
"start": 2221,
"end": 9735
} | class ____:
def __init__(self, shape=()):
"""Initializes a `RunningStat` instance."""
# Keep always a state and a delta from all attributes. Note,
# we use the state for filtering and the delta for updates.
# All deltas will be zero(s) after a state synchronization
# across d... | RunningStat |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axislines.py | {
"start": 8756,
"end": 8881
} | class ____: # Backcompat.
Fixed = _FixedAxisArtistHelperBase
Floating = _FloatingAxisArtistHelperBase
| AxisArtistHelper |
python | numba__numba | numba/core/compiler_machinery.py | {
"start": 2447,
"end": 2612
} | class ____(object):
""" Mixin to indicate a pass is SSA form compliant. Nothing is asserted
about this condition at present.
"""
pass
| SSACompliantMixin |
python | crytic__slither | slither/utils/command_line.py | {
"start": 757,
"end": 13491
} | class ____(enum.Enum):
PEDANTIC = "pedantic"
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
NONE = "none"
# Those are the flags shared by the command line and the config file
defaults_flag_in_config = {
"codex": False,
"codex_contracts": "all",
"codex_model": "text-davinci-003",
"code... | FailOnLevel |
python | donnemartin__system-design-primer | solutions/system_design/mint/mint_snippets.py | {
"start": 290,
"end": 967
} | class ____(object):
def __init__(self, seller_category_map, seller_category_overrides_map):
self.seller_category_map = seller_category_map
self.seller_category_overrides_map = seller_category_overrides_map
def categorize(self, transaction):
if transaction.seller in self.seller_category... | Categorizer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 2003,
"end": 2070
} | class ____(Class6[Sequence[T_co], Sequence[T_co]]): ...
| Class6_Child5 |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 99108,
"end": 106111
} | class ____(rv_continuous):
r"""A generalized extreme value continuous random variable.
%(before_notes)s
See Also
--------
gumbel_r
Notes
-----
For :math:`c=0`, `genextreme` is equal to `gumbel_r` with
probability density function
.. math::
f(x) = \exp(-\exp(-x)) \exp... | genextreme_gen |
python | jazzband__django-oauth-toolkit | oauth2_provider/migrations/0011_refreshtoken_token_family.py | {
"start": 142,
"end": 564
} | class ____(migrations.Migration):
dependencies = [
('oauth2_provider', '0010_application_allowed_origins'),
migrations.swappable_dependency(oauth2_settings.REFRESH_TOKEN_MODEL)
]
operations = [
migrations.AddField(
model_name='refreshtoken',
name='token_fami... | Migration |
python | walkccc__LeetCode | solutions/1498. Number of Subsequences That Satisfy the Given Sum Condition/1498.py | {
"start": 0,
"end": 326
} | class ____:
def numSubseq(self, nums: list[int], target: int) -> int:
MOD = 1_000_000_007
n = len(nums)
ans = 0
nums.sort()
l = 0
r = n - 1
while l <= r:
if nums[l] + nums[r] <= target:
ans += pow(2, r - l, MOD)
l += 1
else:
r -= 1
return ans % MO... | Solution |
python | getsentry__sentry | src/sentry/plugins/sentry_useragents/models.py | {
"start": 110,
"end": 1042
} | class ____(TagPlugin):
version = sentry.VERSION
author = "Sentry Team"
author_url = "https://github.com/getsentry/sentry"
project_default_enabled = True
def get_tag_values(self, event) -> list[str]:
contexts = event.interfaces.get("contexts")
# disable tagging if contexts are presen... | UserAgentPlugin |
python | pytorch__pytorch | torch/_library/utils.py | {
"start": 14637,
"end": 19489
} | class ____:
"""
Check if an operator mutated its arguments.
Usage:
checker = MutationChecker(op, flat_args, args_spec)
op(*args, **kwargs)
checker.check()
"""
def __init__(self, op, flat_args, args_spec):
self.op = op
self.args_spec = args_spec
self.flat_args = ... | MutationChecker |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP044.py | {
"start": 545,
"end": 776
} | class ____(TypedDict):
x: int
y: int
# OK
def f(name: str, /, **kwargs: Unpack[KwargsDict]) -> None:
pass
# OK
def f() -> object:
return Unpack[tuple[int, ...]]
# OK
def f(x: Unpack[int]) -> object: ...
| KwargsDict |
python | Pylons__pyramid | src/pyramid/security.py | {
"start": 7046,
"end": 9537
} | class ____:
"""Mixin for Request class providing auth-related properties."""
@property
def identity(self):
"""
Return an opaque object identifying the current user or ``None`` if no
user is authenticated or there is no :term:`security policy` in effect.
"""
policy =... | SecurityAPIMixin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_public_methods.py | {
"start": 485,
"end": 797
} | class ____:
def __init__(self):
pass
def _private(self):
pass
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def method4(self):
pass
def method5(self):
pass
def method6(self):
pass
| Small |
python | graphql-python__graphene | graphene/relay/tests/test_mutation.py | {
"start": 1863,
"end": 1919
} | class ____(ObjectType):
something = String()
| RootQuery |
python | facelessuser__pymdown-extensions | pymdownx/tilde.py | {
"start": 3311,
"end": 4177
} | class ____(util.PatternSequenceProcessor):
"""Emphasis processor for handling delete and subscript matches."""
PATTERNS = [
util.PatSeqItem(re.compile(DEL_SUB, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
util.PatSeqItem(re.compile(SUB_DEL, re.DOTALL | re.UNICODE), 'double', 'sub,del'),
... | TildeProcessor |
python | doocs__leetcode | lcci/10.02.Group Anagrams/Solution.py | {
"start": 0,
"end": 228
} | class ____:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list)
for s in strs:
k = ''.join(sorted(s))
d[k].append(s)
return list(d.values())
| Solution |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 29767,
"end": 29963
} | class ____(PrefectBaseModel):
"""Filter by `Artifact.id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of artifact ids to include"
)
| ArtifactFilterId |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 11163,
"end": 11428
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
######################################################################
| shortTestCase |
python | sphinx-doc__sphinx | sphinx/transforms/compact_bullet_list.py | {
"start": 1495,
"end": 2861
} | class ____(SphinxTransform):
"""Change refonly bullet lists to use compact_paragraphs.
Specifically implemented for 'Indices and Tables' section, which looks
odd when html_compact_lists is false.
"""
default_priority = 100
def apply(self, **kwargs: Any) -> None:
if self.config.html_co... | RefOnlyBulletListTransform |
python | pytorch__pytorch | torch/utils/data/datapipes/datapipe.py | {
"start": 1419,
"end": 10131
} | class ____(IterableDataset[_T_co], metaclass=_IterDataPipeMeta):
r"""
Iterable-style DataPipe.
All DataPipes that represent an iterable of data samples should subclass this.
This style of DataPipes is particularly useful when data come from a stream, or
when the number of samples is too large to fi... | IterDataPipe |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 105559,
"end": 110464
} | class ____(SendrecvmsgServerTimeoutBase):
# Tests for sendmsg() which can use any socket type and do not
# involve recvmsg() or recvmsg_into().
def testSendmsg(self):
# Send a simple message with sendmsg().
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
def _testSendmsg(self):
... | SendmsgTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/origin.py | {
"start": 451,
"end": 2894
} | class ____(
NamedTuple(
"_RepositoryPythonOrigin",
[
("executable_path", str),
("code_pointer", CodePointer),
("container_image", Optional[str]),
("entry_point", Optional[Sequence[str]]),
("container_context", Optional[Mapping[str, Any]]),
... | RepositoryPythonOrigin |
python | django__django | tests/select_related_onetoone/models.py | {
"start": 399,
"end": 601
} | class ____(models.Model):
user = models.OneToOneField(User, models.CASCADE, primary_key=True)
posts = models.IntegerField()
results = models.ForeignKey(UserStatResult, models.CASCADE)
| UserStat |
python | facebook__pyre-check | client/tests/coverage_data_tests.py | {
"start": 44744,
"end": 50072
} | class ____(testslide.TestCase):
def test_empty_containers__literal(self) -> None:
self.assertEqual(
coverage_data.collect_empty_containers(
parse_code(
"""
a = []
b = {}
not_c = [1]
... | EmptyContainerCollectorTest |
python | pytorch__pytorch | test/quantization/eager/test_quantize_eager_ptq.py | {
"start": 1706,
"end": 10957
} | class ____(QuantizationTestCase):
@override_qengines
def _test_reference_module_impl(
self,
float_module_class,
quantized_module_class,
extra_module_kwargs,
input_size,
):
class M(torch.nn.Module):
def __init__(self) -> None:
super(... | TestQuantizeEagerOps |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 506480,
"end": 507518
} | class ____(BinopNode):
def analyse_types(self, env):
node = BinopNode.analyse_types(self, env)
if node.is_py_operation():
node.type = PyrexTypes.error_type
return node
def py_operation_function(self, code):
return ""
def calculate_result_code(self):
ret... | CBinopNode |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 2514,
"end": 2598
} | class ____(ASTNode):
left: ASTNode
op: str
right: ASTNode
@dataclass
| BinOp |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 11603,
"end": 15881
} | class ____(test_util.TensorFlowTestCase):
def test_adjust_gamma_less_zero_float32(self):
"""White image should be returned for gamma equal to zero"""
with self.cached_session():
x_data = np.random.uniform(0, 1.0, (8, 8))
x_np = np.array(x_data, dtype=np.float32)
x = constant_op.constant(x_... | AdjustGamma |
python | getsentry__sentry | tests/snuba/test_metrics_layer.py | {
"start": 902,
"end": 33070
} | class ____(TestCase, BaseMetricsTestCase):
def ts(self, dt: datetime) -> int:
return int(dt.timestamp())
def setUp(self) -> None:
super().setUp()
self.generic_metrics: Mapping[str, Literal["counter", "set", "distribution", "gauge"]] = {
TransactionMRI.DURATION.value: "distr... | MQLTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/constant_op_eager_test.py | {
"start": 17123,
"end": 19226
} | class ____(test.TestCase):
def _Ones(self, shape):
ret = array_ops.ones(shape)
self.assertEqual(shape, ret.get_shape())
return ret.numpy()
def testConst(self):
self.assertTrue(np.array_equal(self._Ones([2, 3]), np.array([[1] * 3] * 2)))
def testScalar(self):
self.assertEqual(1, self._Ones([... | OnesTest |
python | realpython__materials | python-serialize/schema-based/avro-demo/models.py | {
"start": 126,
"end": 223
} | class ____(StrEnum):
DE = "de"
EN = "en"
ES = "es"
FR = "fr"
IT = "it"
| Language |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 9307,
"end": 9874
} | class ____(IterableExportStream, ABC):
"""
This class use RangeSliceGenerator class to break single request into
ranges with same (or less for final range) number of days. By default it 90
days.
"""
def stream_slices(
self,
sync_mode: SyncMode,
cursor_field: List[str] = ... | IterableExportStreamRanged |
python | apache__airflow | airflow-core/src/airflow/cli/commands/info_command.py | {
"start": 3903,
"end": 4525
} | class ____(Enum):
"""Operating system."""
WINDOWS = "Windows"
LINUX = "Linux"
MACOSX = "Mac OS"
CYGWIN = "Cygwin"
UNKNOWN = "Unknown"
@staticmethod
def get_current() -> OperatingSystem:
"""Get current operating system."""
if os.name == "nt":
return Operating... | OperatingSystem |
python | ray-project__ray | python/ray/train/tests/test_backend.py | {
"start": 2507,
"end": 19253
} | class ____(Backend):
def on_start(self, worker_group: WorkerGroup, backend_config: TestConfig):
pass
def on_shutdown(self, worker_group: WorkerGroup, backend_config: TestConfig):
pass
original_add_workers = WorkerGroup.add_workers
def mock_add_workers(self, num_workers):
original_add_wo... | TestBackend |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py | {
"start": 11148,
"end": 11318
} | class ____(str, Enum):
"""Enumeration for HNSW iterative scan modes."""
off = "off"
relaxed = "relaxed_order"
strict = "strict_order"
| HNSWIterativeScanMode |
python | python-pillow__Pillow | src/PIL/ImageFile.py | {
"start": 3051,
"end": 14980
} | class ____(Image.Image):
"""Base class for image file format handlers."""
def __init__(
self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None
) -> None:
super().__init__()
self._min_frame = 0
self.custom_mimetype: str | None = None
self.tile: l... | ImageFile |
python | lazyprogrammer__machine_learning_examples | rl/optimistic_initial_values.py | {
"start": 454,
"end": 1755
} | class ____:
def __init__(self, m, upper_limit):
self.m = m
self.mean = upper_limit
self.N = 1
def pull(self):
return np.random.randn() + self.m
def update(self, x):
self.N += 1
self.mean = (1 - 1.0/self.N)*self.mean + 1.0/self.N*x
def run_experiment(m1, m2, m3, N, upper_limit=10):
ba... | Bandit |
python | doocs__leetcode | solution/0100-0199/0145.Binary Tree Postorder Traversal/Solution.py | {
"start": 192,
"end": 499
} | class ____:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root):
if root is None:
return
dfs(root.left)
dfs(root.right)
ans.append(root.val)
ans = []
dfs(root)
return ans
| Solution |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 37550,
"end": 38227
} | class ____(AsyncHTTPTestCase):
def get_app(self):
return Application([("/", EchoHandler)])
def post_gzip(self, body):
bytesio = BytesIO()
gzip_file = gzip.GzipFile(mode="w", fileobj=bytesio)
gzip_file.write(utf8(body))
gzip_file.close()
compressed_body = bytesio.... | GzipBaseTest |
python | Textualize__textual | tests/css/test_screen_css.py | {
"start": 774,
"end": 1108
} | class ____(App):
"""Base app for testing screen CSS when pushing screens."""
CSS = """
#app-css {
background: #00ff00;
}
#screen-css-path {
background: #00ff00;
}
#screen-css {
background: #00ff00;
}
"""
def on_mount(self):
self.push_screen(BaseS... | BaseApp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gcs/source_gcs/helpers.py | {
"start": 1551,
"end": 2631
} | class ____(UploadableRemoteFile):
"""
Extends RemoteFile instance with displayed_uri attribute.
displayed_uri is being used by Cursor to identify files with temporal local path in their uri attribute.
"""
blob: Any
displayed_uri: str = None
def __init__(self, blob: Any, displayed_uri: str ... | GCSUploadableRemoteFile |
python | huggingface__transformers | src/transformers/integrations/ggml.py | {
"start": 13640,
"end": 15485
} | class ____:
def __init__(self, dict_):
for k, v in dict_.items():
setattr(self, k, v)
if not hasattr(self, "merges"):
if not hasattr(self, "tokens") or not hasattr(self, "scores"):
raise ValueError(
"tokens and scores need to be passed for... | GGUFTokenizerSkeleton |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 282750,
"end": 283728
} | class ____(sgqlc.types.Input):
"""Parameters to be used for the repository_name condition"""
__schema__ = github_schema
__field_names__ = ("exclude", "include", "protected")
exclude = sgqlc.types.Field(sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(String))), graphql_name="exclude")
... | RepositoryNameConditionTargetInput |
python | apache__thrift | lib/py/test/test_sslsocket.py | {
"start": 3591,
"end": 3984
} | class ____(object):
def __init__(self, expected):
self._expected = expected
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if not exc_type or not issubclass(exc_type, self._expected):
raise Exception('fail')
return True
@unittest... | AssertRaises |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 72827,
"end": 78720
} | class ____(LukePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.luke = LukeModel(config)
self.dropout = nn.Dropout(
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout... | LukeForSequenceClassification |
python | huggingface__transformers | src/transformers/models/flex_olmo/modular_flex_olmo.py | {
"start": 1384,
"end": 10133
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FlexOlmoModel`]. It is used to instantiate an FlexOlmo
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar co... | FlexOlmoConfig |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Solve_LunarLander/A3C.py | {
"start": 914,
"end": 5434
} | class ____(object):
def __init__(self, scope, globalAC=None):
if scope == GLOBAL_NET_SCOPE: # get global network
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self._build_net(N_A)
self.a_params = tf.get_coll... | ACNet |
python | pandas-dev__pandas | pandas/tests/frame/test_api.py | {
"start": 362,
"end": 13088
} | class ____:
def test_getitem_pop_assign_name(self, float_frame):
s = float_frame["A"]
assert s.name == "A"
s = float_frame.pop("A")
assert s.name == "A"
s = float_frame.loc[:, "B"]
assert s.name == "B"
s2 = s.loc[:]
assert s2.name == "B"
def te... | TestDataFrameMisc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.