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 | test/dynamo/cpython/3_13/typinganndata/ann_module695.py | {
"start": 65,
"end": 140
} | class ____[T, *Ts, **P]:
x: T
y: tuple[*Ts]
z: Callable[P, str]
| A |
python | apache__airflow | providers/edge3/src/airflow/providers/edge3/cli/dataclasses.py | {
"start": 1619,
"end": 2116
} | class ____:
"""Status of the worker."""
job_count: int
jobs: list
state: EdgeWorkerState
maintenance: bool
maintenance_comments: str | None
drain: bool
@property
def json(self) -> str:
"""Get the status as JSON."""
return json.dumps(asdict(self))
@staticmethod
... | WorkerStatus |
python | spack__spack | lib/spack/spack/vendor/pyrsistent/_pset.py | {
"start": 102,
"end": 5706
} | class ____(object):
"""
Persistent set implementation. Built on top of the persistent map. The set supports all operations
in the Set protocol and is Hashable.
Do not instantiate directly, instead use the factory functions :py:func:`s` or :py:func:`pset`
to create an instance.
Random access an... | PSet |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 67068,
"end": 70331
} | class ____(Operation):
def __init__(self, axis, epsilon=1e-3, *, name=None):
super().__init__(name=name)
self.axis = axis
self.epsilon = epsilon
def call(self, x, mean, variance, offset=None, scale=None):
return backend.nn.batch_normalization(
x,
mean,
... | BatchNorm |
python | huggingface__transformers | examples/modular-transformers/modeling_new_task_model.py | {
"start": 1429,
"end": 1986
} | class ____(BaseModelOutputWithPast):
r"""
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
... | NewTaskModelModelOutputWithPast |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 1825,
"end": 3714
} | class ____(DemoSafePermission):
scope_map = {
"GET": ["org:read", "org:write", "org:admin"],
"POST": ["org:write", "org:admin"],
"PUT": ["org:write", "org:admin"],
"DELETE": ["org:admin"],
}
def is_not_2fa_compliant(
self, request: Request, organization: RpcOrganizat... | OrganizationPermission |
python | pyca__cryptography | src/cryptography/x509/name.py | {
"start": 12017,
"end": 15363
} | class ____:
_OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+")
_DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*")
_ESCAPE_SPECIAL = r"[\\ #=\"\+,;<>]"
_ESCAPE_HEX = r"[\da-zA-Z]{2}"
_PAIR = rf"\\({_ESCAPE_SPECIAL}|{_ESCAPE_HEX})"
_PAIR_MULTI_RE = re.compile(rf"(\\{_ESCAPE_SPECIAL})|((\\{_E... | _RFC4514NameParser |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-genesys/source_genesys/source.py | {
"start": 1901,
"end": 2125
} | class ____(GenesysStream):
"""
API Docs: https://developer.genesys.cloud/routing/routing/
"""
primary_key = "id"
def path(self, **kwargs) -> str:
return "routing/assessments"
| RoutingOutboundEvents |
python | wandb__wandb | wandb/vendor/pygments/styles/algol.py | {
"start": 1372,
"end": 2263
} | class ____(Style):
background_color = "#ffffff"
default_style = ""
styles = {
Comment: "italic #888",
Comment.Preproc: "bold noitalic #888",
Comment.Special: "bold noitalic #888",
Keyword: "underline bold",
Ke... | AlgolStyle |
python | tensorflow__tensorflow | tensorflow/python/util/dispatch_test.py | {
"start": 2047,
"end": 2862
} | class ____(object):
"""A fake composite tensor class, for testing type-based dispatching."""
def __init__(self, tensor, score):
self.tensor = ops.convert_to_tensor(tensor)
self.score = score
@tf_export("test_op")
@dispatch.add_dispatch_support
def test_op(x, y, z):
"""A fake op for testing dispatch of ... | CustomTensor |
python | PrefectHQ__prefect | src/prefect/transactions.py | {
"start": 1105,
"end": 1211
} | class ____(AutoEnum):
READ_COMMITTED = AutoEnum.auto()
SERIALIZABLE = AutoEnum.auto()
| IsolationLevel |
python | getsentry__sentry | src/sentry/grouping/variants.py | {
"start": 547,
"end": 693
} | class ____(TypedDict):
values: list[str]
client_values: NotRequired[list[str]]
matched_rule: NotRequired[str]
| FingerprintVariantMetadata |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 56251,
"end": 58190
} | class ____(TestCase):
validator = None
def application(self, environ, start_response):
content_length = int(environ['CONTENT_LENGTH'])
if content_length > 1024:
start_response('417 Expectation Failed', [('Content-Length', '7'), ('Content-Type', 'text/plain')])
return [b'... | Expect100ContinueTests |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/tokenize_stage.py | {
"start": 367,
"end": 1878
} | class ____(StatefulStageUDF):
def __init__(
self,
data_column: str,
expected_input_keys: List[str],
model: str,
):
"""
Initialize the TokenizeUDF.
Args:
data_column: The data column name.
expected_input_keys: The expected input key... | TokenizeUDF |
python | pypa__setuptools | setuptools/_distutils/command/build.py | {
"start": 356,
"end": 5923
} | class ____(Command):
description = "build everything needed to install"
user_options = [
('build-base=', 'b', "base directory for build library"),
('build-purelib=', None, "build directory for platform-neutral distributions"),
('build-platlib=', None, "build directory for platform-speci... | build |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 91117,
"end": 91548
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("branch_protection_rule_id", "client_mutation_id")
branch_protection_rule_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="branchProtectionRuleId"
)
... | DeleteBranchProtectionRuleInput |
python | pytorch__pytorch | test/test_tensorexpr.py | {
"start": 399,
"end": 1089
} | class ____(JitTestCase):
def setUp(self):
super().setUp()
self.tensorexpr_options = TensorExprTestOptions()
self.devices = ['cpu'] if not torch.cuda.is_available() else ['cpu', 'cuda']
self.dtypes = [torch.float32, torch.bfloat16] if LLVM_ENABLED else [torch.float32]
def tearDow... | BaseTestClass |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 4020,
"end": 4425
} | class ____(GeneratorCallbackSpider):
name = "GeneratorCallbackSpiderMiddlewareRightAfterSpider"
custom_settings = {
"SPIDER_MIDDLEWARES": {
LogExceptionMiddleware: 100000,
},
}
# ================================================================================
# (3) exceptions f... | GeneratorCallbackSpiderMiddlewareRightAfterSpider |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 106842,
"end": 109917
} | class ____(ASTDeclarator):
def __init__(self, inner: ASTDeclarator, next: ASTDeclarator) -> None:
assert inner
assert next
self.inner = inner
self.next = next
# TODO: we assume the name, params, and qualifiers are in inner
def __eq__(self, other: object) -> bool:
... | ASTDeclaratorParen |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 40389,
"end": 40651
} | class ____(Operator):
""" Increment a lower b index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(-bi + _x, _x)
def __str__(self):
return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1])
| MeijerShiftC |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 407,
"end": 435
} | class ____[T = 3]: ...
| ClassT1 |
python | huggingface__transformers | src/transformers/models/rwkv/modeling_rwkv.py | {
"start": 8316,
"end": 11589
} | class ____(nn.Module):
def __init__(self, config, layer_id=0):
super().__init__()
self.config = config
kernel_loaded = rwkv_cuda_kernel is not None and rwkv_cuda_kernel.max_seq_length == config.context_length
if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded... | RwkvSelfAttention |
python | pytorch__pytorch | test/functorch/test_memory_efficient_fusion.py | {
"start": 11993,
"end": 12596
} | class ____(TestCase):
def test_random(self):
def f(x):
vals = [x]
ops = [torch.clone, torch.cos, torch.tanh, torch.nn.functional.gelu]
for _ in range(100):
new_val = random.choice(ops)(random.choice(vals))
vals.append(new_val)
r... | RandomOpTestCase |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py | {
"start": 1004,
"end": 1114
} | class ____(DbtCloudException):
"""Raised when a triggered job run is not complete."""
| DbtCloudJobRunIncomplete |
python | getsentry__sentry | src/sentry/api/endpoints/organization_trace.py | {
"start": 910,
"end": 3906
} | class ____(OrganizationEventsV2EndpointBase):
"""Replaces OrganizationEventsTraceEndpoint"""
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get_projects(
self,
request: HttpRequest,
organization: Organization | RpcOrganization,
force_global_perms: boo... | OrganizationTraceEndpoint |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 293,
"end": 420
} | class ____:
def func1(self, a: int, b: int = 3) -> str: ...
# This should generate an error because func1 is incompatible.
| A2 |
python | coleifer__peewee | tests/sqlite.py | {
"start": 91515,
"end": 91692
} | class ____(TestModel):
key = TextField(primary_key=True)
value = IntegerField()
@skip_unless(database.server_version >= (3, 35, 0), 'sqlite returning clause required')
| KVR |
python | django__django | tests/m2m_regress/models.py | {
"start": 1168,
"end": 1212
} | class ____(SelfRefer):
pass
| SelfReferChild |
python | doocs__leetcode | solution/1200-1299/1255.Maximum Score Words Formed by Letters/Solution.py | {
"start": 0,
"end": 491
} | class ____:
def maxScoreWords(
self, words: List[str], letters: List[str], score: List[int]
) -> int:
cnt = Counter(letters)
n = len(words)
ans = 0
for i in range(1 << n):
cur = Counter(''.join([words[j] for j in range(n) if i >> j & 1]))
if all(v ... | Solution |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_autograd.py | {
"start": 10091,
"end": 11171
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(1)
def test_post_acc_grad_hook_runs(self):
param_name_to_hook_count = collections.defaultdict(int)
def hook(param_name: str, param: torch.Tensor) -> None:
nonlocal par... | TestFullyShardPostAccGradHookMultiThread |
python | google__pytype | pytype/tests/test_typing2.py | {
"start": 23492,
"end": 26915
} | class ____(test_base.BaseTest):
"""Typing tests (Python 3)."""
def test_namedtuple_item(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from typing import NamedTuple
class Ret(NamedTuple):
x: int
y: str
def f() -> Ret: .... | TypingTestPython3Feature |
python | getsentry__sentry | src/sentry_plugins/github/webhooks/integration.py | {
"start": 623,
"end": 1479
} | class ____(GithubWebhookBase):
_handlers = {
"push": PushEventWebhook,
"installation": InstallationEventWebhook,
"installation_repositories": InstallationRepositoryEventWebhook,
}
@method_decorator(csrf_exempt)
def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpRes... | GithubPluginIntegrationsWebhookEndpoint |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/complex_schema_asset.py | {
"start": 453,
"end": 959
} | class ____(Component, Resolvable):
"""An asset that has a complex schema."""
value: str
list_value: list[str]
obj_value: dict[str, str]
op: Optional[OpSpec] = None
asset_attributes: Optional[ResolvedAssetAttributes] = None
def build_defs(self, context: ComponentLoadContext) -> Definitions:... | ComplexAssetComponent |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 7258,
"end": 7383
} | class ____(Unsupported):
pass
# debug exception thrown when tracing torch._dynamo.step_unsupported()
| RecompileLimitExceeded |
python | django-haystack__django-haystack | haystack/indexes.py | {
"start": 13939,
"end": 14879
} | class ____(SearchIndex):
text = CharField(document=True, use_template=True)
# End SearchIndexes
# Begin ModelSearchIndexes
def index_field_from_django_field(f, default=CharField):
"""
Returns the Haystack field type that would likely be associated with each
Django type.
"""
result = default
... | BasicSearchIndex |
python | django__django | tests/delete_regress/tests.py | {
"start": 777,
"end": 2243
} | class ____(TransactionTestCase):
available_apps = ["delete_regress"]
def setUp(self):
# Create a second connection to the default database
self.conn2 = connection.copy()
self.conn2.set_autocommit(False)
# Close down the second connection.
self.addCleanup(self.conn2.close... | DeleteLockingTest |
python | django-extensions__django-extensions | tests/management/test_modelviz.py | {
"start": 129,
"end": 2354
} | class ____(SimpleTestCase):
def test_generate_graph_data_can_render_label(self):
app_labels = ["auth"]
data = generate_graph_data(app_labels)
models = data["graphs"][0]["models"]
user_data = [x for x in models if x["name"] == "User"][0]
relation_labels = [x["label"] for x in... | ModelVizTests |
python | sqlalchemy__sqlalchemy | test/ext/declarative/test_reflection.py | {
"start": 1559,
"end": 1742
} | class ____(DeclarativeReflectionBase):
def teardown_test(self):
super().teardown_test()
_DeferredDeclarativeConfig._configs.clear()
Base = None
| DeferredReflectBase |
python | tornadoweb__tornado | tornado/testing.py | {
"start": 2287,
"end": 13493
} | class ____(unittest.TestCase):
"""`~unittest.TestCase` subclass for testing `.IOLoop`-based
asynchronous code.
The unittest framework is synchronous, so the test must be
complete by the time the test method returns. This means that
asynchronous code cannot be used in quite the same way as usual
... | AsyncTestCase |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 10374,
"end": 10723
} | class ____(desc_sig_element, _sig_element=True):
"""Node for a space in a signature."""
classes = ['w']
def __init__(
self,
rawsource: str = '',
text: str = ' ',
*children: Element,
**attributes: Any,
) -> None:
super().__init__(rawsource, text, *childre... | desc_sig_space |
python | django-haystack__django-haystack | test_haystack/elasticsearch7_tests/test_backend.py | {
"start": 63580,
"end": 67489
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = Elasticsearch7FacetingMockSearchIndex()
se... | Elasticsearch7FacetingTestCase |
python | readthedocs__readthedocs.org | readthedocs/storage/__init__.py | {
"start": 864,
"end": 1013
} | class ____(LazyObject):
def _setup(self):
self._wrapped = get_storage_class(settings.RTD_BUILD_MEDIA_STORAGE)()
| ConfiguredBuildMediaStorage |
python | great-expectations__great_expectations | great_expectations/data_context/types/base.py | {
"start": 21211,
"end": 35487
} | class ____(AbstractConfigSchema):
class Meta:
unknown = INCLUDE
name = fields.String(
required=False,
allow_none=True,
)
id = fields.String(
required=False,
allow_none=True,
)
class_name = fields.String(
required=True,
allow_none=False,
... | DataConnectorConfigSchema |
python | pytorch__pytorch | test/inductor/test_custom_post_grad_passes.py | {
"start": 2079,
"end": 2338
} | class ____(CustomGraphPass):
def __init__(self) -> None:
super().__init__()
def __call__(self, g: torch.fx.graph.Graph):
change_cos_pass(g)
def uuid(self) -> bytes:
return get_hash_for_files((__file__,))
| ChangeCosCustomPass |
python | Netflix__metaflow | metaflow/client/core.py | {
"start": 36254,
"end": 37453
} | class ____(object):
"""
Container of data artifacts produced by a `Task`. This object is
instantiated through `Task.data`.
`MetaflowData` allows results to be retrieved by their name
through a convenient dot notation:
```python
Task(...).data.my_object
```
You can also test the ex... | MetaflowData |
python | django__django | tests/admin_views/tests.py | {
"start": 309585,
"end": 313991
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
def setUp(self):
self.client.force_login(self.superuser)
def test_limit_choices_to(self):
... | RawIdFieldsTest |
python | plotly__plotly.py | plotly/graph_objs/layout/newshape/_line.py | {
"start": 235,
"end": 4451
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.newshape"
_path_str = "layout.newshape.line"
_valid_props = {"color", "dash", "width"}
@property
def color(self):
"""
Sets the line color. By default uses either dark grey or white
to increase contrast with bac... | Line |
python | pytorch__pytorch | test/distributed/pipelining/test_schedule.py | {
"start": 37366,
"end": 38715
} | class ____(TestCase):
def test_valid_schedule(self):
schedule_actions = [
{
0: [_Action(0, F, 0), _Action(0, B, 0)],
1: [_Action(1, F, 0), _Action(1, B, 0)],
},
{
0: [_Action(0, F, 0), _Action(0, I, 0), _Action(0, W, 0)],
... | TestValidateSchedule |
python | hyperopt__hyperopt | hyperopt/base.py | {
"start": 25111,
"end": 34756
} | class ____:
"""Picklable representation of search space and evaluation function."""
rec_eval_print_node_on_error = False
# -- the Ctrl object is not used directly, but rather
# a live Ctrl instance is inserted for the pyll_ctrl
# in self.evaluate so that it can be accessed from within
# ... | Domain |
python | huggingface__transformers | src/transformers/models/falcon/modeling_falcon.py | {
"start": 45797,
"end": 50482
} | class ____(FalconPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "transformer.word_embeddings.weight"}
def __init__(self, config: FalconConfig):
super().__init__(config)
self.transformer = FalconModel(config)
self.lm_head = nn.Linear(config.hidden_size, config... | FalconForCausalLM |
python | pennersr__django-allauth | tests/apps/account/test_models.py | {
"start": 145,
"end": 1146
} | class ____(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta(AbstractUser.Meta): # type: ignore[name-defined]
swappable = "AUTH_USER_MODEL"
app_label = "dummy"
def test_add_new_email(rf, user, settings):
settings.ACCOUNT_CHANGE_EMAIL = ... | UUIDUser |
python | getsentry__sentry | src/sentry/integrations/jira/client.py | {
"start": 814,
"end": 8944
} | class ____(ApiClient):
# TODO: Update to v3 endpoints
COMMENTS_URL = "/rest/api/2/issue/%s/comment"
COMMENT_URL = "/rest/api/2/issue/%s/comment/%s"
STATUS_URL = "/rest/api/2/status"
CREATE_URL = "/rest/api/2/issue"
ISSUE_URL = "/rest/api/2/issue/%s"
META_URL = "/rest/api/2/issue/createmeta"
... | JiraCloudClient |
python | numba__numba | numba/tests/test_mandelbrot.py | {
"start": 262,
"end": 595
} | class ____(unittest.TestCase):
def test_mandelbrot(self):
pyfunc = is_in_mandelbrot
cfunc = njit((types.complex64,))(pyfunc)
points = [0+0j, 1+0j, 0+1j, 1+1j, 0.1+0.1j]
for p in points:
self.assertEqual(cfunc(p), pyfunc(p))
if __name__ == '__main__':
unittest.main... | TestMandelbrot |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict18.py | {
"start": 1650,
"end": 1858
} | class ____(TD7[Literal[1]]): ...
def func6(a: TD8) -> Literal[1]:
return a["x"]
func6({"x": 1, "y": 1, "z": "a"})
f4: TD8 = {"x": 1, "y": 1, "z": "a"}
reveal_type(func6({"x": 1, "y": 1, "z": "a"}))
| TD8 |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/manager/ssh.py | {
"start": 939,
"end": 14358
} | class ____(SpyderRemoteAPIManagerBase):
"""Class to manage a remote SSH server and its APIs."""
_extra_options = ["platform", "id", "default_kernel_spec"]
START_SERVER_COMMAND = (
f"/${{HOME}}/.local/bin/micromamba run -n {SERVER_ENV} spyder-server"
)
GET_SERVER_INFO_COMMAND = (
f"... | SpyderRemoteSSHAPIManager |
python | django__django | tests/many_to_many/models.py | {
"start": 1436,
"end": 1650
} | class ____(models.Model):
user = models.ForeignKey(User, models.CASCADE, to_field="username")
article = models.ForeignKey(Article, models.CASCADE)
# Models to test correct related_name inheritance
| UserArticle |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeIs1.py | {
"start": 2078,
"end": 4386
} | class ____(Animal): ...
T = TypeVar("T")
def is_marsupial(val: Animal) -> TypeIs[Kangaroo | Koala]:
return isinstance(val, Kangaroo | Koala)
# This should generate an error because list[T] isn't consistent with list[T | None].
def has_no_nones(val: list[T | None]) -> TypeIs[list[T]]:
return None not in va... | Koala |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 30733,
"end": 31308
} | class ____(AsyncHTTPTestCase):
def get_app(self):
class LargeBody(RequestHandler):
def get(self):
self.write("a" * 1024 * 100)
return Application([("/large", LargeBody)])
def get_http_client(self):
# 100KB body with 64KB buffer
return SimpleAsyncHTTP... | MaxBufferSizeTest |
python | getsentry__sentry | src/sentry/api/serializers/models/exporteddata.py | {
"start": 245,
"end": 1743
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
attrs = {}
serialized_users = {
u["id"]: u
for u in user_service.serialize_many(
filter=dict(user_ids=[item.user_id for item in item_list])
)
}
for item in item... | ExportedDataSerializer |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 26776,
"end": 27906
} | class ____(_base.StatMixin, watcher):
_watcher_type = 'fs_poll'
_watcher_struct_name = 'gevent_fs_poll_t'
_watcher_callback_name = '_gevent_fs_poll_callback3'
def _watcher_set_data(self, the_watcher, data):
the_watcher.handle.data = data
return data
def _watcher_ffi_init(self, args... | stat |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 96321,
"end": 100229
} | class ____:
def test_simple(self):
[X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
assert_array_equal(X, np.array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]))
assert_array_eq... | TestMeshgrid |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_numeric.py | {
"start": 2693,
"end": 4861
} | class ____:
def test_operator_series_comparison_zerorank(self):
# GH#13006
result = np.float64(0) > Series([1, 2, 3])
expected = 0.0 > Series([1, 2, 3])
tm.assert_series_equal(result, expected)
result = Series([1, 2, 3]) < np.float64(0)
expected = Series([1, 2, 3]) < ... | TestNumericComparisons |
python | numpy__numpy | numpy/lib/tests/test_type_check.py | {
"start": 5369,
"end": 6810
} | class ____:
def test_basic(self):
z = np.array([-1, 0, 1])
assert_(not iscomplexobj(z))
z = np.array([-1j, 0, -1])
assert_(iscomplexobj(z))
def test_scalar(self):
assert_(not iscomplexobj(1.0))
assert_(iscomplexobj(1 + 0j))
def test_list(self):
asse... | TestIscomplexobj |
python | walkccc__LeetCode | solutions/3395. Subsequences with a Unique Middle Mode I/3395-2.py | {
"start": 0,
"end": 1237
} | class ____:
def subsequencesWithMiddleMode(self, nums: list[int]) -> int:
MOD = 1_000_000_007
ans = 0
p = collections.Counter() # prefix counter
s = collections.Counter(nums) # suffix counter
def nC2(n: int) -> int:
return n * (n - 1) // 2
for i, a in enumerate(nums):
s[a] -= 1... | Solution |
python | Textualize__textual | src/textual/widgets/_welcome.py | {
"start": 744,
"end": 1535
} | class ____(Static):
"""A Textual welcome widget.
This widget can be used as a form of placeholder within a Textual
application; although also see
[Placeholder][textual.widgets._placeholder.Placeholder].
"""
DEFAULT_CSS = """
Welcome {
width: 100%;
height: 100%;
... | Welcome |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run_event.py | {
"start": 1076,
"end": 1305
} | class ____(BaseModel):
"""Paginated run events response."""
items: list[DgApiRunEvent]
total: int
cursor: Optional[str] = None
has_more: bool = False
class Config:
from_attributes = True
| RunEventList |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/window.py | {
"start": 1933,
"end": 1986
} | class ____:
Window = "window"
| EditorMainWindowMenus |
python | gevent__gevent | src/gevent/tests/test__hub.py | {
"start": 2839,
"end": 3175
} | class ____(gevent.testing.timing.AbstractGenericWaitTestCase):
def setUp(self):
super(TestWaiterGet, self).setUp()
self.waiter = Waiter()
def wait(self, timeout):
with get_hub().loop.timer(timeout) as evt:
evt.start(self.waiter.switch, None)
return self.waiter.g... | TestWaiterGet |
python | kamyu104__LeetCode-Solutions | Python/remove-k-balanced-substrings.py | {
"start": 37,
"end": 900
} | class ____(object):
def removeSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
def count(x):
if x == '(':
if cnt[0] < k:
cnt[0] += 1
elif cnt[0] > k:
cnt[0] = 1
... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 208657,
"end": 213191
} | class ____(TypedDict, total=False):
"""
:class:`altair.PointSelectionConfigWithoutType` ``TypedDict`` wrapper.
Parameters
----------
clear
Clears the selection, emptying it of all values. This property can be a `Event
Stream <https://vega.github.io/vega/docs/event-streams/>`__ or ``... | PointSelectionConfigWithoutTypeKwds |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 9793,
"end": 9972
} | class ____(InvalidRequestError):
"""An object that tracks state encountered an illegal state change
of some kind.
.. versionadded:: 2.0
"""
| IllegalStateChangeError |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 84443,
"end": 85621
} | class ____(Operation):
def call(self, x, bins):
return backend.numpy.digitize(x, bins)
def compute_output_spec(self, x, bins):
bins_shape = bins.shape
if len(bins_shape) > 1:
raise ValueError(
f"`bins` must be a 1D array. Received: bins={bins} "
... | Digitize |
python | marshmallow-code__apispec | tests/test_ext_marshmallow.py | {
"start": 779,
"end": 7703
} | class ____:
@pytest.mark.parametrize("schema", [PetSchema, PetSchema()])
def test_can_use_schema_as_definition(self, spec, schema):
spec.components.schema("Pet", schema=schema)
definitions = get_schemas(spec)
props = definitions["Pet"]["properties"]
assert props["id"]["type"] ==... | TestDefinitionHelper |
python | ansible__ansible | test/lib/ansible_test/_util/controller/sanity/pylint/plugins/deprecated_calls.py | {
"start": 1536,
"end": 22241
} | class ____(pylint.checkers.BaseChecker):
"""Checks for deprecated calls to ensure proper usage."""
name = 'deprecated-calls'
msgs = {
'E9501': (
"Deprecated version %r found in call to %r",
"ansible-deprecated-version",
None,
),
'E9502': (
... | AnsibleDeprecatedChecker |
python | PyCQA__pylint | tests/functional/m/member/member_checks.py | {
"start": 2062,
"end": 2222
} | class ____:
"""no-member shouldn't be emitted for classes with dunder getattr."""
def __getattr__(self, attr):
return self.__dict__[attr]
| Getattr |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 279,
"end": 1293
} | class ____(BaseIO):
fname = "__test__.csv"
params = ["wide", "long", "mixed"]
param_names = ["kind"]
def setup(self, kind):
wide_frame = DataFrame(np.random.randn(3000, 30))
long_frame = DataFrame(
{
"A": np.arange(50000),
"B": np.arange(50000... | ToCSV |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink25.py | {
"start": 315,
"end": 945
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink25.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | sympy__sympy | sympy/vector/basisdependent.py | {
"start": 10160,
"end": 11871
} | class ____(BasisDependent):
"""
Class to denote a zero basis dependent instance.
"""
components: dict['BaseVector', Expr] = {}
_latex_form: str
def __new__(cls):
obj = super().__new__(cls)
# Pre-compute a specific hash value for the zero vector
# Use the same one always
... | BasisDependentZero |
python | joke2k__faker | faker/providers/internet/en_NZ/__init__.py | {
"start": 46,
"end": 425
} | class ____(InternetProvider):
free_email_domains = (
"gmail.com",
"yahoo.com",
"hotmail.com",
"inspire.net.nz",
"xtra.co.nz",
)
tlds = (
"nz",
"co.nz",
"org.nz",
"kiwi",
"kiwi.nz",
"geek.nz",
"net.nz",
"... | Provider |
python | ray-project__ray | python/ray/experimental/channel/cpu_communicator.py | {
"start": 299,
"end": 3351
} | class ____:
"""
Barrier actor that blocks the given number of actors until all actors have
reached the Barrier.
p2p operations are not done here (completed via shared memory channel).
"""
def __init__(self, num_actors: int):
self.num_actors = num_actors
self.condition = asyncio... | CPUCommBarrier |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/libtool_deletion/package.py | {
"start": 637,
"end": 1237
} | class ____(autotools.AutotoolsBuilder):
install_libtool_archives = False
def autoreconf(self, pkg, spec, prefix):
mkdirp(os.path.dirname(self.configure_abs_path))
touch(self.configure_abs_path)
def configure(self, pkg, spec, prefix):
pass
def build(self, pkg, spec, prefix):
... | AutotoolsBuilder |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 8097,
"end": 8922
} | class ____(ModelEvent):
''' Announce a location where an axis was clicked.
For continuous numerical axes, the value will be a number. For log axes,
this number is the log decade.
For categorical axes, the value will be a categorical factor, i.e. a string
or a list of strings, representing the clos... | AxisClick |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 13411,
"end": 13504
} | class ____(ExceptionFieldMatch):
field_path = ["mechanism", "type"]
| ExceptionMechanismMatch |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_process_runner.py | {
"start": 46501,
"end": 60102
} | class ____(RuntimeError):
"""An error indicating `multi_process_runner.run` is used without init.
When this is raised, user is supposed to call
`tf.__internal__.distribute.multi_process_runner.test_main()` within
`if __name__ == '__main__':` block to properly initialize
`multi_process_runner.run`.
"""
pa... | NotInitializedError |
python | jazzband__tablib | src/tablib/core.py | {
"start": 2263,
"end": 25261
} | class ____:
"""The :class:`Dataset` object is the heart of Tablib. It provides all core
functionality.
Usually you create a :class:`Dataset` instance in your main module, and append
rows as you collect data. ::
data = tablib.Dataset()
data.headers = ('name', 'age')
for (name, ... | Dataset |
python | astropy__astropy | astropy/time/formats.py | {
"start": 76795,
"end": 78513
} | class ____(TimeString):
"""
Base class to support string Besselian and Julian epoch dates
such as 'B1950.0' or 'J2000.0' respectively.
"""
_default_scale = "tt" # As of astropy 3.2, this is no longer 'utc'.
def set_jds(self, val1, val2):
epoch_prefix = self.epoch_prefix
# Be l... | TimeEpochDateString |
python | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/model.py | {
"start": 568,
"end": 1106
} | class ____(BaseModel):
"""pydantic BaseModel configured with recommended default settings for use with the Resolved framework.
Extra fields are disallowed when instantiating this model to help catch errors earlier.
Example:
.. code-block:: python
import dagster as dg
class MyModel(d... | Model |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25561,
"end": 25686
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Altlinux'
strategy_class = RedHatStrategy
| ALTLinuxHostname |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 2105,
"end": 2220
} | class ____(RequestHandler):
def get(self):
self.finish(self.request.headers["Authorization"])
| AuthHandler |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/resources/pythonic_resources.py | {
"start": 10123,
"end": 23026
} | class ____:
def connect(self) -> Connection:
return Connection()
def create_engine(*args, **kwargs):
return Engine()
def raw_github_resource_dep() -> None:
# start_raw_github_resource_dep
import dagster as dg
class DBResource(dg.ConfigurableResource):
engine: dg.ResourceDependen... | Engine |
python | python-attrs__attrs | typing-examples/baseline.py | {
"start": 1066,
"end": 1160
} | class ____:
num: int = attrs.field(validator=attrs.validators.ge(0))
@attrs.define
| Validated |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_timedelta64.py | {
"start": 53513,
"end": 81512
} | class ____:
# Tests for timedelta64[ns]
# __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__
# ------------------------------------------------------------------
# Multiplication
# organized with scalar others first, then array-like
def test_td64arr_mul_int(self, box_with_array)... | TestTimedeltaArraylikeMulDivOps |
python | etianen__django-reversion | tests/test_app/tests/test_commands.py | {
"start": 6417,
"end": 7162
} | class ____(TestModelMixin, TestBase):
def testDeleteRevisionsDays(self):
date_created = timezone.now() - timedelta(days=20)
with reversion.create_revision():
TestModel.objects.create()
reversion.set_date_created(date_created)
self.callCommand("deleterevisions", days=... | DeleteRevisionsDaysTest |
python | keras-team__keras | keras/src/metrics/accuracy_metrics_test.py | {
"start": 15008,
"end": 17248
} | class ____(testing.TestCase):
def test_config(self):
top_k_cat_acc_obj = accuracy_metrics.TopKCategoricalAccuracy(
k=1, name="top_k_categorical_accuracy", dtype="float32"
)
self.assertEqual(top_k_cat_acc_obj.name, "top_k_categorical_accuracy")
self.assertEqual(len(top_k_c... | TopKCategoricalAccuracyTest |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 324,
"end": 519
} | class ____(pydantic.BaseModel):
column_name: str
sort_ascending: bool = True
method_name: Literal["partition_on_year_and_month"] = "partition_on_year_and_month"
| ColumnPartitionerMonthly |
python | ray-project__ray | python/ray/util/tracing/tracing_helper.py | {
"start": 3772,
"end": 5024
} | class ____(Exception):
pass
def _import_from_string(import_str: Union[ModuleType, str]) -> ModuleType:
"""Given a string that is in format "<module>:<attribute>",
import the attribute."""
if not isinstance(import_str, str):
return import_str
module_str, _, attrs_str = import_str.partition... | _ImportFromStringError |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 35239,
"end": 36784
} | class ____(JsIterable[KT], Generic[KT, VT_co], Mapping[KT, VT_co], metaclass=_ABCMeta):
"""A JavaScript Map
To be considered a map, a JavaScript object must have a ``get`` method, it
must have a ``size`` or a ``length`` property which is a number
(idiomatically it should be called ``size``) and it must... | JsMap |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokeh_prop.py | {
"start": 2216,
"end": 4494
} | class ____(BokehDirective):
has_content = True
required_arguments = 1
optional_arguments = 2
option_spec = {"module": unchanged, "type": unchanged}
def run(self):
full_name = self.arguments[0]
model_name, prop_name = full_name.rsplit(".")
module_name = self.options["module... | BokehPropDirective |
python | mwaskom__seaborn | tests/_core/test_properties.py | {
"start": 16751,
"end": 19112
} | class ____(DataFixtures):
def norm(self, x):
return (x - x.min()) / (x.max() - x.min())
@pytest.mark.parametrize("data_type,scale_class", [
("cat", Nominal),
("num", Continuous),
("bool", Boolean),
])
def test_default(self, data_type, scale_class, vectors):
x =... | IntervalBase |
python | PrefectHQ__prefect | src/integrations/prefect-redis/prefect_redis/messaging.py | {
"start": 6047,
"end": 6391
} | class ____:
"""
A subscription-like object for Redis. We mimic the memory subscription interface
so that we can set max_retries and handle dead letter queue storage in Redis.
"""
def __init__(self, max_retries: int = 3, dlq_key: str = "dlq"):
self.max_retries = max_retries
self.dlq_... | Subscription |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.