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 | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 14749,
"end": 15918
} | class ____(Benchmark):
r"""
Schwefel 21 objective function.
This class defines the Schwefel 21 [1]_ global optimization problem. This
is a unimodal minimization problem defined as follows:
.. math::
f_{\text{Schwefel21}}(x) = \smash{\displaystyle\max_{1 \leq i \leq n}}
... | Schwefel21 |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 12309,
"end": 12400
} | class ____:
def __init__(self) -> None:
self.val = 0.5
self.count = 3
| Cfg |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 28289,
"end": 58240
} | class ____(object):
"""Informational class which holds the details about an
archive member given by a tar header block.
TarInfo objects are returned by TarFile.getmember(),
TarFile.getmembers() and TarFile.gettarinfo() and are
usually created internally.
"""
__slots__ = dict(
... | TarInfo |
python | jazzband__django-oauth-toolkit | oauth2_provider/scopes.py | {
"start": 40,
"end": 1100
} | class ____:
def get_all_scopes(self):
"""
Return a dict-like object with all the scopes available in the
system. The key should be the scope name and the value should be
the description.
ex: {"read": "A read scope", "write": "A write scope"}
"""
raise NotImpl... | BaseScopes |
python | huggingface__transformers | src/transformers/models/sam3_video/configuration_sam3_video.py | {
"start": 828,
"end": 11507
} | class ____(PreTrainedConfig):
r"""
Configuration class for [`Sam3VideoModel`]. This combines configurations for the detector (Sam3) and tracker
(Sam2Video) components, along with detection-tracking fusion hyperparameters.
Instantiating a configuration defaults will yield a similar configuration to that... | Sam3VideoConfig |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 19939,
"end": 23474
} | class ____(nn.Module):
"""
Cross-Attention used in DAB-DETR 'DAB-DETR for Fast Training Convergence' paper.
The key q_proj, k_proj, v_proj are defined outside the attention. This attention allows the dim of q, k to be
different to v.
"""
def __init__(self, config: DabDetrConfig, bias: bool = T... | DabDetrAttention |
python | ray-project__ray | python/ray/train/examples/pytorch/torch_quick_start.py | {
"start": 380,
"end": 2882
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28 * 28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
)
... | NeuralNetwork |
python | walkccc__LeetCode | solutions/2309. Greatest English Letter in Upper and Lower Case/2309.py | {
"start": 0,
"end": 240
} | class ____:
def greatestLetter(self, s: str) -> str:
seen = set(s)
for i in range(25, -1, -1):
if (chr(ord('a') + i) in seen and
chr(ord('A') + i) in seen):
return chr(ord('A') + i)
return ''
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hardcoded-records/source_hardcoded_records/source.py | {
"start": 295,
"end": 831
} | class ____(AbstractSource):
def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Any]:
if type(config["count"]) == int or type(config["count"]) == float:
return True, None
else:
return False, "Count option is missing"
def streams(s... | SourceHardcodedRecords |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/deep_learning/optimizers.py | {
"start": 2161,
"end": 3306
} | class ____():
def __init__(self, rho=0.95, eps=1e-6):
self.E_w_updt = None # Running average of squared parameter updates
self.E_grad = None # Running average of the squared gradient of w
self.w_updt = None # Parameter update
self.eps = eps
self.rho = rho
def update(... | Adadelta |
python | jazzband__django-waffle | test_app/views.py | {
"start": 3123,
"end": 3198
} | class ____(WaffleFlagMixin, BaseWaffleView):
waffle_flag = 'foo'
| FlagView |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py | {
"start": 10066,
"end": 13602
} | class ____(ReadonlyGraphQLContextTestMatrix):
def _create_backfill(self, graphql_context):
code_location = graphql_context.get_code_location(main_repo_location_name())
repository = code_location.get_repository("test_repo")
backfill = PartitionBackfill(
backfill_id=make_new_backf... | TestPartitionBackillReadonlyFailure |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 32259,
"end": 33708
} | class ____(unittest.TestCase):
def test_build(self):
class TestObject:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
... | NonKwargParametersTestCase |
python | huggingface__transformers | tests/utils/test_tokenization_utils.py | {
"start": 12019,
"end": 13094
} | class ____(unittest.TestCase):
def test_extensions(self):
# Test searching by prefix
trie = ExtensionsTrie()
trie.add("foo")
trie.add("food")
trie.add("foodie")
trie.add("helium")
self.assertEqual(trie.extensions("foo"), ["foo", "food", "foodie"])
self... | ExtensionsTrieTest |
python | openai__openai-python | src/openai/types/responses/computer_tool_param.py | {
"start": 217,
"end": 693
} | class ____(TypedDict, total=False):
display_height: Required[int]
"""The height of the computer display."""
display_width: Required[int]
"""The width of the computer display."""
environment: Required[Literal["windows", "mac", "linux", "ubuntu", "browser"]]
"""The type of computer environment t... | ComputerToolParam |
python | pandas-dev__pandas | pandas/tests/indexes/test_index_new.py | {
"start": 14235,
"end": 14572
} | class ____:
def test_constructor_overflow_int64(self):
# see GH#15832
msg = (
"The elements provided in the data cannot all be casted to the dtype int64"
)
with pytest.raises(OverflowError, match=msg):
Index([np.iinfo(np.uint64).max - 1], dtype="int64")
| TestIndexConstructionErrors |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 24989,
"end": 27010
} | class ____:
def test_override_builtin(self):
c1 = Column("foo", self._add_override_factory())
self._assert_add_override(c1)
def test_subquery_proxy(self):
t = Table("t", MetaData(), Column("foo", self._add_override_factory()))
proxied = t.select().subquery().c.foo
self._... | _CustomComparatorTests |
python | Netflix__metaflow | metaflow/datastore/datastore_storage.py | {
"start": 592,
"end": 9038
} | class ____(object):
"""
A DataStoreStorage defines the interface of communication between the
higher-level datastores and the actual storage system.
Both the ContentAddressedStore and the TaskDataStore use these methods to
read/write/list from the actual storage system. These methods are meant to
... | DataStoreStorage |
python | doocs__leetcode | solution/0700-0799/0780.Reaching Points/Solution.py | {
"start": 0,
"end": 453
} | class ____:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while tx > sx and ty > sy and tx != ty:
if tx > ty:
tx %= ty
else:
ty %= tx
if tx == sx and ty == sy:
return True
if tx == sx:
ret... | Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_hf_safetensor_e2e.py | {
"start": 11927,
"end": 16387
} | class ____(DTensorTestBase):
"""
Test DCP reshard for DTensor with placements changes and without world_size change and mesh_tensor change.
"""
@with_comms
@skip_if_lt_x_gpu(2)
@with_temp_dir
def test_1d_to_1d_reshard_placement_change(self) -> None:
if importlib.util.find_spec("safe... | TestDTensorReshardPlacementChange |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 60530,
"end": 61834
} | class ____(Response):
"""
Response of queues.move_task_to_front endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_to_front"
_version = "2.9"
_sch... | MoveTaskToFrontResponse |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_gcs.py | {
"start": 14734,
"end": 21642
} | class ____:
TRIGGER = GCSUploadSessionTrigger(
bucket=TEST_BUCKET,
prefix=TEST_PREFIX,
poke_interval=TEST_POLLING_INTERVAL,
google_cloud_conn_id=TEST_GCP_CONN_ID,
hook_params=TEST_HOOK_PARAMS,
inactivity_period=TEST_INACTIVITY_PERIOD,
min_objects=TEST_MIN_OBJE... | TestGCSUploadSessionTrigger |
python | etianen__django-reversion | tests/test_app/models.py | {
"start": 1668,
"end": 1892
} | class ____(models.Model):
test_model = models.ForeignKey(
TestModel,
on_delete=models.CASCADE,
)
inline_name = models.CharField(
max_length=191,
default="v1",
)
| TestModelInline |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_delayed_workflow.py | {
"start": 33478,
"end": 38036
} | class ____(TestDelayedWorkflowBase):
def setUp(self) -> None:
super().setUp()
action1 = self.create_action(
type=Action.Type.DISCORD,
integration_id="1234567890",
config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC},
data={... | TestFireActionsForGroups |
python | kamyu104__LeetCode-Solutions | Python/goat-latin.py | {
"start": 189,
"end": 589
} | class ____(object):
def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
def convert(S):
vowel = set('aeiouAEIOU')
for i, word in enumerate(S.split(), 1):
if word[0] not in vowel:
word = word[1:] + word[:1]
... | Solution |
python | python-pillow__Pillow | src/PIL/ImageTransform.py | {
"start": 2359,
"end": 3184
} | class ____(Transform):
"""
Define a transform to extract a subregion from an image.
Maps a rectangle (defined by two corners) from the image to a rectangle of
the given size. The resulting image will contain data sampled from between
the corners, such that (x0, y0) in the input image will end up at... | ExtentTransform |
python | mlflow__mlflow | examples/pytorch/HPOExample/hpo_mnist.py | {
"start": 595,
"end": 5477
} | class ____(nn.Module):
def __init__(self, hidden_size, dropout_rate):
super().__init__()
self.fc1 = nn.Linear(784, hidden_size)
self.dropout = nn.Dropout(dropout_rate)
self.fc2 = nn.Linear(hidden_size, 10)
def forward(self, x):
x = x.view(-1, 784)
x = F.relu(self... | SimpleNet |
python | getsentry__sentry | src/sentry/workflow_engine/models/action.py | {
"start": 1052,
"end": 1121
} | class ____(TypedDict):
id: int
type: Action.Type
| ActionSnapshot |
python | realpython__materials | python-type-checking/hearts.py | {
"start": 5236,
"end": 8109
} | class ____:
def __init__(self, *names: str) -> None:
self.names = (list(names) + "P1 P2 P3 P4".split())[:4]
self.players = [Player(n) for n in self.names[1:]]
self.players.append(HumanPlayer(self.names[0]))
def play(self) -> None:
"""Play a game of Hearts until one player go bus... | HeartsGame |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/expression8.py | {
"start": 257,
"end": 568
} | class ____(Protocol[_T_contra]):
@abstractmethod
def __lt__(self, __x: _T_contra) -> bool:
pass
def custom_compare(a: ComparableTo[_T], b: _T) -> bool:
return a < b
custom_compare("first", "second")
custom_compare(3, 2)
# This should generate an error.
custom_compare(3, "hi")
| ComparableTo |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_assigned_email.py | {
"start": 145,
"end": 603
} | class ____(ActivityMailDebugView):
def get_activity(self, request: AuthenticatedHttpRequest, event):
return {
"type": ActivityType.ASSIGNED.value,
"user_id": request.user.id,
"data": {
"assignee": "10000000",
"assigneeEmail": "foo@example.c... | DebugAssignedEmailView |
python | kamyu104__LeetCode-Solutions | Python/length-of-longest-v-shaped-diagonal-segment.py | {
"start": 2827,
"end": 4103
} | class ____(object):
def lenOfVDiagonal(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def memoization(i, j, x, d, k):
if not (0 <= i < n and 0 <= j < m):
return 0
if grid[i][j] != x:
return 0
if... | Solution2 |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 118036,
"end": 119838
} | class ____(test_util.TensorFlowTestCase):
def testGraphDefVersion(self):
"""Test that the graphdef version is plumbed through to kernels."""
with ops.Graph().as_default() as g:
version = g.graph_def_versions.producer
with self.session(graph=g):
v = test_ops.graph_def_version().eval()
... | AsGraphDefTest |
python | GoogleCloudPlatform__python-docs-samples | cloud-media-livestream/keypublisher/main_test.py | {
"start": 1053,
"end": 7170
} | class ____:
@pytest.fixture(autouse=True)
def _get_app(self, app: flask.Flask) -> None:
self.app = app
@pytest.fixture(autouse=True)
def _mock(self, mock: unittest.mock.MagicMock) -> None:
self.secret_manager_mock = mock
def test_should_create_secret_and_version(
self, mock... | TestMain |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 6093,
"end": 6538
} | class ____(_Permission[TenantsAction]):
collection: str
tenant: str
def _to_weaviate(self) -> List[WeaviatePermission]:
return [
{
"action": action,
"tenants": {
"collection": _capitalize_first_letter(self.collection),
... | _TenantsPermission |
python | getsentry__sentry | src/sentry/analytics/events/first_sourcemaps_sent.py | {
"start": 349,
"end": 528
} | class ____(FirstSourcemapsSentEvent):
pass
analytics.register(FirstSourcemapsSentEvent)
analytics.register(FirstSourcemapsSentEventForProject)
| FirstSourcemapsSentEventForProject |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 275885,
"end": 276555
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("DeploymentProtectionRuleEdge"), graphql_name="edges"
)
no... | DeploymentProtectionRuleConnection |
python | jazzband__django-polymorphic | src/polymorphic/admin/forms.py | {
"start": 140,
"end": 684
} | class ____(forms.Form):
"""
The default form for the ``add_type_form``. Can be overwritten and replaced.
"""
#: Define the label for the radiofield
type_label = _("Type")
ct_id = forms.ChoiceField(
label=type_label, widget=AdminRadioSelect(attrs={"class": "radiolist"})
)
def _... | PolymorphicModelChoiceForm |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess25.py | {
"start": 219,
"end": 831
} | class ____(Generic[T]):
x: T
y: int
def __init__(self, label: T | None = None) -> None: ...
ClassA[int].y = 1
ClassA[int].y
del ClassA[int].y
ClassA.y = 1
ClassA.y
del ClassA.y
# This should generate an error because x is generic.
ClassA[int].x = 1
# This should generate an error because x is generic.... | ClassA |
python | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 38667,
"end": 39087
} | class ____(LogFormatter):
"""
Format values for log axis using ``exponent = log_base(value)``.
"""
def _num_to_string(self, x, vmin, vmax):
fx = math.log(x) / math.log(self._base)
if 1 <= abs(fx) <= 10000:
fd = math.log(vmax - vmin) / math.log(self._base)
s = sel... | LogFormatterExponent |
python | dask__dask | dask/array/random.py | {
"start": 17670,
"end": 40714
} | class ____:
"""
Mersenne Twister pseudo-random number generator
This object contains state to deterministically generate pseudo-random
numbers from a variety of probability distributions. It is identical to
``np.random.RandomState`` except that all functions also take a ``chunks=``
keyword arg... | RandomState |
python | pytorch__pytorch | test/jit/test_attr.py | {
"start": 247,
"end": 2151
} | class ____(JitTestCase):
def test_getattr_with_default(self):
class A(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.init_attr_val = 1.0
def forward(self, x):
y = getattr(self, "init_attr_val") # noqa: B009
... | TestGetDefaultAttr |
python | mahmoud__glom | glom/mutation.py | {
"start": 2246,
"end": 8551
} | class ____:
"""*New in glom 18.3.0*
The ``Assign`` specifier type enables glom to modify the target,
performing a "deep-set" to mirror glom's original deep-get use
case.
``Assign`` can be used to perform spot modifications of large data
structures when making a copy is not desired::
# d... | Assign |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1214248,
"end": 1214440
} | class ____(Sort):
"""SortArray schema wrapper."""
_schema = {"$ref": "#/definitions/SortArray"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| SortArray |
python | PyCQA__pylint | pylint/testutils/_primer/primer_command.py | {
"start": 585,
"end": 999
} | class ____:
"""Generic primer action with required arguments."""
def __init__(
self,
primer_directory: Path,
packages: dict[str, PackageToLint],
config: argparse.Namespace,
) -> None:
self.primer_directory = primer_directory
self.packages = packages
s... | PrimerCommand |
python | pennersr__django-allauth | allauth/account/fields.py | {
"start": 805,
"end": 1373
} | class ____(forms.CharField):
def __init__(self, *args, **kwargs):
render_value = kwargs.pop(
"render_value", app_settings.PASSWORD_INPUT_RENDER_VALUE
)
kwargs["widget"] = forms.PasswordInput(
render_value=render_value,
attrs={"placeholder": kwargs.get("lab... | PasswordField |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 24969,
"end": 25639
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("es_CL")
Faker.seed(0)
def test_rut(self):
for _ in range(100):
rut = self.fake.rut(min=10000000)
digits, check_digit = self._extract_digits(rut)
assert len(rut) == 12
asse... | TestEsCL |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 41265,
"end": 43947
} | class ____(CompositeModel):
def __init__(self, dmm, fe_type):
super(DeferredStructModel, self).__init__(dmm, fe_type)
self.typename = "deferred.{0}".format(id(fe_type))
self.actual_fe_type = fe_type.get()
def get_value_type(self):
return ir.global_context.get_identified_type(sel... | DeferredStructModel |
python | viewflow__viewflow | tests/json/test_json__datetime.py | {
"start": 270,
"end": 1142
} | class ____(TestCase):
def test_crud(self):
model = DateTimeFieldModel(datetime_field=timezone.datetime(2020, 1, 31, 12, 59, 3))
self.assertIsInstance(
model._meta.get_field('datetime_field'),
models.DateTimeField
)
self.assertEqual(model.data, {
'd... | Test |
python | openai__openai-python | src/openai/resources/realtime/calls.py | {
"start": 1570,
"end": 16063
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> CallsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com... | Calls |
python | apache__airflow | providers/atlassian/jira/src/airflow/providers/atlassian/jira/notifications/jira.py | {
"start": 1106,
"end": 3952
} | class ____(BaseNotifier):
"""
Jira notifier for creating Jira issues upon failures.
:param jira_conn_id: The HTTP connection ID for the Jira instance.
:param proxies: Proxies to make the Jira REST API call. Optional
:param api_version: Jira api version to use. Optional
:param api_root: root for... | JiraNotifier |
python | ansible__ansible | test/integration/targets/jinja_plugins/collections/ansible_collections/foo/bar/plugins/test/bad_collection_test.py | {
"start": 180,
"end": 266
} | class ____:
def tests(self):
raise TypeError('bad_collection_test')
| TestModule |
python | apache__airflow | devel-common/src/sphinx_exts/exampleinclude.py | {
"start": 1467,
"end": 1562
} | class ____(nodes.reference, nodes.FixedTextElement):
"""Header for examples."""
| ExampleHeader |
python | django__django | tests/auth_tests/test_checks.py | {
"start": 9636,
"end": 14648
} | class ____(SimpleTestCase):
def test_clashing_default_permissions(self):
class Checked(models.Model):
class Meta:
permissions = [("change_checked", "Can edit permission (duplicate)")]
errors = checks.run_checks(self.apps.get_app_configs())
self.assertEqual(
... | ModelsPermissionsChecksTests |
python | sympy__sympy | sympy/functions/special/zeta_functions.py | {
"start": 7856,
"end": 13012
} | class ____(DefinedFunction):
r"""
Polylogarithm function.
Explanation
===========
For $|z| < 1$ and $s \in \mathbb{C}$, the polylogarithm is
defined by
.. math:: \operatorname{Li}_s(z) = \sum_{n=1}^\infty \frac{z^n}{n^s},
where the standard branch of the argument is used for $n$. It ... | polylog |
python | PrefectHQ__prefect | src/integrations/prefect-azure/tests/experimental/bundles/test_execute.py | {
"start": 1154,
"end": 5270
} | class ____:
"""Tests for the execute_bundle_from_azure_blob_storage function."""
async def test_execute_bundle_with_credentials_block(
self, mock_blob_storage_credentials: MagicMock, mock_runner: MagicMock
) -> None:
"""Test executing a bundle using a credentials block."""
container... | TestExecuteBundleFromAzureBlobStorage |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 27971,
"end": 29448
} | class ____(SpmConverter):
def pre_tokenizer(self, replacement, add_prefix_space):
list_pretokenizers = []
if self.original_tokenizer.split_by_punct:
list_pretokenizers.append(pre_tokenizers.Punctuation(behavior="isolated"))
prepend_scheme = _get_prepend_scheme(add_prefix_space, s... | DebertaV2Converter |
python | has2k1__plotnine | plotnine/iapi.py | {
"start": 6301,
"end": 7782
} | class ____:
"""
Strip Label Details
"""
# facet variable: label for the value
variables: dict[str, str]
meta: dict[str, Any] # TODO: use a typeddict
@staticmethod
def make(
layout_info: layout_details,
vars: Sequence[str],
location: StripPosition,
) -> stri... | strip_label_details |
python | kamyu104__LeetCode-Solutions | Python/longest-repeating-substring.py | {
"start": 54,
"end": 1203
} | class ____(object):
def longestRepeatingSubstring(self, S):
"""
:type S: str
:rtype: int
"""
M = 10**9+7
D = 26
def check(S, L):
p = pow(D, L, M)
curr = reduce(lambda x, y: (D*x+ord(y)-ord('a')) % M, S[:L], 0)
lookup = coll... | Solution |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 12517,
"end": 15072
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_num):
super().__init__()
self.config = config
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = BlipTextAttention(config, layer_idx=layer_num)
se... | BlipTextLayer |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/useless_return.py | {
"start": 849,
"end": 1055
} | class ____:
def get(self, key: str) -> str | None:
print(f"{key} not found")
return None
def get(self, key: str) -> None:
print(f"{key} not found")
return None
| BaseCache |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_common_errors.py | {
"start": 7259,
"end": 10633
} | class ____:
"""Test detection of invalid RST syntax in docstrings."""
# Using function-based validation approach
def test_malformed_code_blocks(self):
"""Test detection of malformed code blocks."""
docstring = '''"""Function with malformed code blocks.
Example:
.. code... | TestRSTSyntaxErrors |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/sqlite_storage.py | {
"start": 1277,
"end": 5118
} | class ____(DagsterStorage, ConfigurableClass):
"""SQLite-backed run storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in
``$DAGSTER_HOME``. Configu... | DagsterSqliteStorage |
python | google__jax | jax/_src/errors.py | {
"start": 1197,
"end": 1294
} | class ____(_JAXErrorMixin, TypeError):
"""JAX-specific :class:`TypeError`"""
@export
| JAXTypeError |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/time.py | {
"start": 2822,
"end": 3400
} | class ____(NamedConfig[Literal["numpy.datetime64"], TimeConfig]):
"""
The JSON representation of the ``numpy.datetime64`` data type in Zarr V3.
References
----------
This representation is defined in the ``numpy.datetime64``
[specification document](https://zarr-specs.readthedocs.io/en/latest/s... | DateTime64JSON_V3 |
python | great-expectations__great_expectations | great_expectations/core/expectation_diagnostics/expectation_test_data_cases.py | {
"start": 3105,
"end": 3490
} | class ____(SerializableDictDot):
"""Pairs a test dataset and a list of test cases to execute against that data."""
data: TestData
dataset_name: str
tests: List[ExpectationTestCase]
schemas: Dict[Backend, Dict[str, str]] = field(default_factory=dict)
test_backends: Optional[List[TestBackend]] = ... | ExpectationTestDataCases |
python | requests__requests-oauthlib | tests/test_oauth2_session.py | {
"start": 810,
"end": 20895
} | class ____(TestCase):
def setUp(self):
self.token = {
"token_type": "Bearer",
"access_token": "asdfoiw37850234lkjsdfsdf",
"refresh_token": "sldvafkjw34509s8dfsdf",
"expires_in": 3600,
"expires_at": fake_time + 3600,
}
# use someclie... | OAuth2SessionTest |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 15129,
"end": 15240
} | class ____(PydanticValueError):
msg_template = 'value is not a valid IPv4 or IPv6 address'
| IPvAnyAddressError |
python | google__jax | jax/_src/checkify.py | {
"start": 6536,
"end": 7004
} | class ____(JaxException):
error_mapping: dict[tuple[int, ...], JaxException]
def __post_init__(self):
traceback_info = list(self.error_mapping.values())[0].traceback_info
super().__init__(traceback_info)
def __str__(self):
return '\n'.join(f'at mapped index {", ".join(map(str, idx))}: {e}'
... | BatchedError |
python | redis__redis-py | tests/test_search.py | {
"start": 105500,
"end": 113799
} | class ____(SearchTestsBase):
@pytest.mark.redismod
@skip_ifmodversion_lt("2.4.3", "search")
def test_vector_field(self, client):
client.flushdb()
client.ft().create_index(
(
VectorField(
"v", "HNSW", {"TYPE": "FLOAT32", "DIM": 2, "DISTANCE_METR... | TestDifferentFieldTypesSearch |
python | Netflix__metaflow | metaflow/_vendor/packaging/_tokenizer.py | {
"start": 239,
"end": 2024
} | class ____(Exception):
"""The provided source text could not be parsed correctly."""
def __init__(
self,
message: str,
*,
source: str,
span: Tuple[int, int],
) -> None:
self.span = span
self.message = message
self.source = source
supe... | ParserSyntaxError |
python | getsentry__sentry | src/sentry/taskworker/scheduler/runner.py | {
"start": 6058,
"end": 10709
} | class ____:
"""
A task scheduler that a command run process can use to spawn tasks
based on their schedules.
Contains a collection of ScheduleEntry objects which are composed
using `ScheduleRunner.add()`. Once the scheduler is built, `tick()`
is used in a while loop to spawn tasks and sleep.
... | ScheduleRunner |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 23969,
"end": 24259
} | class ____(NotFoundError):
"""
DJBFFT (https://cr.yp.to/djbfft.html) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [djbfft]) or by setting
the DJBFFT environment variable."""
| DJBFFTNotFoundError |
python | anthropics__anthropic-sdk-python | src/anthropic/_exceptions.py | {
"start": 2151,
"end": 2536
} | class ____(APIConnectionError):
def __init__(self, request: httpx.Request) -> None:
super().__init__(
message="Request timed out or interrupted. This could be due to a network timeout, dropped connection, or request cancellation. See https://docs.anthropic.com/en/api/errors#long-requests for mor... | APITimeoutError |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 4333,
"end": 4910
} | class ____(type):
"""
Thread-safe implementation of single to be used in the config heuristic subclasses
to ensure heavy __init__ calls are not repeatedly run
"""
_instances: dict[type[Any], Any] = {}
_lock: Lock = Lock()
def __call__(
cls: BaseHeuristicSingleton, *args: Any, **kwa... | BaseHeuristicSingleton |
python | django__django | django/contrib/gis/geos/prototypes/io.py | {
"start": 5997,
"end": 7580
} | class ____(IOBase):
_constructor = wkt_writer_create
ptr_type = WKT_WRITE_PTR
destructor = wkt_writer_destroy
_precision = None
def __init__(self, dim=2, trim=False, precision=None):
super().__init__()
self._trim = DEFAULT_TRIM_VALUE
self.trim = trim
if precision is ... | WKTWriter |
python | fabric__fabric | tests/testing.py | {
"start": 800,
"end": 4064
} | class ____:
class mocks_by_default:
@patch("paramiko.transport.socket")
def prevents_real_ssh_connectivity_via_paramiko_guts(self, socket):
with MockRemote():
cxn = Connection(host="host")
cxn.run("nope")
# High level mock...
... | MockRemote_ |
python | paramiko__paramiko | paramiko/auth_strategy.py | {
"start": 345,
"end": 1126
} | class ____:
"""
Some SSH authentication source, such as a password, private key, or agent.
See subclasses in this module for concrete implementations.
All implementations must accept at least a ``username`` (``str``) kwarg.
"""
def __init__(self, username):
self.username = username
... | AuthSource |
python | kamyu104__LeetCode-Solutions | Python/number-of-strings-which-can-be-rearranged-to-contain-substring.py | {
"start": 571,
"end": 1331
} | class ____(object):
def stringCount(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9+7
L, E, EE, T = [1<<i for i in xrange(4)]
dp = [0]*(1<<4)
dp[0] = 1
for _ in xrange(n):
new_dp = [0]*(1<<4)
for mask in xrange(le... | Solution2 |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 102064,
"end": 107954
} | class ____:
def test_frozen(self):
# Test that the frozen and non-frozen inverse Wishart gives the same
# answers
# Construct an arbitrary positive definite scale matrix
dim = 4
scale = np.diag(np.arange(dim)+1)
scale[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-... | TestInvwishart |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/variables/variables_test.py | {
"start": 36435,
"end": 37432
} | class ____(test.TestCase):
def testV1V2Equal(self):
v1 = variables.VariableAggregation
v2 = variables.VariableAggregationV2
self.assertEqual(v1.NONE, v2.NONE)
self.assertEqual(v1.SUM, v2.SUM)
self.assertEqual(v1.MEAN, v2.MEAN)
self.assertEqual(v1.ONLY_FIRST_REPLICA, v2.ONLY_FIRST_REPLICA)
... | AggregationModesTest |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 6489,
"end": 6608
} | class ____(BaseNoInputReprocessingLoader):
default_item_class = NoInputReprocessingItem
| NoInputReprocessingItemLoader |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_plugins.py | {
"start": 6096,
"end": 7128
} | class ____:
@patch(
"airflow.plugins_manager.import_errors",
new={"plugins/test_plugin.py": "something went wrong"},
)
def test_should_respond_200(self, test_client, session):
with assert_queries_count(2):
response = test_client.get("/plugins/importErrors")
assert... | TestGetPluginImportErrors |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 28279,
"end": 28350
} | class ____(BinExpr):
"""Left modulo right."""
operator = "%"
| Mod |
python | kamyu104__LeetCode-Solutions | Python/count-pairs-of-equal-substrings-with-minimum-difference.py | {
"start": 29,
"end": 818
} | class ____(object):
def countQuadruples(self, firstString, secondString):
"""
:type firstString: str
:type secondString: str
:rtype: int
"""
lookup1 = [-1]*26
for i in reversed(xrange(len(firstString))):
lookup1[ord(firstString[i])-ord('a')] = i
... | Solution |
python | tornadoweb__tornado | maint/test/redbot/red_test.py | {
"start": 426,
"end": 568
} | class ____(RequestHandler):
def get(self, path):
self.redirect(path, status=int(self.get_argument('status', '302')))
| RedirectHandler |
python | falconry__falcon | falcon/errors.py | {
"start": 82464,
"end": 85023
} | class ____(HTTPError):
"""507 Insufficient Storage.
The 507 (Insufficient Storage) status code means the method could not
be performed on the resource because the server is unable to store
the representation needed to successfully complete the request. This
condition is considered to be temporary. ... | HTTPInsufficientStorage |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 20322,
"end": 21866
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreMemcachedHook")
def test_assert_valid_hook_call(self, mock_hook):
mock_hook.return_value.update_instance.return_value.name = TEST_UPDATE_INSTANCE_NAME.format(
project_id=TEST_PROJECT_ID,
... | TestCloudMemorystoreMemcachedUpdateInstanceOperator |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/examples/scrapegraph-agentic-scraper-llama-index.py | {
"start": 351,
"end": 725
} | class ____(BaseModel):
"""Schema for representing product information."""
name: str = Field(description="Product name")
price: str = Field(description="Product price", default="N/A")
description: str = Field(description="Product description", default="N/A")
features: List[str] = Field(description="... | ProductInfo |
python | huggingface__transformers | tests/models/lxmert/test_modeling_lxmert.py | {
"start": 17947,
"end": 28346
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (LxmertModel, LxmertForPreTraining, LxmertForQuestionAnswering) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": LxmertModel, "question-answering": LxmertForQuestionAnswering}
... | LxmertModelTest |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_spans_histogram.py | {
"start": 279,
"end": 13112
} | class ____(APITestCase, SnubaTestCase):
URL = "sentry-api-0-organization-events-spans-histogram"
def setUp(self) -> None:
super().setUp()
self.features: dict[str, bool] = {}
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
self.project =... | OrganizationEventsSpansHistogramEndpointTest |
python | walkccc__LeetCode | solutions/2337. Move Pieces to Obtain a String/2337.py | {
"start": 0,
"end": 555
} | class ____:
def canChange(self, start: str, target: str) -> bool:
n = len(start)
i = 0 # start's index
j = 0 # target's index
while i <= n and j <= n:
while i < n and start[i] == '_':
i += 1
while j < n and target[j] == '_':
j += 1
if i == n or j == n:
retu... | Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_loading.py | {
"start": 3699,
"end": 5018
} | class ____(_fixtures.FixtureTest):
def test_state_no_load_path_comparison(self):
# test issue #5110
User, Order, Address = self.classes("User", "Order", "Address")
users, orders, addresses = self.tables("users", "orders", "addresses")
self.mapper_registry.map_imperatively(
... | InstanceProcessorTest |
python | doocs__leetcode | solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution2.py | {
"start": 0,
"end": 447
} | class ____:
def validPartition(self, nums: List[int]) -> bool:
n = len(nums)
f = [True] + [False] * n
for i, x in enumerate(nums, 1):
a = i - 2 >= 0 and nums[i - 2] == x
b = i - 3 >= 0 and nums[i - 3] == nums[i - 2] == x
c = i - 3 >= 0 and x - nums[i - 2] ... | Solution |
python | huggingface__transformers | src/transformers/models/blt/modular_blt.py | {
"start": 10077,
"end": 10117
} | class ____(MllamaTextMLP):
pass
| BltMLP |
python | PyCQA__pyflakes | pyflakes/test/harness.py | {
"start": 164,
"end": 891
} | class ____(unittest.TestCase):
withDoctest = False
def flakes(self, input, *expectedOutputs, **kw):
tree = ast.parse(textwrap.dedent(input))
if kw.get('is_segment'):
tree = tree.body[0]
kw.pop('is_segment')
w = checker.Checker(tree, withDoctest=self.withDoctest,... | TestCase |
python | joke2k__faker | faker/providers/phone_number/fi_FI/__init__.py | {
"start": 49,
"end": 260
} | class ____(PhoneNumberProvider):
formats = (
"+358 ## #######",
"+358 #########",
"+358#########",
"(+358) #########",
"0#########",
"0## ### ####",
)
| Provider |
python | doocs__leetcode | solution/1700-1799/1796.Second Largest Digit in a String/Solution.py | {
"start": 0,
"end": 287
} | class ____:
def secondHighest(self, s: str) -> int:
a = b = -1
for c in s:
if c.isdigit():
v = int(c)
if v > a:
a, b = v, a
elif b < v < a:
b = v
return b
| Solution |
python | django-extensions__django-extensions | django_extensions/db/models.py | {
"start": 1748,
"end": 2137
} | class ____(models.query.QuerySet):
"""
ActivatorQuerySet
Query set that returns statused results
"""
def active(self):
"""Return active query set"""
return self.filter(status=ActivatorModel.ACTIVE_STATUS)
def inactive(self):
"""Return inactive query set"""
retu... | ActivatorQuerySet |
python | huggingface__transformers | src/transformers/models/ernie/modular_ernie.py | {
"start": 4972,
"end": 5014
} | class ____(BertPooler):
pass
| ErniePooler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.