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 | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 256074,
"end": 257528
} | class ____(ExternKernel):
"""
This needs to be a custom class to handle mutation properly
"""
def codegen(self, wrapper: PythonWrapperCodegen) -> None:
(dst, src, non_blocking) = self.codegen_args()
wrapper.codegen_device_copy(src, dst, non_blocking)
def should_allocate(self) -> bo... | InplaceCopyFallback |
python | numba__numba | numba/core/withcontexts.py | {
"start": 1692,
"end": 2540
} | class ____(WithContext):
"""A simple context-manager that tells the compiler to bypass the body
of the with-block.
"""
def mutate_with_body(
self,
func_ir,
blocks,
blk_start,
blk_end,
body_blocks,
dispatcher_factory,
extra,
):
... | _ByPassContextType |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/rapidsmpf/dispatch.py | {
"start": 1442,
"end": 4021
} | class ____(TypedDict):
"""
State used for generating a streaming sub-network.
Parameters
----------
context
The rapidsmpf context.
config_options
GPUEngine configuration options.
partition_info
Partition information.
fanout_nodes
Dictionary mapping IR nod... | GenState |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/etcd_rendezvous_backend_test.py | {
"start": 949,
"end": 1762
} | class ____(TestCase, RendezvousBackendTestMixin):
_server: ClassVar[EtcdServer]
@classmethod
def setUpClass(cls) -> None:
cls._server = EtcdServer()
cls._server.start(stderr=subprocess.DEVNULL)
@classmethod
def tearDownClass(cls) -> None:
cls._server.stop()
def setUp(s... | EtcdRendezvousBackendTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_gcs.py | {
"start": 9220,
"end": 10904
} | class ____:
OPERATOR = GCSObjectUpdateSensor(
task_id="gcs-obj-update",
bucket=TEST_BUCKET,
object=TEST_OBJECT,
google_cloud_conn_id=TEST_GCP_CONN_ID,
deferrable=True,
)
@mock.patch("airflow.providers.google.cloud.sensors.gcs.GCSHook")
def test_gcs_object_update_... | TestGCSObjectUpdateAsyncSensor |
python | keon__algorithms | tests/test_search.py | {
"start": 447,
"end": 6499
} | class ____(unittest.TestCase):
def test_first_occurrence(self):
def helper(array, query):
idx = array.index(query) if query in array else None
return idx
array = [1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]
self.assertEqual(first_occurrence(array, 1), helper(array, ... | TestSuite |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/externalvirtual/package.py | {
"start": 217,
"end": 611
} | class ____(Package):
homepage = "http://somewhere.com"
url = "http://somewhere.com/stuff-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
version("2.0", md5="234567890abcdef1234567890abcdef1")
version("2.1", md5="34567890abcdef1234567890abcdef12")
version("2.2", md5="4567890ab... | Externalvirtual |
python | sympy__sympy | sympy/functions/elementary/piecewise.py | {
"start": 2041,
"end": 58461
} | class ____(DefinedFunction):
"""
Represents a piecewise function.
Usage:
Piecewise( (expr,cond), (expr,cond), ... )
- Each argument is a 2-tuple defining an expression and condition
- The conds are evaluated in turn returning the first that is True.
If any of the evaluated ... | Piecewise |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 3773,
"end": 4078
} | class ____(Parent3):
@overload
def method(self, x: int) -> int: ...
@overload
def method(self, x: str) -> str: ...
@overload
def method(self, x: list[float]) -> list[float]: ...
def method(self, x: int | str | list[float]) -> int | str | list[float]:
return x
| Child3_1 |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/latex.py | {
"start": 219,
"end": 574
} | class ____(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Latex-formatted layout elements."""
def __init__(self, **kwargs: Any) -> None:
"""Initialize a LatexTextSplitter."""
separators = self.get_separators_for_language(Language.LATEX)
super().__init__(separators=... | LatexTextSplitter |
python | pyca__cryptography | tests/hazmat/primitives/test_ssh.py | {
"start": 73317,
"end": 77405
} | class ____:
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.MD5()),
skip_message="Does not support MD5",
)
def test_ssh_key_fingerprint_rsa_md5(self):
ssh_key = load_vectors_from_file(
os.path.join("asymmetric", "OpenSSH", "rsa-nopsw.key.pub"... | TestSSHKeyFingerprint |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 89805,
"end": 97950
} | class ____(TestCase):
def test_exceptions(self):
assert_raises(ValueError, interp, 0, [], [])
assert_raises(ValueError, interp, 0, [0], [1, 2])
assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)
assert_raises(ValueError, interp, 0, [], [], period=360)
assert_raise... | TestInterp |
python | davidhalter__jedi | test/refactor/extract_variable.py | {
"start": 2902,
"end": 3027
} | class ____(x):
pass
# -------------------------------------------------- class-inheritance-2
#? 16 text {'new_name': 'x'}
| Foo |
python | prabhupant__python-ds | data_structures/binary_trees/children_sum_property.py | {
"start": 129,
"end": 620
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def sum_prop(root):
l = r = 0
if not root or (not root.left and not root.right):
return True
else:
if root.left:
l = root.left.val
if root.right:
... | Node |
python | pydantic__pydantic | pydantic/deprecated/config.py | {
"start": 958,
"end": 1876
} | class ____(metaclass=_ConfigMetaclass):
"""This class is only retained for backwards compatibility.
!!! Warning "Deprecated"
BaseConfig is deprecated. Use the [`pydantic.ConfigDict`][pydantic.ConfigDict] instead.
"""
def __getattr__(self, item: str) -> Any:
try:
obj = super... | BaseConfig |
python | PrefectHQ__prefect | src/integrations/prefect-kubernetes/tests/test_credentials.py | {
"start": 3600,
"end": 5258
} | class ____:
@pytest.mark.parametrize(
"resource_type,client_type",
[
("apps", AppsV1Api),
("batch", BatchV1Api),
("core", CoreV1Api),
("custom_objects", CustomObjectsApi),
],
)
async def test_client_return_type(
self, kubernetes... | TestCredentials |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_trace.py | {
"start": 35424,
"end": 44093
} | class ____(OrganizationEventsTraceEndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
@staticmethod
def get_current_transaction(
transactions: Sequence[SnubaTransaction],
errors: Sequence[SnubaError],
event_id: str,
) -> tuple[SnubaTransaction | None... | OrganizationEventsTraceLightEndpoint |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/test_date_range.py | {
"start": 28826,
"end": 32723
} | class ____:
"""Tests for date_range with timezones"""
def test_hongkong_tz_convert(self):
# GH#1673 smoke test
dr = date_range("2012-01-01", "2012-01-10", freq="D", tz="Hongkong")
# it works!
dr.hour
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
... | TestDateRangeTZ |
python | dagster-io__dagster | python_modules/dagster/dagster/_vendored/dateutil/tz/tz.py | {
"start": 41197,
"end": 63035
} | class ____(object):
"""
This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure
as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects.
:param `fileobj`:
A file or stream in iCalendar format, which should be UTF-8 encoded
with CRLF endings.
..... | tzical |
python | tensorflow__tensorflow | tensorflow/python/grappler/remapper_test.py | {
"start": 2764,
"end": 12903
} | class ____(test.TestCase, parameterized.TestCase):
"""Tests the Grappler remapper optimizer."""
def setUp(self):
super(RemapperTest, self).setUp()
# GeluApproximate fusion on GPU requires cublasLt.
os.environ['TF_USE_CUBLASLT'] = '1'
os.environ['TF_CUDNN_USE_RUNTIME_FUSION'] = '1'
def maybe_ski... | RemapperTest |
python | mlflow__mlflow | mlflow/projects/submitted_run.py | {
"start": 1727,
"end": 3533
} | class ____(SubmittedRun):
"""
Instance of ``SubmittedRun`` corresponding to a subprocess launched to run an entry point
command locally.
"""
def __init__(self, run_id, command_proc):
super().__init__()
self._run_id = run_id
self.command_proc = command_proc
@property
... | LocalSubmittedRun |
python | numba__numba | numba/tests/test_vectorization.py | {
"start": 504,
"end": 2932
} | class ____(TestCase):
"""
Tests to assert that code which should vectorize does indeed vectorize
"""
def gen_ir(self, func, args_tuple, fastmath=False):
self.assertEqual(config.CPU_NAME, "skylake-avx512")
self.assertEqual(config.CPU_FEATURES, "")
jitted = njit(args_tuple, fastma... | TestVectorization |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict25.py | {
"start": 198,
"end": 268
} | class ____(TypedDict):
items: int
td1 = TD1(items=0)
td1.items()
| TD1 |
python | getsentry__sentry | src/sentry/notifications/notification_action/issue_alert_registry/handlers/discord_issue_alert_handler.py | {
"start": 406,
"end": 790
} | class ____(BaseIssueAlertHandler):
@classmethod
def get_additional_fields(cls, action: Action, mapping: ActionFieldMapping) -> dict[str, Any]:
blob = DiscordDataBlob(**action.data)
return {"tags": blob.tags}
@classmethod
def get_target_display(cls, action: Action, mapping: ActionFieldMa... | DiscordIssueAlertHandler |
python | apache__airflow | providers/alibaba/tests/unit/alibaba/cloud/hooks/test_base_alibaba.py | {
"start": 1165,
"end": 2083
} | class ____:
def setup_method(self):
with mock.patch(
BASE_ALIBABA_HOOK_MODULE.format("AlibabaBaseHook.get_connection"),
) as mock_get_connection:
mock_conn = mock.MagicMock()
mock_conn.extra_dejson = {
"access_key_id": MOCK_ACCESS_KEY_ID,
... | TestAlibabaBaseHook |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/sql_vector_query_engine.py | {
"start": 1887,
"end": 7042
} | class ____(SQLJoinQueryEngine):
"""
SQL + Vector Index Auto Retriever Query Engine.
This query engine can query both a SQL database
as well as a vector database. It will first decide
whether it needs to query the SQL database or vector store.
If it decides to query the SQL database, it will als... | SQLAutoVectorQueryEngine |
python | google__jax | tests/mosaic/gpu_dialect_test.py | {
"start": 38737,
"end": 52268
} | class ____(MosaicGpuTest):
def test_lowering_removes_mosaic_gpu_ops(self):
with ir.InsertionPoint(self.module.body):
mgpu.dialect.initialize_barrier(
llvm.UndefOp(workgroup_ptr_ty()),
arrival_count=1,
num_barriers=2,
)
mgpu.lower_mgpu_dialect(self.module, None)
... | DialectLoweringTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/sponsored_brands_record_builder.py | {
"start": 156,
"end": 775
} | class ____(RecordBuilder):
@classmethod
def ad_groups_record(cls) -> "SponsoredBrandsRecordBuilder":
return cls(find_template("sponsored_brands_ad_groups", __file__)[0], FieldPath("adGroupId"), None)
@classmethod
def campaigns_record(cls) -> "SponsoredBrandsRecordBuilder":
return cls(fi... | SponsoredBrandsRecordBuilder |
python | python-rapidjson__python-rapidjson | benchmarks/conftest.py | {
"start": 2012,
"end": 2229
} | class ____(rj.Decoder):
def end_array(self, a):
return a
def start_object(self):
return {}
def end_object(self, d):
return d
def string(self, s):
return s
| DecoderPython |
python | spack__spack | lib/spack/spack/test/util/package_hash.py | {
"start": 6055,
"end": 6787
} | class ____:
{directives}
def foo():
# just a method to get in the way
pass
{directives}
""".format(
directives="\n".join(" %s()" % name for name in spack.directives_meta.directive_names)
)
def test_remove_all_directives():
"""Ensure all directives are removed from packages before hash... | HasManyDirectives |
python | huggingface__transformers | src/transformers/core_model_loading.py | {
"start": 17427,
"end": 26210
} | class ____(WeightTransform):
operations: list[ConversionOps] = field(default_factory=list, repr=False)
def __post_init__(self):
WeightTransform.__post_init__(self)
if bool(len(self.source_patterns) - 1) + bool(len(self.target_patterns) - 1) >= 2:
raise ValueError(
f"... | WeightConverter |
python | getsentry__sentry | src/sentry/integrations/github/client.py | {
"start": 2357,
"end": 4475
} | class ____(IntegrationProxyClient):
"""
API Client that doesn't require an installation.
This client is used during integration setup to fetch data
needed to build installation metadata
"""
base_url = "https://api.github.com"
integration_name = "github_setup"
def __init__(self, access_... | GithubSetupApiClient |
python | pypa__setuptools | setuptools/_vendor/more_itertools/more.py | {
"start": 63182,
"end": 75537
} | class ____(abc.Sequence, abc.Hashable):
"""An extension of the built-in ``range()`` function whose arguments can
be any orderable numeric type.
With only *stop* specified, *start* defaults to ``0`` and *step*
defaults to ``1``. The output items will match the type of *stop*:
>>> list(numeric_r... | numeric_range |
python | jina-ai__jina | tests/docker_compose/multiprotocol-gateway/multiprotocol_gateway.py | {
"start": 365,
"end": 2620
} | class ____(Gateway):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.http_port = self.ports[0]
self.grpc_port = self.ports[1]
self.health_servicer = health.HealthServicer(experimental_non_blocking=True)
async def _setup_http_server(self):
from fastapi impor... | MultiProtocolGateway |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 256386,
"end": 256994
} | class ____:
def test_basic(self):
x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)],
dtype=[('r', np.int8), ('g', np.int8),
('b', np.int8), ('a', np.int8)])
# We must be specific about the endianness here:
y = x.view(dtype='<i4')
# ... and aga... | TestView |
python | kamyu104__LeetCode-Solutions | Python/closest-nodes-queries-in-a-binary-search-tree.py | {
"start": 177,
"end": 1395
} | class ____(object):
def closestNodes(self, root, queries):
"""
:type root: Optional[TreeNode]
:type queries: List[int]
:rtype: List[List[int]]
"""
def iter_dfs():
inorder = []
stk = [(1, root)]
while stk:
step, node ... | Solution |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 2624,
"end": 2829
} | class ____(collections.namedtuple("_Edge", ["source", "destination"])):
"""A directed graph edge."""
__slots__ = ()
def __str__(self):
return "{} -> {}".format(self.source, self.destination)
| _Edge |
python | cython__cython | tests/run/purecdef.py | {
"start": 1802,
"end": 2736
} | class ____(object):
@ccall
def meth(self):
return 0
def test_ccall():
"""
>>> test_ccall()
25
>>> ccall_sqr(5)
25
"""
return ccall_sqr(5)
def test_ccall_method(x):
"""
>>> test_ccall_method(Overridable())
0
>>> Overridable().meth()
0
>>> class Foo(Ov... | Overridable |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 59291,
"end": 61983
} | class ____(ErniePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.ernie = ErnieModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None e... | ErnieForTokenClassification |
python | scikit-image__scikit-image | benchmarks/benchmark_measure.py | {
"start": 481,
"end": 925
} | class ____:
param_names = ['prop']
params = sorted(list(PROP_VALS))
def setup(self, prop):
self.label_image, self.intensity_image = init_regionprops_data()
def time_single_region_property(self, prop):
measure.regionprops_table(
self.label_image, self.intensity_image, proper... | RegionpropsTableIndividual |
python | PrefectHQ__prefect | tests/client/test_prefect_client.py | {
"start": 3874,
"end": 8446
} | class ____:
"""Regression test for https://github.com/PrefectHQ/nebula/issues/2356, where
a customer reported that the Cloud client supported proxies, but the client
did not. This test suite is implementation-specific to httpx/httpcore, as there are
no other inexpensive ways to confirm both the proxy-a... | TestClientProxyAwareness |
python | pytorch__pytorch | torch/_library/fake_profile.py | {
"start": 844,
"end": 11491
} | class ____:
args_profile: tuple[Optional[TensorMetadata]]
out_profile: Union[TensorMetadata, tuple[TensorMetadata]]
def _generate_fake_kernel(op_name: str, op_profile: set[OpProfile]) -> Callable:
def _match_args(args_profile: tuple[Optional[TensorMetadata]], args: Any) -> bool:
return all(
... | OpProfile |
python | streamlit__streamlit | lib/tests/streamlit/web/server/authlib_tornado_integration_test.py | {
"start": 889,
"end": 3915
} | class ____(unittest.TestCase):
def test_load_basic_config(self):
basic_config_mock = MagicMock(
config={
"google": {
"client_id": "GOOGLE_CLIENT_ID",
"client_secret": "GOOGLE_CLIENT_SECRET",
"something": "else",
... | TornadoIntegrationTest |
python | geekcomputers__Python | Credit_Card_Validator.py | {
"start": 19,
"end": 2286
} | class ____:
def __init__(self, card_no):
self.card_no = card_no
@property
def company(self):
comp = None
if str(self.card_no).startswith("4"):
comp = "Visa Card"
elif str(self.card_no).startswith(
(
"50",
"67",
... | CreditCard |
python | fastai__fastai | fastai/callback/fp16.py | {
"start": 607,
"end": 790
} | class ____(Enum):
"Automatic mixed precision modes for ease of completion"
FP16 = 'fp16'
BF16 = 'bf16'
# %% ../../nbs/18_callback.fp16.ipynb 20
@delegates(GradScaler)
| AMPMode |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/utils/config.py | {
"start": 4707,
"end": 5168
} | class ____(str, enum.Enum):
"""
The cluster configuration for the streaming executor.
* ``Cluster.SINGLE`` : Single-GPU execution. Currently uses a zero-dependency,
synchronous, single-threaded task scheduler.
* ``Cluster.DISTRIBUTED`` : Multi-GPU distributed execution. Currently
uses a Das... | Cluster |
python | Pylons__pyramid | tests/test_viewderivers.py | {
"start": 70369,
"end": 70464
} | class ____:
content_type = None
default_content_type = None
body = None
| DummyResponse |
python | ray-project__ray | rllib/env/wrappers/atari_wrappers.py | {
"start": 10362,
"end": 14215
} | class ____(gym.ObservationWrapper):
def __init__(self, env, dim, grayscale: bool = True):
"""Warp frames to the specified size (dim x dim)."""
gym.ObservationWrapper.__init__(self, env)
self.width = dim
self.height = dim
self.grayscale = grayscale
self.observation_spa... | GrayScaleAndResize |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 30491,
"end": 31299
} | class ____(unittest.TestCase):
"""Tests SSN in the hr_HR locale"""
def setUp(self):
self.fake = Faker("hr_HR")
Faker.seed(0)
def test_ssn_checksum(self):
assert hr_checksum([0, 0, 2, 2, 8, 2, 6, 9, 2, 8]) == 9
assert hr_checksum([5, 8, 9, 3, 6, 9, 5, 1, 2, 5]) == 1
... | TestHrHR |
python | scipy__scipy | scipy/interpolate/tests/test_rbfinterp.py | {
"start": 20046,
"end": 20714
} | class ____(TestRBFInterpolatorNeighborsNone):
# RBFInterpolator using neighbors=np.inf. This should give exactly the same
# results as neighbors=None, but it will be slower.
def build(self, *args, **kwargs):
return RBFInterpolator(*args, **kwargs, neighbors=np.inf)
def test_equivalent_to_rbf_in... | TestRBFInterpolatorNeighborsInf |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 14829,
"end": 15307
} | class ____(HTTPSuccessful):
"""
subclass of :class:`~HTTPSuccessful`
This indicates that the server has fulfilled the partial GET
request for the resource.
code: 206, title: Partial Content
"""
code = 206
title = 'Partial Content'
# FIXME: add 207 Multi-Status (but it's complicated)... | HTTPPartialContent |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/bigtable.py | {
"start": 1429,
"end": 12342
} | class ____(GoogleBaseHook):
"""
Hook for Google Cloud Bigtable APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
def __init__(
self,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain... | BigtableHook |
python | joke2k__faker | faker/providers/ssn/el_GR/__init__.py | {
"start": 677,
"end": 3090
} | class ____(BaseProvider):
"""
A Faker provider for Greek identification numbers
"""
police_id_format = "??######"
# TIN checksum algo sourced from here
# http://epixeirisi.gr/%CE%9A%CE%A1%CE%99%CE%A3%CE%99%CE%9C%CE%91-%CE%98%CE%95%CE%9C%CE%91%CE%A4%CE%91-%CE%A6%CE%9F%CE%A1%CE%9F%CE%9B%CE%9F%CE... | Provider |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 7925,
"end": 13660
} | class ____:
def test_setitem_mask_cast(self):
# GH#2746
# need to upcast
ser = Series([1, 2], index=[1, 2], dtype="int64")
ser[[True, False]] = Series([0], index=[1], dtype="int64")
expected = Series([0, 2], index=[1, 2], dtype="int64")
tm.assert_series_equal(ser, ex... | TestSetitemBooleanMask |
python | pyparsing__pyparsing | tests/test_unit.py | {
"start": 5234,
"end": 6447
} | class ____(TestCase):
def runTest(self):
# test warnings enable detection
# fmt: off
tests = [
(([], "",), False),
((["d", ], "",), True),
((["d", "i:::pyparsing", ], "",), False),
((["d:::pyparsing", ], "",), True),
((["d:::pyparsi... | Test01a_PyparsingEnvironmentTests |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 9519,
"end": 9777
} | class ____(A21):
@classmethod
def m1(cls, arg):
return arg
def no_issue_taint_transform_with_class_interval_for_classmethods():
# Should not see an issue, due to not going through the taint transform
sink_d(C21.m0(_test_source()))
| C21 |
python | pypa__pipenv | pipenv/utils/locking.py | {
"start": 10257,
"end": 19693
} | class ____:
lockfile: lockfiles.Lockfile
path: Path = field(
default_factory=lambda: Path(os.curdir).joinpath("Pipfile.lock").absolute()
)
_requirements: Optional[List[Any]] = field(default_factory=list)
_dev_requirements: Optional[List[Any]] = field(default_factory=list)
projectfile: Pr... | Lockfile |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 7294,
"end": 7430
} | class ____:
def a(self):
pass
def b(self):
pass
# end
# E303
if True:
a = 1
a = 2
# end
# E303
| Class |
python | getsentry__sentry | src/sentry/search/eap/columns.py | {
"start": 3462,
"end": 3979
} | class ____(ResolvedColumn):
value: float
is_aggregate: bool = False
@property
def proto_definition(self) -> Column.BinaryFormula:
"""rpc doesn't understand a bare literal, so we return a no-op formula"""
return Column.BinaryFormula(
op=constants.ARITHMETIC_OPERATOR_MAP["plus... | ResolvedLiteral |
python | cherrypy__cherrypy | cherrypy/tutorial/tut05_derived_objects.py | {
"start": 1158,
"end": 1867
} | class ____(Page):
"""Home page app."""
# Different title for this page
title = 'Tutorial 5'
def __init__(self):
"""Mount another page into the home page app."""
# create a subpage
self.another = AnotherPage()
@cherrypy.expose
def index(self):
"""Produce HTTP re... | HomePage |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 12984,
"end": 13563
} | class ____(BaseIO):
fname = "__test__.csv"
params = ["c", "python"]
param_names = ["engine"]
def setup(self, engine):
N = 100000
group1 = ["aaaaaaaa", "bbbbbbb", "cccccccc", "dddddddd", "eeeeeeee"]
df = DataFrame(np.random.choice(group1, (N, 3)), columns=list("abc"))
df.... | ReadCSVCategorical |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/context.py | {
"start": 1023,
"end": 10202
} | class ____:
"""Context object that provides environment and path information during loading of
ComponentDecls. This context is automatically created and passed to ComponentDecl
objects when loading a project's defs folder. Each Python module or folder in the
defs directory receives a unique context inst... | ComponentDeclLoadContext |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_dialect.py | {
"start": 2390,
"end": 3929
} | class ____(fixtures.TestBase):
__only_on__ = "oracle+oracledb"
def test_oracledb_version_parse(self):
dialect = oracledb.OracleDialect_oracledb()
def check(version):
dbapi = Mock(version=version)
dialect._load_version(dbapi)
return dialect.oracledb_ver
... | OracleDbDialectTest |
python | huggingface__transformers | src/transformers/models/siglip2/modeling_siglip2.py | {
"start": 41065,
"end": 45748
} | class ____(Siglip2PreTrainedModel):
main_input_name = "pixel_values"
input_modalities = ("image",)
def __init__(self, config: Siglip2Config) -> None:
super().__init__(config)
self.num_labels = config.num_labels
# Create the vision model with proper attention
# and take onl... | Siglip2ForImageClassification |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_collections.py | {
"start": 383,
"end": 543
} | class ____(GQLResult):
org_entity: Optional[RegistryCollectionsOrganizationOrgEntity] = Field(
alias="orgEntity"
)
| RegistryCollectionsOrganization |
python | huggingface__transformers | src/transformers/models/blt/modular_blt.py | {
"start": 11104,
"end": 11537
} | class ____(MllamaSelfAttentionDecoderLayer):
def __init__(self, config, layer_idx: int):
super().__init__()
self.self_attn = BltSelfAttention(config=config, layer_idx=layer_idx)
self.mlp = BltMLP(config)
self.input_layernorm = BltRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
... | BltTransformerLayer |
python | scrapy__scrapy | tests/test_utils_signal.py | {
"start": 2111,
"end": 2380
} | class ____(TestSendCatchLogDeferred):
def ok_handler(self, arg, handlers_called):
handlers_called.add(self.ok_handler)
assert arg == "test"
d = defer.Deferred()
call_later(0, d.callback, "OK")
return d
| TestSendCatchLogDeferred2 |
python | huggingface__transformers | src/transformers/models/univnet/modeling_univnet.py | {
"start": 17657,
"end": 25461
} | class ____(PreTrainedModel):
config: UnivNetConfig
main_input_name = "input_features"
input_modalities = "audio"
def __init__(self, config: UnivNetConfig):
super().__init__(config)
self.num_kernels = len(config.resblock_kernel_sizes)
self.leaky_relu_slope = config.leaky_relu_sl... | UnivNetModel |
python | explosion__spaCy | spacy/schemas.py | {
"start": 20055,
"end": 20167
} | class ____(BaseModel):
efficiency: RecommendationTrfItem
accuracy: RecommendationTrfItem
| RecommendationTrf |
python | mlflow__mlflow | mlflow/store/artifact/databricks_artifact_repo_resources.py | {
"start": 892,
"end": 1029
} | class ____:
signed_uri: str
type: Any
headers: list[HttpHeader] = field(default_factory=list)
@dataclass
| ArtifactCredentialInfo |
python | django__django | django/db/utils.py | {
"start": 540,
"end": 580
} | class ____(Error):
pass
| InterfaceError |
python | apache__airflow | providers/elasticsearch/src/airflow/providers/elasticsearch/log/es_json_formatter.py | {
"start": 930,
"end": 1796
} | class ____(JSONFormatter):
"""Convert a log record to JSON with ISO 8601 date and time format."""
default_time_format = "%Y-%m-%dT%H:%M:%S"
default_msec_format = "%s.%03d"
default_tz_format = "%z"
def formatTime(self, record, datefmt=None):
"""Return the creation time of the LogRecord in I... | ElasticsearchJSONFormatter |
python | tensorflow__tensorflow | tensorflow/python/framework/composite_tensor_gradient.py | {
"start": 1236,
"end": 3322
} | class ____(object, metaclass=abc.ABCMeta):
"""Class used to help compute gradients for CompositeTensors.
This abstract base class defines two methods: `get_gradient_components`, which
returns the components of a value that should be included in gradients; and
`replace_gradient_components`, which replaces the g... | CompositeTensorGradient |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/monitoring_job/event_stream.py | {
"start": 6540,
"end": 16465
} | class ____(AirflowEvent):
dag_run: DagRun
@property
def timestamp(self) -> float:
return self.dag_run.end_date.timestamp()
def persist_state(
self,
context: OpExecutionContext,
airflow_data: AirflowDefinitionsData,
airflow_instance: AirflowInstance,
) -> Non... | DagRunCompleted |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/quantization_test.py | {
"start": 6781,
"end": 9530
} | class ____(op_bench.TorchBenchmarkBase):
r"""Benchmarks 3 different fake quantize per tensor operators."""
def init(self, N, C, H, W, zero_point_dtype, nbits, device, op_func):
self.quant_min = 0
self.quant_max = 2**nbits - 1
self.quant_range = 2**nbits
self.input = nn.Parameter... | FakeQuantizePerTensorBaseOpBenchmark |
python | astropy__astropy | astropy/io/fits/verify.py | {
"start": 3809,
"end": 5506
} | class ____(list):
"""
Verification errors list class. It has a nested list structure
constructed by error messages generated by verifications at
different class levels.
"""
def __init__(self, val=(), unit="Element"):
super().__init__(val)
self.unit = unit
def __str__(self)... | _ErrList |
python | celery__celery | t/unit/app/test_backends.py | {
"start": 345,
"end": 2494
} | class ____(CacheBackend):
test_instance_count = 0
test_call_stats = {}
def _track_attribute_access(self, method_name):
cls = type(self)
instance_no = getattr(self, '_instance_no', None)
if instance_no is None:
instance_no = self._instance_no = cls.test_instance_count
... | CachedBackendWithTreadTrucking |
python | sympy__sympy | sympy/integrals/laplace.py | {
"start": 81733,
"end": 87038
} | class ____(IntegralTransform):
"""
Class representing unevaluated inverse Laplace transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Laplace transforms, see the
:func:`inverse_laplace_transform` docstring.
"""
_name = 'Inverse Lap... | InverseLaplaceTransform |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_infra_overrides.py | {
"start": 196,
"end": 2250
} | class ____(Block):
context_name: str
config: Dict[str, Any]
@pytest.fixture
async def k8s_credentials():
block = MockKubernetesClusterConfig(context_name="default", config={})
await block.save("k8s-credentials")
return block
async def create_work_pool(
session, job_template: dict, type: str ... | MockKubernetesClusterConfig |
python | fastai__fastai | fastai/vision/augment.py | {
"start": 53023,
"end": 57050
} | class ____(RandTransform):
"Randomly selects a rectangle region in an image and randomizes its pixels."
order = 100 # After Normalize
def __init__(self,
p:float=0.5, # Probability of appying Random Erasing
sl:float=0., # Minimum proportion of erased area
sh:float=0.3, # Maximum prop... | RandomErasing |
python | apache__airflow | providers/google/tests/unit/google/ads/operators/test_ads.py | {
"start": 1486,
"end": 3313
} | class ____:
@mock.patch("airflow.providers.google.ads.operators.ads.GoogleAdsHook")
@mock.patch("airflow.providers.google.ads.operators.ads.GCSHook")
@mock.patch("airflow.providers.google.ads.operators.ads.NamedTemporaryFile")
@mock.patch("airflow.providers.google.ads.operators.ads.csv.writer")
def ... | TestGoogleAdsListAccountsOperator |
python | ray-project__ray | python/ray/serve/tests/unit/test_deployment_state.py | {
"start": 164592,
"end": 191095
} | class ____:
"""Test the behavior when draining node(s)."""
def test_draining_start_then_stop_replica(self, mock_deployment_state_manager):
"""A new replica should be started before stopping old replica.
If the new replica starts quickly, the replica on the draining
node should then be ... | TestStopReplicasOnDrainingNodes |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 27547,
"end": 29269
} | class ____(ABC):
assertEqual: Callable
def setUp(self) -> None:
self._node = _NodeDesc("this_node", 1, 1)
self._min_nodes = 1
self._max_nodes = 2
self._keep_alive_interval = timedelta(seconds=30)
self._state = _RendezvousState()
self._state.participants[_NodeD... | AbstractTestRendezvousOp |
python | scipy__scipy | scipy/fftpack/tests/test_pseudo_diffs.py | {
"start": 6895,
"end": 8228
} | class ____:
def test_definition(self):
for h in [0.1,0.5,1,5.5,10]:
for n in [16,17,64,127]:
x = arange(n)*2*pi/n
y = tilbert(sin(x),h)
y1 = direct_tilbert(sin(x),h)
assert_array_almost_equal(y,y1)
assert_array_almo... | TestTilbert |
python | pypa__pip | src/pip/_internal/build_env.py | {
"start": 8410,
"end": 13529
} | class ____:
"""Creates and manages an isolated environment to install build deps"""
def __init__(self, installer: BuildEnvironmentInstaller) -> None:
self.installer = installer
temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
self._prefixes = OrderedDict(
... | BuildEnvironment |
python | pandas-dev__pandas | pandas/io/excel/_base.py | {
"start": 18864,
"end": 33749
} | class ____(Generic[_WorkbookT]):
book: _WorkbookT
def __init__(
self,
filepath_or_buffer,
storage_options: StorageOptions | None = None,
engine_kwargs: dict | None = None,
) -> None:
if engine_kwargs is None:
engine_kwargs = {}
self.handles = IOH... | BaseExcelReader |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/utils.py | {
"start": 401,
"end": 1230
} | class ____(UserDict):
"""
openid puts e.g. class OpenIDServiceEndpoint in the session.
Django 1.6 no longer pickles stuff, so we'll need to do some
hacking here...
"""
def __init__(self, session):
UserDict.__init__(self)
self.data = session
def __setitem__(self, key, value)... | JSONSafeSession |
python | openai__openai-python | src/openai/types/responses/response_function_web_search.py | {
"start": 1261,
"end": 1794
} | class ____(BaseModel):
id: str
"""The unique ID of the web search tool call."""
action: Action
"""
An object describing the specific action taken in this web search call. Includes
details on how the model used the web (search, open_page, find).
"""
status: Literal["in_progress", "searc... | ResponseFunctionWebSearch |
python | apache__avro | lang/py/avro/test/test_io.py | {
"start": 16114,
"end": 17947
} | class ____(unittest.TestCase):
def __init__(self, field_type: Collection[str], default: Union[Dict[str, int], List[int], None, float, str]) -> None:
"""Ignore the normal signature for unittest.TestCase because we are generating
many test cases from this one class. This is safe as long as the autoloa... | DefaultValueTestCase |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/bijector_impl.py | {
"start": 1276,
"end": 4512
} | class ____(collections.namedtuple(
"_Mapping", ["x", "y", "ildj_map", "kwargs"])):
"""Helper class to make it easier to manage caching in `Bijector`."""
def __new__(cls, x=None, y=None, ildj_map=None, kwargs=None):
"""Custom __new__ so namedtuple items have defaults.
Args:
x: `Tensor`. Forward.
... | _Mapping |
python | bokeh__bokeh | examples/advanced/extensions/ticking.py | {
"start": 665,
"end": 853
} | class ____(TickFormatter):
__implementation__ = TypeScript(CODE)
p = figure()
p.scatter([1, 2, 3, 4, 6], [5, 7, 3, 2, 4], size=20)
p.xaxis.formatter = MyFormatter()
show(p)
| MyFormatter |
python | gevent__gevent | src/greentest/3.14/test_subprocess.py | {
"start": 2856,
"end": 71314
} | class ____(BaseTestCase):
def test_io_buffered_by_default(self):
p = subprocess.Popen(ZERO_RETURN_CMD,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
self.assertIsInstance(p.stdin, io.BufferedIOBase)
... | ProcessTestCase |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 93588,
"end": 97231
} | class ____(Normalize):
def __init__(self, vcenter, vmin=None, vmax=None):
"""
Normalize data with a set center.
Useful when mapping data with an unequal rates of change around a
conceptual center, e.g., data that range from -2 to 4, with 0 as
the midpoint.
Parameter... | TwoSlopeNorm |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/extra_trace.py | {
"start": 1826,
"end": 3929
} | class ____(TransformBase):
def transform(self, arg):
return transform_x(arg)
def extra_trace_through_override(o: TransformBase):
source = _test_source()
source_x = o.transform(source)
_test_sink(source_x)
# ExtraTraceSink is propagated as a sink, while LocalReturn is propagated as tito.
# Th... | OverrideTransform |
python | sqlalchemy__sqlalchemy | test/orm/test_syntax_extensions.py | {
"start": 2910,
"end": 3162
} | class ____(SyntaxExtension, ClauseElement):
_traverse_internals = []
def apply_to_select(self, select_stmt):
select_stmt.apply_syntax_extension_point(
lambda existing: [self],
"post_body",
)
| PostBodyClause |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 8890,
"end": 8962
} | class ____(ReauthenticateForm, inputs.Input):
pass
| ReauthenticateInput |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 7759,
"end": 10453
} | class ____(nn.Module):
def __init__(self, config: GroupViTVisionConfig, num_group_token, num_output_group):
super().__init__()
self.num_output_group = num_output_group
# norm on group_tokens
self.norm_tokens = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
assign... | GroupViTTokenAssign |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 53311,
"end": 58071
} | class ____(AiryBase):
r"""
The derivative $\operatorname{Ai}^\prime$ of the Airy function of the first
kind.
Explanation
===========
The Airy function $\operatorname{Ai}^\prime(z)$ is defined to be the
function
.. math::
\operatorname{Ai}^\prime(z) := \frac{\mathrm{d} \operato... | airyaiprime |
python | getsentry__sentry | tests/sentry/integrations/vsts_extension/test_provider.py | {
"start": 566,
"end": 3141
} | class ____(VstsIntegrationTestCase):
provider = VstsExtensionIntegrationProvider()
provider.pipeline = Mock()
provider.pipeline.organization.id = 1
@patch(
"sentry.integrations.vsts.integration.VstsIntegrationProvider.get_scopes",
return_value=FULL_SCOPES,
)
def test_get_pipelin... | VstsExtensionIntegrationProviderTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 51463,
"end": 52446
} | class ____(RegisterOp):
"""Get the address of a value: result = (type)&src
Attributes:
type: Type of the loaded address(e.g. ptr/object_ptr)
src: Source value (str for globals like 'PyList_Type',
Register for temporary values or locals, LoadStatic
for statics.)
"""
er... | LoadAddress |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.