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 | redis__redis-py | redis/commands/search/querystring.py | {
"start": 2879,
"end": 5652
} | class ____:
def __init__(self, *children, **kwparams):
"""
Create a node
### Parameters
- **children**: One or more sub-conditions. These can be additional
`intersect`, `disjunct`, `union`, `optional`, or any other `Node`
type.
The semantics of ... | Node |
python | numba__numba | numba/cuda/cudadrv/devices.py | {
"start": 1705,
"end": 2578
} | class ____(object):
"""
Provides a context manager for executing in the context of the chosen
device. The normal use of instances of this type is from
``numba.cuda.gpus``. For example, to execute on device 2::
with numba.cuda.gpus[2]:
d_a = numba.cuda.to_device(a)
to copy the arr... | _DeviceContextManager |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 162193,
"end": 162943
} | class ____(AtomicExprNode): #, Nodes.ParallelNode):
"""
Implements cython.parallel.threadid()
"""
type = PyrexTypes.c_int_type
def analyse_types(self, env):
self.is_temp = True
# env.add_include_file("omp.h")
return self
def generate_result_code(self, code):
c... | ParallelThreadIdNode |
python | ray-project__ray | python/ray/data/_internal/memory_tracing.py | {
"start": 2070,
"end": 5861
} | class ____:
def __init__(self):
self.allocated: Dict[ray.ObjectRef, dict] = {}
self.deallocated: Dict[ray.ObjectRef, dict] = {}
self.skip_dealloc: Dict[ray.ObjectRef, str] = {}
self.peak_mem = 0
self.cur_mem = 0
def trace_alloc(self, ref: List[ray.ObjectRef], loc: str):
... | _MemActor |
python | lazyprogrammer__machine_learning_examples | cnn_class/cifar.py | {
"start": 2288,
"end": 3001
} | class ____(object):
def __init__(self, mi, mo, fw=5, fh=5, poolsz=(2, 2)):
# mi = input feature map size
# mo = output feature map size
sz = (mo, mi, fw, fh)
W0 = init_filter(sz, poolsz)
self.W = theano.shared(W0)
b0 = np.zeros(mo, dtype=np.float32)
self.b = t... | ConvPoolLayer |
python | pypa__pip | src/pip/_vendor/urllib3/response.py | {
"start": 1570,
"end": 1669
} | class ____(object):
FIRST_MEMBER = 0
OTHER_MEMBERS = 1
SWALLOW_DATA = 2
| GzipDecoderState |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/scheduler/scheduler.py | {
"start": 1026,
"end": 1921
} | class ____(
NamedTuple(
"SchedulerDebugInfo",
[
("errors", Sequence[str]),
("scheduler_config_info", str),
("scheduler_info", str),
("schedule_storage", Sequence[str]),
],
)
):
def __new__(
cls,
errors: Sequence[str],
... | SchedulerDebugInfo |
python | langchain-ai__langchain | libs/standard-tests/langchain_tests/integration_tests/cache.py | {
"start": 3821,
"end": 7503
} | class ____(BaseStandardTests):
"""Test suite for checking the `BaseCache` API of a caching layer for LLMs.
Verifies the basic caching API of a caching layer for LLMs.
The test suite is designed for synchronous caching layers.
Implementers should subclass this test suite and provide a fixture that ret... | AsyncCacheTestSuite |
python | kamyu104__LeetCode-Solutions | Python/maximum-profit-in-job-scheduling.py | {
"start": 614,
"end": 1172
} | class ____(object):
def jobScheduling(self, startTime, endTime, profit):
"""
:type startTime: List[int]
:type endTime: List[int]
:type profit: List[int]
:rtype: int
"""
min_heap = zip(startTime, endTime, profit)
heapq.heapify(min_heap)
result =... | Solution |
python | streamlit__streamlit | lib/streamlit/runtime/uploaded_file_manager.py | {
"start": 1129,
"end": 1295
} | class ____(NamedTuple):
"""Information we provide for single file in get_upload_urls."""
file_id: str
upload_url: str
delete_url: str
| UploadFileUrlInfo |
python | mlflow__mlflow | tests/store/artifact/test_databricks_artifact_repo.py | {
"start": 65823,
"end": 68109
} | class ____:
def __init__(self, content: bytes):
self.content = content
def iter_content(self, chunk_size):
yield self.content
def close(self):
pass
def raise_for_status(self):
pass
def __enter__(self):
return self
def __exit__(self, *args):
pa... | MockResponse |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dags.py | {
"start": 1732,
"end": 15630
} | class ____(TestPublicDagEndpoint):
@pytest.fixture(autouse=True)
@provide_session
def setup_dag_runs(self, session=None) -> None:
# Create DAG Runs
for dag_id in [DAG1_ID, DAG2_ID, DAG3_ID, DAG4_ID, DAG5_ID]:
dag_runs_count = 5 if dag_id in [DAG1_ID, DAG2_ID] else 2
f... | TestGetDagRuns |
python | Pylons__pyramid | src/pyramid/events.py | {
"start": 3671,
"end": 4093
} | class ____:
"""An instance of this class is emitted as an :term:`event`
whenever :app:`Pyramid` begins to process a new request. The
event instance has an attribute, ``request``, which is a
:term:`request` object. This event class implements the
:class:`pyramid.interfaces.INewRequest` interface.""... | NewRequest |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 35992,
"end": 36082
} | class ____(SettingsOverrideObject):
_default_class = TranslationBaseForm
| TranslationForm |
python | django__django | tests/inspectdb/models.py | {
"start": 3642,
"end": 3833
} | class ____(models.Model):
text_field = models.TextField(db_collation=test_collation)
class Meta:
required_db_features = {"supports_collation_on_textfield"}
| TextFieldDbCollation |
python | streamlit__streamlit | lib/tests/streamlit/form_test.py | {
"start": 18145,
"end": 23660
} | class ____(DeltaGeneratorTestCase):
"""Test form width and height."""
def test_form_with_stretch_width(self):
"""Test form with width='stretch'."""
with st.form("form_with_stretch", width="stretch"):
st.text_input("Input")
st.form_submit_button("Submit")
form_pr... | FormDimensionsTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 448063,
"end": 465170
} | class ____(VegaLiteSchema):
"""
Header schema wrapper.
Headers of row / column channels for faceted plots.
Parameters
----------
format : str, dict, :class:`Dict`, :class:`Format`, :class:`TimeFormatSpecifier`
The text format specifier for formatting number and date/time in labels of g... | Header |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 107888,
"end": 108676
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, start_date: str, access_token: str):
"""Airbyte Source for Intercom.
Documentation can be found at https://docs.airbyte.com/integrations/sources/intercom
Args:
name (str): The name of the destination.... | IntercomSource |
python | sanic-org__sanic | guide/webapp/display/layouts/models.py | {
"start": 260,
"end": 329
} | class ____(Struct, kw_only=False):
current_version: str
| GeneralConfig |
python | graphql-python__graphene | graphene/types/union.py | {
"start": 274,
"end": 360
} | class ____(BaseOptions):
types = () # type: Iterable[Type[ObjectType]]
| UnionOptions |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 11611,
"end": 13005
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
cluster_id: Optional[str] = Field(
default=None,
description=(
"The canonical identifier for the cluster used by a run. This field is"
... | ClusterInstance |
python | google__python-fire | fire/test_components_py3.py | {
"start": 1222,
"end": 1405
} | class ____:
@functools.lru_cache()
def lru_cache_in_class(self, arg1):
return arg1
@functools.lru_cache()
def lru_cache_decorated(arg1):
return arg1
| LruCacheDecoratedMethod |
python | tensorflow__tensorflow | tensorflow/python/client/virtual_gpu_test.py | {
"start": 1283,
"end": 7484
} | class ____(object):
def __init__(self,
dim=1000,
num_ops=100,
virtual_devices_per_gpu=None,
device_probabilities=None):
self._dim = dim
self._num_ops = num_ops
if virtual_devices_per_gpu is None:
self._virtual_devices_per_gpu = [3]
els... | VirtualGpuTestUtil |
python | graphql-python__graphene | graphene/validation/disable_introspection.py | {
"start": 183,
"end": 539
} | class ____(ValidationRule):
def enter_field(self, node: FieldNode, *_args):
field_name = node.name.value
if is_introspection_key(field_name):
self.report_error(
GraphQLError(
f"Cannot query '{field_name}': introspection is disabled.", node
... | DisableIntrospection |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass9.py | {
"start": 193,
"end": 340
} | class ____(ABC):
@property
@abstractmethod
def myproperty(self) -> str: ...
MixinB = NamedTuple("MixinB", [("myproperty", str)])
| ClassA |
python | facebook__pyre-check | client/commands/query_response.py | {
"start": 664,
"end": 1517
} | class ____:
payload: object
@staticmethod
def from_json(
response_json: object,
) -> Response:
if (
isinstance(response_json, list)
and len(response_json) > 1
and response_json[0] == "Query"
):
return Response(response_json[1])
... | Response |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-zyte-serp/llama_index/readers/zyte_serp/base.py | {
"start": 235,
"end": 2249
} | class ____(BasePydanticReader):
"""
Get google search results URLs for a search query.
Args:
api_key: Zyte API key.
extract_from: Determines the mode while extracting the search results.
It can take one of the following values: 'httpResponseBody', 'browserHtml'
Example:
... | ZyteSerpReader |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 10811,
"end": 11009
} | class ____(collections.abc.Callable[P, ...]):
def __new__(cls: type[Generic4]) -> Generic4: ...
def __enter__(self: Generic4) -> Generic4: ...
from some_module import PotentialTypeVar
| Generic4 |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/data_loss_prevention.py | {
"start": 4801,
"end": 5057
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Data Loss Prevention link."""
name = "Cloud DLP Info Type Details"
key = "cloud_dlp_info_type_details_key"
format_str = DLP_INFO_TYPE_DETAILS_LINK
| CloudDLPInfoTypeDetailsLink |
python | doocs__leetcode | solution/2200-2299/2286.Booking Concert Tickets in Groups/Solution.py | {
"start": 132,
"end": 1793
} | class ____:
def __init__(self, n, m):
self.m = m
self.tr = [Node() for _ in range(n << 2)]
self.build(1, 1, n)
def build(self, u, l, r):
self.tr[u].l, self.tr[u].r = l, r
if l == r:
self.tr[u].s = self.tr[u].mx = self.m
return
mid = (l + r... | SegmentTree |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 12722,
"end": 12802
} | class ____(PydanticValueError):
msg_template = 'invalid date format'
| DateError |
python | davidhalter__jedi | jedi/inference/lazy_value.py | {
"start": 632,
"end": 803
} | class ____(AbstractLazyValue):
def __init__(self, min=1, max=1):
super().__init__(None, min, max)
def infer(self):
return NO_VALUES
| LazyUnknownValue |
python | walkccc__LeetCode | solutions/2256. Minimum Average Difference/2256.py | {
"start": 0,
"end": 457
} | class ____:
def minimumAverageDifference(self, nums: list[int]) -> int:
n = len(nums)
ans = 0
minDiff = inf
prefix = 0
suffix = sum(nums)
for i, num in enumerate(nums):
prefix += num
suffix -= num
prefixAvg = prefix // (i + 1)
suffixAvg = 0 if i == n - 1 else suffix //... | Solution |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_request_allocation_result.py | {
"start": 383,
"end": 17712
} | 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... | V1beta2DeviceRequestAllocationResult |
python | ApeWorX__ape | src/ape_ethereum/provider.py | {
"start": 68024,
"end": 68815
} | class ____(ManagerAccessMixin):
def __init__(self, eth_call_args: list):
self._arguments = eth_call_args
self.contract_type = None
@cached_property
def trace(self) -> CallTrace:
return CallTrace(
tx=self._arguments[0], arguments=self._arguments[1:], use_tokens_for_symbo... | _LazyCallTrace |
python | jazzband__django-oauth-toolkit | tests/test_authorization_code.py | {
"start": 2126,
"end": 2995
} | class ____(BaseTest):
"""
Test to avoid regression for the issue 315: request object
was being reassigned when getting AuthorizationView
"""
def test_request_is_not_overwritten(self):
self.oauth2_settings.PKCE_REQUIRED = False
self.client.login(username="test_user", password="123456... | TestRegressionIssue315 |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_cli_integration.py | {
"start": 10538,
"end": 12384
} | class ____:
# `ray job status` should exit with 0 if the job exists and non-zero if it doesn't.
# This is the contract between Ray and KubRay v1.3.0.
def test_status_job_exists(self, ray_start_stop):
cmd = "echo hello"
job_id = "test_job_id"
_run_cmd(
f"ray job submit --s... | TestJobStatus |
python | pytest-dev__pytest-mock | src/pytest_mock/plugin.py | {
"start": 1972,
"end": 25297
} | class ____:
"""
Fixture that provides the same interface to functions in the mock module,
ensuring that they are uninstalled at the end of each test.
"""
def __init__(self, config: Any) -> None:
self._mock_cache: MockCache = MockCache()
self.mock_module = mock_module = get_mock_modu... | MockerFixture |
python | facebook__pyre-check | client/identifiers.py | {
"start": 747,
"end": 2299
} | class ____(enum.Enum):
"""
The pyre flavor acts as a name of a particular language-server + daemon
pair. Its value is a factor in determining socket and log paths, which
have to be kept separate if we are running multiple language servers
in parallel, as well as tagging telemetry data.
On the c... | PyreFlavor |
python | getsentry__sentry | src/sentry/integrations/github/blame.py | {
"start": 603,
"end": 730
} | class ____(TypedDict):
oid: str
author: GitHubAuthor | None
message: str
committedDate: str
| GitHubFileBlameCommit |
python | encode__httpx | httpx/_exceptions.py | {
"start": 5573,
"end": 5751
} | class ____(Exception):
"""
URL is improperly formed or cannot be parsed.
"""
def __init__(self, message: str) -> None:
super().__init__(message)
| InvalidURL |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 14131,
"end": 14333
} | class ____(Serializer):
def serialize(
self, obj: CheckinProcessingError, attrs, user, **kwargs
) -> CheckinProcessingErrorData:
return obj.to_dict()
| CheckinProcessingErrorSerializer |
python | huggingface__transformers | src/transformers/models/qwen3_moe/modular_qwen3_moe.py | {
"start": 1895,
"end": 1946
} | class ____(Qwen2MoeExperts):
pass
| Qwen3MoeExperts |
python | walkccc__LeetCode | solutions/2809. Minimum Time to Make Array Sum At Most x/2809.py | {
"start": 0,
"end": 898
} | class ____:
def minimumTime(self, nums1: list[int], nums2: list[int], x: int) -> int:
n = len(nums1)
# dp[i][j] := the maximum reduced value if we do j operations on the first
# i numbers
dp = [[0] * (n + 1) for _ in range(n + 1)]
sum1 = sum(nums1)
sum2 = sum(nums2)
for i, (num2, num1) in... | Solution |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 4011,
"end": 4099
} | class ____(models.Model):
username = models.CharField(max_length=30, unique=True)
| User |
python | django-extensions__django-extensions | django_extensions/auth/mixins.py | {
"start": 61,
"end": 464
} | class ____(UserPassesTestMixin):
model_permission_user_field = "user"
def get_model_permission_user_field(self):
return self.model_permission_user_field
def test_func(self):
model_attr = self.get_model_permission_user_field()
current_user = self.request.user
return current... | ModelUserFieldPermissionMixin |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 130245,
"end": 132555
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('fan', c_uint),
('speed', c_uint),
]
nvmlFanSpeedInfo_v1 = 0x100000C
def nvmlDeviceGetFanSpeedRPM(handle):
c_fanSpeed = c_nvmlFanSpeedInfo_t()
c_fanSpeed.fan = 0
c_fanSpeed.version = nvmlFanSpeedInfo_v1
... | c_nvmlFanSpeedInfo_t |
python | lxml__lxml | benchmark/bench_etree.py | {
"start": 443,
"end": 12547
} | class ____(benchbase.TreeBenchMark):
@anytree
@nochange
def bench_iter_children(self, root):
for child in root:
pass
@anytree
@nochange
def bench_iter_children_reversed(self, root):
for child in reversed(root):
pass
@anytree
@nochange
def ben... | BenchMark |
python | numba__numba | numba/tests/test_sys_monitoring.py | {
"start": 34017,
"end": 34693
} | class ____(TestCase):
def test_skipping_of_tests_if_monitoring_in_use(self):
# check that the unit tests in the TestMonitoring class above will skip
# if there are other monitoring tools registered in the thread (in this
# case cProfile is used to cause that effect).
r = self.subpro... | TestMonitoringSelfTest |
python | PrefectHQ__prefect | src/prefect/server/orchestration/global_policy.py | {
"start": 11595,
"end": 12673
} | class ____(
BaseUniversalTransform[
orm_models.Run, Union[core.FlowRunPolicy, core.TaskRunPolicy]
]
):
"""
Records the scheduled time on a run.
When a run enters a scheduled state, `run.next_scheduled_start_time` is set to
the state's scheduled time. When leaving a scheduled state,
... | SetNextScheduledStartTime |
python | walkccc__LeetCode | solutions/657. Robot Return to Origin/657.py | {
"start": 0,
"end": 150
} | class ____:
def judgeCircle(self, moves: str) -> bool:
return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')
| Solution |
python | hynek__structlog | tests/test_threadlocal.py | {
"start": 8065,
"end": 11271
} | class ____:
def test_alias(self):
"""
We're keeping the old alias around.
"""
assert merge_threadlocal_context is merge_threadlocal
def test_bind_and_merge(self):
"""
Binding a variable causes it to be included in the result of
merge_threadlocal.
... | TestNewThreadLocal |
python | scikit-learn__scikit-learn | examples/gaussian_process/plot_gpr_on_structured_data.py | {
"start": 2156,
"end": 5869
} | class ____(GenericKernelMixin, Kernel):
"""
A minimal (but valid) convolutional kernel for sequences of variable
lengths."""
def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)):
self.baseline_similarity = baseline_similarity
self.baseline_similarity_bounds ... | SequenceKernel |
python | eventlet__eventlet | eventlet/semaphore.py | {
"start": 6086,
"end": 7165
} | class ____(Semaphore):
"""A bounded semaphore checks to make sure its current value doesn't exceed
its initial value. If it does, ValueError is raised. In most situations
semaphores are used to guard resources with limited capacity. If the
semaphore is released too many times it's a sign of a bug. If n... | BoundedSemaphore |
python | huggingface__transformers | tests/models/mistral/test_modeling_mistral.py | {
"start": 1461,
"end": 1594
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = MistralModel
@require_torch
| MistralModelTester |
python | scrapy__scrapy | tests/test_pipeline_crawl.py | {
"start": 1119,
"end": 1267
} | class ____(MediaDownloadSpider):
name = "brokenmedia"
def _process_url(self, url):
return url + ".foo"
| BrokenLinksMediaDownloadSpider |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_quotes/docstring_singles_class.py | {
"start": 0,
"end": 290
} | class ____():
''' Double quotes single line class docstring '''
''' Not a docstring '''
def foo(self, bar='''not a docstring'''):
''' Double quotes single line method docstring'''
pass
class Nested(foo()[:]): ''' inline docstring '''; pass
| SingleLineDocstrings |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 69432,
"end": 70129
} | class ____(BaseModel):
type: Literal["SubstreamPartitionRouter"]
parent_stream_configs: List[ParentStreamConfig] = Field(
...,
description="Specifies which parent streams are being iterated over and how parent records should be used to partition the child stream data set.",
title="Parent... | SubstreamPartitionRouter |
python | jina-ai__jina | tests/unit/hubble-executor/exec.py | {
"start": 61,
"end": 246
} | class ____(Executor):
def __init__(self, bar, **kwargs):
super().__init__(**kwargs)
self.bar = bar
@requests
def foo(self, **kwargs):
hello()
| MyExecutor |
python | kamyu104__LeetCode-Solutions | Python/partition-list.py | {
"start": 233,
"end": 843
} | class ____(object):
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
dummySmaller, dummyGreater = ListNode(-1), ListNode(-1)
smaller, greater = dummySmaller, dummyGreater
while head:
if head.val < x:
... | Solution |
python | PrefectHQ__prefect | tests/blocks/test_core.py | {
"start": 80907,
"end": 82500
} | class ____:
def test_no_description_configured(self):
class A(Block):
message: str
assert A.get_description() is None
def test_description_from_docstring(self, caplog):
class A(Block):
"""
A block, verily
Heading:
This ex... | TestGetDescription |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/core.py | {
"start": 44697,
"end": 51464
} | class ____(PlanePlot):
@property
def _kind(self) -> Literal["scatter"]:
return "scatter"
def __init__(
self,
data,
x,
y,
s=None,
c=None,
*,
colorbar: bool | lib.NoDefault = lib.no_default,
norm=None,
**kwargs,
) -> ... | ScatterPlot |
python | redis__redis-py | tests/test_asyncio/test_monitor.py | {
"start": 165,
"end": 2671
} | class ____:
async def test_wait_command_not_found(self, r):
"""Make sure the wait_for_command func works when command is not found"""
async with r.monitor() as m:
response = await wait_for_command(r, m, "nothing")
assert response is None
async def test_response_values(se... | TestMonitor |
python | numba__numba | numba/core/types/function_type.py | {
"start": 226,
"end": 3186
} | class ____(Type):
"""
First-class function type.
"""
cconv = None
def __init__(self, signature):
sig = types.unliteral(signature)
self.nargs = len(sig.args)
self.signature = sig
self.ftype = FunctionPrototype(sig.return_type, sig.args)
self._key = self.ftype... | FunctionType |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 5283,
"end": 5630
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["org:read", "org:write", "org:admin", "org:integrations"],
"POST": ["org:write", "org:admin", "org:integrations"],
"PUT": ["org:write", "org:admin", "org:integrations"],
"DELETE": ["org:admin", "org:integrations"],
}
| OrganizationIntegrationsPermission |
python | apache__thrift | lib/py/src/transport/TSSLSocket.py | {
"start": 1178,
"end": 7851
} | class ____(object):
# SSLContext is not available for Python < 2.7.9
_has_ssl_context = sys.hexversion >= 0x020709F0
# ciphers argument is not available for Python < 2.7.0
_has_ciphers = sys.hexversion >= 0x020700F0
# For python >= 2.7.9, use latest TLS that both client and server
# supports.
... | TSSLBase |
python | kamyu104__LeetCode-Solutions | Python/evaluate-boolean-binary-tree.py | {
"start": 139,
"end": 1216
} | class ____(object):
def evaluateTree(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
INF = float("inf")
OP = {
2: lambda x, y: x or y,
3: lambda x, y: x and y
}
def iter_dfs(root):
ret = [0]... | Solution |
python | django__django | tests/model_fields/models.py | {
"start": 4463,
"end": 4535
} | class ____(models.Model):
field = models.DurationField()
| DurationModel |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ItemGroup.py | {
"start": 92,
"end": 504
} | class ____(GraphicsObject):
"""
Replacement for QGraphicsItemGroup
"""
def __init__(self, *args):
GraphicsObject.__init__(self, *args)
self.setFlag(self.GraphicsItemFlag.ItemHasNoContents)
def boundingRect(self):
return QtCore.QRectF()
def paint(self, *... | ItemGroup |
python | rapidsai__cudf | python/cudf/cudf/core/udf/groupby_typing.py | {
"start": 1327,
"end": 2472
} | class ____(numba.types.Type):
"""
Numba extension type carrying metadata associated with a single
GroupBy group. This metadata ultimately is passed to the CUDA
__device__ function which actually performs the work.
"""
def __init__(self, group_scalar_type, index_type=index_default_type):
... | GroupType |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 35836,
"end": 36030
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DISMISSED", "FIXED", "OPEN")
| RepositoryVulnerabilityAlertState |
python | getsentry__sentry | src/sentry/api/endpoints/organization_tagkey_values.py | {
"start": 884,
"end": 3584
} | class ____(OrganizationEventsEndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, organization, key) -> Response:
if not TAG_KEY_RE.match(key):
return Response({"detail": f'Invalid tag key format for "{key}"'}, status=400)
... | OrganizationTagKeyValuesEndpoint |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 665,
"end": 829
} | class ____(GenericModel, Generic[ResponseFormatT]):
type: Literal["content.done"]
content: str
parsed: Optional[ResponseFormatT] = None
| ContentDoneEvent |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 119231,
"end": 120673
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(9799340796)
def test_pmf_basic(self):
# Basic case
ln2 = np.log(2)
vals = stats.poisson.pmf([0, 1, 2], ln2)
expected = [0.5, ln2/2, ln2**2/4]
assert_allclose(vals, expected)
def test_mu0(se... | TestPoisson |
python | Netflix__metaflow | test/core/tests/task_exception.py | {
"start": 67,
"end": 981
} | class ____(MetaflowTest):
"""
A test to validate if exceptions are stored and retrieved correctly
"""
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
... | TaskExceptionTest |
python | dagster-io__dagster | python_modules/libraries/dagster-omni/dagster_omni/objects.py | {
"start": 2914,
"end": 3313
} | class ____:
id: str
name: str
query_config: OmniQueryConfig
@classmethod
def from_json(cls, data: dict[str, Any]) -> "OmniQuery":
"""Create OmniQuery from JSON response data."""
return cls(
id=data["id"],
name=data["name"],
query_config=OmniQueryC... | OmniQuery |
python | huggingface__transformers | tests/models/git/test_modeling_git.py | {
"start": 1425,
"end": 4403
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=32,
patch_size=16,
num_channels=3,
is_training=True,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
... | GitVisionModelTester |
python | pytorch__pytorch | torch/distributed/tensor/parallel/style.py | {
"start": 18353,
"end": 26080
} | class ____(ParallelStyle):
"""
Configure the nn.Module's inputs to convert the input tensors of the nn.Module to DTensors at runtime according to
``input_layouts``, and perform layout redistribution according to the ``desired_input_layouts``.
Keyword Args:
input_layouts (Union[Placement, Tuple[... | PrepareModuleInput |
python | openai__openai-python | src/openai/cli/_errors.py | {
"start": 196,
"end": 471
} | class ____(CLIError): ...
def display_error(err: CLIError | APIError | pydantic.ValidationError) -> None:
if isinstance(err, SilentCLIError):
return
sys.stderr.write("{}{}Error:{} {}\n".format(organization_info(), Colors.FAIL, Colors.ENDC, err))
| SilentCLIError |
python | numba__numba | numba/tests/test_builtins.py | {
"start": 35626,
"end": 44239
} | class ____(TestCase):
def test_isinstance(self):
pyfunc = isinstance_usecase
cfunc = jit(nopython=True)(pyfunc)
inputs = (
3, # int
5.0, # float
"Hello", # string
b'world', # bytes
1j, ... | TestIsinstanceBuiltin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_radar01.py | {
"start": 315,
"end": 1345
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_radar01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | numba__numba | numba/tests/test_builtins.py | {
"start": 6918,
"end": 34449
} | class ____(TestCase):
def run_nullary_func(self, pyfunc, flags):
cfunc = jit((), **flags)(pyfunc)
expected = pyfunc()
self.assertPreciseEqual(cfunc(), expected)
def test_abs(self, flags=forceobj_flags):
pyfunc = abs_usecase
cfunc = jit((types.int32,), **flags)(pyfunc)
... | TestBuiltins |
python | mkdocs__mkdocs | mkdocs/structure/toc.py | {
"start": 754,
"end": 1606
} | class ____:
"""A single entry in the table of contents."""
def __init__(self, title: str, id: str, level: int) -> None:
self.title, self.id, self.level = title, id, level
self.children = []
title: str
"""The text of the item, as HTML."""
@property
def url(self) -> str:
... | AnchorLink |
python | tiangolo__fastapi | fastapi/security/http.py | {
"start": 10264,
"end": 13553
} | class ____(HTTPBase):
"""
HTTP Digest authentication.
**Warning**: this is only a stub to connect the components with OpenAPI in FastAPI,
but it doesn't implement the full Digest scheme, you would need to to subclass it
and implement it in your code.
Ref: https://datatracker.ietf.org/doc/html/... | HTTPDigest |
python | pypa__pip | src/pip/_vendor/cachecontrol/filewrapper.py | {
"start": 281,
"end": 4291
} | class ____:
"""
Small wrapper around a fp object which will tee everything read into a
buffer, and when that file is closed it will execute a callback with the
contents of that buffer.
All attributes are proxied to the underlying file object.
This class uses members with a double underscore (_... | CallbackFileWrapper |
python | vyperlang__vyper | vyper/venom/analysis/mem_ssa.py | {
"start": 537,
"end": 1869
} | class ____:
"""Base class for memory SSA nodes"""
def __init__(self, id: int):
self.id = id
self.reaching_def: Optional[MemoryAccess] = None
self.loc: MemoryLocation = MemoryLocation.EMPTY
@property
def is_live_on_entry(self) -> bool:
return self.id == 0
@property
... | MemoryAccess |
python | scrapy__scrapy | scrapy/commands/bench.py | {
"start": 914,
"end": 1372
} | class ____:
def __enter__(self) -> None:
pargs = [sys.executable, "-u", "-m", "scrapy.utils.benchserver"]
self.proc = subprocess.Popen( # noqa: S603
pargs, stdout=subprocess.PIPE, env=get_testenv()
)
assert self.proc.stdout
self.proc.stdout.readline()
def __... | _BenchServer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_merge_cells.py | {
"start": 393,
"end": 1939
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_merge_cells() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
self.worksheet.str_table = SharedStringTable()
def test_write_merge_cel... | TestWriteMergeCells |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 7607,
"end": 7947
} | class ____(AbstractTemplate):
def generic(self, args, kws):
# For datetime64 comparisons, all units are inter-comparable
left, right = args
if not all(isinstance(tp, types.NPDatetime) for tp in args):
return
return signature(types.boolean, left, right)
@infer_global(op... | DatetimeCmpOp |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 45950,
"end": 46264
} | class ____(BaseModel, frozen=True):
targets: List[Target] = Field(description="List of targets for the given route.")
route_prefix: str = Field(description="Prefix route of the targets.")
protocol: RequestProtocol = Field(description="Protocol of the targets.")
@PublicAPI(stability="stable")
| TargetGroup |
python | getsentry__sentry | src/sentry/incidents/metric_issue_detector.py | {
"start": 6908,
"end": 17484
} | class ____(BaseDetectorTypeValidator):
data_sources = serializers.ListField(
child=SnubaQueryValidator(timeWindowSeconds=True), required=False
)
condition_group = MetricIssueConditionGroupValidator(required=True)
def validate(self, attrs):
attrs = super().validate(attrs)
if "co... | MetricIssueDetectorValidator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofilter06.py | {
"start": 315,
"end": 2622
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofilter06.xlsx")
self.set_text_file("autofilter_data.txt")
def test_create_file(self):
"""
Test the creation of a simple... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 293729,
"end": 294199
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node", "role")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("Organization", graphql_name="node")
rol... | EnterpriseOrganizationMembershipEdge |
python | conda__conda | tests/env/test_env.py | {
"start": 967,
"end": 13021
} | class ____:
def __init__(self):
self.output = ""
def write(self, chunk):
self.output += chunk.decode("utf-8")
def get_environment(filename):
return from_file(support_file(filename))
def get_simple_environment():
return get_environment("simple.yml")
def get_valid_keys_environment()... | FakeStream |
python | pypa__setuptools | setuptools/_vendor/wheel/vendored/packaging/utils.py | {
"start": 685,
"end": 5268
} | class ____(ValueError):
"""
An invalid sdist filename was found, users should refer to the packaging user guide.
"""
# Core metadata spec for `Name`
_validate_regex = re.compile(
r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE
)
_canonicalize_regex = re.compile(r"[-_.]+")
_normalized_regex... | InvalidSdistFilename |
python | MongoEngine__mongoengine | tests/fields/test_dict_field.py | {
"start": 255,
"end": 13455
} | class ____(MongoDBTestCase):
def test_storage(self):
class BlogPost(Document):
info = DictField()
BlogPost.drop_collection()
info = {"testkey": "testvalue"}
post = BlogPost(info=info).save()
assert get_as_pymongo(post) == {"_id": post.id, "info": info}
def ... | TestDictField |
python | huggingface__transformers | src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py | {
"start": 12942,
"end": 14966
} | class ____(ASTPreTrainedModel):
def __init__(self, config: ASTConfig) -> None:
super().__init__(config)
self.config = config
self.embeddings = ASTEmbeddings(config)
self.encoder = ASTEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps... | ASTModel |
python | walkccc__LeetCode | solutions/137. Single Number II/137-2.py | {
"start": 0,
"end": 187
} | class ____:
def singleNumber(self, nums: list[int]) -> int:
ones = 0
twos = 0
for num in nums:
ones ^= (num & ~twos)
twos ^= (num & ~ones)
return ones
| Solution |
python | PyCQA__pylint | tests/functional/u/unsupported/unsupported_assignment_operation.py | {
"start": 645,
"end": 1763
} | class ____:
def __setitem__(self, key, value):
return key + value
NonSubscriptable()[0] = 24 # [unsupported-assignment-operation]
NonSubscriptable[0] = 24 # [unsupported-assignment-operation]
Subscriptable()[0] = 24
Subscriptable[0] = 24 # [unsupported-assignment-operation]
# generators are not subscript... | Subscriptable |
python | ijl__orjson | test/test_enum.py | {
"start": 157,
"end": 202
} | class ____(int, enum.Enum):
ONE = 1
| IntEnum |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.