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 | ray-project__ray | python/ray/util/check_serialize.py | {
"start": 707,
"end": 8440
} | class ____:
"""Represents the serialization 'frame'.
Attributes:
obj: The object that fails serialization.
name: The variable name of the object.
parent: The object that references the `obj`.
"""
def __init__(self, obj: Any, name: str, parent: Any):
self.obj = obj
... | FailureTuple |
python | pytorch__pytorch | test/onnx/model_defs/rnn_model_with_packed_sequence.py | {
"start": 611,
"end": 1117
} | class ____(nn.Module):
def __init__(self, model, batch_first):
super().__init__()
self.model = model
self.batch_first = batch_first
def forward(self, input, seq_lengths):
input = rnn_utils.pack_padded_sequence(input, seq_lengths, self.batch_first)
rets = self.model(input... | RnnModelWithPackedSequenceWithoutState |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/ExampleApp.py | {
"start": 3127,
"end": 9273
} | class ____(QSyntaxHighlighter):
"""Syntax highlighter for the Python language.
"""
# Python keywords
keywords = keyword.kwlist
# Python operators
operators = [
r'=',
# Comparison
r'==', r'!=', r'<', r'<=', r'>', r'>=',
# Arithmetic
r'\+', r"-", r'\*', r'/... | PythonHighlighter |
python | Textualize__textual | examples/mother.py | {
"start": 809,
"end": 913
} | class ____(Markdown):
"""Markdown for the reply from the LLM."""
BORDER_TITLE = "Mother"
| Response |
python | keras-team__keras | keras/src/saving/saving_lib.py | {
"start": 32905,
"end": 34873
} | class ____:
"""Asset store backed by disk storage.
If `archive` is specified, then `root_path` refers to the filename
inside the archive.
If `archive` is not specified, then `root_path` refers to the full path of
the target directory.
"""
def __init__(self, root_path, archive=None, mode=N... | DiskIOStore |
python | matplotlib__matplotlib | lib/matplotlib/bezier.py | {
"start": 5251,
"end": 19248
} | class ____:
"""
A d-dimensional Bézier segment.
A BezierSegment can be called with an argument, either a scalar or an array-like
object, to evaluate the curve at that/those location(s).
Parameters
----------
control_points : (N, d) array
Location of the *N* control points.
"""
... | BezierSegment |
python | getsentry__sentry | src/sentry/api/serializers/release_details_types.py | {
"start": 1528,
"end": 1711
} | class ____(TypedDict, total=False):
healthData: HealthData | None
dateReleased: datetime | None
dateCreated: datetime | None
dateStarted: datetime | None
| ProjectOptional |
python | python-visualization__folium | folium/plugins/beautify_icon.py | {
"start": 161,
"end": 3383
} | class ____(JSCSSMixin, MacroElement):
"""
Create a BeautifyIcon that can be added to a Marker
Parameters
----------
icon: string, default None
the Font-Awesome icon name to use to render the marker.
icon_shape: string, default None
the icon shape
border_width: integer, defau... | BeautifyIcon |
python | apache__airflow | airflow-ctl/src/airflowctl/api/operations.py | {
"start": 2434,
"end": 4029
} | class ____(httpx.HTTPStatusError):
"""Server response error (Generic)."""
@classmethod
def from_response(cls, response: httpx.Response) -> ServerResponseError | None:
if response.status_code < 400:
return None
if response.headers.get("content-type") != "application/json":
... | ServerResponseError |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 501448,
"end": 504423
} | class ____(Request):
"""
Mark a task status as in_progress. Optionally allows to set the task's execution progress.
:param force: If not true, call fails if the task status is not 'not_started'
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status ch... | StartedRequest |
python | lxml__lxml | src/lxml/tests/test_etree.py | {
"start": 175309,
"end": 179090
} | class ____(HelperTestCase):
def test_xinclude_text(self):
filename = fileInTestDir('test_broken.xml')
root = etree.XML('''\
<doc xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="%s" parse="text"/>
</doc>
''' % path2url(filename))
old_text = root... | _XIncludeTestCase |
python | getsentry__sentry | tests/sentry/utils/test_safe.py | {
"start": 6251,
"end": 6783
} | class ____(unittest.TestCase):
def test_dict(self) -> None:
d = {"1": None, "3": "4"}
assert safe_urlencode(d) == "1=&3=4"
assert d == {"1": None, "3": "4"}
d = {"1": "2", "3": "4"}
assert safe_urlencode(d) == "1=2&3=4"
def test_pair_sequence(self) -> None:
d = [... | SafeUrlencodeTest |
python | django__django | tests/test_client_regress/tests.py | {
"start": 31218,
"end": 32006
} | class ____(TestDataMixin, TestCase):
def test_exception_cleared(self):
"#5836 - A stale user exception isn't re-raised by the test client."
login = self.client.login(username="testclient", password="password")
self.assertTrue(login, "Could not log in")
with self.assertRaises(CustomT... | ExceptionTests |
python | streamlit__streamlit | lib/tests/streamlit/config_test.py | {
"start": 54291,
"end": 63296
} | class ____(unittest.TestCase):
"""Tests that involve loading the config.toml file."""
def setUp(self):
self.patches = [
patch.object(
config, "_section_descriptions", new=copy.deepcopy(SECTION_DESCRIPTIONS)
),
patch.object(config, "_config_options", n... | ConfigLoadingTest |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 34764,
"end": 42237
} | class ____(QueryTest):
def test_loader_options(self):
User = self.classes.User
s = fixture_session()
u1 = s.get(User, 8, options=[joinedload(User.addresses)])
eq_(len(u1.__dict__["addresses"]), 3)
def test_get_composite_pk_keyword_based_no_result(self):
CompositePk = s... | GetTest |
python | doocs__leetcode | solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/Solution.py | {
"start": 0,
"end": 122
} | class ____:
def hasTrailingZeros(self, nums: List[int]) -> bool:
return sum(x & 1 ^ 1 for x in nums) >= 2
| Solution |
python | nedbat__coveragepy | tests/test_data.py | {
"start": 23505,
"end": 26496
} | class ____(CoverageTest):
"""Tests of CoverageData that need a temporary directory to make files."""
@pytest.mark.parametrize("file_class", FilePathClasses)
def test_read_write_lines(self, file_class: FilePathType) -> None:
self.assert_doesnt_exist("lines.dat")
covdata1 = DebugCoverageData(... | CoverageDataInTempDirTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/openstreetmap/views.py | {
"start": 186,
"end": 388
} | class ____(OAuth):
url = "https://api.openstreetmap.org/api/0.6/user/details.json"
def get_user_info(self):
data = self.query(self.url).json()
return data["user"]
| OpenStreetMapAPI |
python | google__jax | jax/_src/linear_util.py | {
"start": 4582,
"end": 9972
} | class ____:
"""Represents a function `f` to which `transforms` are to be applied.
Args:
f: the function to be transformed.
f_transformed: transformed function.
transforms: a tuple of `(gen, gen_static_args)` tuples representing
transformations to apply to `f.` Here `gen` is a generator function a... | WrappedFun |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 759,
"end": 1949
} | class ____:
"""Use this test mixin for simple license plate validation"""
def perform_extra_checks(self, license_plate, match):
pass
def test_license_plate(self, faker, num_samples):
for _ in range(num_samples):
license_plate = faker.license_plate()
match = self.lic... | _SimpleAutomotiveTestMixin |
python | pallets__werkzeug | tests/test_datastructures.py | {
"start": 36762,
"end": 38200
} | class ____:
@pytest.mark.parametrize(
("values", "matches", "default", "expect"),
[
([("text/*", 1)], ["text/html"], None, "text/html"),
([("text/*", 1)], ["image/png"], "text/plain", "text/plain"),
([("text/*", 1)], ["image/png"], None, None),
(
... | TestMIMEAccept |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 41799,
"end": 43366
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("zh_CN")
Faker.seed(0)
def test_zh_CN_ssn(self):
for _ in range(100):
ssn = self.fake.ssn()
assert len(ssn) == 18
def test_zh_CN_ssn_invalid_gender_passed(self):
with pytest.raises(Val... | TestZhCN |
python | pallets__jinja | src/jinja2/idtracking.py | {
"start": 5079,
"end": 7214
} | class ____(NodeVisitor):
def __init__(self, symbols: "Symbols") -> None:
self.sym_visitor = FrameSymbolVisitor(symbols)
def _simple_visit(self, node: nodes.Node, **kwargs: t.Any) -> None:
for child in node.iter_child_nodes():
self.sym_visitor.visit(child)
visit_Template = _simp... | RootVisitor |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 7326,
"end": 7398
} | class ____(TestAtomFeed):
feed_type = MyCustomAtom1Feed
| TestCustomFeed |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/summary_ops/summary_ops_test.py | {
"start": 47535,
"end": 49243
} | class ____(test_util.TensorFlowTestCase):
def testNoopWriter_doesNothing(self):
logdir = self.get_temp_dir()
with context.eager_mode():
writer = summary_ops.create_noop_writer()
writer.init()
with writer.as_default():
result = summary_ops.write('test', 1.0, step=0)
writer.flus... | NoopWriterTest |
python | oauthlib__oauthlib | oauthlib/oauth1/rfc5849/endpoints/signature_only.py | {
"start": 315,
"end": 3327
} | class ____(BaseEndpoint):
"""An endpoint only responsible for verifying an oauth signature."""
def validate_request(self, uri, http_method='GET',
body=None, headers=None):
"""Validate a signed OAuth request.
:param uri: The full URI of the token request.
:para... | SignatureOnlyEndpoint |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 5210,
"end": 5373
} | class ____(Message):
"""
Indicates a return statement outside of a function/method.
"""
message = '\'return\' outside function'
| ReturnOutsideFunction |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_missouri_zip.py | {
"start": 1751,
"end": 4094
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Missouri zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidMissouriZip |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/cli_shared_test.py | {
"start": 13470,
"end": 15831
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
self.var_a = variables.Variable(42.0, name="a")
def tearDown(self):
ops.reset_default_graph()
def testShapeError(self):
tf_error = errors.OpError(None, self.var_a.initializer, "foo description",
None)
erro... | GetErrorIntroTest |
python | apache__thrift | contrib/zeromq/test-server.py | {
"start": 885,
"end": 1591
} | class ____(storage.Storage.Iface):
def __init__(self):
self.value = 0
def incr(self, amount):
self.value += amount
def get(self):
return self.value
def main():
handler = StorageHandler()
processor = storage.Storage.Processor(handler)
ctx = zmq.Context()
reqrep_se... | StorageHandler |
python | django-import-export__django-import-export | tests/core/admin.py | {
"start": 647,
"end": 804
} | class ____(ModelResource):
class Meta:
model = Book
fields = ["id", "name"]
name = "Export/Import only book names"
| BookNameResource |
python | kamyu104__LeetCode-Solutions | Python/strong-password-checker-ii.py | {
"start": 38,
"end": 566
} | class ____(object):
def strongPasswordCheckerII(self, password):
"""
:type password: str
:rtype: bool
"""
SPECIAL = set("!@#$%^&*()-+")
return (len(password) >= 8 and
any(c.islower() for c in password) and
any(c.isupper() for c in passw... | Solution |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_geometry_not_to_overlap.py | {
"start": 1845,
"end": 5058
} | class ____(ColumnAggregateExpectation):
"""Expect geometries in this column Not to overlap with each other. If any two geometries do overlap, expectation will return False.
For more information look here \
https://stackoverflow.com/questions/64042379/shapely-is-valid-returns-true-to-invalid-overlap-polygon... | ExpectColumnValuesGeometryNotToOverlap |
python | getsentry__sentry | src/sentry/api/endpoints/organization_profiling_profiles.py | {
"start": 1196,
"end": 2472
} | class ____(serializers.Serializer):
# fingerprint is an UInt32
fingerprint = serializers.IntegerField(min_value=0, max_value=(1 << 32) - 1, required=False)
dataSource = serializers.ChoiceField(
["transactions", "profiles", "functions", "spans"], required=False
)
query = serializers.CharField... | OrganizationProfilingFlamegraphSerializer |
python | sqlalchemy__sqlalchemy | examples/space_invaders/space_invaders.py | {
"start": 7327,
"end": 7468
} | class ____(Glyph):
"""Describe a glyph for displaying a message."""
__mapper_args__ = {"polymorphic_identity": "message"}
| MessageGlyph |
python | spack__spack | lib/spack/spack/vendor/jinja2/loaders.py | {
"start": 18769,
"end": 20287
} | class ____(BaseLoader):
"""This loader works like the `PrefixLoader` just that no prefix is
specified. If a template could not be found by one loader the next one
is tried.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/syste... | ChoiceLoader |
python | pytorch__pytorch | benchmarks/dynamo/huggingface_llm_models.py | {
"start": 648,
"end": 811
} | class ____:
@staticmethod
def get_model_and_inputs(model_name, device):
raise NotImplementedError("get_model_and_inputs() not implemented")
| Benchmark |
python | sqlalchemy__sqlalchemy | examples/space_invaders/space_invaders.py | {
"start": 7745,
"end": 19709
} | class ____(Glyph):
"""Describe a glyph representing a "splat"."""
__mapper_args__ = {"polymorphic_identity": "splat"}
def glyph_for_state(self, coord, state):
age = state["tick"] - coord.tick
if age > 5:
return self.alt_data
else:
return self.data
def init... | SplatGlyph |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 12113,
"end": 12180
} | class ____(UnaryOp):
pass
@infer_global(operator.pos)
| UnaryNegate |
python | huggingface__transformers | src/transformers/models/data2vec/modular_data2vec_audio.py | {
"start": 7524,
"end": 8848
} | class ____(Data2VecAudioPreTrainedModel, Wav2Vec2ForCTC):
def __init__(self, config):
Data2VecAudioPreTrainedModel.__init__(self, config)
self.data2vec_audio = Data2VecAudioModel(config)
self.dropout = nn.Dropout(config.final_dropout)
if config.vocab_size is None:
raise... | Data2VecAudioForCTC |
python | walkccc__LeetCode | solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167.py | {
"start": 0,
"end": 738
} | class ____:
def minimumTime(self, s: str) -> int:
n = len(s)
# left[i] := the minimum time to remove the illegal cars of s[0..i]
left = [0] * n
left[0] = int(s[0])
# dp[i] := the minimum time to remove the illegal cars of s[0..i] optimally
# + the time to remove the illegal cars of s[i + 1..n)... | Solution |
python | pyparsing__pyparsing | examples/tiny/tiny_ast.py | {
"start": 8055,
"end": 9412
} | class ____(TinyNode):
"""Declaration statement node.
Represents one declaration statement possibly declaring multiple
identifiers with optional initializers, for example:
int x := 1, y, z := 2;
Fields:
- dtype: declared datatype ("int", "float", or "string").
- decls: list of (name, i... | DeclStmtNode |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 920739,
"end": 926069
} | class ____(ValueChannelMixin, core.StringValueDefWithCondition):
"""
UrlValue schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefstringnullExprRef`, :class:`ConditionalParameterMarkPropFieldOrDatumDef`, :class:`Conditional... | UrlValue |
python | mwaskom__seaborn | tests/test_base.py | {
"start": 15642,
"end": 19667
} | class ____:
def test_plotter_default_init(self, long_df):
p = VectorPlotter(
data=long_df,
variables=dict(x="x", y="y"),
)
assert not hasattr(p, "_map_style")
p = VectorPlotter(
data=long_df,
variables=dict(x="x", y="y", style="a"),
... | TestStyleMapping |
python | google__jax | jax/_src/lax/lax.py | {
"start": 321448,
"end": 343179
} | class ____:
def __init__(self, value_comparator: Callable[[Any, Any], Any]):
self._value_comparator = value_comparator
def __repr__(self):
# Override the repr so that the metadata attached to the lowered op does not
# contain unstable function ids. This plays more nicely with computation
# fingerp... | _ArgMinMaxReducer |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 11962,
"end": 14947
} | class ____:
"""Make sure all options which have an attribute interface work as they should.
Also make sure option settings are copied correctly when a table is cloned by
slicing."""
def test_set_for_all_columns(self, city_data: PrettyTable) -> None:
city_data.field_names = sorted(city_data.fiel... | TestOptionAttribute |
python | pytorch__pytorch | test/dynamo/test_guard_manager.py | {
"start": 32754,
"end": 33839
} | class ____(torch._dynamo.test_case.TestCase):
def test_duplicate_guard(self):
class Foo:
def __init__(self):
self.x = 4
self.bar = 4
foo = Foo()
def fn(x):
if hasattr(foo, "y"):
x = torch.sin(x)
if hasattr(... | DuplicateGuardTest |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/manifest_component_transformer.py | {
"start": 7089,
"end": 12539
} | class ____:
def propagate_types_and_parameters(
self,
parent_field_identifier: str,
declarative_component: Mapping[str, Any],
parent_parameters: Mapping[str, Any],
) -> Mapping[str, Any]:
"""
Recursively transforms the specified declarative component and subcompon... | ManifestComponentTransformer |
python | getsentry__sentry | src/sentry/notifications/platform/templates/sample.py | {
"start": 9682,
"end": 12102
} | class ____(NotificationTemplate[PerformanceAlertData]):
category = NotificationCategory.DEBUG
example_data = PerformanceAlertData(
metric_name="API response time",
threshold="500ms",
current_value="1.2s",
project_name="my-app",
chart_url="https://example.com/chart",
... | PerformanceAlertNotificationTemplate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 1559,
"end": 1666
} | class ____(Proto_CoGeneric):
def m[T: Impl_CoGenericExplicit3](self: T) -> T: ...
| Impl_CoGenericExplicit3 |
python | dask__dask | dask/array/tests/test_dispatch.py | {
"start": 2767,
"end": 7200
} | class ____(np.lib.mixins.NDArrayOperatorsMixin):
"""
Another mock duck array class (like EncapsulateNDArray), but
designed to be above Dask in the type casting hierarchy (that is,
WrappedArray wraps Dask Array) and be even more minimal in API.
Tests that Dask defers properly to upcast types.
"""... | WrappedArray |
python | patrys__httmock | tests.py | {
"start": 11844,
"end": 13969
} | class ____(unittest.TestCase):
@staticmethod
def several_calls(count, method, *args, **kwargs):
results = []
for _ in range(count):
results.append(method(*args, **kwargs))
return results
def test_several_calls(self):
with HTTMock(google_mock_count, facebook_mock... | RememberCalledTest |
python | getsentry__sentry | src/sentry_plugins/heroku/plugin.py | {
"start": 916,
"end": 5175
} | class ____(ReleaseHook):
def get_auth(self) -> AuthenticatedToken | None:
try:
return AuthenticatedToken.from_token(
ApiKey(organization_id=self.project.organization_id, scope_list=["project:write"])
)
except ApiKey.DoesNotExist:
return None
d... | HerokuReleaseHook |
python | getsentry__sentry | src/sentry/migrations/1001_prevent_grouphistory_infinte_recursion.py | {
"start": 222,
"end": 1662
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1211680,
"end": 1211899
} | class ____(VegaLiteSchema):
"""SingleDefUnitChannel schema wrapper."""
_schema = {"$ref": "#/definitions/SingleDefUnitChannel"}
def __init__(self, *args):
super().__init__(*args)
| SingleDefUnitChannel |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 47787,
"end": 59548
} | class ____(Request):
"""
Edit an existing model
:param model: Model ID
:type model: str
:param uri: URI for the model
:type uri: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined ... | EditRequest |
python | google__jax | jax/_src/shard_map.py | {
"start": 57865,
"end": 88721
} | class ____(core.Tracer):
vma: frozenset[AxisName]
val: JaxType
def __init__(self, trace, vma, val):
self._trace = trace
if isinstance(vma, set):
vma = frozenset(vma)
assert isinstance(vma, frozenset)
self.vma = vma
self.val = val
@property
def aval(self):
aval = core.get_aval(s... | ShardMapTracer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/snap/node.py | {
"start": 1874,
"end": 2795
} | class ____(IHaveNew):
name: str
dagster_type_key: str
description: Optional[str]
is_required: bool
metadata: Mapping[str, MetadataValue]
is_dynamic: bool
def __new__(
cls,
name: str,
dagster_type_key: str,
description: Optional[str],
is_required: bool... | OutputDefSnap |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 29667,
"end": 30313
} | class ____(Model):
'''Describes how to calculate totals and sub-totals
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
getter = String('', help="""
References the column which generates the uni... | GroupingInfo |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 15701,
"end": 17138
} | class ____(UptimeTestCase):
def test_create_update_delete(self) -> None:
for status in (
UptimeSubscription.Status.CREATING,
UptimeSubscription.Status.UPDATING,
UptimeSubscription.Status.DELETING,
):
sub = self.create_uptime_subscription(
... | SubscriptionCheckerTest |
python | mwaskom__seaborn | tests/test_statistics.py | {
"start": 399,
"end": 793
} | class ____:
@pytest.fixture
def x(self, rng):
return rng.normal(0, 1, 100)
@pytest.fixture
def x2(self, rng):
return rng.normal(0, 1, 742) # random value to avoid edge cases
@pytest.fixture
def y(self, rng):
return rng.normal(0, 5, 100)
@pytest.fixture
def we... | DistributionFixtures |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 3088,
"end": 3237
} | class ____:
def m[S](self: S, other: S) -> int: ...
@classmethod
def n[S](cls: type[S], other: S) -> int: ...
| SelfNotUsedInReturnAnnotation |
python | gevent__gevent | src/greentest/3.12/test_threading.py | {
"start": 70373,
"end": 71748
} | class ____(unittest.TestCase):
def test__all__(self):
restore_default_excepthook(self)
extra = {"ThreadError"}
not_exported = {'currentThread', 'activeCount'}
support.check__all__(self, threading, ('threading', '_thread'),
extra=extra, not_exported=not_e... | MiscTestCase |
python | Delgan__loguru | loguru/_colorizer.py | {
"start": 1145,
"end": 1477
} | class ____:
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
RESET = 39
LIGHTBLACK_EX = 90
LIGHTRED_EX = 91
LIGHTGREEN_EX = 92
LIGHTYELLOW_EX = 93
LIGHTBLUE_EX = 94
LIGHTMAGENTA_EX = 95
LIGHTCYAN_EX = 96
LIGHTWHIT... | Fore |
python | scipy__scipy | scipy/signal/tests/test_ltisys.py | {
"start": 10695,
"end": 16421
} | class ____:
def check_matrix_shapes(self, p, q, r):
ss2tf(np.zeros((p, p)),
np.zeros((p, q)),
np.zeros((r, p)),
np.zeros((r, q)), 0)
def test_shapes(self):
# Each tuple holds:
# number of states, number of inputs, number of outputs
fo... | TestSS2TF |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 1774,
"end": 4031
} | class ____(GoogleCloudBaseOperator):
"""
Base class for Managed Kafka operators.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param retry: Designation of what e... | ManagedKafkaBaseOperator |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/base_aws.py | {
"start": 1134,
"end": 3914
} | class ____(BaseOperator, AwsBaseHookMixin[AwsHookType]):
"""
Base AWS (Amazon) Operator Class to build operators on top of AWS Hooks.
.. warning::
Only for internal usage, this class might be changed, renamed or removed in the future
without any further notice.
Examples:
.. code-b... | AwsBaseOperator |
python | optuna__optuna | optuna/visualization/_edf.py | {
"start": 648,
"end": 727
} | class ____(NamedTuple):
study_name: str
y_values: np.ndarray
| _EDFLineInfo |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 28696,
"end": 29080
} | class ____(RoleImpl):
__slots__ = ()
def _literal_coercion(self, element, *, argname=None, **kw):
if element is None:
return elements.Null()
elif element is False:
return elements.False_()
elif element is True:
return elements.True_()
else:
... | ConstExprImpl |
python | huggingface__transformers | tests/models/biogpt/test_modeling_biogpt.py | {
"start": 1340,
"end": 10708
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_hea... | BioGptModelTester |
python | patrick-kidger__equinox | equinox/nn/_rnn.py | {
"start": 280,
"end": 3786
} | class ____(Module):
"""A single step of a Gated Recurrent Unit (GRU).
!!! example
This is often used by wrapping it into a `jax.lax.scan`. For example:
```python
class Model(Module):
cell: GRUCell
def __init__(self, **kwargs):
self.cell = GRUCe... | GRUCell |
python | sphinx-doc__sphinx | sphinx/util/images.py | {
"start": 715,
"end": 4106
} | class ____(NamedTuple):
mimetype: str
charset: str
data: bytes
def get_image_size(filename: str | PathLike[str]) -> tuple[int, int] | None:
filename = Path(filename)
try:
size = imagesize.get(filename)
if size[0] == -1:
size = None
elif isinstance(size[0], float... | DataURI |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 4524,
"end": 6423
} | class ____(ShuffleBase):
"""Abstract shuffle class
Parameters
----------
frame: Expr
The DataFrame-like expression to shuffle.
partitioning_index: str, list
Column and/or index names to hash and partition by.
npartitions: int
Number of output partitions.
ignore_index... | Shuffle |
python | pytorch__pytorch | test/nn/test_pooling.py | {
"start": 19665,
"end": 86221
} | class ____(NNTestCase):
@expectedFailureMPS # No double, float shape prop does not work
@onlyNativeDeviceTypes
@dtypes(torch.float, torch.double)
def test_adaptive_pooling_zero_batch(self, dtype, device):
inp = torch.ones(0, 10, dtype=dtype, device=device)
mod = torch.nn.AdaptiveAvgPool... | TestPoolingNNDeviceType |
python | walkccc__LeetCode | solutions/240. Search a 2D Matrix II/240.py | {
"start": 0,
"end": 309
} | class ____:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
r = 0
c = len(matrix[0]) - 1
while r < len(matrix) and c >= 0:
if matrix[r][c] == target:
return True
if target < matrix[r][c]:
c -= 1
else:
r += 1
return False
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/engines.py | {
"start": 13086,
"end": 13624
} | class ____:
"""Proxy a DBAPI connection.
Tests can provide subclasses of this to intercept
DBAPI-level connection operations.
"""
def __init__(self, engine, conn, cursor_cls):
self.conn = conn
self.engine = engine
self.cursor_cls = cursor_cls
def cursor(self, *args, *... | DBAPIProxyConnection |
python | kamyu104__LeetCode-Solutions | Python/find-servers-that-handled-most-number-of-requests.py | {
"start": 65,
"end": 1600
} | class ____(object):
def busiestServers(self, k, arrival, load):
"""
:type k: int
:type arrival: List[int]
:type load: List[int]
:rtype: List[int]
"""
count = [0]*k
min_heap_of_endtimes = []
min_heap_of_nodes_after_curr = []
min_heap_of_... | Solution |
python | optuna__optuna | optuna/terminator/improvement/evaluator.py | {
"start": 7976,
"end": 10019
} | class ____(BaseImprovementEvaluator):
"""Evaluates the stagnation period of the best value in an optimization process.
This class is initialized with a maximum stagnation period (``max_stagnation_trials``)
and is designed to evaluate the remaining trials before reaching this maximum period
of allowed s... | BestValueStagnationEvaluator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_order01.py | {
"start": 315,
"end": 2233
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_order01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 8326,
"end": 9258
} | class ____:
"""Base class for modifiers that modify the value of an environment variable."""
__slots__ = ("name", "value", "separator", "trace")
def __init__(
self, name: str, value: str, *, separator: str = os.pathsep, trace: Optional[Trace] = None
):
self.name = name.upper() if sys.p... | NameValueModifier |
python | django__django | tests/check_framework/test_security.py | {
"start": 12551,
"end": 13542
} | class ____(SimpleTestCase):
@override_settings(
MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
SECURE_CONTENT_TYPE_NOSNIFF=False,
)
def test_no_content_type_nosniff(self):
"""
Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True.
"""
self.assertEqual(... | CheckContentTypeNosniffTest |
python | kamyu104__LeetCode-Solutions | Python/dice-roll-simulation.py | {
"start": 58,
"end": 956
} | class ____(object):
def dieSimulator(self, n, rollMax):
"""
:type n: int
:type rollMax: List[int]
:rtype: int
"""
MOD = 10**9+7
def sum_mod(array):
return reduce(lambda x, y: (x+y)%MOD, array)
dp = [[1] + [0]*(rollMax[i]-1) for i in xrange... | Solution |
python | TheAlgorithms__Python | data_structures/hashing/quadratic_probing.py | {
"start": 60,
"end": 2361
} | class ____(HashTable):
"""
Basic Hash Table example with open addressing using Quadratic Probing
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _collision_resolution(self, key, data=None): # noqa: ARG002
"""
Quadratic probing is an open addr... | QuadraticProbing |
python | pytorch__pytorch | test/dynamo/test_decorators.py | {
"start": 429,
"end": 67464
} | class ____(torch._dynamo.test_case.TestCase):
def test_disallow_in_graph(self):
cnts = torch._dynamo.testing.CompileCounter()
@torch.compile(backend=cnts)
def fn(a):
x = torch.add(a, 1)
x = torch.add(x, 1)
x = torch.sub(x, 1)
x = torch.add(x, ... | DecoratorTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1061370,
"end": 1062135
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'auto_merge_enabled' event on a given pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "enabler", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the... | AutoMergeEnabledEvent |
python | ethereum__web3.py | web3/_utils/threads.py | {
"start": 2595,
"end": 3352
} | class ____(threading.Thread, Generic[TReturn]):
def __init__(
self,
target: Callable[..., TReturn] = None,
args: Any = None,
kwargs: Any = None,
) -> None:
super().__init__(
target=target,
args=args or tuple(),
kwargs=kwargs or {},
... | ThreadWithReturn |
python | kamyu104__LeetCode-Solutions | Python/subarrays-with-xor-at-least-k.py | {
"start": 2427,
"end": 4250
} | class ____(object):
def countXorSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
class Trie(object):
def __init__(self, bit_length):
self.__nodes = []
self.__cnts = []
self.__n... | Solution_TLE |
python | ray-project__ray | python/ray/data/namespace_expressions/dt_namespace.py | {
"start": 521,
"end": 3208
} | class ____:
"""Datetime namespace for operations on datetime-typed expression columns."""
_expr: "Expr"
def _unary_temporal_int(
self, func: Callable[[pyarrow.Array], pyarrow.Array]
) -> "UDFExpr":
"""Helper for year/month/… that return int32."""
@pyarrow_udf(return_dtype=Data... | _DatetimeNamespace |
python | PrefectHQ__prefect | src/integrations/prefect-shell/prefect_shell/commands.py | {
"start": 4226,
"end": 6450
} | class ____(JobRun[list[str]]):
"""
A class representing a shell process.
"""
def __init__(self, shell_operation: "ShellOperation", process: Process):
self._shell_operation = shell_operation
self._process = process
self._output: list[str] = []
@property
def pid(self) -> ... | ShellProcess |
python | getsentry__sentry | src/sentry/integrations/gitlab/client.py | {
"start": 2509,
"end": 16048
} | class ____(IntegrationProxyClient, RepositoryClient, CommitContextClient):
def __init__(self, installation: GitlabIntegration):
self.installation = installation
verify_ssl = self.metadata["verify_ssl"]
self.is_refreshing_token = False
self.refreshed_identity: RpcIdentity | None = Non... | GitLabApiClient |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 3225,
"end": 3701
} | class ____(AirflowException):
"""Raise when a DAG's ID is already used by another DAG."""
def __init__(self, dag_id: str, incoming: str, existing: str) -> None:
super().__init__(dag_id, incoming, existing)
self.dag_id = dag_id
self.incoming = incoming
self.existing = existing
... | AirflowDagDuplicatedIdException |
python | kamyu104__LeetCode-Solutions | Python/maximum-palindromes-after-operations.py | {
"start": 68,
"end": 525
} | class ____(object):
def maxPalindromesAfterOperations(self, words):
"""
:type words: List[str]
:rtype: int
"""
cnt = [0]*26
for w in words:
for c in w:
cnt[ord(c)-ord('a')] += 1
curr = sum(x//2 for x in cnt)
for i, l in enum... | Solution |
python | davidhalter__parso | parso/python/errors.py | {
"start": 44078,
"end": 45338
} | class ____(_CheckAssignmentRule):
message = "illegal expression for augmented assignment"
extended_message = "'{target}' is an " + message
def is_issue(self, node):
augassign = node.children[1]
is_aug_assign = augassign != '=' and augassign.type != 'annassign'
if self._normalizer.v... | _ExprStmtRule |
python | django-haystack__django-haystack | test_haystack/mocks.py | {
"start": 2989,
"end": 3246
} | class ____(MockSearchBackend):
model_name = "charpkmockmodel"
mock_search_results = [
MockSearchResult("core", "CharPKMockModel", "sometext", 0.5),
MockSearchResult("core", "CharPKMockModel", "1234", 0.3),
]
| CharPKMockSearchBackend |
python | numpy__numpy | numpy/f2py/tests/test_data.py | {
"start": 1749,
"end": 2124
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "crackfortran", "data_common.f")]
# For gh-23276
def test_data_stmts(self):
assert self.module.mycom.mydata == 0
def test_crackedlines(self):
mod = crackfortran(str(self.sources[0]))
print(mod[0]['vars'])
... | TestDataF77 |
python | getsentry__sentry | src/sentry/tasks/auth/auth.py | {
"start": 3873,
"end": 6769
} | class ____(abc.ABC):
"""Remove members who don't comply with a new org requirement."""
log_label = ""
@abc.abstractmethod
def is_compliant(self, user: RpcUser) -> bool:
"""Check whether a member complies with the new requirement."""
raise NotImplementedError()
@abc.abstractmethod
... | OrganizationComplianceTask |
python | huggingface__transformers | tests/quantization/gptq/test_gptq.py | {
"start": 11828,
"end": 13023
} | class ____(GPTQTest):
device_map = {"": 0}
def test_change_loading_attributes(self):
"""
Test the serialization of the model and the loading of the quantized weights works with another config file
"""
with tempfile.TemporaryDirectory() as tmpdirname:
self.quantized_m... | GPTQTestCUDA |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin_ini/plugin_fail.py | {
"start": 6133,
"end": 6356
} | class ____(BaseModel):
x: int = 1
y = 2
# MYPY: error: Untyped fields disallowed [pydantic-field]
z = 2 # type: ignore[pydantic-field]
AliasGeneratorModel2(x=1)
AliasGeneratorModel2(y=1, z=1)
| UntypedFieldModel |
python | ray-project__ray | python/ray/data/tests/test_dynamic_block_split.py | {
"start": 782,
"end": 3530
} | class ____(Datasource):
def __init__(
self,
num_tasks: int,
num_batches_per_task: int,
row_size: int,
num_rows_per_batch=None,
use_bytes=True,
use_arrow=False,
):
self.num_tasks = num_tasks
self.num_batches_per_task = num_batches_per_task
... | RandomBytesDatasource |
python | OmkarPathak__pygorithm | pygorithm/data_structures/linked_list.py | {
"start": 3400,
"end": 5717
} | class ____(object):
"""DoublyLinkedList
DoublyLinkedList Class
"""
def __init__(self):
"""
constructor
"""
self.head = None
def get_data(self):
"""
prints the elements in the linked list
"""
temp = self.head
l_list = []
... | DoublyLinkedList |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.