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 | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 101129,
"end": 101999
} | class ____(TypedDict, total=False):
"""
:class:`altair.GeoJsonFeatureCollection` ``TypedDict`` wrapper.
Parameters
----------
features
type
Specifies the type of GeoJSON object.
bbox
Bounding box of the coordinate range of the object's Geometries, Features, or
Featu... | GeoJsonFeatureCollectionKwds |
python | django__django | django/test/utils.py | {
"start": 25483,
"end": 29537
} | class ____(TestContextDecorator):
def __init__(self, **kwargs):
self.ignore_kwargs = kwargs
if "message" in self.ignore_kwargs or "module" in self.ignore_kwargs:
self.filter_func = warnings.filterwarnings
else:
self.filter_func = warnings.simplefilter
super().... | ignore_warnings |
python | TheAlgorithms__Python | other/number_container_system.py | {
"start": 308,
"end": 6296
} | class ____:
def __init__(self) -> None:
# numbermap keys are the number and its values are lists of indexes sorted
# in ascending order
self.numbermap: dict[int, list[int]] = {}
# indexmap keys are an index and it's values are the number at that index
self.indexmap: dict[int,... | NumberContainer |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/tests/core/test_runner.py | {
"start": 43890,
"end": 48934
} | class ____:
"""Test asset creation functionality."""
def test_create_asset_from_node_creates_asset(self, mock_manifest_node):
"""Test that assets are created correctly from manifest nodes."""
runner = PrefectDbtRunner()
adapter_type = "snowflake"
with patch("prefect_dbt.core.ru... | TestPrefectDbtRunnerAssetCreation |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-linnworks/source_linnworks/streams.py | {
"start": 2909,
"end": 3756
} | class ____(HttpSubStream, StockLocations):
# https://apps.linnworks.net/Api/Method/Locations-GetLocation
# Response: StockLocation https://apps.linnworks.net/Api/Class/linnworks-spa-commondata-Locations-ClassBase-StockLocation
# Allows 150 calls per minute
primary_key = "StockLocationIntId"
def __i... | StockLocationDetails |
python | mitmproxy__pdoc | test/testdata/misc_py313.py | {
"start": 34,
"end": 136
} | class ____(dict):
pass
@deprecated("Do not use this anymore")
def deprecated_func():
pass
| MyDict |
python | ethereum__web3.py | web3/_utils/abi.py | {
"start": 9751,
"end": 18625
} | class ____(encoding.TextStringEncoder):
@classmethod
def validate_value(cls, value: Any) -> None:
if is_bytes(value):
try:
value = to_text(value)
except UnicodeDecodeError:
cls.invalidate_value(
value,
msg="n... | TextStringEncoder |
python | wandb__wandb | tests/system_tests/test_api/conftest.py | {
"start": 243,
"end": 867
} | class ____(http.server.SimpleHTTPRequestHandler):
"""HTTP handler that serves parquet files from memory."""
parquet_files: dict[str, bytes] = {}
def do_GET(self): # noqa: N802
path = self.path.lstrip("/")
if path in self.parquet_files:
content = self.parquet_files[path]
... | ParquetFileHandler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/queue.py | {
"start": 1287,
"end": 1381
} | class ____(Exception):
"Exception raised by Queue.put(block=0)/put_nowait()."
pass
| Full |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_date05.py | {
"start": 342,
"end": 1961
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_date05.xlsx")
self.ignore_elements = {"xl/charts/chart1.xml": ["<c:formatCode"]}
def test_create_file(self):
"""Test the cre... | TestCompareXLSXFiles |
python | langchain-ai__langchain | libs/langchain/langchain_classic/smith/evaluation/string_run_evaluator.py | {
"start": 8640,
"end": 10586
} | class ____(Serializable):
"""Map an example, or row in the dataset, to the inputs of an evaluation."""
reference_key: str | None = None
@property
def output_keys(self) -> list[str]:
"""The keys to extract from the run."""
return ["reference"]
def serialize_chat_messages(self, mess... | StringExampleMapper |
python | doocs__leetcode | solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/Solution3.py | {
"start": 0,
"end": 493
} | class ____:
def mctFromLeafValues(self, arr: List[int]) -> int:
n = len(arr)
f = [[0] * n for _ in range(n)]
g = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
g[i][i] = arr[i]
for j in range(i + 1, n):
g[i][j] = max(g[i][j - 1], ar... | Solution |
python | Lightning-AI__lightning | examples/pytorch/servable_module/production.py | {
"start": 2120,
"end": 2697
} | class ____:
height: Optional[int] = None
width: Optional[int] = None
extension: str = "JPEG"
mode: str = "RGB"
channel_first: bool = False
def deserialize(self, data: str) -> torch.Tensor:
encoded_with_padding = (data + "===").encode("UTF-8")
img = base64.b64decode(encoded_with_... | Image |
python | cherrypy__cherrypy | cherrypy/test/test_core.py | {
"start": 30247,
"end": 30898
} | class ____:
def test_bind_ephemeral_port(self):
"""
A server configured to bind to port 0 will bind to an ephemeral
port and indicate that port number on startup.
"""
cherrypy.config.reset()
bind_ephemeral_conf = {
'server.socket_port': 0,
}
... | TestBinding |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 101422,
"end": 103017
} | class ____:
"""Test fr_CA address provider methods"""
def test_province(self, faker, num_samples):
for _ in range(num_samples):
province = faker.province()
assert isinstance(province, str)
assert province in FrCaAddressProvider.provinces
def test_province_abbr(s... | TestFrCa |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/qcookiecutter.py | {
"start": 2720,
"end": 14021
} | class ____(QtWidgets.QWidget):
"""
QWidget to display cookiecutter.json options.
cookiecutter_settings: dict
A cookiecutter.json settings content.
pre_gen_code: str
The code of the pregeneration script.
"""
sig_validated = QtCore.Signal(int, str)
"""
This signal is emit... | CookiecutterWidget |
python | rushter__MLAlgorithms | mla/naive_bayes.py | {
"start": 119,
"end": 1899
} | class ____(BaseEstimator):
"""Gaussian Naive Bayes."""
# Binary problem.
n_classes = 2
def fit(self, X, y=None):
self._setup_input(X, y)
# Check target labels
assert list(np.unique(y)) == [0, 1]
# Mean and variance for each class and feature combination
self._m... | NaiveBayesClassifier |
python | django__django | django/template/library.py | {
"start": 10678,
"end": 11244
} | class ____(SimpleNode):
def __init__(self, nodelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nodelist = nodelist
def get_resolved_arguments(self, context):
resolved_args, resolved_kwargs = super().get_resolved_arguments(context)
# Restore the "content" argument... | SimpleBlockNode |
python | tensorflow__tensorflow | tensorflow/python/data/ops/iterator_ops.py | {
"start": 23463,
"end": 26806
} | class ____(
collections_abc.Iterator,
trackable.Trackable,
composite_tensor.CompositeTensor,
metaclass=abc.ABCMeta):
"""Represents an iterator of a `tf.data.Dataset`.
`tf.data.Iterator` is the primary mechanism for enumerating elements of a
`tf.data.Dataset`. It supports the Python Iterator proto... | IteratorBase |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 7823,
"end": 8827
} | class ____(AsyncHTTPTestCase):
def get_app(self):
wsgi_app = WSGIContainer(self.wsgi_app)
class Handler(RequestHandler):
def get(self, *args, **kwargs):
self.finish(self.reverse_url("tornado"))
return RuleRouter(
[
(
... | WSGIContainerTestCase |
python | pytorch__pytorch | torch/_subclasses/complex_tensor/_core.py | {
"start": 4692,
"end": 5074
} | class ____(Function):
@staticmethod
def forward(ctx: FunctionCtx, real: Tensor, imag: Tensor) -> ComplexTensor: # type: ignore[bad-override]
return ComplexTensor(real, imag)
@staticmethod
def backward(ctx: FunctionCtx, grad_output: ComplexTensor) -> tuple[Tensor, Tensor]: # type: ignore[bad-o... | Complex |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-reddit/llama_index/readers/reddit/base.py | {
"start": 226,
"end": 1924
} | class ____(BaseReader):
"""
Subreddit post and top-level comments reader for Reddit.
"""
def load_data(
self,
subreddits: List[str],
search_keys: List[str],
post_limit: Optional[int] = [10],
) -> List[Document]:
"""
Load text from relevant posts and t... | RedditReader |
python | django__django | tests/file_storage/tests.py | {
"start": 2246,
"end": 23501
} | class ____(SimpleTestCase):
storage_class = FileSystemStorage
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = self.storage_class(
location=self.temp_dir, base_url="/test_media_url/"
)
def test_empt... | FileStorageTests |
python | django__django | tests/serializers/models/multi_table.py | {
"start": 166,
"end": 401
} | class ____(models.Model):
parent_data = models.CharField(max_length=30, unique=True)
parent_m2m = models.ManyToManyField("self")
objects = ParentManager()
def natural_key(self):
return (self.parent_data,)
| Parent |
python | spack__spack | lib/spack/spack/installer.py | {
"start": 44127,
"end": 50535
} | class ____(Task):
"""Class for representing a build task for a package."""
process_handle: Optional["spack.build_environment.BuildProcess"] = None
started: bool = False
no_op: bool = False
tmpdir = None
backup_dir = None
def start(self):
"""Attempt to use the binary cache to instal... | BuildTask |
python | facebookresearch__faiss | faiss/gpu/test/test_cagra.py | {
"start": 3334,
"end": 5774
} | class ____(unittest.TestCase):
def do_interop(self, metric, numeric_type):
d = 64
k = 12
if numeric_type == faiss.Int8:
data_base_nt = np.random.randint(
-128, 128, size=(10000, d), dtype=np.int8)
data_query_nt = np.random.randint(
-12... | TestInterop |
python | pytorch__pytorch | torch/_numpy/_ndarray.py | {
"start": 763,
"end": 8071
} | class ____:
def __init__(self, flag_to_value: dict):
assert all(k in FLAGS for k in flag_to_value) # sanity check
self._flag_to_value = flag_to_value
def __getattr__(self, attr: str):
if attr.islower() and attr.upper() in FLAGS:
return self[attr.upper()]
else:
... | Flags |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 495282,
"end": 497576
} | class ____(ExprNode):
# Compile-time type of an expression, as a string.
#
# operand ExprNode
# literal UnicodeNode # internal
literal = None
type = py_object_type
subexprs = ['literal'] # 'operand' will be ignored after type analysis!
def analyse_types(self, env):
se... | TypeofNode |
python | PyCQA__pylint | tests/functional/n/not_async_context_manager.py | {
"start": 511,
"end": 583
} | class ____(Portocala):
def __aenter__(self):
pass
| UnknownBases |
python | ansible__ansible | test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py | {
"start": 72,
"end": 241
} | class ____(object):
""" Ansible core jinja2 tests """
def tests(self):
return {
# failure testing
'yolo': yolo,
}
| TestModule |
python | scipy__scipy | scipy/sparse/linalg/_interface.py | {
"start": 22747,
"end": 23621
} | class ____(LinearOperator):
def __init__(self, A, B):
if not isinstance(A, LinearOperator) or \
not isinstance(B, LinearOperator):
raise ValueError('both operands have to be a LinearOperator')
if A.shape != B.shape:
raise ValueError(f'cannot add {A} and {B}: s... | _SumLinearOperator |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/call_to_lambda_function_test.py | {
"start": 952,
"end": 1393
} | class ____(reference_test_base.TestCase):
def test_inline(self):
self.assertFunctionMatchesEager(inline_lambda, 1)
self.assertFunctionMatchesEager(inline_lambda, tf.constant(1))
def test_external(self):
self.assertFunctionMatchesEager(external_lambda, 1, lambda x: x == 0)
self.assertFunctionMatche... | ReferenceTest |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 1891,
"end": 3521
} | class ____(BaseModelOutputWithCrossAttentions):
r"""
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(bat... | ConditionalDetrDecoderOutput |
python | psf__black | tests/data/cases/dummy_implementations.py | {
"start": 380,
"end": 981
} | class ____(Protocol):
def foo(self, a: int) -> int:
...
def bar(self, b: str) -> str: ...
def baz(self, c: bytes) -> str:
...
def dummy_two():
...
@dummy
def dummy_three():
...
def dummy_four():
...
@overload
def b(arg: int) -> int: ...
@overload
def b(arg: str) -> str: ...... | Proto |
python | huggingface__transformers | src/transformers/models/llava_onevision/modular_llava_onevision.py | {
"start": 9307,
"end": 9386
} | class ____(LlavaNextVideoPreTrainedModel):
pass
| LlavaOnevisionPreTrainedModel |
python | getsentry__sentry | src/sentry/analytics/events/issueowners_assignment.py | {
"start": 79,
"end": 261
} | class ____(analytics.Event):
organization_id: int
project_id: int
group_id: int
updated_assignment: bool
analytics.register(IssueOwnersAssignment)
| IssueOwnersAssignment |
python | kamyu104__LeetCode-Solutions | Python/minimum-jumps-to-reach-end-via-prime-teleportation.py | {
"start": 544,
"end": 1673
} | class ____(object):
def minJumps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
adj = collections.defaultdict(list)
for i, x in enumerate(nums):
while x != 1:
p = SPF[x]
while x%p == 0:
x //= p
... | Solution |
python | scipy__scipy | scipy/stats/tests/test_continuous.py | {
"start": 78833,
"end": 82121
} | class ____:
@pytest.mark.fail_slow(20) # Moments require integration
def test_order_statistic(self):
rng = np.random.default_rng(7546349802439582)
X = Uniform(a=0, b=1)
n = 5
r = np.asarray([[1], [3], [5]])
Y = stats.order_statistic(X, n=n, r=r)
Y0 = stats.beta(r... | TestOrderStatistic |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_dms.py | {
"start": 2228,
"end": 6679
} | class ____:
TASK_DATA = {
"replication_task_id": "task_id",
"source_endpoint_arn": "source_endpoint",
"target_endpoint_arn": "target_endpoint",
"replication_instance_arn": "replication_arn",
"table_mappings": {
"rules": [
{
"rul... | TestDmsCreateTaskOperator |
python | huggingface__transformers | src/transformers/models/mbart50/tokenization_mbart50.py | {
"start": 1611,
"end": 14806
} | class ____(TokenizersBackend):
"""
Construct a MBart50 tokenizer (backed by HuggingFace's *tokenizers* library). Based on
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
This tokenizer inherits from [`TokenizersBackend`] which contains most of t... | MBart50Tokenizer |
python | openai__openai-python | src/openai/types/vector_stores/vector_store_file.py | {
"start": 304,
"end": 547
} | class ____(BaseModel):
code: Literal["server_error", "unsupported_file", "invalid_file"]
"""One of `server_error`, `unsupported_file`, or `invalid_file`."""
message: str
"""A human-readable description of the error."""
| LastError |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 1396,
"end": 1499
} | class ____(models.Model):
item = models.ForeignKey(Item, null=True, on_delete=models.CASCADE)
| SubItem |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 19962,
"end": 20541
} | class ____(AdminTestMixin, TestCase):
def test_selectable_fields_rendered_with_resource_index_attribute(self) -> None:
response = self._get_url_response(self.book_export_url)
form_resources = response.context["form"].resources
content = response.content.decode()
for index, resource i... | TestSelectableFieldsExportPage |
python | pytorch__pytorch | test/fx/test_matcher_utils.py | {
"start": 886,
"end": 10823
} | class ____(JitTestCase):
def test_subgraph_matcher_with_attributes(self):
class LargeModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self._weight = torch.nn.Parameter(torch.ones(3, 3))
self._bias = torch.nn.Parameter(torch.on... | TestMatcher |
python | pyparsing__pyparsing | examples/searchparser.py | {
"start": 2514,
"end": 6843
} | class ____:
def __init__(self):
self._methods = {
"and": self.evaluateAnd,
"or": self.evaluateOr,
"not": self.evaluateNot,
"parenthesis": self.evaluateParenthesis,
"quotes": self.evaluateQuotes,
"word": self.evaluateWord,
"w... | SearchQueryParser |
python | pytest-dev__pytest | testing/test_junitxml.py | {
"start": 35630,
"end": 60148
} | class ____:
@parametrize_families
def test_summing_simple(
self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str
) -> None:
pytester.makeconftest(
"""
import pytest
def pytest_collect_file(file_path, parent):
if file_path.... | TestNonPython |
python | cython__cython | Cython/Compiler/FlowControl.py | {
"start": 9801,
"end": 9971
} | class ____:
def __init__(self, next_block, loop_block):
self.next_block = next_block
self.loop_block = loop_block
self.exceptions = []
| LoopDescr |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 135289,
"end": 137726
} | class ____(Request):
"""
Remove a task from its queue.
Fails if task status is not queued.
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type stat... | DequeueRequest |
python | etianen__django-reversion | reversion/models.py | {
"start": 1669,
"end": 4652
} | class ____(models.Model):
"""A group of related serialized versions."""
date_created = models.DateTimeField(
db_index=True,
verbose_name=_("date created"),
help_text="The date and time this revision was created.",
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
... | Revision |
python | py-pdf__pypdf | pypdf/generic/_fit.py | {
"start": 78,
"end": 5515
} | class ____:
def __init__(
self, fit_type: str, fit_args: tuple[Union[None, float, Any], ...] = ()
) -> None:
from ._base import FloatObject, NameObject, NullObject, NumberObject # noqa: PLC0415
self.fit_type = NameObject(fit_type)
self.fit_args: list[Union[NullObject, FloatObje... | Fit |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/config_migrations.py | {
"start": 7521,
"end": 9305
} | class ____:
"""
Runtime config migrator that **removes** the deprecated
``action_report_time`` property.
The field was deprecated starting in version 3.5.0.
"""
migrate_key: str = "action_report_time"
@classmethod
def should_migrate(cls, config: Mapping[str, Any]) -> bool:
"""... | RemoveActionReportTimeMigration |
python | spyder-ide__spyder | spyder/utils/programs.py | {
"start": 1044,
"end": 41232
} | class ____(Exception):
pass
def get_temp_dir(suffix=None):
"""
Return temporary Spyder directory, checking previously that it exists.
"""
to_join = [tempfile.gettempdir()]
if os.name == 'nt':
to_join.append('spyder')
else:
username = encoding.to_unicode_from_fs(getuser())
... | ProgramError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/hybrid.py | {
"start": 44940,
"end": 47594
} | class ____(interfaces.InspectionAttrInfo, Generic[_P, _R]):
"""A decorator which allows definition of a Python object method with both
instance-level and class-level behavior.
"""
is_attribute = True
extension_type = HybridExtensionType.HYBRID_METHOD
def __init__(
self,
func: ... | hybrid_method |
python | bokeh__bokeh | src/bokeh/server/contexts.py | {
"start": 12613,
"end": 14591
} | class ____:
_arguments: dict[str, list[bytes]]
_cookies: dict[str, str]
_headers: dict[str, str | list[str]]
def __init__(
self,
request: HTTPServerRequest,
arguments: dict[str, bytes | list[bytes]] | None = None,
cookies: dict[str, str] | None = None,
headers: ... | _RequestProxy |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 11466,
"end": 11793
} | class ____(OverrideSwitchOnClassTestCase):
"""
Extend ``OverrideSwitchOnClassTestCase``
and make sure ``override_switch`` change still works.
"""
def test_child_undecorated_method_is_set_properly_for_switch(self):
self.assertFalse(waffle.switch_is_active('foo'))
| InheritanceOverrideSwitchOnClassTests |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 151971,
"end": 156122
} | class ____(TestCase):
"""
Tests chunksize handling in ParallelAccelerator.
"""
_numba_parallel_test_ = False
def setUp(self):
set_parallel_chunksize(0)
def tearDown(self):
set_parallel_chunksize(0)
def test_python_parallel_chunksize_basic(self):
# Test basic chunks... | TestParforChunksizing |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 21187,
"end": 21477
} | class ____(VOTableSpecWarning):
"""
If no version number is explicitly given in the VOTable file, the
parser assumes it is written to the VOTable 1.1 specification.
"""
message_template = "No version number specified in file. Assuming {}"
default_args = ("1.1",)
| W20 |
python | getsentry__sentry | src/sentry/interfaces/contexts.py | {
"start": 6178,
"end": 6318
} | class ____(ContextType):
type = "runtime"
context_to_tag_mapping = {"": "{runtime}", "name": "{name}"}
@contexttype
| RuntimeContextType |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py | {
"start": 681,
"end": 758
} | class ____:
"""GetNewArgsEx through the metaclass."""
| ThirdGoodGetNewArgsEx |
python | pytorch__pytorch | torch/_inductor/runtime/debug_utils.py | {
"start": 219,
"end": 4275
} | class ____:
"""
Tracks inductor runtime allocations and deallocations to compare against
expected behavior.
"""
def __init__(self) -> None:
self.tensor_tracker: dict[str, torch.storage.UntypedStorage] = (
weakref.WeakValueDictionary() # type: ignore[assignment]
)
... | BufferMemoryTracker |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_bigquery.py | {
"start": 26493,
"end": 30746
} | class ____:
def test_bigquery_value_check_op_trigger_serialization(self, value_check_trigger):
"""Asserts that the BigQueryValueCheckTrigger correctly serializes its arguments and classpath."""
classpath, kwargs = value_check_trigger.serialize()
assert classpath == "airflow.providers.googl... | TestBigQueryValueCheckTrigger |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 2474,
"end": 2662
} | class ____(pydantic.BaseModel):
regex: re.Pattern
param_names: Tuple[Literal["year"], Literal["month"]] = ("year", "month")
sort_ascending: bool = True
| FileNamePartitionerMonthly |
python | django-haystack__django-haystack | test_haystack/test_loading.py | {
"start": 415,
"end": 3016
} | class ____(TestCase):
def test_init(self):
ch = loading.ConnectionHandler({})
self.assertEqual(ch.connections_info, {})
ch = loading.ConnectionHandler(
{
"default": {
"ENGINE": "haystack.backends.solr_backend.SolrEngine",
"... | ConnectionHandlerTestCase |
python | mlflow__mlflow | mlflow/webhooks/types.py | {
"start": 1099,
"end": 2289
} | class ____(TypedDict):
"""Payload sent when a new model version is created.
Example payload:
.. code-block:: python
{
"name": "example_model",
"version": "1",
"source": "models:/123",
"run_id": "abcd1234abcd5678",
"tags": {"example_key":... | ModelVersionCreatedPayload |
python | Pylons__pyramid | src/pyramid/i18n.py | {
"start": 13918,
"end": 14687
} | class ____:
@reify
def localizer(self):
"""Convenience property to return a localizer"""
registry = self.registry
current_locale_name = self.locale_name
localizer = registry.queryUtility(ILocalizer, name=current_locale_name)
if localizer is None:
# no locali... | LocalizerRequestMixin |
python | ray-project__ray | python/ray/data/tests/unit/test_datatype.py | {
"start": 4474,
"end": 5603
} | class ____:
"""Test factory methods from external systems."""
@pytest.mark.parametrize(
"pa_type",
[
pa.int32(),
pa.string(),
pa.timestamp("s"),
pa.list_(pa.int32()),
pa.decimal128(10, 2),
],
)
def test_from_arrow(self,... | TestDataTypeFactories |
python | django__django | django/forms/widgets.py | {
"start": 12122,
"end": 12222
} | class ____(Input):
input_type = "url"
template_name = "django/forms/widgets/url.html"
| URLInput |
python | plotly__plotly.py | plotly/graph_objs/icicle/_leaf.py | {
"start": 233,
"end": 2322
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.leaf"
_valid_props = {"opacity"}
@property
def opacity(self):
"""
Sets the opacity of the leaves. With colorscale it is defaulted
to 1; otherwise it is defaulted to 0.7
The 'opacity... | Leaf |
python | facelessuser__soupsieve | tests/test_level2/test_focus.py | {
"start": 49,
"end": 1508
} | class ____(util.TestCase):
"""Test focus selector."""
MARKUP = """
<form action="#">
<fieldset id='a' disabled>
<legend>
Simple fieldset <input type="radio" id="1" checked>
<fieldset id='b' disabled>
<legend>Simple fieldset <input type="radio" id="2" checked></... | TestFocus |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 22100,
"end": 22739
} | class ____(object):
def __init__(self):
self.buffer = [] # empty list
def append(self,item):
self.buffer.append(item)
def elementAt(self,index):
return self.buffer[index]
def reset(self):
self.buffer = []
def removeFirst(self):
self.buffer.pop(0)
def... | Queue |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 218918,
"end": 223772
} | class ____(Request):
"""
Add or update task configuration
:param task: Task ID
:type task: str
:param configuration: Task configuration items. The new ones will be added and
the already existing ones will be updated
:type configuration: Sequence[ConfigurationItem]
:param replace_con... | EditConfigurationRequest |
python | celery__celery | t/integration/test_canvas.py | {
"start": 43442,
"end": 61587
} | class ____:
@flaky
def test_ready_with_exception(self, manager):
if not manager.app.conf.result_backend.startswith('redis'):
raise pytest.skip('Requires redis result backend.')
g = group([add.s(1, 2), raise_error.s()])
result = g.apply_async()
while not result.ready(... | test_group |
python | huggingface__transformers | src/transformers/models/x_clip/modeling_x_clip.py | {
"start": 47475,
"end": 48189
} | class ____(nn.Module):
"""This corresponds to the `VideoSpecificPrompt` class in the original implementation."""
def __init__(self, config):
super().__init__()
embed_dim = config.projection_dim
self.layernorm = nn.LayerNorm(embed_dim, eps=config.vision_config.layer_norm_eps)
sel... | XCLIPPromptGenerator |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/expect_queried_column_value_frequency_to_meet_threshold.py | {
"start": 985,
"end": 9565
} | class ____(QueryExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_queried_column_value_frequency_to_meet_threshold.py docstring">
"""Expect the frequency of occurrences of a specified value in a queried column to be at least <thresho... | ExpectQueriedColumnValueFrequencyToMeetThreshold |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-openai/llama_index/embeddings/openai/base.py | {
"start": 987,
"end": 7193
} | class ____(str, Enum):
"""OpenAI embedding mode model."""
# davinci
TEXT_SIMILARITY_DAVINCI = "text-similarity-davinci-001"
TEXT_SEARCH_DAVINCI_QUERY = "text-search-davinci-query-001"
TEXT_SEARCH_DAVINCI_DOC = "text-search-davinci-doc-001"
# curie
TEXT_SIMILARITY_CURIE = "text-similarity-c... | OpenAIEmbeddingModeModel |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 7633,
"end": 7803
} | class ____(models.Model):
poll = CustomAttrNameForeignKey(Poll, models.CASCADE, attr_name="custom_poll")
history = HistoricalRecords()
| ModelWithCustomAttrForeignKey |
python | getsentry__sentry | tests/sentry/seer/autofix/test_issue_summary.py | {
"start": 1377,
"end": 31602
} | class ____(APITestCase, SnubaTestCase, OccurrenceTestMixin):
def setUp(self) -> None:
super().setUp()
self.group = self.create_group()
self.login_as(user=self.user)
def tearDown(self) -> None:
super().tearDown()
# Clear the cache after each test
cache.delete(f"ai... | IssueSummaryTest |
python | kamyu104__LeetCode-Solutions | Python/the-number-of-ways-to-make-the-sum.py | {
"start": 4276,
"end": 4710
} | class ____(object):
def numberOfWays(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9+7
def count_1_2(n):
return n//2+1
def count_1_2_6(n):
return sum(count_1_2(n-6*i) for i in xrange((n//6)+1))
return reduce(lambda ... | Solution3 |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 33224,
"end": 34216
} | class ____:
class B:
def foo():
st_error = STError(
f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
" no parent)."
)
def foo():
user_regex = _lazy_re_compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0... | A |
python | numba__numba | numba/core/types/containers.py | {
"start": 10113,
"end": 10624
} | class ____(_HomogeneousTuple, BaseNamedTuple):
def __init__(self, dtype, count, cls):
self.dtype = dtype
self.count = count
self.fields = tuple(cls._fields)
self.instance_class = cls
name = "%s(%s x %d)" % (cls.__name__, dtype, count)
super(NamedUniTuple, self).__init... | NamedUniTuple |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/database.py | {
"start": 41291,
"end": 51160
} | class ____(object):
"""
Represents a dependency graph between distributions.
The dependency relationships are stored in an ``adjacency_list`` that maps
distributions to a list of ``(other, label)`` tuples where ``other``
is a distribution and the edge is labeled with ``label`` (i.e. the version
... | DependencyGraph |
python | PrefectHQ__prefect | src/prefect/server/events/counting.py | {
"start": 7147,
"end": 12060
} | class ____(AutoEnum):
day = AutoEnum.auto() # `day` will be translated into an equivalent `time`
time = AutoEnum.auto()
event = AutoEnum.auto()
resource = AutoEnum.auto()
# Implementations for storage backend
def get_database_query(
self,
filter: "EventFilter",
time_un... | Countable |
python | huggingface__transformers | utils/test_module/custom_modeling.py | {
"start": 105,
"end": 450
} | class ____(PreTrainedModel):
config_class = CustomConfig
def __init__(self, config):
super().__init__(config)
self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size)
self.post_init()
def forward(self, x):
return self.linear(x)
def _init_weights(self, modu... | CustomModel |
python | rapidsai__cudf | python/cudf/cudf/pandas/_wrappers/pandas.py | {
"start": 4127,
"end": 69363
} | class ____:
"""
Descriptor that ensures that accessors like `.dt` and `.str`
return the corresponding accessor types when accessed on `Series`
and `Index` _types_ (not instances).n
Attribute access for _instances_ uses the regular fast-then-slow
lookup defined in `__getattr__`.
"""
def... | _AccessorAttr |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_util__embed.py | {
"start": 3200,
"end": 5089
} | class ____:
def test_error_on_empty_list(self) -> None:
with pytest.raises(ValueError) as e:
with beu.OutputDocumentFor([]):
pass
assert str(e.value).endswith(_ODFERR)
def test_error_on_mixed_list(self) -> None:
p = SomeModel()
d = Document()
... | Test_OutputDocumentFor_general |
python | pikepdf__pikepdf | src/pikepdf/form.py | {
"start": 20723,
"end": 22371
} | class ____:
"""Represents a single option for a choice field."""
def __init__(self, field: ChoiceField, opt: String | Array, index: int | None):
"""Create a new option for a choice field."""
self._field = field
self._opt = opt
self._index = index
@property
def display_v... | ChoiceFieldOption |
python | celery__celery | t/integration/test_canvas.py | {
"start": 124964,
"end": 128215
} | class ____:
"""
Confirm nested signatures can be rebuilt after passing through a backend.
These tests are expected to finish and return `None` or raise an exception
in the error case. The exception indicates that some element of a nested
signature object was not properly deserialized from its dicti... | test_signature_serialization |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 48511,
"end": 48664
} | class ____(CombineSeries):
_parameters = CombineSeries._parameters + ["overwrite"]
_defaults = {"fill_value": None, "overwrite": True}
| CombineFrame |
python | scikit-learn__scikit-learn | sklearn/tests/test_base.py | {
"start": 1232,
"end": 1358
} | class ____(BaseEstimator):
def __init__(self, l1=0, empty=None):
self.l1 = l1
self.empty = empty
| MyEstimator |
python | numpy__numpy | numpy/_core/_internal.py | {
"start": 6325,
"end": 7214
} | class ____:
def __init__(self, cls):
self._cls = cls
def __mul__(self, other):
return self
def __call__(self, *other):
return self._cls(other)
def __eq__(self, other):
return self._cls == other._cls
def __ne__(self, other):
return self._cls != other._cls
... | dummy_ctype |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 105733,
"end": 106195
} | class ____(str, Enum):
"""
State of the single shard within a replica set.
"""
def __str__(self) -> str:
return str(self.value)
ACTIVE = "Active"
DEAD = "Dead"
PARTIAL = "Partial"
INITIALIZING = "Initializing"
LISTENER = "Listener"
PARTIALSNAPSHOT = "PartialSnapshot"
... | ReplicaState |
python | kubernetes-client__python | kubernetes/client/models/v1_volume_projection.py | {
"start": 383,
"end": 7907
} | 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... | V1VolumeProjection |
python | yaml__pyyaml | lib/yaml/nodes.py | {
"start": 1328,
"end": 1385
} | class ____(CollectionNode):
id = 'sequence'
| SequenceNode |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 90760,
"end": 90837
} | class ____(BinOpSeries):
operation = M.lt
_operator_repr = "<"
| LTSeries |
python | pytorch__pytorch | test/test_cuda.py | {
"start": 207988,
"end": 227582
} | class ____(TestCase):
def _setup_mempool_limited_memory_test(self, additional_allowed_memory_in_mb):
device = torch.device("cuda:0")
self.init_fraction = torch.cuda.get_per_process_memory_fraction()
torch.cuda.memory.empty_cache()
mb = 1024 * 1024
_, all_memory = torch.cuda.... | TestMemPool |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 9386,
"end": 9620
} | class ____(ErrorComponent):
def __init__(self, component_name, error_message):
headline = "Render failed of component named `%s`" % component_name
super().__init__(headline, error_message)
| SerializationErrorComponent |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/remote_explorer.py | {
"start": 2062,
"end": 2864
} | class ____(QSortFilterProxyModel):
def lessThan(self, left, right):
right_data = self.sourceModel().data(
self.sourceModel().index(right.row(), 0), Qt.UserRole + 1
)
if right_data["type"] == "ACTION":
return self.sortOrder() == Qt.AscendingOrder
left_data = ... | RemoteQSortFilterProxyModel |
python | django-debug-toolbar__django-debug-toolbar | tests/panels/test_custom.py | {
"start": 124,
"end": 322
} | class ____(Panel):
def title(self):
return "Title with special chars &\"'<>"
@override_settings(
DEBUG=True, DEBUG_TOOLBAR_PANELS=["tests.panels.test_custom.CustomPanel"]
)
| CustomPanel |
python | neetcode-gh__leetcode | python/1958-check-if-move-is-legal.py | {
"start": 0,
"end": 872
} | class ____:
def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:
ROWS, COLS = len(board), len(board[0])
direction = [[1, 0], [-1, 0], [0, 1], [0, -1],
[1, 1], [-1, -1], [1, -1], [-1, 1]]
board[rMove][cMove] = color
def... | Solution |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_timestamp.py | {
"start": 16305,
"end": 17537
} | class ____:
def test_conversion(self):
# GH#9255
ts = Timestamp("2000-01-01").as_unit("ns")
result = ts.to_pydatetime()
expected = datetime(2000, 1, 1)
assert result == expected
assert type(result) == type(expected)
result = ts.to_datetime64()
expect... | TestTimestampConversion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.