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 | py-pdf__pypdf | pypdf/annotations/_markup_annotations.py | {
"start": 8064,
"end": 8738
} | class ____(MarkupAnnotation):
def __init__(
self,
rect: Union[RectangleObject, tuple[float, float, float, float]],
*,
interior_color: Optional[str] = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.update(
{
Nam... | Ellipse |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 4076,
"end": 4616
} | class ____(OpenAIError):
completion: ChatCompletion
"""The completion that caused this error.
Note: this will *not* be a complete `ChatCompletion` object when streaming as `usage`
will not be included.
"""
def __init__(self, *, completion: ChatCompletion) -> None:
msg = "Could no... | LengthFinishReasonError |
python | conda__conda | conda/gateways/connection/adapters/localfs.py | {
"start": 532,
"end": 1821
} | class ____(BaseAdapter):
def send(
self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None
):
pathname = url_to_path(request.url)
resp = Response()
resp.status_code = 200
resp.url = request.url
try:
stats = stat(pathname)
... | LocalFSAdapter |
python | coleifer__peewee | tests/regressions.py | {
"start": 31460,
"end": 32134
} | class ____(ModelTestCase):
requires = [User]
def tearDown(self):
try:
self.execute('drop view user_testview_fm')
except Exception as exc:
pass
super(TestViewFieldMapping, self).tearDown()
def test_view_field_mapping(self):
user = User.create(username... | TestViewFieldMapping |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 15943,
"end": 16913
} | class ____:
op: str
group: str
description: str | None
frequency: int | None
count: int | None
avg_occurrences: float | None
sum_exclusive_time: float | None
p50_exclusive_time: float | None
p75_exclusive_time: float | None
p95_exclusive_time: float | None
p99_exclusive_time:... | SuspectSpan |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 10117,
"end": 10228
} | class ____(OpcodeWithArg): # Arg: Number of tuple items
_FLAGS = HAS_ARGUMENT
__slots__ = ()
| UNPACK_SEQUENCE |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 168748,
"end": 168922
} | class ____(SendrecvmsgConnectedBase,
ConnectedStreamTestMixin, TCPTestBase):
pass
@requireAttrs(socket.socket, "sendmsg")
| SendrecvmsgTCPTestBase |
python | facebook__pyre-check | tools/upgrade/commands/expand_target_coverage.py | {
"start": 676,
"end": 4357
} | class ____(ErrorSuppressingCommand):
def __init__(
self,
command_arguments: CommandArguments,
*,
repository: Repository,
local_configuration: Optional[str],
fixme_threshold: bool,
target_prefix: str,
) -> None:
super().__init__(command_arguments, r... | ExpandTargetCoverage |
python | getsentry__sentry | src/sentry/hybridcloud/models/webhookpayload.py | {
"start": 571,
"end": 689
} | class ____(TextChoices):
SENTRY_REGION = "sentry_region"
CODECOV = "codecov"
@control_silo_model
| DestinationType |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 1598,
"end": 4462
} | class ____(nn.Module):
def forward(
self,
value: Tensor,
value_spatial_shapes: Tensor,
value_spatial_shapes_list: list[tuple],
level_start_index: Tensor,
sampling_locations: Tensor,
attention_weights: Tensor,
im2col_step: int,
):
batch_size... | MultiScaleDeformableAttention |
python | tensorflow__tensorflow | tensorflow/python/framework/tensor.py | {
"start": 30812,
"end": 42689
} | class ____(DenseSpec, type_spec.BatchableTypeSpec,
trace_type.Serializable, internal.TensorSpec):
"""Describes the type of a tf.Tensor.
>>> t = tf.constant([[1,2,3],[4,5,6]])
>>> tf.TensorSpec.from_tensor(t)
TensorSpec(shape=(2, 3), dtype=tf.int32, name=None)
Contains metadata for describin... | TensorSpec |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_message_bus.py | {
"start": 9021,
"end": 12178
} | class ____:
"""Test integration scenarios and edge cases."""
@pytest.mark.asyncio
async def test_multiple_messages_processing(self):
"""Test processing multiple messages in sequence."""
with patch("airflow.providers.microsoft.azure.triggers.message_bus.MessageHook"):
trigger = A... | TestIntegrationScenarios |
python | catalyst-team__catalyst | catalyst/loggers/wandb.py | {
"start": 301,
"end": 6295
} | class ____(ILogger):
"""Wandb logger for parameters, metrics, images and other artifacts.
W&B documentation: https://docs.wandb.com
Args:
Project: Name of the project in W&B to log to.
name: Name of the run in W&B to log to.
config: Configuration Dictionary for the experiment.
... | WandbLogger |
python | scipy__scipy | scipy/io/_fortran.py | {
"start": 561,
"end": 737
} | class ____(TypeError, OSError):
"""Indicates that the file ended mid-record.
Descends from TypeError for backward compatibility.
"""
pass
| FortranFormattingError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF066.py | {
"start": 510,
"end": 1185
} | class ____(metaclass=abc.ABCMeta): # Test properies inside of an ABC class
@property
@abc.abstractmethod
def abstr_prop1(self): ... # OK: Abstract methods doesn't need to return anything
@property
@abc.abstractmethod
def abstr_prop2(self): # OK: Abstract methods doesn't need to return anythi... | UserMeta |
python | streamlit__streamlit | lib/streamlit/elements/widgets/radio.py | {
"start": 2623,
"end": 16250
} | class ____:
@overload
def radio(
self,
label: str,
options: Sequence[Never],
index: int = 0,
format_func: Callable[[Any], Any] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs... | RadioMixin |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_fetchers.py | {
"start": 9106,
"end": 9246
} | class ____:
def __init__(self, val: Any) -> None:
self.val = val
def wait(self) -> Any:
return self.val
| DummyWaitable |
python | modin-project__modin | modin/config/envvars.py | {
"start": 26892,
"end": 28051
} | class ____(EnvironmentVariable, type=int):
"""How many partitions to use for a Modin DataFrame (along each axis)."""
varname = "MODIN_NPARTITIONS"
@classmethod
def _put(cls, value: int) -> None:
"""
Put specific value if NPartitions wasn't set by a user yet.
Parameters
... | NPartitions |
python | huggingface__transformers | src/transformers/models/xglm/modeling_xglm.py | {
"start": 24373,
"end": 28972
} | class ____(XGLMPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = XGLMModel(config)
self.lm_head = nn.Linear(config.hidden_size, config.... | XGLMForCausalLM |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/analytics_admin.py | {
"start": 10988,
"end": 14077
} | class ____(GoogleCloudBaseOperator):
"""
Creates Data stream.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleAnalyticsAdminCreateDataStreamOperator`
:param property_id: ID of the parent property for the data stream.
... | GoogleAnalyticsAdminCreateDataStreamOperator |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 13317,
"end": 13628
} | class ____(ODE):
r"""Integrate 1/(t + 1j) from t=-10 to t=10"""
stop_t = 20
z0 = [0]
cmplx = True
def f(self, z, t):
return array([1./(t - 10 + 1j)])
def verify(self, zs, t):
u = -2j * np.arctan(10)
return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol)
| Pi |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol32.py | {
"start": 492,
"end": 841
} | class ____(Generic[Arg, Value]):
def method1(self, default: Value) -> Value:
return default
def method2(self, default: Value) -> Value:
return default
def another(self, arg: Arg) -> None:
return
def func1(arg: Arg, value: Value) -> Interface[Arg, Value]:
return Implementation... | Implementation1 |
python | mlflow__mlflow | mlflow/server/graphql/graphql_errors.py | {
"start": 18,
"end": 221
} | class ____(graphene.ObjectType):
# NOTE: This is not an exhaustive list, might need to add more things in the future if needed.
field = graphene.String()
message = graphene.String()
| ErrorDetail |
python | huggingface__transformers | tests/models/colpali/test_processing_colpali.py | {
"start": 1105,
"end": 12379
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = ColPaliProcessor
@classmethod
def _setup_tokenizer(cls):
return GemmaTokenizer(SAMPLE_VOCAB, keep_accents=True)
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from... | ColPaliProcessorTest |
python | geekcomputers__Python | brickout-game/brickout-game.py | {
"start": 779,
"end": 2643
} | class ____(object):
def __init__(self, screen, radius, x, y):
self.__screen = screen
self._radius = radius
self._xLoc = x
self._yLoc = y
self.__xVel = 7
self.__yVel = 2
w, h = pygame.display.get_surface().get_size()
self.__width = w
self.__heig... | Ball |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax.py | {
"start": 1338,
"end": 1533
} | class ____(typing.TypedDict):
my_var: int | str
# Check dataclasses
def my_decorator(*args, **kwargs):
def wraps(*args, **kwargs):
pass
return wraps
@dataclass
| CustomTypedDict4 |
python | pypa__warehouse | warehouse/packaging/models.py | {
"start": 31470,
"end": 31737
} | class ____(str, enum.Enum):
bdist_dmg = "bdist_dmg"
bdist_dumb = "bdist_dumb"
bdist_egg = "bdist_egg"
bdist_msi = "bdist_msi"
bdist_rpm = "bdist_rpm"
bdist_wheel = "bdist_wheel"
bdist_wininst = "bdist_wininst"
sdist = "sdist"
| PackageType |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_tool_result_block_param.py | {
"start": 466,
"end": 827
} | class ____(TypedDict, total=False):
content: Required[BetaCodeExecutionToolResultBlockParamContentParam]
tool_use_id: Required[str]
type: Required[Literal["code_execution_tool_result"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content bl... | BetaCodeExecutionToolResultBlockParam |
python | Farama-Foundation__Gymnasium | gymnasium/vector/async_vector_env.py | {
"start": 1102,
"end": 1307
} | class ____(Enum):
"""The AsyncVectorEnv possible states given the different actions."""
DEFAULT = "default"
WAITING_RESET = "reset"
WAITING_STEP = "step"
WAITING_CALL = "call"
| AsyncState |
python | realpython__materials | python-self-type/accounts.py | {
"start": 618,
"end": 1605
} | class ____(BankAccount):
interest_rate: float
@classmethod
def from_application(
cls, deposit: float = 0, interest_rate: float = 1
) -> Self:
# Generate a random seven-digit bank account number
account_number = random.randint(1000000, 9999999)
return cls(account_number, ... | SavingsAccount |
python | pdm-project__pdm | src/pdm/cli/hooks.py | {
"start": 164,
"end": 1469
} | class ____:
def __init__(self, project: Project, skip: list[str] | None = None):
self.project = project
self.skip = skip or []
@contextlib.contextmanager
def skipping(self, *names: str) -> Generator[None]:
"""
Temporarily skip some hooks.
"""
old_skip = self.... | HookManager |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 8597,
"end": 8912
} | class ____(TypedDict, total=False):
summary: Optional[str]
description: Optional[str]
value: Optional[Any]
externalValue: Optional[AnyUrl]
if PYDANTIC_V2: # type: ignore [misc]
__pydantic_config__ = {"extra": "allow"}
else:
class Config:
extra = "allow"
| Example |
python | numba__llvmlite | versioneer.py | {
"start": 36877,
"end": 40346
} | class ____(Command):
description = ("install/upgrade Versioneer files: "
"__init__.py SRC/_version.py")
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
print(" creating %s" % v... | cmd_update_files |
python | tiangolo__fastapi | docs_src/body_nested_models/tutorial008.py | {
"start": 112,
"end": 273
} | class ____(BaseModel):
url: HttpUrl
name: str
@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):
return images
| Image |
python | doocs__leetcode | solution/2800-2899/2852.Sum of Remoteness of All Cells/Solution.py | {
"start": 0,
"end": 756
} | class ____:
def sumRemoteness(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> (int, int):
s, t = grid[i][j], 1
grid[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] > 0:
... | Solution |
python | sympy__sympy | sympy/core/symbol.py | {
"start": 14086,
"end": 16132
} | class ____(Symbol):
"""Dummy symbols are each unique, even if they have the same name:
Examples
========
>>> from sympy import Dummy
>>> Dummy("x") == Dummy("x")
False
If a name is not supplied then a string value of an internal count will be
used. This is useful when a temporary vari... | Dummy |
python | gevent__gevent | src/gevent/select.py | {
"start": 7973,
"end": 13582
} | class ____(object):
"""
An implementation of :obj:`select.poll` that blocks only the current greenlet.
With only one exception, the interface is the same as the standard library interface.
.. caution:: ``POLLPRI`` data is not supported.
.. versionadded:: 1.1b1
.. versionchanged:: 1.5
T... | poll |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_with_reference_param.py | {
"start": 263,
"end": 953
} | class ____(TypedDict, total=False):
id: str
"""
ID of a previous conversation item to reference (for `item_reference` content
types in `response.create` events). These can reference both client and server
created items.
"""
audio: str
"""Base64-encoded audio bytes, used for `input_audio... | Content |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_access.py | {
"start": 6993,
"end": 7302
} | class ____(OrganizationAccessMixin, TestCase):
"""Test organization paths with authed org owner."""
def login(self):
return self.client.login(username="eric", password="test")
def is_admin(self):
return True
@override_settings(RTD_ALLOW_ORGANIZATIONS=True)
| OrganizationOwnerAccess |
python | Lightning-AI__lightning | examples/pytorch/servable_module/production.py | {
"start": 2832,
"end": 4212
} | class ____(LitModule, ServableModule):
def configure_payload(self):
# 1: Access the train dataloader and load a single sample.
image, _ = self.trainer.train_dataloader.dataset[0]
# 2: Convert the image into a PIL Image to bytes and encode it with base64
pil_image = T.ToPILImage()(im... | ProductionReadyModel |
python | huggingface__transformers | src/transformers/models/ovis2/modular_ovis2.py | {
"start": 12783,
"end": 17176
} | class ____(LlavaForConditionalGeneration, GenerationMixin):
_checkpoint_conversion_mapping = {}
def __init__(self, config: Ovis2Config):
super().__init__(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
def get_image_features(self, pixel_values: torch.Flo... | Ovis2ForConditionalGeneration |
python | jazzband__django-polymorphic | src/polymorphic/admin/helpers.py | {
"start": 420,
"end": 727
} | class ____(InlineAdminForm):
"""
Expose the admin configuration for a form
"""
def polymorphic_ctype_field(self):
return AdminField(self.form, "polymorphic_ctype", False)
@property
def is_empty(self):
return "__prefix__" in self.form.prefix
| PolymorphicInlineAdminForm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 49283,
"end": 49789
} | class ____(sgqlc.types.Enum):
"""The default permission a repository can have in an Organization.
Enumeration Choices:
* `ADMIN`: Can read, clone, push, and add collaborators to
repositories.
* `NONE`: No default permission value.
* `READ`: Can read and clone repositories.
* `WRITE`: Can... | OrgUpdateDefaultRepositoryPermissionAuditEntryPermission |
python | pypa__hatch | backend/src/hatchling/plugin/manager.py | {
"start": 1669,
"end": 3396
} | class ____:
def __init__(self, registration_method: Callable, identifier: str, third_party_plugins: ThirdPartyPlugins) -> None:
self.registration_method = registration_method
self.identifier = identifier
self.third_party_plugins = third_party_plugins
def collect(self, *, include_third_p... | ClassRegister |
python | walkccc__LeetCode | solutions/144. Binary Tree Preorder Traversal/144.py | {
"start": 0,
"end": 296
} | class ____:
def preorderTraversal(self, root: TreeNode | None) -> list[int]:
ans = []
def preorder(root: TreeNode | None) -> None:
if not root:
return
ans.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ans
| Solution |
python | django__django | django/contrib/postgres/operations.py | {
"start": 3577,
"end": 3707
} | class ____(CreateExtension):
def __init__(self, hints=None):
super().__init__("unaccent", hints=hints)
| UnaccentExtension |
python | xlwings__xlwings | xlwings/_xlwindows.py | {
"start": 14559,
"end": 15581
} | class ____:
@property
def apps(self):
return Apps()
@property
def name(self):
return "excel"
@property
def type(self):
return "desktop"
@staticmethod
def prepare_xl_data_element(x, date_format):
if isinstance(x, time_types):
return _datetime... | Engine |
python | getsentry__sentry | tests/sentry/search/eap/test_uptime_results.py | {
"start": 542,
"end": 5867
} | class ____(TestCase):
def setUp(self) -> None:
self.resolver = SearchResolver(
params=SnubaParams(),
config=SearchResolverConfig(),
definitions=UPTIME_RESULT_DEFINITIONS,
)
def test_simple_query(self) -> None:
where, having, _ = self.resolver.resolve_... | SearchResolverQueryTest |
python | getsentry__sentry | src/sentry/backup/comparators.py | {
"start": 883,
"end": 6845
} | class ____(ABC):
"""An abstract class that compares and then scrubs some set of fields that, by a more nuanced
definition than mere strict byte-for-byte equality, are expected to maintain some relation on
otherwise equivalent JSON instances of the same model.
Each class inheriting from `JSONScrubbingCo... | JSONScrubbingComparator |
python | sphinx-doc__sphinx | sphinx/ext/inheritance_diagram.py | {
"start": 12530,
"end": 12658
} | class ____(graphviz):
"""A docutils node to use as a placeholder for the inheritance diagram."""
pass
| inheritance_diagram |
python | numba__numba | numba/core/ir.py | {
"start": 32236,
"end": 33834
} | class ____(EqualityCheckMixin, AbstractRHS):
"""
Attributes
-----------
- scope: Scope
- name: str
- loc: Loc
Definition location
"""
def __init__(self, scope, name, loc):
# NOTE: Use of scope=None should be removed.
assert scope is None or isinstance(scope, Sc... | Var |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/yield_in_init.py | {
"start": 96,
"end": 195
} | class ____:
def __init__(self):
yield from self.gen()
def gen(self):
yield 5
| B |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/templates.py | {
"start": 1001,
"end": 3260
} | class ____(gast.NodeTransformer):
"""Adjusts the ctx field of nodes to ensure consistency.
This transformer can change the ctx fields of a variable, tuple and other
AST elements that allow one, based on whether the element is being read or
written.
"""
def __init__(self, override_value):
self._ctx_ove... | ContextAdjuster |
python | anthropics__anthropic-sdk-python | src/anthropic/types/cache_control_ephemeral_param.py | {
"start": 226,
"end": 529
} | class ____(TypedDict, total=False):
type: Required[Literal["ephemeral"]]
ttl: Literal["5m", "1h"]
"""The time-to-live for the cache control breakpoint.
This may be one the following values:
- `5m`: 5 minutes
- `1h`: 1 hour
Defaults to `5m`.
"""
| CacheControlEphemeralParam |
python | automl__auto-sklearn | autosklearn/util/dask.py | {
"start": 2106,
"end": 3972
} | class ____(Dask):
def __init__(self, n_jobs: int | None = None) -> None:
self.n_jobs = n_jobs
self._client: Client | None = None
self._cluster: LocalCluster | None = None
def client(self) -> Client:
"""Creates a usable dask client or returns an existing one
If there is ... | LocalDask |
python | huggingface__transformers | src/transformers/models/llava_next/processing_llava_next.py | {
"start": 1403,
"end": 12615
} | class ____(ProcessorMixin):
r"""
Constructs a LLaVa-NeXT processor which wraps a LLaVa-NeXT image processor and a LLaMa tokenizer into a single processor.
[`LlavaNextProcessor`] offers all the functionalities of [`LlavaNextImageProcessor`] and [`LlamaTokenizerFast`]. See the
[`~LlavaNextProcessor.__cal... | LlavaNextProcessor |
python | pytorch__pytorch | test/distributed/checkpoint/test_file_system_checkpoint.py | {
"start": 5141,
"end": 7188
} | class ____(ShardedTensorTestBase):
@property
def world_size(self) -> int:
return 2
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(2)
@requires_accelerator_dist_backend()
@parametrize("extensions", [None, [Rot13Example()], [ZStandard()]])
def test_read_write_shard_tensor(self, extensi... | TestDistributedStateDictSaveLoadWithSharedTensor |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 139,
"end": 473
} | class ____(unittest.TestCase):
def _makeOne(self, environ):
from pyramid.testing import DummyRootFactory
return DummyRootFactory(environ)
def test_it(self):
environ = {'bfg.routes.matchdict': {'a': 1}}
factory = self._makeOne(environ)
self.assertEqual(factory.a, 1)
| TestDummyRootFactory |
python | getsentry__sentry | src/sentry/users/api/endpoints/user_index.py | {
"start": 631,
"end": 3029
} | class ____(Endpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (SuperuserOrStaffFeatureFlaggedPermission,)
def get(self, request: Request) -> Response:
queryset = User.objects.distinct()
query = request.GET.get("query")
if query:
... | UserIndexEndpoint |
python | getsentry__sentry | src/sentry/api/serializers/models/apiapplication.py | {
"start": 207,
"end": 934
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
is_secret_visible = obj.date_added > timezone.now() - timedelta(minutes=5)
return {
"id": obj.client_id,
"clientID": obj.client_id,
"clientSecret": obj.client_secret if is_secret_visible else... | ApiApplicationSerializer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 56287,
"end": 56385
} | class ____:
key: str
full_type_name: str
@whitelist_for_serdes
@record
| ComponentInstanceSnap |
python | doocs__leetcode | solution/0500-0599/0593.Valid Square/Solution.py | {
"start": 0,
"end": 792
} | class ____:
def validSquare(
self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]
) -> bool:
def check(a, b, c):
(x1, y1), (x2, y2), (x3, y3) = a, b, c
d1 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
d2 = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 ... | Solution |
python | geekcomputers__Python | BlackJack_game/blackjack_simulate.py | {
"start": 2799,
"end": 5378
} | class ____:
def __init__(self, amount):
"""
:param amount: the chips you own
"""
self._amount = amount
self._bet_amount = 0
self._insurance = 0
self.is_insurance = False
self.is_double = False
def __bool__(self):
return self.amount > 0
... | Chips |
python | ansible__ansible | test/units/module_utils/facts/test_ansible_collector.py | {
"start": 17390,
"end": 17631
} | class ____(TestCollectedFacts):
gather_subset = ['!all']
min_fact_count = 1
max_fact_count = 10
expected_facts = ['gather_subset',
'module_setup']
not_expected_facts = ['lsb']
| TestMinimalCollectedFacts |
python | plotly__plotly.py | plotly/graph_objs/bar/marker/_colorbar.py | {
"start": 233,
"end": 61532
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar.marker"
_path_str = "bar.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",
... | ColorBar |
python | huggingface__transformers | src/transformers/models/clipseg/modeling_clipseg.py | {
"start": 16096,
"end": 18089
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: CLIPSegConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = CLIPSegAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = CLIPSegMLP... | CLIPSegEncoderLayer |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 66142,
"end": 66970
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
def get(self):
self.set_header("Content-Language", "en_US")
self.write("hello")
def test_304_headers(self):
response1 = self.fetch("/")
self.assertEqual(response1.headers["Content-Length"], "5")
... | Header304Test |
python | pandas-dev__pandas | pandas/io/stata.py | {
"start": 116051,
"end": 122284
} | class ____:
"""
Converter for Stata StrLs
Stata StrLs map 8 byte values to strings which are stored using a
dictionary-like format where strings are keyed to two values.
Parameters
----------
df : DataFrame
DataFrame to convert
columns : Sequence[str]
List of columns na... | StataStrLWriter |
python | marshmallow-code__apispec | tests/test_ext_marshmallow_common.py | {
"start": 1160,
"end": 2017
} | class ____:
def test_unique_name(self, spec):
properties = {
"id": {"type": "integer", "format": "int64"},
"name": {"type": "string", "example": "doggie"},
}
name = get_unique_schema_name(spec.components, "Pet")
assert name == "Pet"
spec.components.s... | TestUniqueName |
python | scipy__scipy | scipy/io/tests/test_paths.py | {
"start": 230,
"end": 3190
} | class ____:
data = np.arange(5).astype(np.int64)
def test_savemat(self):
with tempdir() as temp_dir:
path = Path(temp_dir) / 'data.mat'
scipy.io.savemat(path, {'data': self.data})
assert path.is_file()
def test_loadmat(self):
# Save data with string path... | TestPaths |
python | python__mypy | mypyc/ir/ops.py | {
"start": 24974,
"end": 25900
} | class ____(RegisterOp):
"""Load an error value.
Each type has one reserved value that signals an error (exception). This
loads the error value for a specific type.
"""
error_kind = ERR_NEVER
def __init__(
self, rtype: RType, line: int = -1, is_borrowed: bool = False, undefines: bool =... | LoadErrorValue |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 8424,
"end": 8891
} | class ____(AirflowException):
"""
Signal by an operator to skip its downstream tasks.
Special exception raised to signal that the operator it was raised from wishes to skip
downstream tasks. This is used in the ShortCircuitOperator.
:param tasks: List of task_ids to skip or a list of tuples with t... | DownstreamTasksSkipped |
python | PyCQA__pylint | tests/functional/u/used/used_before_assignment_py310.py | {
"start": 602,
"end": 2809
} | class ____(Enum):
FOO = 1
BAR = 2
def check_value_if_then_match_return(example: Example, should_check: bool) -> str | None:
if should_check:
result = None
else:
match example:
case Example.FOO:
result = "foo"
case Example.BAR:
resu... | Example |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 31400,
"end": 32861
} | class ____(Bar):
pass
"""
)
assert module_2.Foo.__pydantic_core_schema__['schema']['extras_schema'] == {'type': 'int'}
# TODO remove when we drop support for Python 3.10, in 3.11+ string annotations are properly evaluated
# in PEP 585 generics.
def test_pydantic_extra_forward_ref_evaluated_pep585... | Foo |
python | sympy__sympy | sympy/geometry/polygon.py | {
"start": 45281,
"end": 60494
} | class ____(Polygon):
"""
A regular polygon.
Such a polygon has all internal angles equal and all sides the same length.
Parameters
==========
center : Point
radius : number or Basic instance
The distance from the center to a vertex
n : int
The number of sides
Attr... | RegularPolygon |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-marketo/source_marketo/source.py | {
"start": 14535,
"end": 17074
} | class ____(MarketoExportBase):
"""
Base class for all the activities streams,
provides functionality for dynamically created classes as streams of data.
API Docs: https://developers.marketo.com/rest-api/bulk-extract/bulk-activity-extract/
"""
primary_key = "marketoGUID"
cursor_field = "acti... | Activities |
python | etianen__django-reversion | tests/test_app/tests/test_views.py | {
"start": 777,
"end": 1311
} | class ____(TestModelMixin, TestBase):
def testRevisionMixin(self):
response = self.client.post("/test-app/revision-mixin/")
obj = TestModel.objects.get(pk=response.content)
self.assertSingleRevision((obj,))
def testRevisionMixinGet(self):
self.client.get("/test-app/revision-mix... | RevisionMixinTest |
python | django__django | django/contrib/admin/views/main.py | {
"start": 1335,
"end": 1638
} | class ____(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Populate "fields" dynamically because SEARCH_VAR is a variable:
self.fields = {
SEARCH_VAR: forms.CharField(required=False, strip=False),
}
| ChangeListSearchForm |
python | apache__avro | lang/py/avro/test/test_schema.py | {
"start": 34233,
"end": 36111
} | class ____(unittest.TestCase):
"""Enable generating parse test cases over all the valid and invalid example schema."""
def __init__(self, test_schema):
"""Ignore the normal signature for unittest.TestCase because we are generating
many test cases from this one class. This is safe as long as the... | SchemaParseTestCase |
python | donnemartin__interactive-coding-challenges | recursion_dynamic/coin_change_min/test_coin_change_min.py | {
"start": 18,
"end": 622
} | class ____(unittest.TestCase):
def test_coin_change(self):
coin_changer = CoinChanger()
self.assertRaises(TypeError, coin_changer.make_change, None, None)
self.assertEqual(coin_changer.make_change([], 0), 0)
self.assertEqual(coin_changer.make_change([1, 2, 3], 5), 2)
self.as... | TestCoinChange |
python | scipy__scipy | benchmarks/benchmarks/sparse.py | {
"start": 7239,
"end": 7925
} | class ____(Benchmark):
param_names = ['sparse_type', 'num_matrices']
params = [
['spmatrix', 'sparray'],
[1000, 5000, 10000, 15000, 20000],
]
def setup(self, sparse_type, num_matrices):
self.matrices = []
for i in range(num_matrices):
rows = np.random.randint... | BlockDiagSparseConstruction |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 70744,
"end": 71275
} | class ____(FieldValues):
"""
Invalid values for `MultipleChoiceField(allow_empty=False)`.
"""
valid_inputs = {
}
invalid_inputs = (
([], ['This selection may not be empty.']),
)
outputs = [
]
field = serializers.MultipleChoiceField(
choices=[
('consist... | TestEmptyMultipleChoiceField |
python | ray-project__ray | python/ray/tune/examples/pbt_tune_cifar10_with_keras.py | {
"start": 902,
"end": 7575
} | class ____(Trainable):
def _read_data(self):
# The data, split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Convert class vectors to binary class matrices.
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.... | Cifar10Model |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 1938,
"end": 2232
} | class ____(TestWebSocketHandler):
@gen.coroutine
def on_message(self, message):
try:
yield self.write_message(message, isinstance(message, bytes))
except asyncio.CancelledError:
pass
except WebSocketClosedError:
pass
| EchoHandler |
python | bokeh__bokeh | tests/unit/bokeh/server/test_auth_provider.py | {
"start": 7600,
"end": 7673
} | class ____(RequestHandler): pass
""", func, suffix='.py')
| LogoutHandler |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 691989,
"end": 692503
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of MarkDiscussionCommentAsAnswer"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "discussion")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client perf... | MarkDiscussionCommentAsAnswerPayload |
python | django__django | tests/schema/models.py | {
"start": 3843,
"end": 3988
} | class ____(models.Model):
detail_info = models.TextField()
class Meta:
apps = new_apps
db_table = "schema_note"
| NoteRename |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_tool_20250522_param.py | {
"start": 348,
"end": 1017
} | class ____(TypedDict, total=False):
name: Required[Literal["code_execution"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["code_execution_20250522"]]
allowed_callers: List[Literal["direct", "code_execution_20250825... | BetaCodeExecutionTool20250522Param |
python | huggingface__transformers | tests/models/fuyu/test_modeling_fuyu.py | {
"start": 1451,
"end": 5616
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
num_image_tokens=2,
image_size=30,
patch_size=15,
num_channels=3,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden... | FuyuModelTester |
python | django-compressor__django-compressor | compressor/parser/lxml.py | {
"start": 242,
"end": 1656
} | class ____(ParserBase):
"""
LxmlParser will use `lxml.html` parser to parse rendered contents of
{% compress %} tag.
"""
def __init__(self, content):
try:
from lxml.html import fromstring
from lxml.etree import tostring
except ImportError as err:
... | LxmlParser |
python | getsentry__sentry | tests/sentry/api/serializers/test_recent_searches.py | {
"start": 194,
"end": 837
} | class ____(TestCase):
def test_simple(self) -> None:
search = RecentSearch.objects.create(
organization=self.organization,
user_id=self.user.id,
type=SearchType.ISSUE.value,
query="some query",
)
result = serialize(search)
assert resul... | RecentSearchSerializerTest |
python | google__jax | jax/_src/pallas/mosaic/lowering.py | {
"start": 8256,
"end": 8467
} | class ____(Protocol):
shape: tuple[jax_core.DimSize, ...]
dtype: jnp.dtype
weak_type: bool
def update(self, **kwargs: Any) -> Self:
raise NotImplementedError
@dataclasses.dataclass
| ShapedAbstractValue |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/decision_tree.py | {
"start": 678,
"end": 5380
} | class ____(AutoSklearnClassificationAlgorithm):
def __init__(
self,
criterion,
max_features,
max_depth_factor,
min_samples_split,
min_samples_leaf,
min_weight_fraction_leaf,
max_leaf_nodes,
min_impurity_decrease,
class_weight=None,
... | DecisionTree |
python | mahmoud__glom | glom/grouping.py | {
"start": 6789,
"end": 7948
} | class ____:
"""takes a random sample of the values
>>> glom([1, 2, 3], Group(Sample(2))) # doctest: +SKIP
[1, 3]
>>> glom(range(5000), Group(Sample(2))) # doctest: +SKIP
[272, 2901]
The advantage of this over :func:`random.sample` is that this can
take an arbitrarily-sized, potentially-v... | Sample |
python | ray-project__ray | python/ray/data/_internal/datasource/image_datasource.py | {
"start": 838,
"end": 5883
} | class ____(FileBasedDatasource):
"""A datasource that lets you read images."""
_WRITE_FILE_PER_ROW = True
_FILE_EXTENSIONS = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif"]
# Use 8 threads per task to read image files.
_NUM_THREADS_PER_TASK = 8
def __init__(
self,
paths: Un... | ImageDatasource |
python | openai__openai-python | src/openai/types/fine_tuning/alpha/grader_run_response.py | {
"start": 262,
"end": 1094
} | class ____(BaseModel):
formula_parse_error: bool
invalid_variable_error: bool
api_model_grader_parse_error: bool = FieldInfo(alias="model_grader_parse_error")
api_model_grader_refusal_error: bool = FieldInfo(alias="model_grader_refusal_error")
api_model_grader_server_error: bool = FieldInfo(alia... | MetadataErrors |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 1100,
"end": 1233
} | class ____(ProxyBase):
class Meta:
proxy = True
def __unicode__(self):
return f"<ProxyA: {self.title}>"
| ProxyA |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 2398,
"end": 2449
} | class ____(TypedDict):
image: str
| ImageSourceDict |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | {
"start": 25189,
"end": 57542
} | class ____(QTableView, SpyderWidgetMixin):
"""
View displaying a dataframe in the dataframe editor
This is a view (in the sense of the Qt model/view architecture) that is
used in the dataframe editor to display a dataframe. It only shows the
data but not the index (row headings) or header (column n... | DataFrameView |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 40850,
"end": 48838
} | class ____:
compiled: Any
backend: xb.XlaBackend
local_input_avals: Sequence[core.AbstractValue]
input_shardings: Sequence[JSharding]
local_output_avals: Sequence[ShapedArray]
output_shardings: Sequence[JSharding]
unordered_effects: list[core.Effect]
ordered_effects: list[core.Effect]
keepalive: Seque... | UnloadedPmapExecutable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.