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 | doocs__leetcode | solution/0900-0999/0937.Reorder Data in Log Files/Solution.py | {
"start": 0,
"end": 245
} | class ____:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
def f(log: str):
id_, rest = log.split(" ", 1)
return (0, rest, id_) if rest[0].isalpha() else (1,)
return sorted(logs, key=f)
| Solution |
python | sympy__sympy | sympy/physics/quantum/state.py | {
"start": 1608,
"end": 7555
} | class ____(QExpr):
"""Abstract base class for general abstract states in quantum mechanics.
All other state classes defined will need to inherit from this class. It
carries the basic structure for all other states such as dual, _eval_adjoint
and label.
This is an abstract base class and you should... | StateBase |
python | tornadoweb__tornado | tornado/httpclient.py | {
"start": 28784,
"end": 30195
} | class ____(Exception):
"""Exception thrown for an unsuccessful HTTP request.
Attributes:
* ``code`` - HTTP error integer error code, e.g. 404. Error code 599 is
used when no HTTP response was received, e.g. for a timeout.
* ``response`` - `HTTPResponse` object, if any.
Note that if ``foll... | HTTPClientError |
python | python-pillow__Pillow | src/PIL/GribStubImagePlugin.py | {
"start": 720,
"end": 1759
} | class ____(ImageFile.StubImageFile):
format = "GRIB"
format_description = "GRIB"
def _open(self) -> None:
if not _accept(self.fp.read(8)):
msg = "Not a GRIB file"
raise SyntaxError(msg)
self.fp.seek(-8, os.SEEK_CUR)
# make something up
self._mode = ... | GribStubImageFile |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 13556,
"end": 15145
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
sui... | doubleTestCase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_boolean_trap/FBT.py | {
"start": 2807,
"end": 3312
} | class ____:
force: InitVar[bool] = False
def __post_init__(self, force: bool) -> None:
print(force)
Fit(force=True)
# https://github.com/astral-sh/ruff/issues/10356
from django.db.models import Case, Q, Value, When
qs.annotate(
is_foo_or_bar=Case(
When(Q(is_foo=True) | Q(is_bar=True))... | Fit |
python | realpython__materials | hashtable/04_load_factor/hashtable.py | {
"start": 127,
"end": 3698
} | class ____:
@classmethod
def from_dict(cls, dictionary, capacity=None):
hash_table = cls(capacity or len(dictionary))
for key, value in dictionary.items():
hash_table[key] = value
return hash_table
def __init__(self, capacity=8, load_factor_threshold=0.6):
if cap... | HashTable |
python | django__django | tests/admin_views/models.py | {
"start": 25343,
"end": 25542
} | class ____(models.Model):
work_at = models.ForeignKey(Restaurant, models.CASCADE)
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
# Models for #23329
| Worker |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/core.py | {
"start": 67007,
"end": 100219
} | class ____:
"""This object is provided as the .hypothesis attribute on @given tests.
Downstream users can reassign its attributes to insert custom logic into
the execution of each case, for example by converting an async into a
sync function.
This must be an attribute of an attribute, because reas... | HypothesisHandle |
python | getsentry__sentry | src/sentry/api/endpoints/project_transaction_threshold.py | {
"start": 1342,
"end": 4477
} | class ____(ProjectEndpoint):
owner = ApiOwner.DATA_BROWSING
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectSettingPermission,)
def has_feature(self, project, request):
... | ProjectTransactionThresholdEndpoint |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail_baseConfig.py | {
"start": 8527,
"end": 8816
} | class ____(BaseModel):
x: int
y: str
class Config:
alias_generator = None
frozen = True
extra = Extra.forbid
frozenmodel = FrozenModel(x=1, y='b')
frozenmodel.y = 'a'
# MYPY: error: Property "y" defined in "FrozenModel" is read-only [misc]
| FrozenModel |
python | joke2k__faker | faker/providers/job/uk_UA/__init__.py | {
"start": 218,
"end": 3727
} | class ____(BaseProvider):
jobs = [
# А
"Агроном",
"Адвокат",
"Актор",
"Акушер",
"Антрополог",
"Архітектор",
"Археолог",
"Астронавт",
"Астроном",
"Астрофізик",
# Б
"Бібліограф",
"Біолог",
"Бізнесме... | Provider |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore.py | {
"start": 936,
"end": 1640
} | class ____(Callback):
def __init__(self, driver_semaphore, trainer_semaphore):
self.driver_semaphore = driver_semaphore
self.trainer_semaphore = trainer_semaphore
def on_step_end(self, iteration, trials, **info):
self.driver_semaphore.release() # Driver should continue
self.tra... | SteppingCallback |
python | getsentry__sentry | src/sentry/preprod/api/models/project_preprod_build_details_models.py | {
"start": 2282,
"end": 2641
} | class ____(BaseModel):
state: Literal[PreprodArtifactSizeMetrics.SizeAnalysisState.FAILED] = (
PreprodArtifactSizeMetrics.SizeAnalysisState.FAILED
)
error_code: int
error_message: str
SizeInfo = Annotated[
SizeInfoPending | SizeInfoProcessing | SizeInfoCompleted | SizeInfoFailed,
Field... | SizeInfoFailed |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Display.py | {
"start": 218,
"end": 4038
} | class ____(Node):
"""Connection to PlotWidget. Will plot arrays, and display event lists."""
nodeName = 'PlotWidget'
sigPlotChanged = QtCore.Signal(object)
def __init__(self, name):
Node.__init__(self, name, terminals={'In': {'io': 'in', 'multi': True}})
self.plot = None # currentl... | PlotWidgetNode |
python | getsentry__sentry | src/sentry/analytics/events/issue_mark_reviewed.py | {
"start": 76,
"end": 267
} | class ____(analytics.Event):
user_id: int | None = None
default_user_id: int
organization_id: int
group_id: int
analytics.register(IssueMarkReviewedEvent)
| IssueMarkReviewedEvent |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/cutlass_utils.py | {
"start": 15415,
"end": 17111
} | class ____:
# Helper class for Benchmarking and Testing CUTLASS Kernels in isolation.
# Can be used to capture the sourcecode passed to CUDACodeCache.compile
def __init__(self):
self.sources = []
self._compile_patch = None
def __enter__(self, *args, **kwargs):
import unittest.m... | CUDACompileSourceCapturingContext |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 19912,
"end": 23275
} | class ____(CollectionTestCase):
"""
Test warning in ``collectstatic`` output when a file is skipped because a
previous file was already written to the same path.
"""
# If this string is in the collectstatic output, it means the warning we're
# looking for was emitted.
warning_string = "Foun... | TestCollectionOverwriteWarning |
python | ApeWorX__ape | src/ape/managers/converters.py | {
"start": 2962,
"end": 3692
} | class ____(ConverterAPI):
"""
A converter that converts an :class:`~ape.api.address.BaseAddress`
to a :class`~ape.types.address.AddressType`.
"""
def is_convertible(self, value: Any) -> bool:
return isinstance(value, BaseAddress)
def convert(self, value: BaseAddress) -> AddressType:
... | AddressAPIConverter |
python | getsentry__sentry | src/sentry/api/exceptions.py | {
"start": 2508,
"end": 2860
} | class ____(SentryAPIException):
status_code = status.HTTP_401_UNAUTHORIZED
code = "member-disabled-over-limit"
message = "Organization over member limit"
def __init__(self, organization):
super().__init__(
next=reverse("sentry-organization-disabled-member", args=[organization.slug])... | MemberDisabledOverLimit |
python | Pylons__pyramid | tests/test_session.py | {
"start": 21224,
"end": 21440
} | class ____:
def dumps(self, value):
return base64.b64encode(json.dumps(value).encode('utf-8'))
def loads(self, value):
return json.loads(base64.b64decode(value).decode('utf-8'))
| DummySerializer |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 1553,
"end": 1856
} | class ____(AccountsError):
"""
Raised when attempting to add an account using an alias
that already maps to another account.
"""
def __init__(self, alias: str):
self.alias = alias
super().__init__(f"Account with alias '{alias}' already in use.")
| AliasAlreadyInUseError |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-opendal/llama_index/readers/opendal/base.py | {
"start": 420,
"end": 2728
} | class ____(BaseReader):
"""General reader for any opendal operator."""
def __init__(
self,
scheme: str,
path: str = "/",
file_extractor: Optional[Dict[str, Union[str, BaseReader]]] = None,
**kwargs,
) -> None:
"""
Initialize opendal operator, along wi... | OpendalReader |
python | joke2k__faker | faker/providers/lorem/tl_PH/__init__.py | {
"start": 49,
"end": 325
} | class ____(FilPhProvider):
"""Implement lorem provider for ``tl_PH`` locale.
There is no difference from the |FilPhLoremProvider|.
.. |FilPhLoremProvider| replace::
:meth:`FilPhLoremProvider <faker.providers.lorem.fil_PH.Provider>`
"""
pass
| Provider |
python | mlflow__mlflow | tests/sagemaker/mock/__init__.py | {
"start": 259,
"end": 336
} | class ____(NamedTuple):
resource: Any
arn: str
| SageMakerResourceWithArn |
python | PyCQA__pylint | doc/data/messages/i/invalid-field-call/bad.py | {
"start": 54,
"end": 263
} | class ____:
a: float
b: float
c: float
field(init=False) # [invalid-field-call]
def __post_init__(self):
self.c = self.a + self.b
print(field(init=False)) # [invalid-field-call]
| C |
python | docker__docker-py | docker/types/services.py | {
"start": 26340,
"end": 27430
} | class ____(dict):
"""
Config reference to be used as part of a :py:class:`ContainerSpec`.
Describes how a config is made accessible inside the service's
containers.
Args:
config_id (string): Config's ID
config_name (string): Config's name as defined at its cr... | ConfigReference |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 232010,
"end": 232534
} | class ____(sgqlc.types.Input):
"""Ordering options for Enterprise Server user account email
connections.
"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(EnterpriseServerUserAccountEmailOrderField), graphql_name="field")
... | EnterpriseServerUserAccountEmailOrder |
python | pydata__xarray | xarray/tests/test_concat.py | {
"start": 15606,
"end": 43698
} | class ____:
@pytest.fixture
def data(self, request) -> Dataset:
use_extension_array = request.param if hasattr(request, "param") else False
return create_test_data(use_extension_array=use_extension_array).drop_dims(
"dim3"
)
def rectify_dim_order(self, data: Dataset, dat... | TestConcatDataset |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/property_graph/transformations/simple_llm.py | {
"start": 612,
"end": 4222
} | class ____(TransformComponent):
"""
Extract triples from a graph.
Uses an LLM and a simple prompt + output parsing to extract paths (i.e. triples) from text.
Args:
llm (LLM):
The language model to use.
extract_prompt (Union[str, PromptTemplate]):
The prompt to u... | SimpleLLMPathExtractor |
python | ipython__ipython | IPython/core/magics/__init__.py | {
"start": 1338,
"end": 1619
} | class ____(Magics):
"""Placeholder for user-defined magics to be added at runtime.
All magics are eventually merged into a single namespace at runtime, but we
use this class to isolate the magics defined dynamically by the user into
their own class.
"""
| UserMagics |
python | realpython__materials | django-markdown/dmd_app/models.py | {
"start": 31,
"end": 302
} | class ____(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
slug = models.SlugField(blank=True)
class Meta:
verbose_name_plural = "Markdown content"
def __str__(self):
return self.title
| MarkdownContent |
python | takluyver__flit | flit_core/flit_core/config.py | {
"start": 1580,
"end": 6860
} | class ____(ConfigError):
def __str__(self):
return ('Please specify console_scripts entry points, or [scripts] in '
'flit config, not both.')
def prep_toml_config(d, path):
"""Validate config loaded from pyproject.toml and prepare common metadata
Returns a LoadedConfig object.
"""
... | EntryPointsConflict |
python | getsentry__sentry | tests/sentry/db/models/test_utils.py | {
"start": 223,
"end": 2816
} | class ____(TestCase):
def test_works_with_standard_attrs(self) -> None:
org = self.create_organization()
assert is_model_attr_cached(org, "name") is True
def test_creation_association(self) -> None:
detector = self.create_detector()
assert is_model_attr_cached(detector, "workflo... | TestIsModelAttrCached |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 94849,
"end": 96884
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"parent",
metadata,
Column("pid", Integer, primary_key=True),
Column("pdata", String(30)),
)
Table(
"child",
metadata,
... | InheritingRowSwitchTest |
python | apache__thrift | lib/py/src/transport/TZlibTransport.py | {
"start": 1044,
"end": 2585
} | class ____:
"""Factory transport that builds zlib compressed transports.
This factory caches the last single client/transport that it was passed
and returns the same TZlibTransport object that was created.
This caching means the TServer class will get the _same_ transport
object for both input and... | TZlibTransportFactory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 936567,
"end": 936951
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("Repository", graphql_name... | RepositoryEdge |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_responses_standard.py | {
"start": 453,
"end": 4544
} | class ____(TestOpenAIStandard):
@property
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property
def chat_model_params(self) -> dict:
return {"model": "gpt-4o-mini", "use_responses_api": True}
@property
def supports_image_tool_message(self) -> bool:
... | TestOpenAIResponses |
python | pytorch__pytorch | torch/_higher_order_ops/map.py | {
"start": 4061,
"end": 10025
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, f, num_mapped_args, *flat_args):
ctx._f = f
ctx._num_mapped_args = num_mapped_args
ctx._num_pos_args = len(flat_args) - num_mapped_args
# We snapshot the dispatch keys in for... | MapAutogradOp |
python | getsentry__sentry | src/sentry/migrations/0927_dashboard_add_unique_constraint_user_dashboard.py | {
"start": 155,
"end": 1763
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigquery.py | {
"start": 4156,
"end": 11979
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook")
def test_execute(self, mock_hook):
operator = BigQueryCreateTableOperator(
task_id=TASK_ID,
dataset_id=TEST_DATASET,
project_id=TEST_GCP_PROJECT_ID,
table_id=TEST_TAB... | TestBigQueryCreateTableOperator |
python | mlflow__mlflow | mlflow/genai/judges/tools/get_span_performance_and_timing_report.py | {
"start": 643,
"end": 944
} | class ____:
"""Timing data for a single span."""
span_id: str
name: str
span_type: str
total_duration_s: float
self_duration_s: float
child_duration_s: float
span_number: str
parent_number: str | None
ancestors: list[str]
depth: int
@dataclass
| SpanTimingData |
python | kamyu104__LeetCode-Solutions | Python/amount-of-time-for-binary-tree-to-be-infected.py | {
"start": 2516,
"end": 3683
} | class ____(object):
def amountOfTime(self, root, start):
"""
:type root: Optional[TreeNode]
:type start: int
:rtype: int
"""
def bfs(root):
adj = collections.defaultdict(list)
q = [root]
while q:
new_q = []
... | Solution3 |
python | django__django | tests/db_functions/comparison/test_nullif.py | {
"start": 211,
"end": 1718
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda", alias="Rhonda")
def test_basic(self):
authors = Author.objects.annotate(nullif=NullIf("alias", "name")).values_list(
"... | NullIfTests |
python | Textualize__textual | docs/blog/snippets/2022-12-07-responsive-app-background-task/nonblocking01.py | {
"start": 448,
"end": 1068
} | class ____(App[None]):
BINDINGS = [("l", "load", "Load data")]
CSS = """
Grid {
grid-size: 2;
}
"""
def compose(self) -> ComposeResult:
yield Grid(
ColourChanger(),
VerticalScroll(id="log"),
)
yield Footer()
def action_load(self) -> N... | MyApp |
python | doocs__leetcode | lcof/面试题19. 正则表达式匹配/Solution2.py | {
"start": 0,
"end": 583
} | class ____:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
f = [[False] * (n + 1) for _ in range(m + 1)]
f[0][0] = True
for i in range(m + 1):
for j in range(1, n + 1):
if p[j - 1] == "*":
f[i][j] = f[i][j - 2]
... | Solution |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 213944,
"end": 214080
} | class ____(Protocol[Input, Output]):
def __call__(self, _in: Input, /, *, config: RunnableConfig) -> Output: ...
| _RunnableCallableSync |
python | aio-libs__aiohttp | tests/test_websocket_parser.py | {
"start": 21437,
"end": 23193
} | class ____:
def test_ctor(self) -> None:
err = WebSocketError(WSCloseCode.PROTOCOL_ERROR, "Something invalid")
assert err.code == WSCloseCode.PROTOCOL_ERROR
assert str(err) == "Something invalid"
def test_pickle(self) -> None:
err = WebSocketError(WSCloseCode.PROTOCOL_ERROR, "So... | TestWebSocketError |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/10_A3C/A3C_RNN.py | {
"start": 890,
"end": 5384
} | class ____(object):
def __init__(self, scope, globalAC=None):
if scope == GLOBAL_NET_SCOPE: # get global network
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self.a_params, self.c_params = self._build_net(scope)[-2:]
... | ACNet |
python | ansible__ansible | lib/ansible/_internal/_templating/_marker_behaviors.py | {
"start": 525,
"end": 1157
} | class ____(MarkerBehavior):
"""
The default behavior when encountering a `Marker` value during concatenation or finalization.
This always raises the template-internal `MarkerError` exception.
"""
def handle_marker(self, value: Marker) -> t.Any:
value.trip()
# FAIL_ON_MARKER_BEHAVIOR
# _DE... | FailingMarkerBehavior |
python | kubernetes-client__python | kubernetes/client/api/networking_v1beta1_api.py | {
"start": 543,
"end": 213296
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | NetworkingV1beta1Api |
python | django__django | django/template/defaulttags.py | {
"start": 29677,
"end": 54595
} | class ____(IfParser):
error_class = TemplateSyntaxError
def __init__(self, parser, *args, **kwargs):
self.template_parser = parser
super().__init__(*args, **kwargs)
def create_var(self, value):
return TemplateLiteral(self.template_parser.compile_filter(value), value)
@register.ta... | TemplateIfParser |
python | mlflow__mlflow | tests/pyfunc/test_chat_agent.py | {
"start": 2970,
"end": 16030
} | class ____(ChatAgent):
def predict(
self, messages: list[ChatAgentMessage], context: ChatContext, custom_inputs: dict[str, Any]
) -> ChatAgentResponse:
mock_response = get_mock_response(messages)
return ChatAgentResponse(
**mock_response,
custom_outputs=custom_inp... | ChatAgentWithCustomInputs |
python | openai__openai-python | src/openai/resources/containers/containers.py | {
"start": 1193,
"end": 8787
} | class ____(SyncAPIResource):
@cached_property
def files(self) -> Files:
return Files(self._client)
@cached_property
def with_raw_response(self) -> ContainersWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response obj... | Containers |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 77863,
"end": 78580
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"repository_id",
"title",
"body",
"category_id",
"client_mutation_id",
)
repository_id = sgqlc.types.Field(
sgqlc.types.non_n... | CreateDiscussionInput |
python | cython__cython | runtests.py | {
"start": 80095,
"end": 81951
} | class ____(unittest.TestCase):
working_dir = "Demos/embed"
def setUp(self):
self.old_dir = os.getcwd()
os.chdir(self.working_dir)
os.system(
"make PYTHON='%s' clean > /dev/null" % sys.executable)
def tearDown(self):
try:
os.system(
"... | EmbedTest |
python | pydantic__pydantic | pydantic-core/tests/conftest.py | {
"start": 3550,
"end": 5727
} | class ____:
def __init__(self, schema: bool, extra: bool):
assert schema or extra
self.schema = schema
self.validator_args = {'strict': True} if extra else {}
@pytest.fixture(
params=[
StrictModeType(schema=True, extra=False),
StrictModeType(schema=False, extra=True),
... | StrictModeType |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 33423,
"end": 34563
} | class ____(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is unwilling to process
the request because its header fields are too large. The request MAY
be resubmitted after reducing the size of the request header fields.
RFC 6585.5
code: 431, ti... | HTTPRequestHeaderFieldsTooLarge |
python | numba__numba | numba/tests/test_struct_ref.py | {
"start": 7579,
"end": 8431
} | class ____(MemoryLeakMixin, TestCase):
def test_overload_method(self):
@njit
def check(x):
vs = np.arange(10, dtype=np.float64)
ctr = 11
obj = MyStruct(vs, ctr)
return obj.testme(x)
x = 3
got = check(x)
expect = check.py_func(x... | TestStructRefExtending |
python | getsentry__sentry | src/sentry/users/models/user_option.py | {
"start": 5458,
"end": 10264
} | class ____(Model):
"""
User options apply only to a user, and optionally a project OR an organization.
Options which are specific to a plugin should namespace
their key. e.g. key='myplugin:optname'
Keeping user feature state
key: "feature:assignment"
value: { updated: datetime, state: bool... | UserOption |
python | apache__airflow | airflow-core/src/airflow/dag_processing/bundles/base.py | {
"start": 2769,
"end": 7946
} | class ____:
"""
Utility helper for removing stale bundles.
:meta private:
"""
def _parse_dt(self, val) -> DateTime | None:
try:
return pendulum.parse(val)
except ParserError:
return None
@staticmethod
def _filter_for_min_versions(val: list[TrackedBu... | BundleUsageTrackingManager |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 88239,
"end": 88511
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
AutoModelForZeroShotObjectDetection = auto_class_update(
AutoModelForZeroShotObjectDetection, head_doc="zero-shot object detection"
)
| AutoModelForZeroShotObjectDetection |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/other/decorator.py | {
"start": 60,
"end": 173
} | class ____:
pass
@decorator
def f(): ...
@a.b.c
def f(): ...
@a
@a.b.c
def f(): ...
@a
@1 | 2
@a.b.c
| Test |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 19219,
"end": 19561
} | class ____:
# GH 16798
def setup(self):
self.csv = StringIO(
"strings\n" + "\n".join(["x" * (1 << 20) for _ in range(2100)])
)
def peakmem_over_2gb_input(self):
read_csv(self.csv, engine="c", low_memory=False)
from ..pandas_vb_common import setup # noqa: F401 isort:sk... | ReadCSVCParserLowMemory |
python | tensorflow__tensorflow | tensorflow/compiler/tests/lstm_test.py | {
"start": 1653,
"end": 10381
} | class ____(test.TestCase):
def setUp(self):
# The tests for a single LSTM cell and LSTM layer use these values as
# inputs. We always set the dimensionality of num_inputs=1; thus batch_size
# actually represents the different input cases.
self._inputs = np.array([[-1.], [-.5], [0.], [.5], [1.]], np.... | LSTMTest |
python | django__django | tests/auth_tests/models/with_foreign_key.py | {
"start": 229,
"end": 515
} | class ____(BaseUserManager):
def create_superuser(self, username, email, group, password):
user = self.model(username_id=username, email_id=email, group_id=group)
user.set_password(password)
user.save(using=self._db)
return user
| CustomUserWithFKManager |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_gather_op_test.py | {
"start": 1493,
"end": 19868
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.named_parameters([
# Basic gather (axis=0 and batch_dims=0)
dict(testcase_name='Params1DTensor_Indices1DTensor',
params=['a', 'b', 'c', 'd', 'e'],
indices=[2, 0, 2, 1],
expected=['c', 'a', 'c... | RaggedGatherOpTest |
python | pytorch__pytorch | test/inductor/test_aot_inductor_package.py | {
"start": 2581,
"end": 39115
} | class ____(TestCase):
def check_model(
self: TestCase,
model,
example_inputs,
inductor_configs=None,
dynamic_shapes=None,
atol=None,
rtol=None,
) -> AOTICompiledModel:
with torch.no_grad():
torch.manual_seed(0)
model = model... | TestAOTInductorPackage |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/fsdp.py | {
"start": 34791,
"end": 41236
} | class ____(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager:
"""Blocks gradient synchronization inside the :class:`~torch.distributed.fsdp.FullyShardedDataParallel`
wrapper."""
if not enabled:
return nullcont... | _FSDPBackwardSyncControl |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/argparsing/parsers.py | {
"start": 16164,
"end": 17708
} | class ____(Parser, metaclass=abc.ABCMeta):
"""Base class for composite argument parsers that store their results in a namespace."""
def parse(self, state: ParserState) -> t.Any:
"""Parse the input from the given state and return the result."""
namespace = state.current_namespace
current... | NamespaceParser |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_packaging.py | {
"start": 12065,
"end": 13299
} | class ____:
def test_fail_when_missing_metadata_docker_image_tag(self, mocker):
# Arrange
connector = mocker.MagicMock(metadata={})
# Act
result = packaging.CheckVersionFollowsSemver()._run(connector)
# Assert
assert result.status == CheckStatus.FAILED
asser... | TestCheckVersionFollowsSemver |
python | facebookresearch__faiss | tests/test_build_blocks.py | {
"start": 1822,
"end": 2160
} | class ____(unittest.TestCase):
def test_maplong2long(self):
keys = np.array([13, 45, 67], dtype=np.int64)
vals = np.array([3, 8, 2], dtype=np.int64)
m = faiss.MapLong2Long()
m.add(keys, vals)
assert np.all(m.search_multiple(keys) == vals)
assert m.search(12343) ==... | TestMapLong2Long |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 2356,
"end": 5241
} | class ____(ModelViewSet):
pagination_class = ExamplePagination
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
filter_backends = [filters.OrderingFilter]
serializer_class = ExampleSerializer
@action(methods=['post'], detail=True, serializer_class=AnotherSerializer)
def custom_actio... | ExampleViewSet |
python | kamyu104__LeetCode-Solutions | Python/best-time-to-buy-and-sell-stock-iv.py | {
"start": 115,
"end": 3208
} | class ____(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
... | Solution |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 5399,
"end": 9339
} | class ____(nn.Module):
def __init__(self, config: DFineConfig):
"""
D-Fine version of multiscale deformable attention
"""
super().__init__()
self.d_model = config.d_model
self.n_heads = config.decoder_attention_heads
self.n_levels = config.num_feature_levels
... | DFineMultiscaleDeformableAttention |
python | numba__numba | numba/cuda/stubs.py | {
"start": 1507,
"end": 1794
} | class ____(Dim3):
'''
The block indices in the grid of thread blocks. Each index is an integer
spanning the range from 0 inclusive to the corresponding value of the
attribute in :attr:`numba.cuda.gridDim` exclusive.
'''
_description_ = '<blockIdx.{x,y,z}>'
| blockIdx |
python | anthropics__anthropic-sdk-python | tests/lib/streaming/test_messages.py | {
"start": 3355,
"end": 6388
} | class ____:
@pytest.mark.respx(base_url=base_url)
def test_basic_response(self, respx_mock: MockRouter) -> None:
respx_mock.post("/v1/messages").mock(
return_value=httpx.Response(200, content=get_response("basic_response.txt"))
)
with sync_client.messages.stream(
... | TestSyncMessages |
python | weaviate__weaviate-python-client | mock_tests/conftest.py | {
"start": 11719,
"end": 13345
} | class ____(weaviate_pb2_grpc.WeaviateServicer):
def Search(
self, request: search_get_pb2.SearchRequest, context: grpc.ServicerContext
) -> search_get_pb2.SearchReply:
context.set_code(grpc.StatusCode.PERMISSION_DENIED)
context.set_details("Permission denied")
return search_get_p... | MockForbiddenWeaviateService |
python | donnemartin__interactive-coding-challenges | graphs_trees/bst_min/test_bst_min.py | {
"start": 153,
"end": 669
} | class ____(unittest.TestCase):
def test_bst_min(self):
min_bst = MinBst()
array = [0, 1, 2, 3, 4, 5, 6]
root = min_bst.create_min_bst(array)
self.assertEqual(height(root), 3)
min_bst = MinBst()
array = [0, 1, 2, 3, 4, 5, 6, 7]
root = min_bst.create_min_bst(a... | TestBstMin |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/attributes.py | {
"start": 2411,
"end": 2539
} | class ____:
buffer: List[str] = []
def test_issue_with_update_to_self_attribute(d: D):
d.buffer.append(_test_source())
| D |
python | doocs__leetcode | solution/3000-3099/3012.Minimize Length of Array Using Operations/Solution.py | {
"start": 0,
"end": 197
} | class ____:
def minimumArrayLength(self, nums: List[int]) -> int:
mi = min(nums)
if any(x % mi for x in nums):
return 1
return (nums.count(mi) + 1) // 2
| Solution |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 37481,
"end": 37654
} | class ____(Pix2SkyProjection, PseudoConic):
r"""
Polyconic projection - pixel to sky.
Corresponds to the ``PCO`` projection in FITS WCS.
"""
| Pix2Sky_Polyconic |
python | redis__redis-py | tests/test_asyncio/test_multidb/test_healthcheck.py | {
"start": 9790,
"end": 15115
} | class ____:
@pytest.mark.asyncio
async def test_database_is_healthy_when_bdb_matches_by_dns_name(
self, mock_client, mock_cb
):
"""
Ensures health check succeeds when /v1/bdbs contains an endpoint whose dns_name
matches database host, and availability endpoint returns success... | TestLagAwareHealthCheck |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 14353,
"end": 17597
} | class ____(nn.Module):
def __init__(self, config: GroupViTVisionConfig):
super().__init__()
self.patch_embeddings = GroupViTPatchEmbeddings(
image_size=config.image_size,
patch_size=config.patch_size,
num_channels=config.num_channels,
embed_dim=config... | GroupViTVisionEmbeddings |
python | numpy__numpy | tools/swig/test/testMatrix.py | {
"start": 11513,
"end": 11776
} | class ____(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "long"
self.typeCode = "l"
######################################################################
| longTestCase |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 9306,
"end": 9997
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(sel... | BlipTextSelfOutput |
python | astropy__astropy | astropy/coordinates/angles/errors.py | {
"start": 642,
"end": 1153
} | class ____(RangeError):
"""
Raised when an hour value is not in the range [0,24).
Parameters
----------
hour : int, float
Examples
--------
.. code-block:: python
if not 0 <= hr < 24:
raise IllegalHourError(hour)
"""
def __init__(self, hour):
self.h... | IllegalHourError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-retently/components.py | {
"start": 397,
"end": 735
} | class ____(DeclarativeAuthenticator):
config: Mapping[str, Any]
api_auth: ApiKeyAuthenticator
oauth: DeclarativeOauth2Authenticator
def __new__(cls, api_auth, oauth, config, *args, **kwargs):
if config["credentials"]["api_key"]:
return api_auth
else:
return oauth... | AuthenticatorRetently |
python | numpy__numpy | numpy/ma/core.py | {
"start": 5453,
"end": 25168
} | class ____(MAError):
"""
Class for mask related errors.
"""
pass
###############################################################################
# Filling options #
############################################################################... | MaskError |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 19813,
"end": 20946
} | class ____(Processor):
"""
Make leading whitespace visible.
:param get_char: Callable that returns one character.
"""
def __init__(
self,
get_char: Callable[[], str] | None = None,
style: str = "class:leading-whitespace",
) -> None:
def default_get_char() -> str... | ShowLeadingWhiteSpaceProcessor |
python | fastapi__sqlmodel | sqlmodel/main.py | {
"start": 2639,
"end": 5700
} | class ____(PydanticFieldInfo): # type: ignore[misc]
# mypy - ignore that PydanticFieldInfo is @final
def __init__(self, default: Any = Undefined, **kwargs: Any) -> None:
primary_key = kwargs.pop("primary_key", False)
nullable = kwargs.pop("nullable", Undefined)
foreign_key = kwargs.pop(... | FieldInfo |
python | pytorch__pytorch | benchmarks/dynamo/timm_models.py | {
"start": 4959,
"end": 12089
} | class ____(BenchmarkRunner):
def __init__(self):
super().__init__()
self.suite_name = "timm_models"
@property
def _config(self):
return load_yaml_file("timm_models.yaml")
@property
def _skip(self):
return self._config["skip"]
@property
def skip_models_for_c... | TimmRunner |
python | coleifer__peewee | tests/model_save.py | {
"start": 309,
"end": 398
} | class ____(TestModel):
pk = IntegerField(primary_key=True)
value = IntegerField()
| T3 |
python | joke2k__faker | faker/providers/geo/pl_PL/__init__.py | {
"start": 41,
"end": 2893
} | class ____(GeoProvider):
# Source:
# https://latitude.to/map/pl/poland/cities/
land_coords = (
("52.22977", "21.01178", "Warszawa", "PL", "Europe/Warsaw"),
("51.75", "19.46667", "Łódź", "PL", "Europe/Warsaw"),
("50.06143", "19.93658", "Kraków", "PL", "Europe/Warsaw"),
("51.... | Provider |
python | TheAlgorithms__Python | maths/pythagoras.py | {
"start": 100,
"end": 712
} | class ____:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self) -> str:
return f"Point({self.x}, {self.y}, {self.z})"
def distance(a: Point, b: Point) -> float:
"""
>>> point1 = Point(2, -1, 7)
>>> point2 = Point(1, -3, 5)
>>> print... | Point |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/run_coordinator_tests/test_queued_run_coordinator.py | {
"start": 547,
"end": 8121
} | class ____:
"""You can extend this class to easily run these set of tests on any custom run coordinator
that subclasses the QueuedRunCoordinator. When extending, you simply need to override the
`coordinator` fixture and return your implementation of `QueuedRunCoordinator`.
For example:
```
cla... | TestQueuedRunCoordinator |
python | kennethreitz__tablib | src/tablib/formats/_df.py | {
"start": 118,
"end": 1124
} | class ____:
title = 'df'
extensions = ('df',)
@classmethod
def detect(cls, stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
elif isinstance(stream, DataFrame):
return True
try:
DataFrame(st... | DataFrameFormat |
python | python__mypy | mypyc/codegen/emit.py | {
"start": 3944,
"end": 4028
} | class ____:
"""Describes handling errors in unbox/cast operations."""
| ErrorHandler |
python | Textualize__textual | src/textual/css/styles.py | {
"start": 4973,
"end": 27681
} | class ____:
"""A common base class for Styles and RenderStyles"""
ANIMATABLE = {
"offset",
"padding",
"margin",
"width",
"height",
"min_width",
"min_height",
"max_width",
"max_height",
"auto_color",
"color",
"backgr... | StylesBase |
python | run-llama__llama_index | llama-index-instrumentation/src/llama_index_instrumentation/dispatcher.py | {
"start": 14626,
"end": 14953
} | class ____:
def __init__(self, root: Dispatcher) -> None:
self.dispatchers: Dict[str, Dispatcher] = {root.name: root}
def add_dispatcher(self, d: Dispatcher) -> None:
if d.name in self.dispatchers:
pass
else:
self.dispatchers[d.name] = d
Dispatcher.model_rebuil... | Manager |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.