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 | openai__openai-python | src/openai/resources/fine_tuning/jobs/jobs.py | {
"start": 17174,
"end": 33259
} | class ____(AsyncAPIResource):
@cached_property
def checkpoints(self) -> AsyncCheckpoints:
return AsyncCheckpoints(self._client)
@cached_property
def with_raw_response(self) -> AsyncJobsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
... | AsyncJobs |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 61354,
"end": 66463
} | class ____(_CreateBase):
_id = "create_from_blueprint"
_inputs = [("target", AddressT())]
_kwargs = {
"value": KwargSettings(UINT256_T, zero_value),
"salt": KwargSettings(BYTES32_T, empty_value),
"raw_args": KwargSettings(BoolT(), False, require_literal=True),
"code_offset": ... | CreateFromBlueprint |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 167305,
"end": 171688
} | class ____:
def test_singles_mk(self):
assert self.locale._format_timeframe("second", 1) == "bir soniya"
assert self.locale._format_timeframe("minute", 1) == "bir daqiqa"
assert self.locale._format_timeframe("hour", 1) == "bir soat"
assert self.locale._format_timeframe("day", 1) == "... | TestUzbekLocale |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 17358,
"end": 17617
} | class ____(_Multi2VecBase):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.MULTI2VEC_AWS, frozen=True, exclude=True
)
region: Optional[str]
model: Optional[str]
dimensions: Optional[int]
| _Multi2VecAWSConfig |
python | eventlet__eventlet | tests/isolated/patcher_existing_locks_exception.py | {
"start": 19,
"end": 306
} | class ____(dict):
def items(self):
raise Exception()
if __name__ == '__main__':
import threading
test_lock = threading.RLock()
test_lock.acquire()
baddict = BadDict(testkey='testvalue')
import eventlet
eventlet.monkey_patch()
print('pass')
| BadDict |
python | realpython__materials | solid-principles-python/app_dip.py | {
"start": 716,
"end": 810
} | class ____(DataSource):
def get_data(self):
return "Data from the database"
| Database |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 22389,
"end": 24802
} | class ____(object):
"""Check a given tensor against the numpy result."""
REF_TENSOR = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3)
REF_TENSOR_ALIGNED = np.arange(1, 97, dtype=np.float32).reshape(3, 4, 8)
def __init__(self, test, x, tensor_type=dtypes.int32, check_type_infer=True):
self.x_np = np.ar... | StridedSliceChecker |
python | nryoung__algorithms | tests/test_factorization.py | {
"start": 212,
"end": 444
} | class ____(unittest.TestCase):
def test_fermat(self):
x = random.randint(1, 100000000)
factors = fermat(x)
res = 1
for i in factors:
res *= i
self.assertEqual(x, res)
| TestFermat |
python | google__python-fire | fire/test_components.py | {
"start": 10526,
"end": 11723
} | class ____:
def double(self, number):
return 2 * number
@property
def prop(self):
raise ValueError('test')
def simple_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
@simple_decorator
def decorated_method(name='World'):
return 'Hel... | InvalidProperty |
python | kamyu104__LeetCode-Solutions | Python/maximal-range-that-each-element-is-maximum-in-it.py | {
"start": 42,
"end": 485
} | class ____(object):
def maximumLengthOfRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [0]*len(nums)
stk = [-1]
nums.append(float("inf"))
for i, x in enumerate(nums):
while stk[-1] != -1 and nums[stk[-1]] < x:
... | Solution |
python | ansible__ansible | lib/ansible/executor/play_iterator.py | {
"start": 5093,
"end": 33268
} | class ____:
def __init__(self, inventory, play, play_context, variable_manager, all_vars, start_at_done=False):
self._play = play
self._blocks = []
self._variable_manager = variable_manager
setup_block = Block(play=self._play)
# Gathering facts with run_once would copy the ... | PlayIterator |
python | Textualize__rich | rich/markdown.py | {
"start": 15712,
"end": 25839
} | class ____(JupyterMixin):
"""A Markdown renderable.
Args:
markup (str): A string containing markdown.
code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes.
justify (JustifyMethod, optional): Justify value for... | Markdown |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 30503,
"end": 46416
} | class ____(DataprocClusterTestBase):
def test_deprecation_warning(self):
with pytest.warns(AirflowProviderDeprecationWarning) as warnings:
op = DataprocCreateClusterOperator(
task_id=TASK_ID,
region=GCP_REGION,
project_id=GCP_PROJECT,
... | TestDataprocCreateClusterOperator |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore.py | {
"start": 21762,
"end": 22711
} | class ____(unittest.TestCase):
def test_resource_exhausted_info(self):
"""This is to test if helpful information is displayed when
the objects captured in trainable/training function are too
large and RESOURCES_EXHAUSTED error of gRPC is triggered."""
# generate some random data to ... | ResourceExhaustedTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/identity.py | {
"start": 3432,
"end": 9250
} | class ____(IdentityMap):
_dict: Dict[_IdentityKeyType[Any], InstanceState[Any]]
def __getitem__(self, key: _IdentityKeyType[_O]) -> _O:
state = cast("InstanceState[_O]", self._dict[key])
o = state.obj()
if o is None:
raise KeyError(key)
return o
def __contains__... | _WeakInstanceDict |
python | numba__numba | numba/tests/test_dyn_array.py | {
"start": 49348,
"end": 55791
} | class ____(MemoryLeakMixin, TestCase):
"""
Tests for np.stack().
"""
def _3d_arrays(self):
a = np.arange(24).reshape((4, 3, 2))
b = a + 10
c = (b + 10).copy(order='F')
d = (c + 10)[::-1]
e = (d + 10)[...,::-1]
return a, b, c, d, e
@contextlib.context... | TestNpStack |
python | joerick__pyinstrument | pyinstrument/renderers/speedscope.py | {
"start": 1978,
"end": 3075
} | class ____(json.JSONEncoder):
"""
Encoder class used by json.dumps to serialize the various
speedscope data classes.
"""
def default(self, o: Any) -> Any:
if isinstance(o, SpeedscopeFile):
return {
"$schema": o.schema,
"name": o.name,
... | SpeedscopeEncoder |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_describe.py | {
"start": 183,
"end": 16064
} | class ____:
def test_describe_bool_in_mixed_frame(self):
df = DataFrame(
{
"string_data": ["a", "b", "c", "d", "e"],
"bool_data": [True, True, False, False, False],
"int_data": [10, 20, 30, 40, 50],
}
)
# Integer data a... | TestDataFrameDescribe |
python | cherrypy__cherrypy | cherrypy/lib/locking.py | {
"start": 51,
"end": 239
} | class ____(object):
"""A representation of a never expiring object."""
def expired(self):
"""Communicate that the object hasn't expired."""
return False
| NeverExpires |
python | jazzband__django-oauth-toolkit | tests/test_client_credential.py | {
"start": 4064,
"end": 5912
} | class ____(BaseTest):
@classmethod
def setUpClass(cls):
cls.request_factory = RequestFactory()
super().setUpClass()
def test_extended_request(self):
token_request_data = {
"grant_type": "client_credentials",
}
auth_headers = get_basic_auth_header(self.app... | TestExtendedRequest |
python | django__django | django/core/paginator.py | {
"start": 552,
"end": 5160
} | class ____:
# Translators: String used to replace omitted page numbers in elided page
# range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10].
ELLIPSIS = _("…")
default_error_messages = {
"invalid_page": _("That page number is not an integer"),
"min_page": _("That page num... | BasePaginator |
python | django__django | tests/prefetch_related/tests.py | {
"start": 1065,
"end": 2139
} | class ____:
@classmethod
def setUpTestData(cls):
cls.book1 = Book.objects.create(title="Poems")
cls.book2 = Book.objects.create(title="Jane Eyre")
cls.book3 = Book.objects.create(title="Wuthering Heights")
cls.book4 = Book.objects.create(title="Sense and Sensibility")
cl... | TestDataMixin |
python | pytorch__pytorch | torch/export/_safeguard.py | {
"start": 158,
"end": 1956
} | class ____(TorchFunctionMode):
"""
Detect grad state ops during exporting the graph and fail the process by
raising an error, to avoid unexpected behavior. Those grad mode ops could be:
`torch.no_grad`
`torch.enable_grad`
`torch.set_grad_enabled`
Export with predispatch mode is exempted.
... | AutogradStateOpsFailSafeguard |
python | kamyu104__LeetCode-Solutions | Python/cat-and-mouse-ii.py | {
"start": 3035,
"end": 6470
} | class ____(object):
def canMouseWin(self, grid, catJump, mouseJump):
"""
:type grid: List[str]
:type catJump: int
:type mouseJump: int
:rtype: bool
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
DRAW, MOUSE, CAT = range(3)
def parents(m, c... | Solution2 |
python | astropy__astropy | astropy/io/ascii/fastbasic.py | {
"start": 12634,
"end": 16272
} | class ____(FastBasic):
"""
A faster version of the :class:`Rdb` reader. This format is similar to
tab-delimited, but it also contains a header line after the column
name line denoting the type of each column (N for numeric, S for string).
"""
_format_name = "fast_rdb"
_description = "Tab-se... | FastRdb |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 39589,
"end": 41166
} | class ____(SineCosineTypeTransform):
"""
Class representing unevaluated sine transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute sine transforms, see the :func:`sine_transform`
docstring.
"""
_name = 'Sine'
_kern = sin
def a(self)... | SineTransform |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 85206,
"end": 87880
} | class ____(Request):
"""
Archive tasks.
If a task is queued it will first be dequeued and then archived.
:param tasks: List of task ids
:type tasks: Sequence[str]
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding ... | ArchiveRequest |
python | django__django | tests/string_lookup/models.py | {
"start": 31,
"end": 158
} | class ____(models.Model):
name = models.CharField(max_length=50)
friend = models.CharField(max_length=50, blank=True)
| Foo |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 34820,
"end": 35061
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("nl_NL")
Faker.seed(0)
def test_vat_id(self):
for _ in range(100):
assert re.search(r"^NL\d{9}B\d{2}$", self.fake.vat_id())
| TestNlNL |
python | walkccc__LeetCode | solutions/2008. Maximum Earnings From Taxi/2008-2.py | {
"start": 0,
"end": 505
} | class ____:
def maxTaxiEarnings(self, n: int, rides: list[list[int]]) -> int:
endToStartAndEarns = [[] for _ in range(n + 1)]
# dp[i] := the maximum dollars you can earn starting at i
dp = [0] * (n + 1)
for start, end, tip in rides:
earn = end - start + tip
endToStartAndEarns[end].append(... | Solution |
python | falconry__falcon | falcon/util/deprecation.py | {
"start": 927,
"end": 1218
} | class ____(AttributeError):
"""A deprecated attribute, class, or function has been subsequently removed."""
# NOTE(kgriffs): We don't want our deprecations to be ignored by default,
# so create our own type.
#
# TODO(kgriffs): Revisit this decision if users complain.
| AttributeRemovedError |
python | google__pytype | pytype/overlays/typing_overlay.py | {
"start": 15130,
"end": 17462
} | class ____(abstract.PyTDFunction):
"""Implementation of typing.NewType as a function."""
def __init__(self, name, signatures, kind, decorators, ctx):
super().__init__(name, signatures, kind, decorators, ctx)
assert len(self.signatures) == 1, "NewType has more than one signature."
signature = self.signa... | NewType |
python | doocs__leetcode | solution/0900-0999/0994.Rotting Oranges/Solution.py | {
"start": 0,
"end": 893
} | class ____:
def orangesRotting(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
cnt = 0
q = deque()
for i, row in enumerate(grid):
for j, x in enumerate(row):
if x == 2:
q.append((i, j))
elif x == 1:
... | Solution |
python | davidhalter__parso | parso/python/tree.py | {
"start": 8414,
"end": 8621
} | class ____(PythonLeaf):
"""
f-strings contain f-string expressions and normal python strings. These are
the string parts of f-strings.
"""
type = 'fstring_end'
__slots__ = ()
| FStringEnd |
python | pytorch__pytorch | torch/_inductor/runtime/caching/exceptions.py | {
"start": 957,
"end": 1581
} | class ____(SystemError):
"""Error raised when a lock operation times out.
This exception is raised when a lock operation exceeds the specified timeout
limit, indicating that the lock could not be acquired within the allotted time.
"""
def __init__(self, lock: Lock, timeout: float) -> None:
... | LockTimeoutError |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 57854,
"end": 59154
} | class ____(Response):
"""
Response of queues.move_task_to_back endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_to_back"
_version = "2.9"
_schem... | MoveTaskToBackResponse |
python | django__django | tests/decorators/test_common.py | {
"start": 196,
"end": 1311
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = no_append_slash(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_is_cor... | NoAppendSlashTests |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/agent_action.py | {
"start": 293,
"end": 7189
} | class ____(NamedTuple):
"""
A NamedTuple containing the tensor for continuous actions and list of tensors for
discrete actions. Utility functions provide numpy <=> tensor conversions to be
sent as actions to the environment manager as well as used by the optimizers.
:param continuous_tensor: Torch t... | AgentAction |
python | GoogleCloudPlatform__python-docs-samples | speech/microphone/transcribe_streaming_mic_test.py | {
"start": 834,
"end": 2683
} | class ____:
def __init__(self: object, audio_filename: str) -> None:
self.audio_filename = audio_filename
def __call__(self: object, *args: object) -> object:
return self
def open(
self: object,
stream_callback: object,
rate: int,
*args: object,
**kw... | MockPyAudio |
python | joke2k__faker | faker/providers/job/bs_BA/__init__.py | {
"start": 204,
"end": 175211
} | class ____(BaseProvider):
jobs = [
"Аdministrаtivni pоmоćnik u mеdicinskој оrdinаciјi",
"Administrativni službenik",
"Administrator",
"Administrator baza podataka",
"Administrator obrade podataka",
"Administrator područne računarske mreže",
"Advokat",
... | Provider |
python | spack__spack | lib/spack/spack/vendor/macholib/MachOStandalone.py | {
"start": 328,
"end": 374
} | class ____(MissingMachO):
pass
| ExcludedMachO |
python | sympy__sympy | sympy/functions/special/error_functions.py | {
"start": 19347,
"end": 23295
} | class ____(DefinedFunction):
r"""
Two-argument error function.
Explanation
===========
This function is defined as:
.. math ::
\mathrm{erf2}(x, y) = \frac{2}{\sqrt{\pi}} \int_x^y e^{-t^2} \mathrm{d}t
Examples
========
>>> from sympy import oo, erf2
>>> from sympy.abc... | erf2 |
python | celery__celery | t/unit/tasks/test_tasks.py | {
"start": 30263,
"end": 53923
} | class ____(TasksCase):
def now(self):
return self.app.now()
def test_typing(self):
@self.app.task()
def add(x, y, kw=1):
pass
with pytest.raises(TypeError):
add.delay(1)
with pytest.raises(TypeError):
add.delay(1, kw=2)
wit... | test_tasks |
python | openai__openai-python | src/openai/types/evals/run_create_params.py | {
"start": 12557,
"end": 13579
} | class ____(TypedDict, total=False):
source: Required[DataSourceCreateEvalResponsesRunDataSourceSource]
"""Determines what populates the `item` namespace in this run's data source."""
type: Required[Literal["responses"]]
"""The type of run data source. Always `responses`."""
input_messages: DataSou... | DataSourceCreateEvalResponsesRunDataSource |
python | pypa__setuptools | setuptools/_vendor/jaraco/context.py | {
"start": 5735,
"end": 8312
} | class ____:
"""
A context manager that will catch certain exceptions and provide an
indication they occurred.
>>> with ExceptionTrap() as trap:
... raise Exception()
>>> bool(trap)
True
>>> with ExceptionTrap() as trap:
... pass
>>> bool(trap)
False
>>> with Ex... | ExceptionTrap |
python | huggingface__transformers | src/transformers/integrations/integration_utils.py | {
"start": 25646,
"end": 26419
} | class ____(str, Enum):
"""Enum of possible log model values in W&B."""
CHECKPOINT = "checkpoint"
END = "end"
FALSE = "false"
@property
def is_enabled(self) -> bool:
"""Check if the value corresponds to a state where the `WANDB_LOG_MODEL` setting is enabled."""
return self in (W... | WandbLogModel |
python | ray-project__ray | python/ray/train/lightgbm/v2.py | {
"start": 354,
"end": 5714
} | class ____(DataParallelTrainer):
"""A Trainer for distributed data-parallel LightGBM training.
Example
-------
.. testcode::
:skipif: True
import lightgbm as lgb
import ray.data
import ray.train
from ray.train.lightgbm import RayTrainReportCallback, LightGBMTr... | LightGBMTrainer |
python | huggingface__transformers | tests/models/aya_vision/test_modeling_aya_vision.py | {
"start": 1450,
"end": 5197
} | class ____:
def __init__(
self,
parent,
batch_size=3,
seq_length=7,
vision_feature_layer=-1,
downsample_factor=2,
ignore_index=-100,
bos_token_id=0,
eos_token_id=0,
pad_token_id=0,
image_token_index=2,
num_channels=3,
... | AyaVisionVisionText2TextModelTester |
python | TheAlgorithms__Python | data_structures/arrays/prefix_sum.py | {
"start": 139,
"end": 2571
} | class ____:
def __init__(self, array: list[int]) -> None:
len_array = len(array)
self.prefix_sum = [0] * len_array
if len_array > 0:
self.prefix_sum[0] = array[0]
for i in range(1, len_array):
self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
def g... | PrefixSum |
python | encode__httpx | tests/models/test_responses.py | {
"start": 86,
"end": 30023
} | class ____:
def __iter__(self):
yield b"Hello, "
yield b"world!"
def streaming_body() -> typing.Iterator[bytes]:
yield b"Hello, "
yield b"world!"
async def async_streaming_body() -> typing.AsyncIterator[bytes]:
yield b"Hello, "
yield b"world!"
def autodetect(content):
retur... | StreamingBody |
python | Textualize__textual | tests/test_app.py | {
"start": 794,
"end": 10677
} | class ____(App):
def compose(self) -> ComposeResult:
yield Input()
yield Button("Click me!")
async def test_hover_update_styles():
app = MyApp(ansi_color=False)
async with app.run_test() as pilot:
button = app.query_one(Button)
assert button.pseudo_classes == {
... | MyApp |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 27449,
"end": 27590
} | class ____(RayError):
"""Called when an object was not available within the given timeout."""
pass
@PublicAPI
| PlasmaObjectNotAvailable |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 77256,
"end": 79632
} | class ____(fixtures.MappedTest):
run_create_tables = None
@classmethod
def define_tables(cls, metadata):
Table("a", metadata, Column("id", Integer, primary_key=True))
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid",... | DictOfTupleUpdateTest |
python | numba__numba | numba/core/typing/mathdecl.py | {
"start": 2834,
"end": 3118
} | class ____(ConcreteTemplate):
cases = [
signature(types.boolean, types.int64),
signature(types.boolean, types.uint64),
signature(types.boolean, types.float32),
signature(types.boolean, types.float64),
]
@infer_global(math.isfinite)
| Math_predicate |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 13723,
"end": 14248
} | class ____(NamePathModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"RemovePath: {self.name}-{self.value}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator)
directories = [
path_to_os_path(os.... | RemovePath |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_strategy_test.py | {
"start": 50206,
"end": 54336
} | class ____(
multi_worker_test_base.MultiWorkerTestBase,
strategy_test_lib.DistributionTestBase):
def _configure_distribution_strategy(self, distribution):
cluster_spec = server_lib.ClusterSpec({
"worker": ["/job:worker/task:0", "/job:worker/task:1"]
})
distribution.configure(cluster_spec=... | MultiWorkerMirroredStrategyTest |
python | mlflow__mlflow | dev/clint/tests/rules/test_redundant_test_docstring.py | {
"start": 1859,
"end": 2262
} | class ____:
"""This is a longer docstring than the class name TestShort."""
pass
'''
config = Config(select={RedundantTestDocstring.name})
violations = lint_file(Path("test_classes.py"), code, config, index_path)
assert len(violations) == 1
def test_non_test_files_are_ignored(index_path: Path) ->... | TestShort |
python | django__django | tests/db_functions/models.py | {
"start": 1542,
"end": 1723
} | class ____(models.Model):
n1 = models.DecimalField(decimal_places=2, max_digits=6)
n2 = models.DecimalField(decimal_places=7, max_digits=9, null=True, blank=True)
| DecimalModel |
python | huggingface__transformers | src/transformers/models/t5gemma/modular_t5gemma.py | {
"start": 54824,
"end": 60085
} | class ____(T5GemmaPreTrainedModel):
def __init__(self, config: T5GemmaConfig, is_encoder_decoder: Optional[bool] = None):
r"""
is_encoder_decoder (`Optional`, *optional*):
Whether use encoder_decoder for token classification. When set to False, only encoder is used.
"""
i... | T5GemmaForTokenClassification |
python | graphql-python__graphene | graphene/utils/subclass_with_meta.py | {
"start": 299,
"end": 1616
} | class ____(metaclass=SubclassWithMeta_Meta):
"""This class improves __init_subclass__ to receive automatically the options from meta"""
def __init_subclass__(cls, **meta_options):
"""This method just terminates the super() chain"""
_Meta = getattr(cls, "Meta", None)
_meta_props = {}
... | SubclassWithMeta |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 285243,
"end": 286195
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of RequestReviews"""
__schema__ = github_schema
__field_names__ = ("pull_request_id", "user_ids", "team_ids", "union", "client_mutation_id")
pull_request_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="pullRequestId")
"""The ... | RequestReviewsInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_transactions.py | {
"start": 9331,
"end": 14953
} | class ____(TestCase):
@HttpMocker()
def test_given_no_state_when_read_then_use_transactions_endpoint(self, http_mocker: HttpMocker) -> None:
cursor_value = int(_A_START_DATE.timestamp()) + 1
http_mocker.get(
_transactions_request().with_created_gte(_A_START_DATE).with_created_lte(_NO... | IncrementalTest |
python | huggingface__transformers | src/transformers/models/donut/modeling_donut_swin.py | {
"start": 21970,
"end": 22600
} | class ____(nn.Module):
def __init__(self, config, dim):
super().__init__()
self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = con... | DonutSwinIntermediate |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 21962,
"end": 25091
} | class ____(BaseModel, extra="forbid"):
"""
Operation for creating new collection and (optionally) specify index params
"""
vectors: Optional["VectorsConfig"] = Field(
default=None, description="Operation for creating new collection and (optionally) specify index params"
)
shard_number: ... | CreateCollection |
python | getsentry__sentry | tests/sentry/deletions/tasks/test_overwatch.py | {
"start": 313,
"end": 11274
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization_id = 12345
self.organization_slug = "test-org"
# Mock region
self.mock_region = MagicMock()
self.mock_region.name = "us"
@override_settings(
OVERWATCH_WEBHOOK_SECRET="test-s... | NotifyOverwatchOrganizationDeletedTest |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/sglang_engine_stage.py | {
"start": 2687,
"end": 7774
} | class ____:
"""Wrapper around the SGLang engine to handle async requests.
Args:
*args: The positional arguments for the engine.
max_pending_requests: The maximum number of pending requests in the queue.
**kwargs: The keyword arguments for the engine.
"""
def __init__(
s... | SGLangEngineWrapper |
python | django-haystack__django-haystack | test_haystack/test_app_loading.py | {
"start": 2074,
"end": 2356
} | class ____(TestCase):
# Confirm that everything works if an app is enabled
def test_simple_view(self):
url = reverse("app-without-models:simple-view")
resp = self.client.get(url)
self.assertEqual(resp.content.decode("utf-8"), "OK")
| AppWithoutModelsTests |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 13676,
"end": 15144
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = ElectraCrossAttention if is_cross_attention else ElectraSelfAttention
self.self = attention_... | ElectraAttention |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP050.py | {
"start": 291,
"end": 329
} | class ____(A, metaclass=type):
...
| B |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 19805,
"end": 21306
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.n_relations = config.n_relations
self.backbone_hidden_size = config.hidden_size
self.head_hidden_size = config.hidden_size
self.classifier_dropout_prob = config.classifier_dropout_prob
self.dr... | BrosRelationExtractor |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 544761,
"end": 545398
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("PushAllowanceEdge"), graphql_name="edges"
)
nodes = sgqlc... | PushAllowanceConnection |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 5073,
"end": 7478
} | class ____(StaticFilesTestCase):
def test_location_empty(self):
msg = "without having set the STATIC_ROOT setting to a filesystem path"
err = StringIO()
for root in ["", None]:
with override_settings(STATIC_ROOT=root):
with self.assertRaisesMessage(ImproperlyConfi... | TestConfiguration |
python | bokeh__bokeh | src/bokeh/plotting/contour.py | {
"start": 3431,
"end": 10495
} | class ____:
''' Complete geometry data for filled polygons and/or contour lines over a
whole sequence of contour levels.
:func:`~bokeh.plotting.contour.contour_data` returns an object of
this class that can then be passed to :func:`bokeh.models.ContourRenderer.set_data`.
'''
fill_data: FillData... | ContourData |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image21.py | {
"start": 315,
"end": 886
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image21.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/regnet/modeling_regnet.py | {
"start": 6945,
"end": 7781
} | class ____(nn.Module):
"""
A RegNet stage composed by stacked layers.
"""
def __init__(
self,
config: RegNetConfig,
in_channels: int,
out_channels: int,
stride: int = 2,
depth: int = 2,
):
super().__init__()
layer = RegNetXLayer if co... | RegNetStage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 156030,
"end": 156467
} | class ____(sgqlc.types.Input):
"""The filters that are available when fetching check suites."""
__schema__ = github_schema
__field_names__ = ("app_id", "check_name")
app_id = sgqlc.types.Field(Int, graphql_name="appId")
"""Filters the check suites created by this application ID."""
check_name ... | CheckSuiteFilter |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py | {
"start": 300,
"end": 3802
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
team: Team | None = Relationship(back_popula... | Hero |
python | psf__requests | tests/test_utils.py | {
"start": 8295,
"end": 8688
} | class ____:
def test_valid(self):
assert is_valid_cidr("192.168.1.0/24")
@pytest.mark.parametrize(
"value",
(
"8.8.8.8",
"192.168.1.0/a",
"192.168.1.0/128",
"192.168.1.0/-1",
"192.168.1.999/24",
),
)
def test_in... | TestIsValidCIDR |
python | jazzband__django-pipeline | pipeline/compilers/livescript.py | {
"start": 87,
"end": 625
} | class ____(SubProcessCompiler):
output_extension = "js"
def match_file(self, path):
return path.endswith(".ls")
def compile_file(self, infile, outfile, outdated=False, force=False):
if not outdated and not force:
return # File doesn't need to be recompiled
command = (
... | LiveScriptCompiler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes11.py | {
"start": 564,
"end": 648
} | class ____(Sequence[float], Mapping[int, int]): ...
# This should generate an error.
| E |
python | aio-libs__aiohttp | examples/combined_middleware.py | {
"start": 2836,
"end": 4627
} | class ____:
"""Middleware that retries failed requests with exponential backoff."""
def __init__(
self,
max_retries: int = 3,
retry_statuses: set[HTTPStatus] | None = None,
initial_delay: float = 1.0,
backoff_factor: float = 2.0,
) -> None:
self.max_retries =... | RetryMiddleware |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_background07.py | {
"start": 315,
"end": 1210
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("background07.xlsx")
self.ignore_elements = {"xl/worksheets/sheet1.xml": ["<pageSetup"]}
def test_create_file(self):
"""Test the cre... | TestCompareXLSXFiles |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1409198,
"end": 1420913
} | class ____(VegaLiteSchema):
"""
TitleConfig schema wrapper.
Parameters
----------
align : :class:`Align`, Literal['left', 'center', 'right']
Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or
``"right"``.
anchor : dict, :class:`ExprRef`, :class:`TitleA... | TitleConfig |
python | ray-project__ray | python/ray/tests/test_autoscaler_fake_scaledown.py | {
"start": 254,
"end": 6340
} | class ____:
def __init__(self):
self.data = []
def f(self):
pass
def recv(self, obj):
pass
def create(self, size):
return np.zeros(size)
# Tests that we scale down even if secondary copies of objects are present on
# idle nodes: https://github.com/ray-project/ray/iss... | Actor |
python | numba__llvmlite | llvmlite/ir/_utils.py | {
"start": 1196,
"end": 1433
} | class ____(object):
def get_reference(self):
try:
return self.__cached_refstr
except AttributeError:
s = self.__cached_refstr = self._get_reference()
return s
| _StringReferenceCaching |
python | ray-project__ray | python/ray/serve/tests/test_config_files/broken_app.py | {
"start": 57,
"end": 554
} | class ____(Exception):
"""This exception cannot be serialized."""
def __reduce__(self):
raise RuntimeError("This exception cannot be serialized!")
# Confirm that NonserializableException cannot be serialized.
try:
pickle.dumps(NonserializableException())
except RuntimeError as e:
assert "This... | NonserializableException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass9.py | {
"start": 557,
"end": 689
} | class ____(metaclass=Meta1, param1="", param2=""): ...
# This should generate an error because param1 and param2 are missing.
| Class1_3 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gnews/components.py | {
"start": 369,
"end": 1006
} | class ____(BackoffStrategy):
"""
Backoff strategy that waits until next midnight
"""
parameters: InitVar[Mapping[str, Any]]
config: Config
def backoff_time(
self, response_or_exception: Optional[Union[requests.Response, requests.RequestException]], attempt_count: int
) -> Optional[... | WaitUntilMidnightBackoffStrategy |
python | scikit-learn__scikit-learn | sklearn/frozen/_frozen.py | {
"start": 623,
"end": 5015
} | class ____(BaseEstimator):
"""Estimator that wraps a fitted estimator to prevent re-fitting.
This meta-estimator takes an estimator and freezes it, in the sense that calling
`fit` on it has no effect. `fit_predict` and `fit_transform` are also disabled.
All other methods are delegated to the original e... | FrozenEstimator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 3954,
"end": 4216
} | class ____(sgqlc.types.Enum):
"""The possible types of check runs.
Enumeration Choices:
* `ALL`: Every check run available.
* `LATEST`: The latest check run.
"""
__schema__ = github_schema
__choices__ = ("ALL", "LATEST")
| CheckRunType |
python | realpython__materials | python-enum/roles.py | {
"start": 187,
"end": 482
} | class ____(Flag):
OWNER = 8
POWER_USER = 4
USER = 2
SUPERVISOR = 1
ADMIN = OWNER | POWER_USER | USER | SUPERVISOR
john = Role.USER | Role.SUPERVISOR
if Role.USER in john:
print("John, you're a user")
if Role.SUPERVISOR in john:
print("John, you're a supervisor")
| Role |
python | django__django | django/db/migrations/state.py | {
"start": 24921,
"end": 25490
} | class ____(AppConfig):
"""Stub of an AppConfig. Only provides a label and a dict of models."""
def __init__(self, label):
self.apps = None
self.models = {}
# App-label and app-name are not the same thing, so technically passing
# in the label here is wrong. In practice, migratio... | AppConfigStub |
python | doocs__leetcode | solution/2400-2499/2432.The Employee That Worked on the Longest Task/Solution.py | {
"start": 0,
"end": 285
} | class ____:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
last = mx = ans = 0
for uid, t in logs:
t -= last
if mx < t or (mx == t and ans > uid):
ans, mx = uid, t
last += t
return ans
| Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 76054,
"end": 77545
} | class ____(TestCase):
def test_simple(self):
assert_almost_equal(i0(0.5), np.array(1.0634833707413234))
# need at least one test above 8, as the implementation is piecewise
A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0])
expected = np.array(
[1.0630782... | Test_I0 |
python | wandb__wandb | wandb/vendor/pygments/lexers/ecl.py | {
"start": 440,
"end": 5875
} | class ____(RegexLexer):
"""
Lexer for the declarative big-data `ECL
<http://hpccsystems.com/community/docs/ecl-language-reference/html>`_
language.
.. versionadded:: 1.5
"""
name = 'ECL'
aliases = ['ecl']
filenames = ['*.ecl']
mimetypes = ['application/x-ecl']
flags = re.I... | ECLLexer |
python | gevent__gevent | src/greentest/3.11/test_signal.py | {
"start": 442,
"end": 2647
} | class ____(unittest.TestCase):
def test_enums(self):
for name in dir(signal):
sig = getattr(signal, name)
if name in {'SIG_DFL', 'SIG_IGN'}:
self.assertIsInstance(sig, signal.Handlers)
elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}:
... | GenericTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/feature_store.py | {
"start": 12539,
"end": 16842
} | class ____(GoogleCloudBaseOperator, OperationHelper):
"""
Create request for Feature View creation.
This method initiates VertexAI Feature View request for the existing Feature Online Store.
Feature View represents features and data according to the source provided.
:param feature_view_id: The ID ... | CreateFeatureViewOperator |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/base_selector.py | {
"start": 421,
"end": 531
} | class ____(BaseModel):
"""A single selection of a choice."""
index: int
reason: str
| SingleSelection |
python | ethereum__web3.py | web3/_utils/events.py | {
"start": 15557,
"end": 15820
} | class ____(BaseArgumentFilter):
# type ignore b/c conflict with BaseArgumentFilter.match_values type
@property
def match_values(self) -> tuple[TypeStr, tuple[Any, ...]]: # type: ignore
return self.arg_type, self._match_values
| DataArgumentFilter |
python | django__django | tests/serializers/models/data.py | {
"start": 999,
"end": 1108
} | class ____(models.Model):
data = models.DecimalField(null=True, decimal_places=3, max_digits=5)
| DecimalData |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.