language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pydantic__pydantic | tests/mypy/modules/plugin_success_baseConfig.py | {
"start": 3063,
"end": 3250
} | class ____(FrozenModel):
a: int = 1
model_config = dict(frozen=False, from_attributes=True)
NotFrozenModel(x=1).x = 2
NotFrozenModel.model_validate(model.__dict__)
| NotFrozenModel |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 7831,
"end": 8265
} | class ____:
def get_object(self, request, content_type_id, object_id):
ct = get_object_or_404(ContentType, pk=content_type_id)
try:
obj = ct.get_object_for_this_type(pk=object_id)
except ObjectDoesNotExist:
raise Http404('No %s matches the given query.' % ct.model_cl... | ObjectActivityMixin |
python | davidhalter__jedi | jedi/inference/arguments.py | {
"start": 5453,
"end": 9944
} | class ____(AbstractArguments):
def __init__(self, inference_state, context, argument_node, trailer=None):
"""
:param argument_node: May be an argument_node or a list of nodes.
"""
self.argument_node = argument_node
self.context = context
self._inference_state = infere... | TreeArguments |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-nile/tests/test_vector_stores_nile.py | {
"start": 359,
"end": 3828
} | class ____(unittest.TestCase):
@pytest.fixture(autouse=True)
@mock.patch("psycopg.connect")
def vector_store_setup(self, mock_connect):
# Mock the psycopg connection and cursor
self.mock_connection = (
mock_connect.return_value
) # result of psycopg2.connect(**connection... | TestNileVectorStore |
python | sphinx-doc__sphinx | sphinx/testing/util.py | {
"start": 8684,
"end": 9886
} | class ____(SphinxTestApp):
"""A wrapper for SphinxTestApp.
This class is used to speed up the test by skipping ``app.build()``
if it has already been built and there are any output files.
"""
def build(self, force_all: bool = False, filenames: Sequence[Path] = ()) -> None:
if not list(self... | SphinxTestAppWrapperForSkipBuilding |
python | pytorch__pytorch | torch/distributed/fsdp/_flat_param.py | {
"start": 3725,
"end": 4162
} | class ____(Enum):
FULL_SHARD = auto()
SHARD_GRAD_OP = auto()
NO_SHARD = auto()
HYBRID_SHARD = auto()
_HYBRID_SHARD_ZERO2 = auto()
RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES = (
HandleShardingStrategy.FULL_SHARD,
HandleShardingStrategy.HYBRID_SHARD,
)
NO_RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES... | HandleShardingStrategy |
python | jd__tenacity | tenacity/__init__.py | {
"start": 6470,
"end": 16095
} | class ____(ABC):
def __init__(
self,
sleep: t.Callable[[t.Union[int, float]], None] = sleep,
stop: "StopBaseT" = stop_never,
wait: "WaitBaseT" = wait_none(),
retry: "RetryBaseT" = retry_if_exception_type(),
before: t.Callable[["RetryCallState"], None] = before_nothing... | BaseRetrying |
python | has2k1__plotnine | plotnine/scales/scale_identity.py | {
"start": 306,
"end": 885
} | class ____:
"""
Override map and train methods
"""
def map(self, x, limits=None) -> Sequence[Any]:
"""
Identity map
Notes
-----
Identity scales bypass the palette completely since the
map is the identity function.
"""
return x
def tr... | MapTrainMixin |
python | requests__requests-oauthlib | tests/test_compliance_fixes.py | {
"start": 8114,
"end": 10027
} | class ____(TestCase):
def setUp(self):
mocker = requests_mock.Mocker()
mocker.request(
method="GET",
url="https://api.instagram.com/v1/users/self",
json={
"data": {
"id": "1574083",
"username": "snoopdogg",
... | InstagramComplianceFixTest |
python | readthedocs__readthedocs.org | readthedocs/api/v3/tests/test_notifications.py | {
"start": 750,
"end": 2584
} | class ____(APIEndpointMixin):
def test_notifications_list(self):
url = reverse("notifications-list")
self.client.logout()
response = self.client.get(url)
self.assertEqual(response.status_code, 401)
self.client.credentials(HTTP_AUTHORIZATION=f"Token {self.token.key}")
... | NotificationsEndpointTests |
python | lepture__authlib | tests/flask/test_oauth1/oauth1_server.py | {
"start": 3141,
"end": 8952
} | class ____(db.Model):
__table_args__ = (
db.UniqueConstraint(
"client_id", "timestamp", "nonce", "oauth_token", name="unique_nonce"
),
)
id = db.Column(db.Integer, primary_key=True)
client_id = db.Column(db.String(48), nullable=False)
timestamp = db.Column(db.Integer, nul... | TimestampNonce |
python | spack__spack | lib/spack/spack/vendor/typing_extensions.py | {
"start": 12647,
"end": 100425
} | class ____(GenericMeta):
def __subclasscheck__(self, subclass):
"""This mimics a more modern GenericMeta.__subclasscheck__() logic
(that does not have problems with recursion) to work around interactions
between collections, typing, and spack.vendor.typing_extensions on older
version... | _ExtensionsGenericMeta |
python | facebook__pyre-check | tools/playground/application.py | {
"start": 2272,
"end": 4756
} | class ____:
def __init__(self) -> None:
self._directory: Path = Path(tempfile.mkdtemp())
LOG.debug(f"Starting server in `{self._directory}`...")
pyre_configuration = json.dumps(
{
"source_directories": ["."],
}
)
LOG.debug(f"Writing co... | Pyre |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 648286,
"end": 649076
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for EnterpriseRepositoryInfo."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseRepositoryInfoEdge"), graphql_name="edges")
"""A lis... | EnterpriseRepositoryInfoConnection |
python | redis__redis-py | redis/commands/core.py | {
"start": 121559,
"end": 125070
} | class ____(ScanCommands):
async def scan_iter(
self,
match: Union[PatternT, None] = None,
count: Optional[int] = None,
_type: Optional[str] = None,
**kwargs,
) -> AsyncIterator:
"""
Make an iterator using the SCAN command so that the client doesn't
... | AsyncScanCommands |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 110944,
"end": 112079
} | class ____(Response):
"""
Response of models.make_public endpoint.
:param updated: Number of models updated
:type updated: int
"""
_service = "models"
_action = "make_public"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"updated": {
... | MakePublicResponse |
python | langchain-ai__langchain | libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py | {
"start": 1007,
"end": 2108
} | class ____(FakeEmbeddings):
"""Consistent fake embeddings.
Fake embeddings which remember all the texts seen so far to return consistent
vectors for the same texts.
"""
def __init__(self, dimensionality: int = 10) -> None:
self.known_texts: list[str] = []
self.dimensionality = dime... | ConsistentFakeEmbeddings |
python | pytorch__pytorch | test/quantization/core/experimental/test_bits.py | {
"start": 1639,
"end": 3538
} | class ____(TestCase):
@skipIfRocm
def test_types(self, device):
bits_types = [torch.bits1x8, torch.bits2x4, torch.bits4x2, torch.bits8, torch.bits16]
for bits_type in bits_types:
_ = torch.zeros(20, dtype=torch.int32, device=device).view(bits_type)
_ = torch.empty(20, dty... | TestBits |
python | py-pdf__pypdf | pypdf/_doc_common.py | {
"start": 8636,
"end": 51883
} | class ____:
"""
Common functions from PdfWriter and PdfReader objects.
This root class is strongly abstracted.
"""
strict: bool = False # default
flattened_pages: Optional[list[PageObject]] = None
_encryption: Optional[Encryption] = None
_readonly: bool = False
@property
@... | PdfDocCommon |
python | eventlet__eventlet | tests/mysqldb_test.py | {
"start": 917,
"end": 6930
} | class ____(tests.LimitedTestCase):
TEST_TIMEOUT = 50
def setUp(self):
self._auth = tests.get_database_auth()['MySQLdb']
self.create_db()
self.connection = None
self.connection = MySQLdb.connect(**self._auth)
cursor = self.connection.cursor()
cursor.execute("""CRE... | TestMySQLdb |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/eks.py | {
"start": 9486,
"end": 11009
} | class ____(AwsBaseWaiterTrigger):
"""
Asynchronously wait for the fargate profile to be created.
:param cluster_name: The name of the EKS cluster
:param fargate_profile_name: The name of the fargate profile
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param wait... | EksCreateFargateProfileTrigger |
python | sympy__sympy | sympy/stats/stochastic_process_types.py | {
"start": 86402,
"end": 88562
} | class ____(CountingProcess):
r"""
A Gamma process is a random process with independent gamma distributed
increments. It is a pure-jump increasing Levy process.
Parameters
==========
sym : Symbol/str
lamda : Positive number
Jump size of the process, ``lamda > 0``
gamma : Positiv... | GammaProcess |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_squeeze_op_test.py | {
"start": 1233,
"end": 8635
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([
{
'input_list': []
},
{
'input_list': [[]],
'squeeze_ranks': [0]
},
{
'input_list': [[[[], []], [[], []]]],
'squeeze_ra... | RaggedSqueezeTest |
python | huggingface__transformers | src/transformers/models/autoformer/configuration_autoformer.py | {
"start": 816,
"end": 12192
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of an [`AutoformerModel`]. It is used to instantiate an
Autoformer model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a simil... | AutoformerConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType20.py | {
"start": 242,
"end": 316
} | class ____(Parent[Any]):
# This should generate an error.
y = 42
| Child |
python | getsentry__sentry | tests/sentry/issues/test_json_schemas.py | {
"start": 107,
"end": 753
} | class ____(TestCase):
def test_loads_json_schema(self) -> None:
assert json_schemas.EVENT_PAYLOAD_SCHEMA != json_schemas.LEGACY_EVENT_PAYLOAD_SCHEMA
assert (
json_schemas.EVENT_PAYLOAD_SCHEMA.get("description")
== " The sentry v7 event structure."
)
def test_fall... | JsonSchemasTest |
python | PyCQA__pylint | tests/functional/i/init_not_called.py | {
"start": 956,
"end": 1091
} | class ____(NewStyleC):
"""No init called, but abstract so that is fine."""
def __init__(self):
self.arg = 0
| AssignedInit |
python | doocs__leetcode | lcof/面试题03. 数组中重复的数字/Solution.py | {
"start": 0,
"end": 164
} | class ____:
def findRepeatNumber(self, nums: List[int]) -> int:
for a, b in pairwise(sorted(nums)):
if a == b:
return a
| Solution |
python | gevent__gevent | src/gevent/tests/known_failures.py | {
"start": 5795,
"end": 17690
} | class ____(metaclass=DefinitionsMeta):
test__util = RunAlone(
"""
If we have extra greenlets hanging around due to changes in GC, we won't
match the expected output.
So far, this is only seen on one version, in CI environment.
""",
when=(CI & (PY312B3_EXACTLY | PY31... | Definitions |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_with.py | {
"start": 25796,
"end": 29785
} | class ____(__TestCase):
class Dummy(object):
def __init__(self, value=None, gobble=False):
if value is None:
value = self
self.value = value
self.gobble = gobble
self.enter_called = False
self.exit_called = False
def __ent... | NestedWith |
python | walkccc__LeetCode | solutions/1474. Delete N Nodes After M Nodes of a Linked List/1474.py | {
"start": 0,
"end": 557
} | class ____:
def deleteNodes(
self,
head: ListNode | None,
m: int,
n: int,
) -> ListNode | None:
curr = head
prev = None # prev.next == curr
while curr:
# Set the m-th node as `prev`.
for _ in range(m):
if not curr:
break
prev = curr
... | Solution |
python | django__django | tests/queries/models.py | {
"start": 14910,
"end": 15028
} | class ____(models.Model):
annotation = models.ForeignKey(Annotation, models.CASCADE, null=True, blank=True)
| BaseUser |
python | giampaolo__psutil | tests/test_contracts.py | {
"start": 4127,
"end": 5395
} | class ____(PsutilTestCase):
def test_win_service_iter(self):
assert hasattr(psutil, "win_service_iter") == WINDOWS
def test_win_service_get(self):
assert hasattr(psutil, "win_service_get") == WINDOWS
@pytest.mark.skipif(MACOS and AARCH64, reason="skipped due to #1892")
def test_cpu_fre... | TestAvailSystemAPIs |
python | celery__celery | celery/exceptions.py | {
"start": 3866,
"end": 3948
} | class ____(UserWarning):
"""Base class for all Celery warnings."""
| CeleryWarning |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_keys.py | {
"start": 388,
"end": 539
} | class ____(graphene.ObjectType):
partitionKeys = non_null_list(graphene.String)
class Meta:
name = "PartitionKeys"
| GraphenePartitionKeys |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 129878,
"end": 133088
} | class ____(
TestCase,
AssignmentTestMixin,
ProcessCommitsTestMixin,
CorePostProcessGroupTestMixin,
DeriveCodeMappingsProcessGroupTestMixin,
InboxTestMixin,
ResourceChangeBoundsTestMixin,
KickOffSeerAutomationTestMixin,
TriageSignalsV0TestMixin,
SeerAutomationHelperFunctionsTestMi... | PostProcessGroupErrorTest |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 3631,
"end": 4900
} | class ____(BaseConverter):
"""Baseclass for `IntegerConverter` and `FloatConverter`.
:internal:
"""
weight = 50
num_convert: t.Callable[[t.Any], t.Any] = int
def __init__(
self,
map: Map,
fixed_digits: int = 0,
min: int | None = None,
max: int | None = ... | NumberConverter |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 14943,
"end": 15802
} | class ____:
"""Mixin class for handlers that are hashing records."""
def hash_record_raw(self, record):
"""Returns a hashlib object with the hash of the record."""
hash = sha1()
hash.update(("%d\x00" % record.level).encode("ascii")) # noqa: UP031
hash.update((record.channel or ... | HashingHandlerMixin |
python | great-expectations__great_expectations | great_expectations/core/run_identifier.py | {
"start": 537,
"end": 3905
} | class ____(DataContextKey):
"""A RunIdentifier identifies a run (collection of validations) by run_name and run_time.
Args:
run_name: a string or None.
run_time: a Datetime.datetime instance, a string, or None.
"""
def __init__(
self,
run_name: Optional[str] = None,
... | RunIdentifier |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 16730,
"end": 16799
} | class ____(AugmentedAssignment):
binop = '/'
| DivAugmentedAssignment |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/event_seen_count_handler.py | {
"start": 310,
"end": 620
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.ACTION_FILTER
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
group = event_data.group
return group.times_seen == comparison
| EventSeenCountConditionHandler |
python | google__jax | docs/autodidax.py | {
"start": 51772,
"end": 52241
} | class ____:
val: Any
def __init__(self, val):
self.val = val
def __hash__(self) -> int:
return id(self.val)
def __eq__(self, other):
return type(other) is IDHashable and id(self.val) == id(other.val)
# Next, we'll define the evaluation rule for `xla_call`:
# +
import io
from jax.extend.mlir im... | IDHashable |
python | django__django | tests/migrations/migrations_test_apps/mutate_state_a/migrations/0001_initial.py | {
"start": 43,
"end": 785
} | class ____(migrations.Migration):
dependencies = [
("mutate_state_b", "0001_initial"),
]
operations = [
migrations.SeparateDatabaseAndState(
[],
[
migrations.CreateModel(
name="A",
fields=[
... | Migration |
python | pytorch__pytorch | test/dynamo/test_graph_deduplication.py | {
"start": 10377,
"end": 12943
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[10, 10]", L_y_: "f32[10, 20]"):
subgraph_1 = self.subgraph_1
subgraph_0 = self.subgraph_0
l_x_ = L_x_
l_y_ = L_y_
x0: "f32[10, 10]" = torch.cos(l_x_)
y0: "f32[10, 20]" = torch.sin(l_y_)
invoke_subgra... | GraphModule |
python | getsentry__sentry | src/sentry/web/forms/accounts.py | {
"start": 8676,
"end": 8937
} | class ____(forms.Form):
otp = forms.CharField(
label=_("Authenticator code"),
max_length=20,
widget=forms.TextInput(
attrs={"placeholder": _("Authenticator or recovery code"), "autofocus": True}
),
)
| TwoFactorForm |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 3798,
"end": 11599
} | class ____(Endpoint):
authentication_classes = ()
permission_classes = ()
_handlers: dict[str, type[GitHubWebhook]] = {}
# https://developer.github.com/webhooks/
def get_handler(self, event_type):
return self._handlers.get(event_type)
def is_valid_signature(self, method, body, secret,... | GitHubEnterpriseWebhookBase |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/view/primitives.py | {
"start": 1599,
"end": 2171
} | class ____:
content: str
point: Point
def draw(self, **attributes) -> str:
return tag(
"text", self.content, x=self.point.x, y=self.point.y, **attributes
)
def tag(name: str, value: str | None = None, **attributes) -> str:
attrs = (
""
if not attributes
... | Text |
python | tensorflow__tensorflow | tensorflow/lite/python/lite.py | {
"start": 9501,
"end": 10467
} | class ____:
"""Representative dataset used to optimize the model.
This is a generator function that provides a small dataset to calibrate or
estimate the range, i.e, (min, max) of all floating-point arrays in the model
(such as model input, activation outputs of intermediate layers, and model
output) for qua... | RepresentativeDataset |
python | celery__celery | celery/schedules.py | {
"start": 3037,
"end": 6462
} | class ____(BaseSchedule):
"""Schedule for periodic task.
Arguments:
run_every (float, ~datetime.timedelta): Time interval.
relative (bool): If set to True the run time will be rounded to the
resolution of the interval.
nowfun (Callable): Function returning the current date ... | schedule |
python | numba__numba | numba/tests/test_random.py | {
"start": 4343,
"end": 4627
} | class ____(TestCase):
def _follow_cpython(self, ptr, seed=2):
r = random.Random(seed)
_copy_py_state(r, ptr)
return r
def _follow_numpy(self, ptr, seed=2):
r = np.random.RandomState(seed)
_copy_np_state(r, ptr)
return r
| BaseTest |
python | kubernetes-client__python | kubernetes/client/models/core_v1_event_list.py | {
"start": 383,
"end": 6840
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | CoreV1EventList |
python | kamyu104__LeetCode-Solutions | Python/find-number-of-ways-to-reach-the-k-th-stair.py | {
"start": 51,
"end": 608
} | class ____(object):
def waysToReachStair(self, k):
"""
:type k: int
:rtype: int
"""
def ceil_log2_x(x):
return (x-1).bit_length()
l = ceil_log2_x(k)
while (1<<l)-k <= l+1:
l += 1
fact = [1]*(l+1)
for i in xrange(len(fac... | Solution |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 86414,
"end": 89246
} | class ____(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-cell
__slots__ = tuple()
# helper
def closeCell(self):
if self.tree.elementInScope("td", variant="table"):
self.endTagTableCell(impliedTagToken("td"))
elif self.tree.elementInScope("th", variant="tabl... | InCellPhase |
python | imageio__imageio | imageio/config/plugins.py | {
"start": 74,
"end": 20277
} | class ____:
"""Plugin Configuration Metadata
This class holds the information needed to lazy-import plugins.
Parameters
----------
name : str
The name of the plugin.
class_name : str
The name of the plugin class inside the plugin module.
module_name : str
The name o... | PluginConfig |
python | falconry__falcon | falcon/errors.py | {
"start": 99022,
"end": 101042
} | class ____(HTTPBadRequest):
"""400 Bad Request.
Exception raised by a media handler when trying to parse an empty body.
Note:
Some media handlers, like the one for URL-encoded forms, allow an
empty body. In these cases this exception will not be raised.
Args:
media_type (str):... | MediaNotFoundError |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_values.py | {
"start": 5529,
"end": 8652
} | class ____(TPUVariableMixin, values.DistributedVariable):
"""DistributedVariable subclass for TPUStrategy."""
def assign_sub(self, value, use_locking=False, name=None, read_value=True):
if values_util.is_saving_non_distributed():
return self._primary.assign_sub(value, use_locking, name, read_value)
r... | TPUDistributedVariable |
python | numba__numba | numba/tests/test_listimpl.py | {
"start": 5811,
"end": 16147
} | class ____(TestCase):
def setUp(self):
"""Bind to the c_helper library and provide the ctypes wrapper.
"""
list_t = ctypes.c_void_p
iter_t = ctypes.c_void_p
def wrap(name, restype, argtypes=()):
proto = ctypes.CFUNCTYPE(restype, *argtypes)
return prot... | TestListImpl |
python | wandb__wandb | wandb/integration/torch/wandb_torch.py | {
"start": 11148,
"end": 21526
} | class ____(wandb.data_types.Graph):
def __init__(self):
super().__init__("torch")
self._graph_hooks = set()
@classmethod
def hook_torch(cls, model, criterion=None, graph_idx=0):
wandb.termlog("logging graph, to disable use `wandb.watch(log_graph=False)`")
graph = TorchGraph(... | TorchGraph |
python | django__django | tests/datatypes/models.py | {
"start": 184,
"end": 585
} | class ____(models.Model):
name = models.CharField(max_length=100)
is_frosted = models.BooleanField(default=False)
has_sprinkles = models.BooleanField(null=True)
baked_date = models.DateField(null=True)
baked_time = models.TimeField(null=True)
consumed_at = models.DateTimeField(null=True)
rev... | Donut |
python | davidhalter__jedi | jedi/inference/value/module.py | {
"start": 639,
"end": 1296
} | class ____(AbstractNameDefinition):
"""
For module attributes like __file__, __str__ and so on.
"""
api_type = 'instance'
def __init__(self, parent_module, string_name, string_value=None):
self.parent_context = parent_module
self.string_name = string_name
self._string_value ... | _ModuleAttributeName |
python | astropy__astropy | astropy/modeling/polynomial.py | {
"start": 5850,
"end": 13301
} | class ____(PolynomialBase):
"""
This is a base class for the 2D Chebyshev and Legendre models.
The polynomials implemented here require a maximum degree in x and y.
For explanation of ``x_domain``, ``y_domain``, ```x_window`` and ```y_window``
see :ref:`Notes regarding usage of domain and window <... | OrthoPolynomialBase |
python | scipy__scipy | scipy/optimize/tests/test_slsqp.py | {
"start": 378,
"end": 1003
} | class ____:
"""pass a custom callback function
This makes sure it's being used.
"""
def __init__(self):
self.been_called = False
self.ncalls = 0
def __call__(self, x):
assert not isinstance(x, OptimizeResult)
self.been_called = True
self.ncalls += 1
def... | MyCallBack |
python | PyCQA__pylint | tests/functional/o/overridden_final_method_py38.py | {
"start": 178,
"end": 241
} | class ____:
@final
def my_method(self):
pass
| Base |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/control_flow_test.py | {
"start": 2021,
"end": 3497
} | class ____(ControlFlowTestBase):
def test_basic(self):
def f(n):
i = 0
j = 0
s = 0
while i < n:
while j < i:
j += 3
u = i + j # 'u' is not defined within the inner loop
s += u
i += 1
j = 0
return s, i, j, n
self.assertTransfor... | NestedControlFlowTest |
python | django__django | django/tasks/base.py | {
"start": 7527,
"end": 7653
} | class ____:
task_result: TaskResult
@property
def attempt(self):
return self.task_result.attempts
| TaskContext |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1059904,
"end": 1060072
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (Organization, User)
| OrganizationOrUser |
python | walkccc__LeetCode | solutions/337. House Robber III/337.py | {
"start": 0,
"end": 407
} | class ____:
def rob(self, root: TreeNode | None) -> int:
def robOrNot(root: TreeNode | None) -> tuple:
if not root:
return (0, 0)
robLeft, notRobLeft = robOrNot(root.left)
robRight, notRobRight = robOrNot(root.right)
return (root.val + notRobLeft + notRobRight,
max(... | Solution |
python | django__django | tests/many_to_one/models.py | {
"start": 2091,
"end": 2218
} | class ____(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey(Parent, models.CASCADE)
| Child |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin_ini/plugin_strict_fields.py | {
"start": 286,
"end": 707
} | class ____(BaseModel):
model_config = {'strict': True}
a: int
b: int = Field(strict=True)
c: int = Field(strict=False)
# expected error: a, b
ModelStrictMode(a='1', b='2', c='3')
# MYPY: error: Argument "a" to "ModelStrictMode" has incompatible type "str"; expected "int" [arg-type]
# MYPY: error: Ar... | ModelStrictMode |
python | django__django | tests/asgi/tests.py | {
"start": 1398,
"end": 34539
} | class ____(SimpleTestCase):
async_request_factory = AsyncRequestFactory()
def setUp(self):
request_started.disconnect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)
async def test_get_asgi_application(self):
"""
get_asgi_application()... | ASGITest |
python | sphinx-doc__sphinx | sphinx/util/display.py | {
"start": 2019,
"end": 3125
} | class ____:
def __init__(self, message: str, *, nonl: bool = True) -> None:
self.message = message
self.nonl = nonl
def __enter__(self) -> None:
logger.info(bold(self.message + '... '), nonl=self.nonl)
def __exit__(
self,
typ: type[BaseException] | None,
val... | progress_message |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 4348,
"end": 4634
} | class ____(BaseConfig):
name: str
bypass_reason: Optional[str] = Field(default=None, description="Reason why this stream is considered empty.")
def __hash__(self): # make it hashable
return hash((type(self),) + tuple(self.__dict__.values()))
| EmptyStreamConfiguration |
python | ray-project__ray | doc/source/ray-core/doc_code/cgraph_quickstart.py | {
"start": 2455,
"end": 3074
} | class ____:
def echo(self, msg):
return msg
actor = EchoActor.remote()
with ray.dag.InputNode() as inp:
dag = actor.echo.bind(inp)
cdag = dag.experimental_compile(enable_asyncio=True)
# __cgraph_async_compile_end__
# __cgraph_async_execute_start__
import asyncio
async def async_method(i):
fut ... | EchoActor |
python | nedbat__coveragepy | coverage/plugin_support.py | {
"start": 8458,
"end": 10444
} | class ____(FileReporter):
"""A debugging `FileReporter`."""
def __init__(self, filename: str, reporter: FileReporter, debug: LabelledDebug) -> None:
super().__init__(filename)
self.reporter = reporter
self.debug = debug
def relative_filename(self) -> str:
ret = self.reporte... | DebugFileReporterWrapper |
python | sympy__sympy | sympy/physics/quantum/hilbert.py | {
"start": 13022,
"end": 16499
} | class ____(HilbertSpace):
"""A direct sum of Hilbert spaces [1]_.
This class uses the ``+`` operator to represent direct sums between
different Hilbert spaces.
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. Also, addition of
``Hilb... | DirectSumHilbertSpace |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 7085,
"end": 11580
} | class ____(ShopifyBulkQuery):
"""
Only 2 lvl nesting is available: https://shopify.dev/docs/api/usage/bulk-operations/queries#operation-restrictions
Output example to BULK query `customers.metafields` with `filter query` by `updated_at` sorted `ASC`:
{
<Type>(
query: "updated_at:>='2... | Metafield |
python | davidhalter__jedi | test/static_analysis/attribute_error.py | {
"start": 0,
"end": 1428
} | class ____():
class_attr = ''
def __init__(self, input):
self.instance_attr = 3
self.input = input
def f(self):
#! 12 attribute-error
return self.not_existing
def undefined_object(self, obj):
"""
Uses an arbitrary object and performs an operation on it, ... | Cls |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/data_sampler.py | {
"start": 266,
"end": 3457
} | class ____(abc.ABC): # noqa: B024 # abstract-base-class-without-abstract-method
"""Abstract base class containing methods for sampling data accessible via Execution Engines."""
def get_sampler_method(self, sampler_method_name: str) -> Callable:
"""Get the appropriate sampler method from the method nam... | DataSampler |
python | huggingface__transformers | tests/models/perception_lm/test_image_processing_perception_lm.py | {
"start": 3596,
"end": 10100
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
fast_image_processing_class = PerceptionLMImageProcessorFast if is_torchvision_available() else None
test_slow_image_processor = False
def setUp(self):
super().setUp()
self.image_processor_tester = PerceptionLMImageProcessingTester(se... | PerceptionLMImageProcessingTest |
python | kamyu104__LeetCode-Solutions | Python/collecting-chocolates.py | {
"start": 1519,
"end": 2475
} | class ____(object):
def minCost(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
def cost(k):
w = k+1
result = x*k
dq = collections.deque()
for i in xrange(len(nums)+w-1):
if dq and ... | Solution2 |
python | catalyst-team__catalyst | catalyst/contrib/schedulers/base.py | {
"start": 790,
"end": 928
} | class ____(BaseScheduler, ABC):
"""@TODO: Docs. Contribution is welcome."""
__all__ = ["BaseScheduler", "BatchScheduler"]
| BatchScheduler |
python | pypa__warehouse | tests/unit/manage/views/test_organizations.py | {
"start": 120210,
"end": 124682
} | class ____:
def test_get(self, db_request, user_service):
organization = OrganizationFactory.create()
older_event = OrganizationEventFactory.create(
source=organization,
tag="fake:event",
time=datetime.datetime(2017, 2, 5, 17, 18, 18, 462_634),
)
n... | TestManageOrganizationHistory |
python | keon__algorithms | algorithms/map/randomized_set.py | {
"start": 367,
"end": 1501
} | class ____:
def __init__(self):
self.nums = []
self.idxs = {}
def insert(self, val):
if val not in self.idxs:
self.nums.append(val)
self.idxs[val] = len(self.nums)-1
return True
return False
def remove(self, val):
if val in self.i... | RandomizedSet |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_reviews.py | {
"start": 9107,
"end": 14659
} | class ____(TestCase):
@HttpMocker()
def test_given_no_state_when_read_then_use_reviews_endpoint(self, http_mocker: HttpMocker) -> None:
cursor_value = int(_A_START_DATE.timestamp()) + 1
http_mocker.get(
_reviews_request().with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_li... | IncrementalTest |
python | PrefectHQ__prefect | src/integrations/prefect-docker/prefect_docker/worker.py | {
"start": 14625,
"end": 14775
} | class ____(BaseWorkerResult):
"""Contains information about a completed Docker container"""
P = ParamSpec("P")
R = TypeVar("R")
| DockerWorkerResult |
python | requests__requests-oauthlib | requests_oauthlib/oauth2_auth.py | {
"start": 158,
"end": 1508
} | class ____(AuthBase):
"""Adds proof of authorization (OAuth2 token) to the request."""
def __init__(self, client_id=None, client=None, token=None):
"""Construct a new OAuth 2 authorization object.
:param client_id: Client id obtained during registration
:param client: :class:`oauthlib.... | OAuth2 |
python | has2k1__plotnine | doc/_renderer.py | {
"start": 915,
"end": 1146
} | class ____(QRenderer):
pass
exclude_parameters(
{
"plotnine.scale_color_hue": ("s", "color_space"),
}
)
summary_name_lookup = {
"Beside": f"{Code('|')} Beside",
"Stack": f"{Code('/')} Stack",
}
| Renderer |
python | pytorch__pytorch | torch/jit/__init__.py | {
"start": 6756,
"end": 8366
} | class ____:
"""
Give errors if not all nodes have been fused in inference, or symbolically differentiated in training.
Example:
Forcing fusion of additions.
.. code-block:: python
@torch.jit.script
def foo(x):
with torch.jit.strict_fusion():
return x + ... | strict_fusion |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 15540,
"end": 21552
} | class ____(NonStrictDataModel):
"""
:param id: Source unique ID within this DatasetVersion
:type id: str
:param uri: Source data URI
:type uri: str
:param content_type: Content type (e.g. 'image/jpeg', 'image/png')
:type content_type: str
:param width: Width in pixels
:type width: in... | Source |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_code_mapping_details.py | {
"start": 307,
"end": 5082
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-code-mapping-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.user2 = self.create_user("nisanthan@sentry.io", is_superuser=False)
self.org = self.create_organization(owner=self.us... | OrganizationCodeMappingDetailsTest |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 44948,
"end": 45204
} | class ____(Node):
# Abstract base class for C base type nodes.
#
# Processing during analyse_declarations phase:
#
# analyse
# Returns the type.
def analyse_as_type(self, env):
return self.analyse(env)
| CBaseTypeNode |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/self_adjoint_eig_op_test.py | {
"start": 1509,
"end": 6560
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testWrongDimensions(self):
# The input to self_adjoint_eig should be a tensor of
# at least rank 2.
scalar = constant_op.constant(1.)
with self.assertRaises(ValueError):
linalg_ops.self_adjoint_eig(scalar)
vector = constant_op.co... | SelfAdjointEigTest |
python | ray-project__ray | python/ray/train/v2/tests/test_thread_runner.py | {
"start": 285,
"end": 5189
} | class ____(ThreadRunner):
def join(self):
"""Join both the target thread and the monitor thread.
Do not include this with the main ThreadRunner class because:
* It is tricky to avoid hangs when nested threads raise errors
* We don't need to join in that case since the controller wil... | ThreadRunnerWithJoin |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 10295,
"end": 10464
} | class ____(ProjectVersionEditMixin, CreateView):
success_message = _("Version created")
template_name = "projects/project_version_detail.html"
| ProjectVersionCreate |
python | Textualize__textual | src/textual/logging.py | {
"start": 342,
"end": 1187
} | class ____(Handler):
"""A Logging handler for Textual apps."""
def __init__(self, stderr: bool = True, stdout: bool = False) -> None:
"""Initialize a Textual logging handler.
Args:
stderr: Log to stderr when there is no active app.
stdout: Log to stdout when there is no... | TextualHandler |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_userroles_index.py | {
"start": 1494,
"end": 2046
} | class ____(UserRolesTest):
method = "POST"
def test_simple(self) -> None:
resp = self.get_response(name="test-role", permissions=["users.admin"])
assert resp.status_code == 201
assert resp.data["name"] == "test-role"
role = UserRole.objects.get(name="test-role")
assert r... | UserRolesPostTest |
python | celery__celery | t/unit/app/test_backends.py | {
"start": 2494,
"end": 4510
} | class ____:
@pytest.mark.parametrize('url,expect_cls', [
('cache+memory://', CacheBackend),
])
def test_get_backend_aliases(self, url, expect_cls, app):
backend, url = backends.by_url(url, app.loader)
assert isinstance(backend(app=app, url=url), expect_cls)
def test_unknown_bac... | test_backends |
python | huggingface__transformers | src/transformers/models/mgp_str/configuration_mgp_str.py | {
"start": 784,
"end": 5810
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of an [`MgpstrModel`]. It is used to instantiate an
MGP-STR model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar conf... | MgpstrConfig |
python | pypa__warehouse | tests/unit/macaroons/test_security_policy.py | {
"start": 1756,
"end": 12678
} | class ____:
def test_verify(self):
assert verifyClass(
ISecurityPolicy,
security_policy.MacaroonSecurityPolicy,
)
def test_noops(self):
policy = security_policy.MacaroonSecurityPolicy()
with pytest.raises(NotImplementedError):
policy.authentic... | TestMacaroonSecurityPolicy |
python | hynek__structlog | tests/processors/test_processors.py | {
"start": 5952,
"end": 6966
} | class ____:
def test_removes_stack_info(self, sir):
"""
The `stack_info` key is removed from `event_dict`.
"""
ed = sir(None, None, {"stack_info": True})
assert "stack_info" not in ed
def test_adds_stack_if_asked(self, sir):
"""
If `stack_info` is true, ... | TestStackInfoRenderer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.