language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pydantic__pydantic | pydantic/v1/config.py | {
"start": 915,
"end": 2479
} | class ____(str, Enum):
allow = 'allow'
ignore = 'ignore'
forbid = 'forbid'
# https://github.com/cython/cython/issues/4003
# Fixed in Cython 3 and Pydantic v1 won't support Cython 3.
# Pydantic v2 doesn't depend on Cython at all.
if not compiled:
from typing_extensions import TypedDict
class Confi... | Extra |
python | pytorch__pytorch | test/distributed/tensor/parallel/test_tp_style.py | {
"start": 900,
"end": 17489
} | class ____(DTensorTestBase):
@property
def world_size(self):
return NUM_DEVICES
@with_comms
def test_colwise_parallel_style(self):
mesh = init_device_mesh(self.device_type, (self.world_size,))
comm_mode = CommDebugMode()
tensor = torch.rand(8, 16, device=self.device_typ... | TensorParallelStyleTest |
python | ansible__ansible | test/units/plugins/cache/test_cache.py | {
"start": 1029,
"end": 3305
} | class ____(unittest.TestCase):
def setUp(self):
# memory plugin cache
self.cache = CachePluginAdjudicator()
self.cache['cache_key'] = {'key1': 'value1', 'key2': 'value2'}
self.cache['cache_key_2'] = {'key': 'value'}
def test___setitem__(self):
self.cache['new_cache_key']... | TestCachePluginAdjudicator |
python | encode__django-rest-framework | tests/test_exceptions.py | {
"start": 1610,
"end": 2692
} | class ____(TestCase):
def test_eq(self):
assert ErrorDetail('msg') == ErrorDetail('msg')
assert ErrorDetail('msg', 'code') == ErrorDetail('msg', code='code')
assert ErrorDetail('msg') == 'msg'
assert ErrorDetail('msg', 'code') == 'msg'
def test_ne(self):
assert ErrorDe... | ErrorDetailTests |
python | mlflow__mlflow | mlflow/store/tracking/dbmodels/models.py | {
"start": 4452,
"end": 9022
} | class ____(Base):
"""
DB model for :py:class:`mlflow.entities.Run`. These are recorded in ``runs`` table.
"""
__tablename__ = "runs"
run_uuid = Column(String(32), nullable=False)
"""
Run UUID: `String` (limit 32 characters). *Primary Key* for ``runs`` table.
"""
name = Column(Strin... | SqlRun |
python | apache__airflow | providers/alibaba/tests/unit/alibaba/cloud/operators/test_analyticdb_spark.py | {
"start": 4784,
"end": 6568
} | class ____:
@mock.patch(ADB_SPARK_OPERATOR_STRING.format("AnalyticDBSparkHook"))
def test_execute(self, mock_hook):
"""Test submit AnalyticDB Spark SQL Application works as expected."""
operator = AnalyticDBSparkSQLOperator(
sql=MOCK_SQL,
cluster_id=MOCK_CLUSTER_ID,
... | TestAnalyticDBSparklSQLOperator |
python | getsentry__sentry | src/sentry/snuba/metrics/fields/base.py | {
"start": 12335,
"end": 12718
} | class ____(MetricOperationDefinition):
can_orderby: bool
can_groupby: bool = False
can_filter: bool = False
meta_type: str | None = None
post_query_func: Callable[..., PostQueryFuncReturnType] = lambda data, *args: data
snql_func: Callable[..., Function | None] = lambda _: None
default_null_... | DerivedOpDefinition |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 22288,
"end": 23456
} | class ____(NDArrayMixin):
"""Wrap an array, converting tuples into the indicated explicit indexer."""
__slots__ = ("array", "indexer_cls")
def __init__(self, array, indexer_cls: type[ExplicitIndexer] = BasicIndexer):
self.array = as_indexable(array)
self.indexer_cls = indexer_cls
def ... | ImplicitToExplicitIndexingAdapter |
python | encode__django-rest-framework | rest_framework/authentication.py | {
"start": 1488,
"end": 3639
} | class ____(BaseAuthentication):
"""
HTTP Basic authentication against username/password.
"""
www_authenticate_realm = 'api'
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise... | BasicAuthentication |
python | sphinx-doc__sphinx | sphinx/pycode/parser.py | {
"start": 18746,
"end": 21666
} | class ____(TokenProcessor):
"""Python source code parser to detect location of functions,
classes and methods.
"""
def __init__(self, lines: list[str]) -> None:
super().__init__(lines)
self.decorator: Token | None = None
self.context: list[str] = []
self.indents: list[tu... | DefinitionFinder |
python | facebookresearch__faiss | faiss/gpu/test/torch_test_contrib_gpu.py | {
"start": 9372,
"end": 14059
} | class ____(unittest.TestCase):
def test_knn_gpu(self, use_cuvs=False):
torch.manual_seed(10)
d = 32
nb = 1024
nq = 10
k = 10
res = faiss.StandardGpuResources()
# make GT on torch cpu and test using IndexFlatL2
xb = torch.rand(nb, d, dtype=torch.float3... | TestTorchUtilsKnnGpu |
python | encode__django-rest-framework | tests/test_filters.py | {
"start": 19153,
"end": 19407
} | class ____(models.Model):
related_object = models.ForeignKey(OrderingFilterModel, related_name="related", on_delete=models.CASCADE)
index = models.SmallIntegerField(help_text="A non-related field to test with", default=0)
| OrderingFilterRelatedModel |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_moe/modeling_hunyuan_v1_moe.py | {
"start": 7021,
"end": 10449
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden... | HunYuanMoEV1Attention |
python | openai__openai-python | src/openai/resources/embeddings.py | {
"start": 11902,
"end": 12131
} | class ____:
def __init__(self, embeddings: Embeddings) -> None:
self._embeddings = embeddings
self.create = to_streamed_response_wrapper(
embeddings.create,
)
| EmbeddingsWithStreamingResponse |
python | wandb__wandb | tests/system_tests/test_automations/test_automations_api.py | {
"start": 23977,
"end": 27187
} | class ____:
@fixture(scope="class")
def num_projects(self) -> int:
return 10
@fixture(scope="class", params=[1, 2, 3])
def page_size(self, request: FixtureRequest) -> int:
return request.param
@fixture(scope="class")
def num_pages(self, num_projects: int, page_size: int) -> int... | TestPaginatedAutomations |
python | dask__dask | dask/tests/test_expr.py | {
"start": 2511,
"end": 2571
} | class ____:
def __init__(self, *args, **kwargs): ...
| Mixin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 330,
"end": 375
} | class ____(
#
object
#
):
...
| A |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 52888,
"end": 53989
} | class ____(Request):
"""
Clear an open Scroll ID
:param scroll_id: Scroll ID as returned by previous events service calls
:type scroll_id: str
"""
_service = "events"
_action = "clear_scroll"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
... | ClearScrollRequest |
python | pytorch__pytorch | test/test_sparse.py | {
"start": 198194,
"end": 210588
} | class ____(TestCase):
exact_dtype = True
def _test_meta_sparse_coo(self, dtype):
r = torch.empty(4, 4, layout=torch.sparse_coo, device='meta', dtype=dtype)
self.assertTrue(r.is_meta)
self.assertEqual(r.device.type, "meta")
r2 = torch.empty_like(r)
self.assertTrue(r2.is_m... | TestSparseMeta |
python | gevent__gevent | src/greentest/3.9/test_subprocess.py | {
"start": 136818,
"end": 147182
} | class ____(BaseTestCase):
def test_startupinfo(self):
# startupinfo argument
# We uses hardcoded constants, because we do not want to
# depend on win32all.
STARTF_USESHOWWINDOW = 1
SW_MAXIMIZE = 3
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = S... | Win32ProcessTestCase |
python | doocs__leetcode | solution/2900-2999/2917.Find the K-or of an Array/Solution.py | {
"start": 0,
"end": 237
} | class ____:
def findKOr(self, nums: List[int], k: int) -> int:
ans = 0
for i in range(32):
cnt = sum(x >> i & 1 for x in nums)
if cnt >= k:
ans |= 1 << i
return ans
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 22323,
"end": 23396
} | class ____(Request):
"""
Archive models
:param ids: Entities to move
:type ids: Sequence[str]
"""
_service = "models"
_action = "archive_many"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Entit... | ArchiveManyRequest |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 28853,
"end": 41813
} | class ____(TickFormatter):
''' A ``TickFormatter`` for displaying timedelta values nicely across a
range of scales. The largest scale for differentiating between formats
is "days", as the conversion from "days" to "months" or "years" is not
well defined.
``TimedeltaTickFormatter`` has the following... | TimedeltaTickFormatter |
python | apache__airflow | providers/presto/src/airflow/providers/presto/transfers/gcs_to_presto.py | {
"start": 1448,
"end": 5047
} | class ____(BaseOperator):
"""
Loads a csv file from Google Cloud Storage into a Presto table.
Assumptions:
1. CSV file should not have headers
2. Presto table with requisite columns is already created
3. Optionally, a separate JSON file with headers or list of headers can be provided
:para... | GCSToPrestoOperator |
python | aio-libs__aiohttp | tests/test_resolver.py | {
"start": 2721,
"end": 3035
} | class ____:
def __init__(self, hosts: Collection[str]) -> None:
self.nodes = [
FakeAIODNSAddrInfoNode(
socket.AF_INET6,
(h.encode(), 0, 0, 3 if ip_address(h).is_link_local else 0),
)
for h in hosts
]
| FakeAIODNSAddrInfoIPv6Result |
python | run-llama__llama_index | llama-index-core/tests/voice_agents/test_subclasses.py | {
"start": 3105,
"end": 7317
} | class ____(BaseVoiceAgent):
def __init__(
self,
ws: BaseVoiceAgentWebsocket,
interface: BaseVoiceAgentInterface,
api_key: Optional[str] = None,
):
super().__init__(ws=ws, interface=interface, api_key=api_key)
self._is_started = False
self._sent: List[Any] ... | MockVoiceAgent |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 1013,
"end": 1099
} | class ____(TypedDict):
success: bool
message: NotRequired[str]
| StoreDataResponse |
python | django__django | tests/custom_managers/models.py | {
"start": 5597,
"end": 5729
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_public=True)
| RestrictedManager |
python | pandas-dev__pandas | pandas/tests/indexing/test_indexing.py | {
"start": 30316,
"end": 39342
} | class ____:
def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli):
# dispatching _can_hold_element to underlying DatetimeArray
tz = tz_naive_fixture
dti = date_range("2016-01-01", periods=3, tz=tz)
ser = Series(dti.copy(deep=True))
values = ser._values
... | TestDatetimelikeCoercion |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B021.py | {
"start": 212,
"end": 335
} | class ____:
f"""hello {VARIABLE}!"""
def foo1():
"""hello world!"""
def foo2():
f"""hello {VARIABLE}!"""
| bar2 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_header_image01.py | {
"start": 339,
"end": 2432
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("header_image01.xlsx")
self.ignore_elements = {
"xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"]
}
def test_c... | TestCompareXLSXFiles |
python | cython__cython | Cython/Compiler/Tests/TestUtilityLoad.py | {
"start": 3121,
"end": 3923
} | class ____(unittest.TestCase):
def test_equality(self):
c1 = Code.UtilityCode.load("NumpyImportUFunc", "NumpyImportArray.c")
c2 = Code.UtilityCode.load("NumpyImportArray", "NumpyImportArray.c")
c3 = Code.UtilityCode.load("pyunicode_strlen", "StringTools.c")
c4 = Code.UtilityCode.load... | TestUtilityCode |
python | numba__numba | numba/cuda/tests/doc_examples/test_vecadd.py | {
"start": 201,
"end": 2043
} | class ____(CUDATestCase):
"""
Test simple vector addition
"""
def setUp(self):
# Prevent output from this test showing
# up when running the test suite
self._captured_stdout = captured_stdout()
self._captured_stdout.__enter__()
super().setUp()
def tearDown(s... | TestVecAdd |
python | realpython__materials | asterioids-pygame-project/source_code_step_2/space_rocks/game.py | {
"start": 16,
"end": 760
} | class ____:
def __init__(self):
self._init_pygame()
self.screen = pygame.display.set_mode((800, 600))
def main_loop(self):
while True:
self._handle_input()
self._process_game_logic()
self._draw()
def _init_pygame(self):
pygame.init()
... | SpaceRocks |
python | walkccc__LeetCode | solutions/792. Number of Matching Subsequences/792.py | {
"start": 0,
"end": 715
} | class ____:
def numMatchingSubseq(self, s: str, words: list[str]) -> int:
root = {}
def insert(word: str) -> None:
node = root
for c in word:
if c not in node:
node[c] = {'count': 0}
node = node[c]
node['count'] += 1
for word in words:
insert(word)
... | Solution |
python | openai__openai-python | src/openai/cli/_api/image.py | {
"start": 2691,
"end": 2883
} | class ____(BaseModel):
image: str
num_images: int
size: str
response_format: str
prompt: str
mask: Omittable[str] = omit
model: Omittable[str] = omit
| CLIImageEditArgs |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/ext/hybrid/hybrid_five.py | {
"start": 322,
"end": 853
} | class ____(Base):
__tablename__ = "my_model"
id: Mapped[int] = mapped_column(primary_key=True)
int_col: Mapped[int | None] = mapped_column()
@hybrid_property
def some_col(self) -> int:
return (self.int_col or 0) + 1
@some_col.inplace.setter
def _str_col_setter(self, value: int | ... | MyModel |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 5474,
"end": 13829
} | class ____(TestCase):
def test_regular_fields(self):
"""
Model fields should map to their equivalent serializer fields.
"""
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = RegularFieldsModel
fields = '__all__'
... | TestRegularFieldMappings |
python | numba__numba | numba/stencils/stencil.py | {
"start": 621,
"end": 2449
} | class ____(object):
'''Callable class responsible for lowering calls to a specific StencilFunc.
'''
def __init__(self, sf):
self.stencilFunc = sf
def __call__(self, context, builder, sig, args):
cres = self.stencilFunc.compile_for_argtys(sig.args, {},
sig.return_type... | StencilFuncLowerer |
python | boto__boto3 | tests/functional/docs/test_ec2.py | {
"start": 705,
"end": 2089
} | class ____(BaseDocsFunctionalTests):
def setUp(self):
super().setUp()
self.documenter = ServiceDocumenter(
'ec2',
session=Session(region_name='us-east-1'),
root_docs_path=self.root_services_path,
)
self.generated_contents = self.documenter.document... | TestInstanceDeleteTags |
python | pyqtgraph__pyqtgraph | pyqtgraph/exporters/Matplotlib.py | {
"start": 5216,
"end": 5689
} | class ____(QtWidgets.QMainWindow):
def __init__(self):
from ..widgets import MatplotlibWidget
QtWidgets.QMainWindow.__init__(self)
self.mpl = MatplotlibWidget.MatplotlibWidget()
self.setCentralWidget(self.mpl)
self.show()
def __getattr__(self, attr):
retu... | MatplotlibWindow |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 9545,
"end": 9889
} | class ____(SpanToken):
"""
A "block" macro opening tag. ("{{macroName<optionalParams>}}<newLine>")
We want to keep it on a separate line instead of "soft" merging it with the *following* line.
"""
pattern = re.compile(r'(?<!\\)(\{\{\w+.*?(?<![\\/])\}\})\s*\n')
parse_inner = False
parse_grou... | XWikiBlockMacroStart |
python | mwaskom__seaborn | seaborn/_stats/aggregation.py | {
"start": 3587,
"end": 3684
} | class ____(Stat):
...
def __call__(self, data, groupby, orient, scales):
...
| Rolling |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 59428,
"end": 60884
} | class ____(unittest.TestCase):
def test_atexit_output(self):
rc, out, err = assert_python_ok("-c", """if True:
import threading
def run_last():
print('parrot')
threading._register_atexit(run_last)
""")
self.assertFalse(err)
self... | AtexitTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes9.py | {
"start": 793,
"end": 913
} | class ____(TypedDict):
x: NotRequired[int]
y: Required[int]
# This should generate an error for x but not y.
| TD_A2 |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-diff-private-simple-dataset/llama_index/packs/diff_private_simple_dataset/events.py | {
"start": 88,
"end": 237
} | class ____(BaseEvent):
@classmethod
def class_name(cls):
"""Class name."""
return "LLMEmptyResponseEvent"
| LLMEmptyResponseEvent |
python | python__mypy | mypy/nodes.py | {
"start": 57822,
"end": 58155
} | class ____(Statement):
__slots__ = ("expr",)
__match_args__ = ("expr",)
expr: Expression | None
def __init__(self, expr: Expression | None) -> None:
super().__init__()
self.expr = expr
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_return_stmt(s... | ReturnStmt |
python | dask__distributed | distributed/deploy/old_ssh.py | {
"start": 424,
"end": 10080
} | class ____:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def async_ssh(cmd_dict):
import paramiko
from paramiko.buffered_pipe import PipeTimeout
from paramiko.ssh_... | bcolors |
python | redis__redis-py | redis/asyncio/multidb/healthcheck.py | {
"start": 2859,
"end": 4260
} | class ____(AbstractHealthCheckPolicy):
"""
Policy that returns True if a majority of health check probes are successful.
"""
def __init__(self, health_check_probes: int, health_check_delay: float):
super().__init__(health_check_probes, health_check_delay)
async def execute(self, health_che... | HealthyMajorityPolicy |
python | scikit-learn__scikit-learn | sklearn/externals/_numpydoc/docscrape.py | {
"start": 17958,
"end": 19092
} | class ____(NumpyDocString):
def __init__(self, func, role="func", doc=None, config=None):
self._f = func
self._role = role # e.g. "func" or "meth"
if doc is None:
if func is None:
raise ValueError("No function or docstring given")
doc = inspect.getdo... | FunctionDoc |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 5877,
"end": 6032
} | class ____(TestRss2Feed):
stylesheets = [
"/stylesheet1.xsl",
feedgenerator.Stylesheet("/stylesheet2.xsl"),
]
| TestFeedWithStylesheets |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-walk-in-weighted-graph.py | {
"start": 50,
"end": 1712
} | class ____(object):
def minimumCost(self, n, edges, query):
"""
:type n: int
:type edges: List[List[int]]
:type query: List[List[int]]
:rtype: List[int]
"""
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
... | Solution |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 39608,
"end": 40281
} | class ____(Reduction):
"""
Some reductions reduce the number of rows in your object but keep the original
dimension, e.g. a DataFrame stays a DataFrame instead of getting reduced to
a Series.
"""
@classmethod
def chunk(cls, df, **kwargs):
return cls.reduction_chunk(df, **kwargs)
... | ReductionConstantDim |
python | getsentry__sentry | src/sentry/analytics/event.py | {
"start": 2314,
"end": 3619
} | class ____:
"""
Base class for custom analytics Events.
"""
# the type of the event, used for serialization and matching. Can be None for abstract base event classes
type: ClassVar[str | None]
_eventclass_initialized: ClassVar[bool] = False
def __new__(cls, *args: Any, **kwargs: Any) -> Se... | Event |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_logging.py | {
"start": 2117,
"end": 7808
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"),
new=mock_base_gcp_hook_default_project_id,
):
self.hook = CloudLoggingHook(gcp_conn_id=GCP_CONN_ID)
@mock.patch(
"airflow.providers.google.common.hooks... | TestCloudLoggingHook |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py | {
"start": 3260,
"end": 4171
} | class ____(Step):
context: PythonRegistryPublishContext
title = "Check if the connector is published on python registry"
async def _run(self) -> StepResult:
is_published = is_package_published(
self.context.package_metadata.name, self.context.package_metadata.version, self.context.regis... | CheckPythonRegistryPackageDoesNotExist |
python | run-llama__llama_index | llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py | {
"start": 1887,
"end": 1975
} | class ____(CustomEvent, Event):
type: EventType = EventType.CUSTOM
| CustomWorkflowEvent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 391371,
"end": 392472
} | class ____(sgqlc.types.Interface):
"""Represents a contribution a user made on GitHub, such as opening
an issue.
"""
__schema__ = github_schema
__field_names__ = ("is_restricted", "occurred_at", "resource_path", "url", "user")
is_restricted = sgqlc.types.Field(sgqlc.types.non_null(Boolean), gra... | Contribution |
python | getsentry__sentry | src/sentry/features/handler.py | {
"start": 2204,
"end": 3529
} | class ____(FeatureHandler):
"""
Base class for feature handlers that apply to an organization
and an optional collection of `objects` (e.g. projects).
Subclasses are expected to implement `_check_for_batch` and perform a feature check
using only the organization.
It is generally better to exte... | BatchFeatureHandler |
python | django__django | tests/queries/tests.py | {
"start": 150494,
"end": 150937
} | class ____(TestCase):
def test_reverse_trimming(self):
# We don't accidentally trim reverse joins - we can't know if there is
# anything on the other side of the join, so trimming reverse joins
# can't be done, ever.
t = Tag.objects.create()
qs = Tag.objects.filter(annotation... | ReverseJoinTrimmingTest |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/comparison/eval_chain.py | {
"start": 3693,
"end": 5113
} | class ____(BaseOutputParser[dict]):
"""A parser for the output of the PairwiseStringEvalChain.
Attributes:
_type: The type of the output parser.
"""
@property
def _type(self) -> str:
"""Return the type of the output parser.
Returns:
The type of the output pars... | PairwiseStringResultOutputParser |
python | kamyu104__LeetCode-Solutions | Python/check-if-number-is-a-sum-of-powers-of-three.py | {
"start": 32,
"end": 274
} | class ____(object):
def checkPowersOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
while n > 0:
if n%3 == 2:
return False
n //= 3
return True
| Solution |
python | kamyu104__LeetCode-Solutions | Python/earliest-finish-time-for-land-and-water-rides-i.py | {
"start": 40,
"end": 767
} | class ____(object):
def earliestFinishTime(self, landStartTime, landDuration, waterStartTime, waterDuration):
"""
:type landStartTime: List[int]
:type landDuration: List[int]
:type waterStartTime: List[int]
:type waterDuration: List[int]
:rtype: int
"""
... | Solution |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 835582,
"end": 836796
} | class ____(mupdf.FzOutput2):
def __init__(self, bio):
super().__init__()
self.bio = bio
self.use_virtual_write()
self.use_virtual_seek()
self.use_virtual_tell()
self.use_virtual_truncate()
def seek( self, ctx, offset, whence):
return self.bio.seek( of... | JM_new_output_fileptr_Output |
python | huggingface__transformers | src/transformers/models/musicgen_melody/configuration_musicgen_melody.py | {
"start": 853,
"end": 6724
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of an [`MusicgenMelodyDecoder`]. It is used to instantiate a
Musicgen Melody decoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will y... | MusicgenMelodyDecoderConfig |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_omni_utils.py | {
"start": 2536,
"end": 3712
} | class ____(OmniComponent):
async def write_state_to_path(self, state_path):
"""Override to use mock data."""
import dagster as dg
# Create a mock workspace with the same credentials
mock_workspace = MockOmniWorkspace(**self.workspace.model_dump())
# Fetch and store mock dat... | MockOmniComponent |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_utilities.py | {
"start": 1197,
"end": 3665
} | class ____:
@pytest.mark.parametrize(
"ready_condition,expected_value",
[({"status": "True"}, True), ({"status": "False"}, False), ({}, False)],
)
def test_is_ready(self, ready_condition, expected_value):
job = Job(
metadata={},
spec={},
status={},... | TestJob |
python | scipy__scipy | scipy/stats/tests/test_rank.py | {
"start": 2424,
"end": 12775
} | class ____:
def desired_dtype(self, method='average', has_nans=False, *, xp):
if has_nans:
return xp.asarray(1.).dtype
return xp.asarray(1.).dtype if method=='average' else xp.asarray(1).dtype
def test_empty(self, xp):
"""stats.rankdata of empty array should return an empty... | TestRankData |
python | PrefectHQ__prefect | tests/test_futures.py | {
"start": 12168,
"end": 17673
} | class ____:
async def test_wait_with_timeout(self, task_run):
@task
async def my_task():
return 42
task_run = await my_task.create_run()
future = PrefectDistributedFuture(task_run_id=task_run.id)
asyncio.create_task(
run_task_async(
t... | TestPrefectDistributedFuture |
python | python-poetry__poetry | src/poetry/publishing/uploader.py | {
"start": 835,
"end": 12361
} | class ____:
def __init__(self, poetry: Poetry, io: IO, dist_dir: Path | None = None) -> None:
self._poetry = poetry
self._package = poetry.package
self._io = io
self._dist_dir = dist_dir or self.default_dist_dir
self._username: str | None = None
self._password: str | ... | Uploader |
python | PyCQA__pylint | tests/functional/m/missing/missing_function_docstring.py | {
"start": 306,
"end": 413
} | class ____:
def __init__(self, my_param: int) -> None: # [missing-function-docstring]
pass
| MyClass |
python | huggingface__transformers | src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py | {
"start": 6979,
"end": 8638
} | class ____(nn.Module):
def __init__(self, config: MobileNetV2Config, in_channels: int, expanded_channels: int, out_channels: int) -> None:
super().__init__()
# The very first layer is a regular 3x3 convolution with stride 2 that expands to 32 channels.
# All other expansion layers use the e... | MobileNetV2Stem |
python | celery__celery | t/unit/concurrency/test_gevent.py | {
"start": 3057,
"end": 4170
} | class ____:
def test_apply_timeout(self):
self.patching.modules(*gevent_modules)
class Timeout(Exception):
value = None
def __init__(self, value):
self.__class__.value = value
def __enter__(self):
return self
def __... | test_apply_timeout |
python | jazzband__django-formtools | tests/wizard/wizardtests/models.py | {
"start": 201,
"end": 430
} | class ____(models.Model):
poet = models.ForeignKey(Poet, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
app_label = 'formtools'
def __str__(self):
return self.name
| Poem |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_project_monitor_details.py | {
"start": 293,
"end": 465
} | class ____(BaseMonitorDetailsTest, BaseProjectMonitorTest):
endpoint = "sentry-api-0-project-monitor-details"
__test__ = True
@freeze_time()
| ProjectMonitorDetailsTest |
python | joke2k__faker | faker/providers/phone_number/nl_NL/__init__.py | {
"start": 49,
"end": 512
} | class ____(PhoneNumberProvider):
formats = (
"0### ######",
"0## #######",
"+31### ######",
"+31## #######",
"+31(0)### ######",
"+31(0)## #######",
"(0###) ######",
"(0##) #######",
"0###-######",
"0##-#######",
"+31###-######"... | Provider |
python | django__django | tests/null_fk_ordering/tests.py | {
"start": 106,
"end": 2013
} | class ____(TestCase):
def test_ordering_across_null_fk(self):
"""
Regression test for #7512
ordering across nullable Foreign Keys shouldn't exclude results
"""
author_1 = Author.objects.create(name="Tom Jones")
author_2 = Author.objects.create(name="Bob Smith")
... | NullFkOrderingTests |
python | davidhalter__jedi | test/refactor/extract_function.py | {
"start": 6909,
"end": 7093
} | class ____:
#? 9 text {'new_name': 'f', 'until_line': 4}
a = 3
c = a + 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def f():
a = 3
c = a + 2
return c
| X1 |
python | crytic__slither | slither/slithir/operations/member.py | {
"start": 749,
"end": 3068
} | class ____(OperationWithLValue):
def __init__(
self,
variable_left: SourceMapping,
variable_right: Constant,
result: Union[ReferenceVariable, ReferenceVariableSSA],
) -> None:
# Function can happen for something like
# library FunctionExtensions {
# fu... | Member |
python | run-llama__llama_index | llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/answer_similarity.py | {
"start": 356,
"end": 2057
} | class ____(BaseEvaluator):
"""
Tonic Validate's answer similarity metric.
The output score is a float between 0.0 and 5.0.
See https://docs.tonic.ai/validate/ for more details.
Args:
openai_service(OpenAIService): The OpenAI service to use. Specifies the chat
completion model ... | AnswerSimilarityEvaluator |
python | great-expectations__great_expectations | great_expectations/core/util.py | {
"start": 9303,
"end": 10677
} | class ____:
OBJECT_URL_TEMPLATE: str = "s3a://{bucket}/{path}"
"""
>>> s = S3Url("s3://bucket/hello/world")
>>> s.bucket
'bucket'
>>> s.key
'hello/world'
>>> s.url
's3://bucket/hello/world'
>>> s = S3Url("s3://bucket/hello/world?qwe1=3#ddd")
>>> s.bucket
'bucket'
>>... | S3Url |
python | huggingface__transformers | src/transformers/models/encodec/modeling_encodec.py | {
"start": 1655,
"end": 2586
} | class ____(ModelOutput):
r"""
audio_codes (`torch.LongTensor` of shape `(nb_frames, batch_size, nb_quantizers, frame_len)`, *optional*):
Discrete code embeddings computed using `model.encode`.
audio_scales (list of length `nb_frames` of `torch.Tensor` of shape `(batch_size, 1)`, *optional*):
... | EncodecEncoderOutput |
python | django__django | tests/m2m_through_regress/models.py | {
"start": 2209,
"end": 2296
} | class ____(models.Model):
event = models.ForeignKey(Event, models.CASCADE)
| Competitor |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/sagemaker.py | {
"start": 12655,
"end": 13795
} | class ____(SageMakerBaseSensor):
"""
Poll the processing job until it reaches a terminal state; raise AirflowException with the failure reason.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:SageMakerProcessingSensor`
:param jo... | SageMakerProcessingSensor |
python | protocolbuffers__protobuf | python/google/protobuf/internal/reflection_test.py | {
"start": 2877,
"end": 35740
} | class ____(unittest.TestCase):
def assertListsEqual(self, values, others):
self.assertEqual(len(values), len(others))
for i in range(len(values)):
self.assertEqual(values[i], others[i])
def testScalarConstructor(self, message_module):
# Constructor with only scalar types should succeed.
prot... | ReflectionTest |
python | huggingface__transformers | tests/models/barthez/test_tokenization_barthez.py | {
"start": 829,
"end": 2834
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "moussaKam/mbarthez"
tokenizer_class = BarthezTokenizer
integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fals', 'é', '.', '▁', '生活的真谛是... | BarthezTokenizationTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/records/post_votes_records_builder.py | {
"start": 196,
"end": 503
} | class ____(ZendeskSupportRecordBuilder):
@classmethod
def posts_votes_record(cls) -> "PostsVotesRecordBuilder":
record_template = cls.extract_record("votes", __file__, NestedPath(["votes", 0]))
return cls(record_template, FieldPath("id"), FieldPath("updated_at"))
| PostsVotesRecordBuilder |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/postgresql.py | {
"start": 120,
"end": 162
} | class ____(BaseModel):
port: int
| Service |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 27704,
"end": 34549
} | class ____(QueryTest, AssertsCompiledSQL):
@testing.fails(
"ORM refactor not allowing this yet, "
"we may just abandon this use case"
)
def test_from_alias_one(self):
User, addresses, users = (
self.classes.User,
self.tables.addresses,
self.tables.... | InstancesTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-coins-heroes-can-collect.py | {
"start": 66,
"end": 796
} | class ____(object):
def maximumCoins(self, heroes, monsters, coins):
"""
:type heroes: List[int]
:type monsters: List[int]
:type coins: List[int]
:rtype: List[int]
"""
idxs1 = range(len(heroes))
idxs1.sort(key=lambda x: heroes[x])
idxs2 = range... | Solution |
python | automl__auto-sklearn | test/fixtures/caching.py | {
"start": 370,
"end": 3742
} | class ____:
"""Used for the below fixtures.
Mainly used with cases so they don' need to be retrained at every invocation.
The cache can be cleared using `pytest`'s built in mechanism:
pytest --clear-cache
To view cached items use:
pytest --cache-show
..code:: python
def... | Cache |
python | pytorch__pytorch | tools/linter/adapters/clangformat_linter.py | {
"start": 397,
"end": 6824
} | class ____(NamedTuple):
path: str | None
line: int | None
char: int | None
code: str
severity: LintSeverity
name: str
original: str | None
replacement: str | None
description: str | None
def as_posix(name: str) -> str:
return name.replace("\\", "/") if IS_WINDOWS else name
de... | LintMessage |
python | run-llama__llama_index | llama-index-core/llama_index/core/tools/tool_spec/base.py | {
"start": 484,
"end": 3918
} | class ____:
"""Base tool spec class."""
# list of functions that you'd want to convert to spec
spec_functions: List[SPEC_FUNCTION_TYPE]
def get_fn_schema_from_fn_name(
self, fn_name: str, spec_functions: Optional[List[SPEC_FUNCTION_TYPE]] = None
) -> Optional[Type[BaseModel]]:
"""
... | BaseToolSpec |
python | django__django | django/http/response.py | {
"start": 24802,
"end": 24864
} | class ____(HttpResponse):
status_code = 410
| HttpResponseGone |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/gumroad/tests.py | {
"start": 242,
"end": 926
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = GumroadProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"success": true,
"user": {
"bio": "a sailor, a tailor",
"nam... | GumroadTests |
python | sympy__sympy | sympy/stats/rv.py | {
"start": 48084,
"end": 48392
} | class ____:
_argnames: tuple[str, ...] = ()
def __getattr__(self, attr):
try:
return self.args[self._argnames.index(attr)]
except ValueError:
raise AttributeError("'%s' object has no attribute '%s'" % (
type(self).__name__, attr))
| NamedArgsMixin |
python | mlflow__mlflow | tests/sagemaker/mock/__init__.py | {
"start": 39151,
"end": 39833
} | class ____:
"""
Object representing a model description returned by SageMaker's
"DescribeModel" API: https://docs.aws.amazon.com/sagemaker/latest/dg/API_DescribeModel.html.
"""
def __init__(self, model, arn):
self.model = model
self.arn = arn
@property
def response_object(s... | ModelDescription |
python | MongoEngine__mongoengine | tests/test_datastructures.py | {
"start": 159,
"end": 425
} | class ____:
def __init__(self):
self._changed_fields = []
self._unset_fields = []
def _mark_as_changed(self, key):
self._changed_fields.append(key)
def _mark_as_unset(self, key):
self._unset_fields.append(key)
| DocumentStub |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 5452,
"end": 5651
} | class ____(SQLRole):
__slots__ = ()
_role_name = (
"Row returning expression such as a SELECT, a FROM clause, or an "
"INSERT/UPDATE/DELETE with RETURNING"
)
| ReturnsRowsRole |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 102279,
"end": 111370
} | class ____(test_util.TensorFlowTestCase):
def testClearsControlDependencies(self):
g = ops.Graph()
a_1 = _apply_op(g, "FloatOutput", [], [dtypes.float32])
a_2 = _apply_op(g, "FloatOutput", [], [dtypes.float32])
a_3 = _apply_op(g, "FloatOutput", [], [dtypes.float32])
a_4 = _apply_op(g, "FloatOutpu... | InitScopeTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.