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 | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 68512,
"end": 79019
} | class ____(Response):
"""
Response of projects.get_all endpoint.
:param projects: Projects list
:type projects: Sequence[ProjectsGetAllResponseSingle]
:param scroll_id: Scroll ID that can be used with the next calls to get_all_ex
to retrieve more data
:type scroll_id: str
"""
_... | GetAllResponse |
python | cython__cython | tests/run/ext_auto_richcmp.py | {
"start": 7951,
"end": 9512
} | class ____(X):
"""
>>> a = ClassLtGt(1)
>>> b = ClassLtGt(2)
>>> c = ClassLtGt(1)
>>> a < b
True
>>> b > a
True
>>> b < a
False
>>> a > b
False
>>> a < c
False
>>> c > a
False
>>> c < a
False
>>> a > c
False
>>> b < c
False
>... | ClassLtGt |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/dagster_run.py | {
"start": 4184,
"end": 4498
} | class ____(IHaveNew):
run_id: str
steps_succeeded: int
steps_failed: int
materializations: int
expectations: int
enqueued_time: Optional[float]
launch_time: Optional[float]
start_time: Optional[float]
end_time: Optional[float]
@whitelist_for_serdes
@record
| DagsterRunStatsSnapshot |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchaudio_models.py | {
"start": 20634,
"end": 25344
} | class ____(torch.nn.Module):
def __init__(self, dropout=0.0):
r"""Processes a projected query and key-value pair to apply
scaled dot product attention.
Args:
dropout (float): probability of dropping an attention weight.
Examples::
>>> SDP = torchtext.models.Sc... | ScaledDotProduct |
python | pytorch__pytorch | test/fx/test_z3_gradual_types.py | {
"start": 2553,
"end": 39519
} | class ____(unittest.TestCase):
def test_eq_dim(self):
"""
test dimensions and equalities
"""
class BasicBlock(torch.nn.Module):
def forward(self, x: TensorType([32, 4, 4])):
eq = x.dim() == 3
return eq
ast_rewriter = RewritingTrac... | HFOperations |
python | numba__numba | numba/tests/test_dyn_array.py | {
"start": 38092,
"end": 39046
} | class ____(BaseTest):
def test_linspace_2(self):
def pyfunc(n, m):
return np.linspace(n, m)
self.check_outputs(pyfunc,
[(0, 4), (1, 100), (-3.5, 2.5), (-3j, 2+3j),
(2, 1), (1+0.5j, 1.5j)])
def test_linspace_3(self):
def... | TestLinspace |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callable1.py | {
"start": 149,
"end": 874
} | class ____:
pass
Callable2 = Callable[[A], None]
def func1(a: Callable1):
a(A())
def func2(a: Callable2):
a(A())
Callable3 = Callable[..., int]
def func3(a: Callable3) -> int:
return a(1, 2, 3) + a() + a("hello") + a([])
# This should generate an error (... not allowed in param list).
Callab... | A |
python | falconry__falcon | tests/test_uri_templates.py | {
"start": 1152,
"end": 1391
} | class ____:
def __init__(self):
self.id = None
self.name = None
self.called = False
def on_get(self, req, resp, id, name):
self.id = id
self.name = name
self.called = True
| NameResource |
python | allegroai__clearml | clearml/storage/manager.py | {
"start": 537,
"end": 25821
} | class ____(object):
"""
StorageManager is helper interface for downloading & uploading files to supported remote storage
Support remote servers: http(s)/S3/GS/Azure/File-System-Folder
Cache is enabled by default for all downloaded remote urls/files
"""
_file_upload_retries = deferred_config("net... | StorageManager |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypedDict1.py | {
"start": 230,
"end": 3280
} | class ____(TypedDict, total=False):
a: int
d: str
def f1(p: TD1 | TD2):
if "b" in p:
# This should technically be TD1 | TD2, but the
# current narrowing logic implements a not-entirely-safe
# narrowing behavior. We can fix this once PEP 728
# is accepted.
reveal_typ... | TD3 |
python | mlflow__mlflow | mlflow/genai/scorers/builtin_scorers.py | {
"start": 67942,
"end": 68265
} | class ____(MlflowException):
def __init__(self, scorer: str, missing_columns: set[str]):
self.scorer = scorer
self.missing_columns = list(missing_columns)
super().__init__(
f"The following columns are required for the scorer {scorer}: {missing_columns}"
)
| MissingColumnsException |
python | plotly__plotly.py | plotly/graph_objs/choropleth/colorbar/_title.py | {
"start": 233,
"end": 3992
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choropleth.colorbar"
_path_str = "choropleth.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
t... | Title |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 12943,
"end": 15370
} | class ____(nn.Module):
def __init__(self, config: DPTConfig):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size {config.hidden_size} is not a multiple of the number of ... | DPTSelfAttention |
python | crytic__slither | slither/slithir/operations/return_operation.py | {
"start": 330,
"end": 1885
} | class ____(Operation):
"""
Return
Only present as last operation in RETURN node
"""
def __init__(
self, values: Optional[Union[RVALUE, TupleVariable, Function, List[RVALUE]]]
) -> None:
# Note: Can return None
# ex: return call()
# where call() dont return
... | Return |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 34733,
"end": 36943
} | class ____(OwlViTPreTrainedModel):
config: OwlViTTextConfig
input_modalities = ("text",)
def __init__(self, config: OwlViTTextConfig):
super().__init__(config)
self.text_model = OwlViTTextTransformer(config)
# Initialize weights and apply final processing
self.post_init()
... | OwlViTTextModel |
python | getsentry__sentry | tests/sentry/middleware/test_subdomain.py | {
"start": 3401,
"end": 4182
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.middleware = settings.MIDDLEWARE
def test_simple(self) -> None:
self.create_organization(name="albertos-apples")
response = self.client.get(
reverse("test-endpoint"),
HTTP_HOST="alber... | End2EndTest |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 46210,
"end": 47007
} | class ____(CythonCommand):
"""
Set a Cython variable to a certain value
cy set my_cython_c_variable = 10
cy set my_cython_py_variable = $cy_eval("{'doner': 'kebab'}")
This is equivalent to
set $cy_value("my_cython_variable") = 10
"""
name = 'cy set'
command_class = gd... | CySet |
python | astropy__astropy | astropy/modeling/parameters.py | {
"start": 581,
"end": 695
} | class ____(Exception):
"""Generic exception class for all exceptions pertaining to Parameters."""
| ParameterError |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/eks.py | {
"start": 1981,
"end": 3633
} | class ____(Enum):
"""Contains the possible State values of an EKS Managed Nodegroup."""
CREATING = "CREATING"
ACTIVE = "ACTIVE"
UPDATING = "UPDATING"
DELETING = "DELETING"
CREATE_FAILED = "CREATE_FAILED"
DELETE_FAILED = "DELETE_FAILED"
DEGRADED = "DEGRADED"
NONEXISTENT = "NONEXISTEN... | NodegroupStates |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 16301,
"end": 16563
} | class ____(graphene.Union):
class Meta:
types = (
GrapheneFailedToMaterializeEvent,
GrapheneMaterializationEvent,
GrapheneObservationEvent,
)
name = "AssetResultEventType"
| GrapheneAssetResultEventType |
python | django__django | django/test/testcases.py | {
"start": 50395,
"end": 56291
} | class ____(TransactionTestCase):
"""
Similar to TransactionTestCase, but use `transaction.atomic()` to achieve
test isolation.
In most situations, TestCase should be preferred to TransactionTestCase as
it allows faster execution. However, there are some situations where using
TransactionTestCas... | TestCase |
python | davidhalter__jedi | jedi/inference/gradual/typing.py | {
"start": 10166,
"end": 10883
} | class ____(BaseTypingInstance):
def py__call__(self, arguments):
"""
def x() -> Callable[[Callable[..., _T]], _T]: ...
"""
# The 0th index are the arguments.
try:
param_values = self._generics_manager[0]
result_values = self._generics_manager[1]
... | Callable |
python | pytorch__pytorch | test/functorch/test_eager_transforms.py | {
"start": 174712,
"end": 176894
} | class ____(TestCase):
# torch.compile is not supported on Windows CUDA.
# Triton only supports GPU with SM70 or later.
@expectedFailureIf((IS_WINDOWS and TEST_CUDA) or (TEST_CUDA and not SM70OrLater))
@unittest.skipIf(
TEST_CUDA_MEM_LEAK_CHECK,
"Leaking memory, see https://github.com/pyt... | TestCompileTransforms |
python | PrefectHQ__prefect | tests/server/orchestration/test_task_concurrency_v2_integration.py | {
"start": 13648,
"end": 28040
} | class ____:
"""Test ReleaseTaskConcurrencySlots with V2 Global Concurrency Limits.
Note: Some of these tests may fail due to a bug in the current implementation
where holder.id (task run ID) is used as lease_id in the release logic.
The correct behavior would require finding the lease_id associated wit... | TestReleaseTaskConcurrencySlotsV2Integration |
python | getsentry__sentry | tests/sentry/release_health/release_monitor/test_metrics.py | {
"start": 349,
"end": 516
} | class ____(
BaseFetchProjectsWithRecentSessionsTest, BaseMetricsTestCase
):
backend_class = MetricReleaseMonitorBackend
| MetricFetchProjectsWithRecentSessionsTest |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 2893,
"end": 2966
} | class ____(Greeter, Overridden, enum.Enum):
"""docstring"""
| _ParentEnum |
python | kamyu104__LeetCode-Solutions | Python/minimum-stability-factor-of-array.py | {
"start": 102,
"end": 2116
} | class ____(object):
def minStable(self, nums, maxC):
"""
:type nums: List[int]
:type maxC: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def binary_search_right(left, right, check):
whil... | Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/constraints.py | {
"start": 7620,
"end": 11444
} | class ____(Constraint):
"""Constrains `Conv2D` kernel weights to be the same for each radius.
Also available via the shortcut function
`tf.keras.constraints.radial_constraint`.
For example, the desired output for the following 4-by-4 kernel:
```
kernel = [[v_00, v_01, v_02, v_03],
[v_... | RadialConstraint |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar23.py | {
"start": 315,
"end": 1915
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar23.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | jupyterlab__jupyterlab | jupyterlab/commands.py | {
"start": 10370,
"end": 19708
} | class ____(HasTraits):
"""Options object for build system"""
def __init__(self, logger=None, core_config=None, **kwargs):
if core_config is not None:
kwargs["core_config"] = core_config
if logger is not None:
kwargs["logger"] = logger
# use the default if app_di... | AppOptions |
python | plotly__plotly.py | plotly/graph_objs/layout/geo/_lonaxis.py | {
"start": 235,
"end": 7311
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.geo"
_path_str = "layout.geo.lonaxis"
_valid_props = {
"dtick",
"gridcolor",
"griddash",
"gridwidth",
"range",
"showgrid",
"tick0",
}
@property
def dtick(self):
"""
... | Lonaxis |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/physical_operator.py | {
"start": 32399,
"end": 34310
} | class ____(abc.ABC):
@abc.abstractmethod
def extra_resource_usage(self: PhysicalOperator) -> ExecutionResources:
"""Returns resources used by this operator beyond standard accounting."""
...
def estimate_total_num_of_blocks(
num_tasks_submitted: int,
upstream_op_num_outputs: int,
m... | ReportsExtraResourceUsage |
python | pytorch__pytorch | torch/distributed/fsdp/api.py | {
"start": 5102,
"end": 11746
} | class ____:
"""
This configures FSDP-native mixed precision training.
Attributes:
param_dtype (Optional[torch.dtype]): This specifies the dtype for model
parameters during forward and backward and thus the dtype for
forward and backward computation. Outside forward and backw... | MixedPrecision |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_vertex_ai.py | {
"start": 11624,
"end": 14145
} | class ____:
def setup_method(self):
self.trigger = CreateBatchPredictionJobTrigger(
conn_id=TEST_CONN_ID,
project_id=TEST_PROJECT_ID,
location=TEST_LOCATION,
job_id=TEST_HPT_JOB_ID,
poll_interval=TEST_POLL_INTERVAL,
impersonation_chain=... | TestCreateBatchPredictionJobTrigger |
python | facelessuser__pymdown-extensions | pymdownx/superfences.py | {
"start": 2602,
"end": 6057
} | class ____:
"""
Stash code for later retrieval.
Store original fenced code here in case we were
too greedy and need to restore in an indented code
block.
"""
def __init__(self):
"""Initialize."""
self.stash = {}
def __len__(self): # pragma: no cover
"""Length... | CodeStash |
python | keras-team__keras | keras/src/layers/normalization/group_normalization.py | {
"start": 348,
"end": 9367
} | class ____(Layer):
"""Group normalization layer.
Group Normalization divides the channels into groups and computes
within each group the mean and variance for normalization.
Empirically, its accuracy is more stable than batch norm in a wide
range of small batch sizes, if learning rate is adjusted l... | GroupNormalization |
python | PyCQA__pylint | tests/functional/n/non_ascii_name/non_ascii_name_staticmethod.py | {
"start": 48,
"end": 301
} | class ____:
"""Class Docstring"""
def public(self):
"""Say it load"""
@staticmethod
def umlaut_ä(): # [non-ascii-name]
"""Say ä"""
return "ä"
# Usage should not raise a second error
OkayClass.umlaut_ä()
| OkayClass |
python | walkccc__LeetCode | solutions/2564. Substring XOR Queries/2564.py | {
"start": 0,
"end": 748
} | class ____:
def substringXorQueries(self, s: str, queries: list[list[int]]) -> list[list[int]]:
MAX_BIT = 30
# {val: [left, right]} := s[left..right]'s decimal value = val
valToLeftAndRight = collections.defaultdict(lambda: [-1, -1])
for left, c in enumerate(s):
val = 0
if c == '0':
... | Solution |
python | encode__django-rest-framework | rest_framework/generics.py | {
"start": 6678,
"end": 6926
} | class ____(mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for creating a model instance.
"""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
| CreateAPIView |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 3836,
"end": 4004
} | class ____(AttributeError, MismatchedABI):
"""
Raised when an attempt is made to access a function
that does not exist in the ABI.
"""
| ABIFunctionNotFound |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 195964,
"end": 196658
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("avatar_url", "login", "resource_path", "url")
avatar_url = sgqlc.types.Field(
sgqlc.types.non_null(URI),
graphql_name="avatarUrl",
args=sgqlc.types.A... | Actor |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_meta.py | {
"start": 4035,
"end": 14777
} | class ____(FSDPTest):
@property
def world_size(self):
return 2
@property
def process_group(self):
return dist.distributed_c10d._get_default_group()
def _compare_fsdp(self, fsdp1, fsdp2):
with FSDP.summon_full_params(fsdp1):
with FSDP.summon_full_params(fsdp2):
... | TestFSDPWithMetaDevice |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_user_stats.py | {
"start": 233,
"end": 2233
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user()
self.org = self.create_organization(owner=None)
self.team = self.create_team(organization=self.org)
self.project = self.create_project(organization=self.org, teams=[self.team])
... | ProjectUserDetailsTest |
python | ansible__ansible | test/integration/targets/ansible-test-container/runme.py | {
"start": 35997,
"end": 38376
} | class ____(Bootstrapper):
"""Bootstrapper for dnf based systems."""
@classmethod
def install_podman(cls) -> bool:
"""Return True if podman will be installed."""
return True
@classmethod
def install_docker(cls) -> bool:
"""Return True if docker will be installed."""
... | DnfBootstrapper |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py | {
"start": 1312,
"end": 10207
} | class ____(EncodecFeatureExtractor):
r"""
Constructs an KyutaiSpeechToText feature extractor.
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
most of the main methods. Users should refer to this superclass for more information regardin... | KyutaiSpeechToTextFeatureExtractor |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/httptester.py | {
"start": 1925,
"end": 2513
} | class ____(CloudEnvironment):
"""HTTP Tester environment plugin. Updates integration test environment after delegation."""
def get_environment_config(self) -> CloudEnvironmentConfig:
"""Return environment configuration for use in the test environment after delegation."""
return CloudEnvironment... | HttptesterEnvironment |
python | keon__algorithms | tests/test_backtrack.py | {
"start": 9276,
"end": 10041
} | class ____(unittest.TestCase):
def test_permute_unique(self):
nums1 = [1, 1, 2]
answer1 = [[2, 1, 1], [1, 2, 1], [1, 1, 2]]
self.assertEqual(sorted(permute_unique(nums1)), sorted(answer1))
nums2 = [1, 2, 1, 3]
answer2 = [[3, 1, 2, 1], [1, 3, 2, 1], [1, 2, 3, 1], [1, 2, 1, 3... | TestPermuteUnique |
python | ray-project__ray | python/ray/serve/_private/benchmarks/serialization/common.py | {
"start": 605,
"end": 802
} | class ____:
text: Optional[str] = None
floats: Optional[List[float]] = None
ints: Optional[List[int]] = None
ts: Optional[float] = None
reason: Optional[str] = None
| PayloadDataclass |
python | gevent__gevent | src/gevent/tests/test__order.py | {
"start": 742,
"end": 1125
} | class ____(greentest.TestCase):
def test(self):
lst = []
gevent.spawn(sleep0, lst, '1')
gevent.spawn(sleep0, lst, '2')
gevent.wait()
self.assertEqual(' '.join(lst), '1A 2A 1B 2B')
def sleep0(lst, param):
lst.append(param + 'A')
gevent.sleep(0)
lst.append(param ... | TestSleep0 |
python | openai__openai-python | src/openai/types/realtime/audio_transcription_param.py | {
"start": 213,
"end": 1275
} | class ____(TypedDict, total=False):
language: str
"""The language of the input audio.
Supplying the input language in
[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)
format will improve accuracy and latency.
"""
model: Literal["whisper-1", "gpt-4o-mini-transc... | AudioTranscriptionParam |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 7743,
"end": 8565
} | class ____:
params = [None, "US/Eastern", "UTC", dateutil.tz.tzutc()]
param_names = "tz"
def setup(self, tz):
N = 100000
self.series = Series(date_range(start="1/1/2000", periods=N, freq="min", tz=tz))
def time_dt_accessor(self, tz):
self.series.dt
def time_dt_accessor_nor... | DatetimeAccessor |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 3690,
"end": 3798
} | class ____(GitHubEnterpriseWebhook, PullRequestEventWebhook):
pass
| GitHubEnterprisePullRequestEventWebhook |
python | conda__conda | tests/plugins/test_manager.py | {
"start": 1442,
"end": 9479
} | class ____:
@plugins.hookimpl
def conda_virtual_packages(*args) -> Iterator[plugins.CondaVirtualPackage]:
yield DummyVirtualPackage
def test_load_without_plugins(plugin_manager: CondaPluginManager):
assert plugin_manager.load_plugins() == 0
def test_load_two_plugins_one_impls(plugin_manager: Con... | DummyVirtualPackagePlugin |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/time.py | {
"start": 3974,
"end": 4608
} | class ____(DTypeConfig_V2[str, None]):
"""
A wrapper around the JSON representation of the ``TimeDelta64`` data type in Zarr V2.
The ``name`` field of this class contains the value that would appear under the
``dtype`` field in Zarr V2 array metadata.
References
----------
The structure of... | TimeDelta64JSON_V2 |
python | jina-ai__jina | tests/integration/hot_reload/exec2/my_executor2.py | {
"start": 73,
"end": 295
} | class ____(Executor):
def __init__(self, **kwargs):
super().__init__(**kwargs)
@requests()
def foo(self, docs, **kwargs):
for doc in docs:
doc.text = get_doc_value()
| MyExecutorToReload2 |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 33275,
"end": 34702
} | class ____(Operator):
"""Operator for torch.nn.functional.elu (Exponential Linear Unit)."""
def __init__(self):
super().__init__("torch.nn.functional.elu")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.nn.functional.elu"
... | ELUOperator |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/resource_tests/pythonic_resources/test_type_signatures.py | {
"start": 3041,
"end": 4221
} | class ____(ConfigurableResource):
a_string: ResourceDependency[str]
reveal_type(StringDependentResource.__init__)
my_str_resource = StringDependentResource(a_string="foo")
reveal_type(my_str_resource.a_string)
"""
)
pyright_out = get_pyright_reveal_type_output(filename)
mypy_out = get... | StringDependentResource |
python | pennersr__django-allauth | allauth/headless/socialaccount/inputs.py | {
"start": 646,
"end": 1503
} | class ____(inputs.Input):
provider = inputs.CharField()
account = inputs.CharField()
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
uid = cleaned_data.get("account")
... | DeleteProviderAccountInput |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format26.py | {
"start": 315,
"end": 1642
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format26.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/2489. Number of Substrings With Fixed Ratio/2489.py | {
"start": 0,
"end": 728
} | class ____:
def fixedRatio(self, s: str, num1: int, num2: int) -> int:
# Let x := the number of 0s and y := the number of 1s in the subarray.
# We want x : y = num1 : num2, so our goal is to find number of subarrays
# with x * num2 - y * num1 = 0. To achieve this, we can use a prefix count
# map to re... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/extra_links.py | {
"start": 937,
"end": 1119
} | class ____(BaseModel):
"""Extra Links Response."""
extra_links: dict[str, str | None]
total_entries: Annotated[int, Field(title="Total Entries")]
| ExtraLinkCollectionResponse |
python | pytorch__pytorch | benchmarks/dynamo/microbenchmarks/operator_inp_utils.py | {
"start": 7058,
"end": 10693
} | class ____:
def __init__(self, json_file_path):
self.operator_db = defaultdict(Counter)
with open(json_file_path) as f:
lines = f.readlines()
i = 0
while i < len(lines):
op_line = lines[i].strip("\n")
assert "Operator: " in op_line, op_line
... | OperatorInputsLoader |
python | google__jax | tests/pallas/tpu_pallas_random_test.py | {
"start": 1259,
"end": 8891
} | class ____(jtu.JaxTestCase):
def setUp(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Need TPU devices")
super().setUp()
@parameterized.parameters(True, False)
@jax.legacy_prng_key('allow')
def test_to_pallas_key_under_vmap(self, use_legacy_key: bool):
if use_legacy_key:
... | PRNGTest |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py | {
"start": 20792,
"end": 23943
} | class ____(nn.Module):
def __init__(self, config: Sam3TrackerVideoMaskDecoderConfig, skip_first_layer_pe: bool = False):
"""
A transformer block with four layers:
(1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
sparse ... | Sam3TrackerVideoTwoWayAttentionBlock |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/services.py | {
"start": 1773,
"end": 11815
} | class ____(abc.ABC, Generic[T]):
_instances: dict[int, Self] = {}
_instance_lock = threading.Lock()
def __init__(self, *args: Hashable) -> None:
self._queue: queue.Queue[Optional[T]] = queue.Queue()
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._done_event: Optional[as... | _QueueServiceBase |
python | PrefectHQ__prefect | src/prefect/settings/models/experiments.py | {
"start": 1747,
"end": 2369
} | class ____(PrefectBaseSettings):
"""
Settings for configuring experimental features
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(("experiments",))
warn: bool = Field(
default=True,
description="If `True`, warn on usage of experimental features.",
v... | ExperimentsSettings |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/services/public/test_task_instances.py | {
"start": 1363,
"end": 4106
} | class ____(TestTaskInstanceEndpoint):
"""Tests for the categorize_task_instances method in BulkTaskInstanceService."""
def setup_method(self):
self.clear_db()
def teardown_method(self):
self.clear_db()
class MockUser:
def get_id(self) -> str:
return "test_user"
... | TestCategorizeTaskInstances |
python | pytorch__pytorch | test/mobile/test_quantize_fx_lite_script_module.py | {
"start": 472,
"end": 3121
} | class ____(QuantizationLiteTestCase):
# Tests from:
# ./caffe2/test/quantization/fx/test_quantize_fx.py
def test_embedding(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.emb = torch.nn.Embedding(num_embeddings=10, emb... | TestLiteFuseFx |
python | pytransitions__transitions | tests/test_nesting.py | {
"start": 910,
"end": 1082
} | class ____(object):
pass
test_states = ['A', 'B',
{'name': 'C', 'children': ['1', '2', {'name': '3', 'children': ['a', 'b', 'c']}]}, 'D', 'E', 'F']
| Dummy |
python | great-expectations__great_expectations | great_expectations/data_context/types/resource_identifiers.py | {
"start": 11335,
"end": 13084
} | class ____(DataContextKey):
def __init__(
self,
resource_type: GXCloudRESTResource,
id: str | None = None,
resource_name: str | None = None,
) -> None:
super().__init__()
self._resource_type = resource_type
self._id = id
self._resource_name = reso... | GXCloudIdentifier |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_new_high_priority_issue_handler.py | {
"start": 452,
"end": 2762
} | class ____(ConditionTestCase):
condition = Condition.NEW_HIGH_PRIORITY_ISSUE
payload = {"id": NewHighPriorityIssueCondition.id}
def setUp(self) -> None:
super().setUp()
self.event_data = WorkflowEventData(
event=self.group_event,
group=self.group_event.group,
... | TestNewHighPriorityIssueCondition |
python | davidhalter__jedi | test/completion/pep0484_comments.py | {
"start": 285,
"end": 544
} | class ____: pass
def test(a, b):
a = a # type: BB
c = a # type: str
d = a
# type: str
e = a # type: str # Should ignore long whitespace
#? BB()
a
#? str()
c
#? BB()
d
#? str()
e
| BB |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/panels/timer.py | {
"start": 326,
"end": 4680
} | class ____(Panel):
"""
Panel that displays the time a response took in milliseconds.
"""
is_async = True
def nav_subtitle(self):
stats = self.get_stats()
if stats.get("utime"):
utime = stats.get("utime")
stime = stats.get("stime")
return _("CPU: ... | TimerPanel |
python | pytest-dev__pytest | src/_pytest/pytester.py | {
"start": 53348,
"end": 53993
} | class ____:
def __init__(self) -> None:
self.stringio = StringIO()
""":class:`python:io.StringIO()` instance used for input."""
def assert_contains_lines(self, lines2: Sequence[str]) -> None:
"""Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.
Lines ... | LineComp |
python | ray-project__ray | rllib/models/torch/attention_net.py | {
"start": 1620,
"end": 10401
} | class ____(RecurrentNetwork, nn.Module):
"""A GTrXL net Model described in [2].
This is still in an experimental phase.
Can be used as a drop-in replacement for LSTMs in PPO and IMPALA.
To use this network as a replacement for an RNN, configure your Algorithm
as follows:
Examples:
>> ... | GTrXLNet |
python | python-openxml__python-docx | src/docx/enum/dml.py | {
"start": 89,
"end": 779
} | class ____(BaseEnum):
"""Specifies the color specification scheme.
Example::
from docx.enum.dml import MSO_COLOR_TYPE
assert font.color.type == MSO_COLOR_TYPE.SCHEME
MS API name: `MsoColorType`
http://msdn.microsoft.com/en-us/library/office/ff864912(v=office.15).aspx
"""
RG... | MSO_COLOR_TYPE |
python | TheAlgorithms__Python | graphs/edmonds_karp_multiple_source_and_sink.py | {
"start": 2939,
"end": 6592
} | class ____(MaximumFlowAlgorithmExecutor):
def __init__(self, flow_network):
super().__init__(flow_network)
self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)]
self.heights = [0] * self.verticies_count
self.excesses = [0] * self.verticies_count
def ... | PushRelabelExecutor |
python | tensorflow__tensorflow | tensorflow/python/util/decorator_utils.py | {
"start": 4197,
"end": 4560
} | class ____(object): # pylint: disable=invalid-name
"""Class property decorator.
Example usage:
class MyClass(object):
@classproperty
def value(cls):
return '123'
> print MyClass.value
123
"""
def __init__(self, func):
self._func = func
def __get__(self, owner_self, owner_cls):
... | classproperty |
python | arrow-py__arrow | tests/test_arrow.py | {
"start": 89478,
"end": 105153
} | class ____:
def test_now(self, locale_list_no_weeks: List[str]):
for lang in locale_list_no_weeks:
arw = arrow.Arrow(2000, 6, 18, 5, 55, 0)
second_ago = arw.shift(seconds=-1)
second_future = arw.shift(seconds=1)
second_ago_string = second_ago.humanize(
... | TestArrowDehumanize |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event.py | {
"start": 2734,
"end": 3354
} | class ____(BaseModel):
group_id: Optional[str] = None
"""
The group id to attach to this trace to enable filtering and grouping in the
traces dashboard.
"""
metadata: Optional[object] = None
"""
The arbitrary metadata to attach to this trace to enable filtering in the traces
dashboa... | SessionTracingTracingConfiguration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-instagram/components.py | {
"start": 12949,
"end": 14251
} | class ____(SubstreamPartitionRouter):
"""
The way the Python user_insights stream was a substream of the Api/Accounts parent stream, but it only incorporated
the business_account_id as the partition field. However, the actual parent stream slice is an account object made
up of a business_account_id and ... | UserInsightsSubstreamPartitionRouter |
python | huggingface__transformers | tests/models/markuplm/test_modeling_markuplm.py | {
"start": 12022,
"end": 13201
} | class ____(unittest.TestCase):
@cached_property
def default_processor(self):
# TODO use from_pretrained here
feature_extractor = MarkupLMFeatureExtractor()
tokenizer = MarkupLMTokenizer.from_pretrained("microsoft/markuplm-base")
return MarkupLMProcessor(feature_extractor, tokeni... | MarkupLMModelIntegrationTest |
python | great-expectations__great_expectations | tests/datasource/fluent/test_invalid_datasource.py | {
"start": 10356,
"end": 12173
} | class ____:
def test_connection_raises_informative_error(
self, invalid_datasource_factory: InvalidDSFactory
):
random_ds_type = random.choice([t for t in DataSourceManager.type_lookup.type_names()])
print(f"{random_ds_type=}")
invalid_datasource: InvalidDatasource = invalid_data... | TestInvalidDataAsset |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/ghostwriter/test_ghostwriter.py | {
"start": 4237,
"end": 7729
} | class ____:
foo: str = attr.ib()
def takes_attrs_class(x: Foo) -> None:
pass
@varied_excepts
@pytest.mark.parametrize(
"func",
[
re.compile,
json.loads,
json.dump,
timsort,
ast.literal_eval,
non_type_annotation,
annotated_any,
space_in_... | Foo |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/completion/base.py | {
"start": 12091,
"end": 13384
} | class ____(Completer):
"""
Wrapper around any other completer that will enable/disable the completions
depending on whether the received condition is satisfied.
:param completer: :class:`.Completer` instance.
:param filter: :class:`.Filter` instance.
"""
def __init__(self, completer: Compl... | ConditionalCompleter |
python | google__pytype | pytype/overlays/functools_overlay.py | {
"start": 534,
"end": 999
} | class ____(overlay.Overlay):
"""An overlay for the functools std lib module."""
def __init__(self, ctx):
member_map = {
"cached_property": overlay.add_name(
"cached_property", special_builtins.Property.make_alias
),
}
if ctx.options.use_functools_partial_overlay:
membe... | FunctoolsOverlay |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/transport/tcp/consumer.py | {
"start": 731,
"end": 882
} | class ____(IncomingMessageThread):
"""TCP socket consumer."""
def read_num_bytes(self, n):
return self.fd.recv(n)
| TCPIncomingMessageThread |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 14937,
"end": 32906
} | class ____:
def test_pearsonr_result_attributes(self):
res = stats.pearsonr(X, X)
attributes = ('correlation', 'pvalue')
check_named_results(res, attributes)
assert_equal(res.correlation, res.statistic)
def test_r_almost_exactly_pos1(self, xp):
a = xp.arange(3.0)
... | TestPearsonr |
python | django__django | django/db/models/lookups.py | {
"start": 26767,
"end": 26887
} | class ____(YearLookup, GreaterThanOrEqual):
def get_bound_params(self, start, finish):
return (start,)
| YearGte |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mirror_gnu/package.py | {
"start": 299,
"end": 578
} | class ____(AutotoolsPackage, GNUMirrorPackage):
"""Simple GNU package"""
homepage = "https://www.gnu.org/software/make/"
gnu_mirror_path = "make/make-4.2.1.tar.gz"
version("4.2.1", sha256="e40b8f018c1da64edd1cc9a6fce5fa63b2e707e404e20cad91fbae337c98a5b7")
| MirrorGnu |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 110974,
"end": 133335
} | class ____(DialectKWArgs, SchemaItem):
"""Defines a dependency between two columns.
``ForeignKey`` is specified as an argument to a :class:`_schema.Column`
object,
e.g.::
t = Table(
"remote_table",
metadata,
Column("remote_id", ForeignKey("main_table.id")),
... | ForeignKey |
python | getsentry__sentry | src/sentry/integrations/issue_alert_image_builder.py | {
"start": 1213,
"end": 7544
} | class ____:
def __init__(self, group: Group, provider: ExternalProviderEnum) -> None:
self.group = group
self.provider = provider
self.cache_key = f"chartcuterie-image:{self.group.id}"
self.tags = {
"provider": self.provider,
"issue_category": self.group.issue... | IssueAlertImageBuilder |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py | {
"start": 1039,
"end": 1176
} | class ____(CloudflareAIGatewayError):
"""Raised when AI Gateway authentication fails."""
pass
| CloudflareAIGatewayUnauthorizedError |
python | kamyu104__LeetCode-Solutions | Python/shortest-word-distance-ii.py | {
"start": 110,
"end": 910
} | class ____(object):
# initialize your data structure here.
# @param {string[]} words
def __init__(self, words):
self.wordIndex = collections.defaultdict(list)
for i in xrange(len(words)):
self.wordIndex[words[i]].append(i)
# @param {string} word1
# @param {string} word2
... | WordDistance |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/blobstore/gcs/main.py | {
"start": 969,
"end": 2492
} | class ____(webapp2.RequestHandler):
def get(self):
# Get the default Cloud Storage Bucket name and create a file name for
# the object in Cloud Storage.
bucket = app_identity.get_default_gcs_bucket_name()
# Cloud Storage file names are in the format /bucket/object.
filename ... | CreateAndReadFileHandler |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 28783,
"end": 30916
} | class ____(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = EfficientLoFTRConfig
base_model_prefix = "efficientloftr"
main_input_name = "pixel_values"
input_modalities = ("im... | EfficientLoFTRPreTrainedModel |
python | ansible__ansible | lib/ansible/executor/task_queue_manager.py | {
"start": 2560,
"end": 2755
} | class ____:
worker_id: int
prompt: str
private: bool = True
seconds: int = None
interrupt_input: t.Iterable[bytes] = None
complete_input: t.Iterable[bytes] = None
| PromptSend |
python | Textualize__textual | tests/test_message_pump.py | {
"start": 1071,
"end": 1833
} | class ____(Widget):
called_by = None
def key_x(self):
self.called_by = self.key_x
def _key_x(self):
self.called_by = self._key_x
def key_tab(self):
self.called_by = self.key_tab
def key_ctrl_i(self):
self.called_by = self.key_ctrl_i
async def test_dispatch_key_r... | DuplicateHandlersWidget |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 25448,
"end": 27058
} | class ____(test.Benchmark):
def _benchmarkAdjustHue(self, device, cpu_count):
image_shape = [299, 299, 3]
warmup_rounds = 100
benchmark_rounds = 1000
config = config_pb2.ConfigProto()
if cpu_count is not None:
config.inter_op_parallelism_threads = 1
config.intra_op_parallelism_threads... | AdjustHueBenchmark |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadb.py | {
"start": 1111,
"end": 2258
} | class ____(UUID[_UUID_RETURN]):
def __init__(self, as_uuid: bool = True, native_uuid: bool = True):
self.as_uuid = as_uuid
# the _MariaDBUUID internal type is only invoked for a Uuid() with
# native_uuid=True. for non-native uuid type, the plain Uuid
# returns itself due to the wo... | _MariaDBUUID |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.