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 | kamyu104__LeetCode-Solutions | Python/groups-of-strings.py | {
"start": 39,
"end": 873
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.size = [1]*n
self.total = n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
... | UnionFind |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 868313,
"end": 868719
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field(PullRequestChangedFile, gr... | PullRequestChangedFileEdge |
python | django__django | tests/admin_filters/tests.py | {
"start": 8404,
"end": 8533
} | class ____(ModelAdmin):
list_filter = (DecadeListFilterWithQuerysetBasedLookups,)
| DecadeFilterBookAdminWithQuerysetBasedLookups |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-alibabacloud-opensearch/llama_index/vector_stores/alibabacloud_opensearch/base.py | {
"start": 2300,
"end": 5487
} | class ____:
"""
`Alibaba Cloud Opensearch` client configuration.
Attribute:
endpoint (str) : The endpoint of opensearch instance, You can find it
from the console of Alibaba Cloud OpenSearch.
instance_id (str) : The identify of opensearch instance, You can find
it from the... | AlibabaCloudOpenSearchConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/slots2.py | {
"start": 186,
"end": 423
} | class ____(NoSlots1):
__slots__ = "aaa", "bbb", "ccc"
# This should generate an error
aaa = 3
# This should generate an error
bbb: int = 3
# This should generate an error
(ccc, ddd) = 3, 4
eee = 5
| Slots1 |
python | kamyu104__LeetCode-Solutions | Python/range-sum-query-2d-immutable.py | {
"start": 68,
"end": 1021
} | class ____(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
m, n = len(matrix), len(matrix[0])
self.__sums = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)]
... | NumMatrix |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 2857,
"end": 3519
} | class ____(nn.Module):
def __init__(self, config, hidden_act):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_s... | MoonshineDecoderMLP |
python | python-pillow__Pillow | src/PIL/ImageShow.py | {
"start": 5675,
"end": 6061
} | class ____(abc.ABC, Viewer):
format = "PNG"
options = {"compress_level": 1, "save_all": True}
@abc.abstractmethod
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
pass
def get_command(self, file: str, **options: Any) -> str:
command = self.get_command_ex(file... | UnixViewer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 12214,
"end": 12888
} | class ____(_IntegerType, sqltypes.SMALLINT):
"""MySQL SMALLINTEGER type."""
__visit_name__ = "SMALLINT"
def __init__(self, display_width: Optional[int] = None, **kw: Any):
"""Construct a SMALLINTEGER.
:param display_width: Optional, maximum display width for this number.
:param u... | SMALLINT |
python | python__mypy | mypy/mixedtraverser.py | {
"start": 489,
"end": 3821
} | class ____(TraverserVisitor, TypeTraverserVisitor):
"""Recursive traversal of both Node and Type objects."""
def __init__(self) -> None:
self.in_type_alias_expr = False
# Symbol nodes
def visit_var(self, var: Var, /) -> None:
self.visit_optional_type(var.type)
def visit_func(self... | MixedTraverserVisitor |
python | apache__airflow | devel-common/src/sphinx_exts/providers_commits.py | {
"start": 1544,
"end": 8742
} | class ____(NamedTuple):
"""Stores details about commits"""
full_hash: str
short_hash: str
date: str
version: str
message: str
message_without_backticks: str
pr: str | None
def get_provider_root_path(provider_id: str) -> Path:
return Path("providers") / provider_id.replace(".", "/"... | Change |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_vector/generate/executor.py | {
"start": 1013,
"end": 19958
} | class ____(
Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType]
):
@overload
def near_vector(
self,
near_vector: NearVectorInputType,
*,
single_prompt: Union[str, _SinglePrompt, None] = None,
grouped_task: Union[str, _GroupedTask, None] = No... | _NearVectorGenerateExecutor |
python | python__mypy | mypy/nodes.py | {
"start": 100165,
"end": 100539
} | class ____(Expression):
"""Await expression (await ...)."""
__slots__ = ("expr",)
__match_args__ = ("expr",)
expr: Expression
def __init__(self, expr: Expression) -> None:
super().__init__()
self.expr = expr
def accept(self, visitor: ExpressionVisitor[T]) -> T:
retur... | AwaitExpr |
python | pandas-dev__pandas | asv_bench/benchmarks/multiindex_object.py | {
"start": 3917,
"end": 4324
} | class ____:
def setup(self):
n, k = 200, 5000
levels = [
np.arange(n),
Index([f"i-{i}" for i in range(n)], dtype=object).values,
1000 + np.arange(n),
]
codes = [np.random.choice(n, (k * n)) for lev in levels]
self.mi = MultiIndex(levels=lev... | Duplicated |
python | pytorch__pytorch | torch/optim/optimizer.py | {
"start": 13661,
"end": 51029
} | class ____:
r"""Base class for all optimizers.
.. warning::
Parameters need to be specified as collections that have a deterministic
ordering that is consistent between runs. Examples of objects that don't
satisfy those properties are sets and iterators over values of dictionaries.
... | Optimizer |
python | langchain-ai__langchain | libs/core/langchain_core/_api/beta_decorator.py | {
"start": 596,
"end": 8664
} | class ____(DeprecationWarning):
"""A class for issuing beta warnings for LangChain users."""
# PUBLIC API
T = TypeVar("T", bound=Callable[..., Any] | type)
def beta(
*,
message: str = "",
name: str = "",
obj_type: str = "",
addendum: str = "",
) -> Callable[[T], T]:
"""Decorator to mar... | LangChainBetaWarning |
python | huggingface__transformers | src/transformers/models/doge/modular_doge.py | {
"start": 34129,
"end": 34345
} | class ____(LlamaForSequenceClassification):
pass
__all__ = [
"DogeConfig",
"DogeForCausalLM",
"DogeModel",
"DogePreTrainedModel",
"DogeForSequenceClassification",
]
| DogeForSequenceClassification |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_uses_keep_param.py | {
"start": 221,
"end": 341
} | class ____(TypedDict, total=False):
type: Required[Literal["tool_uses"]]
value: Required[int]
| BetaToolUsesKeepParam |
python | getsentry__sentry-python | sentry_sdk/client.py | {
"start": 7806,
"end": 8026
} | class ____(BaseClient):
"""
.. versionadded:: 2.0.0
A client that does not send any events to Sentry. This is used as a fallback when the Sentry SDK is not yet initialized.
"""
pass
| NonRecordingClient |
python | astropy__astropy | astropy/time/formats.py | {
"start": 25732,
"end": 30375
} | class ____(TimeNumeric):
"""
Base class for times that represent the interval from a particular
epoch as a numerical multiple of a unit time interval (e.g. seconds
or days).
"""
@classproperty(lazy=True)
def _epoch(cls):
# Ideally we would use `def epoch(cls)` here and not have the ... | TimeFromEpoch |
python | plotly__plotly.py | plotly/graph_objs/surface/colorbar/_title.py | {
"start": 233,
"end": 3971
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "surface.colorbar"
_path_str = "surface.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
that ma... | Title |
python | FactoryBoy__factory_boy | tests/test_transformer.py | {
"start": 2300,
"end": 2449
} | class ____:
def __init__(self, one=None, two=None, three=None):
self.one = one
self.two = two
self.three = three
| TestObject |
python | dagster-io__dagster | python_modules/dagster/dagster/_vendored/dateutil/rrule.py | {
"start": 54439,
"end": 66759
} | class ____(object):
""" Parses a string representation of a recurrence rule or set of
recurrence rules.
:param s:
Required, a string defining one or more recurrence rules.
:param dtstart:
If given, used as the default recurrence start if not specified in the
rule string.
:... | _rrulestr |
python | spyder-ide__spyder | spyder/widgets/elementstable.py | {
"start": 1800,
"end": 6084
} | class ____(QAbstractTableModel, SpyderFontsMixin):
def __init__(
self,
parent: QWidget,
elements: List[Element],
with_description: bool,
with_icons: bool,
with_additional_info: bool,
with_widgets: bool,
):
QAbstractTableModel.__init__(self)
... | ElementsModel |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/managed/types.py | {
"start": 346,
"end": 1242
} | class ____:
"""Represents a user-defined Fivetran destination."""
def __init__(
self,
name: str,
destination_type: str,
region: str,
destination_configuration: dict[str, Any],
time_zone_offset: Optional[int] = None,
):
self.name = check.str_param(name... | FivetranDestination |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 91239,
"end": 91919
} | class ____(nn.Module):
def __init__(self, config: DFineConfig, kernel_size: int, stride: int):
super().__init__()
self.conv1 = DFineConvNormLayer(config, config.encoder_hidden_dim, config.encoder_hidden_dim, 1, 1)
self.conv2 = DFineConvNormLayer(
config,
config.encode... | DFineSCDown |
python | pytorch__pytorch | test/inductor/test_snode_runtime.py | {
"start": 5928,
"end": 10365
} | class ____(TestCase):
device = DEVICE
WORLD_SIZE: int = 8
RANKS = list(range(8))
def _verify_runtime_estimation(self, fn, inps):
from torch.testing._internal.distributed.fake_pg import FakeStore
store = FakeStore()
dist.init_process_group(
backend="fake", rank=0, w... | TestCommAnalysis |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/event_frequency_handlers.py | {
"start": 4273,
"end": 5216
} | class ____(EventFrequencyPercentHandler):
group = DataConditionHandler.Group.ACTION_FILTER
subgroup = DataConditionHandler.Subgroup.FREQUENCY
comparison_json_schema = {
"type": "object",
"properties": {
"interval": {"type": "string", "enum": list(PERCENT_INTERVALS.keys())},
... | PercentSessionsPercentHandler |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 45737,
"end": 47141
} | class ____(nn.Module):
def __init__(self, config: Sam2VideoConfig):
super().__init__()
hidden_size = config.memory_encoder_hidden_size
output_channels = config.memory_encoder_output_channels
self.mask_downsampler = Sam2VideoMaskDownSampler(config)
self.feature_projection = n... | Sam2VideoMemoryEncoder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1243651,
"end": 1246074
} | class ____(sgqlc.types.Type, Node):
"""An OIDC identity provider configured to provision identities for
an enterprise. Visible to enterprise owners or enterprise owners'
personal access tokens (classic) with read:enterprise or
admin:enterprise scope.
"""
__schema__ = github_schema
__field_n... | OIDCProvider |
python | sanic-org__sanic | sanic/router.py | {
"start": 705,
"end": 9341
} | class ____(BaseRouter):
"""The router implementation responsible for routing a `Request` object to the appropriate handler.""" # noqa: E501
DEFAULT_METHOD = "GET"
ALLOWED_METHODS = HTTP_METHODS
def _get(
self, path: str, method: str, host: Optional[str]
) -> tuple[Route, RouteHandler, dic... | Router |
python | scipy__scipy | scipy/optimize/_zeros_py.py | {
"start": 755,
"end": 43169
} | class ____(OptimizeResult):
"""Represents the root finding result.
Attributes
----------
root : float
Estimated root location.
iterations : int
Number of iterations needed to find the root.
function_calls : int
Number of times the function was called.
converged : boo... | RootResults |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/extra/codemods.py | {
"start": 9312,
"end": 11238
} | class ____(VisitorBasedCodemodCommand):
"""Fix deprecated white/blacklist arguments to characters::
st.characters(whitelist_categories=...) -> st.characters(categories=...)
st.characters(blacklist_categories=...) -> st.characters(exclude_categories=...)
st.characters(whitelist_characters=..... | HypothesisFixCharactersArguments |
python | celery__celery | t/unit/apps/test_multi.py | {
"start": 6148,
"end": 10942
} | class ____:
def setup_method(self):
self.p = Mock(name='p')
self.p.options = {
'--executable': 'python',
'--logfile': '/var/log/celery/foo.log',
}
self.p.namespaces = {}
with patch('celery.apps.multi.os.mkdir'):
self.node = Node('foo@bar.c... | test_Node |
python | pytorch__pytorch | torch/distributed/elastic/agent/server/api.py | {
"start": 7684,
"end": 9800
} | class ____(str, Enum):
"""A state of the ``WorkerGroup``.
Workers in a worker group change state as a unit. If a single worker
in a worker group fails the entire set is considered failed::
UNKNOWN - agent lost track of worker group state, unrecoverable
INIT - worker group object created not ye... | WorkerState |
python | huggingface__transformers | tests/models/bark/test_processing_bark.py | {
"start": 814,
"end": 5338
} | class ____(unittest.TestCase):
def setUp(self):
self.checkpoint = "suno/bark-small"
self.tmpdirname = tempfile.mkdtemp()
self.voice_preset = "en_speaker_1"
self.input_string = "This is a test string"
self.speaker_embeddings_dict_path = "speaker_embeddings_path.json"
s... | BarkProcessorTest |
python | readthedocs__readthedocs.org | readthedocs/search/tests/test_views.py | {
"start": 4759,
"end": 14042
} | class ____:
@pytest.fixture(autouse=True)
def setup(self):
self.url = reverse("search")
def _get_search_result(self, url, client, search_params):
resp = client.get(url, search_params)
assert resp.status_code == 200
results = resp.context["results"]
facets = resp.con... | TestPageSearch |
python | pypa__warehouse | tests/unit/test_forms.py | {
"start": 287,
"end": 1074
} | class ____:
@pytest.mark.parametrize(
"uri",
[
"https://example.com/",
"http://example.com/",
"https://sub.example.com/path?query#thing",
],
)
def test_valid(self, uri):
URIValidator()(pretend.stub(), pretend.stub(data=uri))
@pytest.ma... | TestURIValidator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 884566,
"end": 884956
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("PushAllowance", graphql_n... | PushAllowanceEdge |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial003_py39.py | {
"start": 519,
"end": 747
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
headquarters: str
hero_links: list[HeroTeamLink] = Relationship(back_populates="team")
| Team |
python | huggingface__transformers | tests/generation/test_candidate_generator.py | {
"start": 9891,
"end": 15054
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.target_name = "hf-internal-testing/tiny-random-LlamaForCausalLM"
cls.assistant_name = "hf-internal-testing/tiny-random-PhiForCausalLM"
def setUp(self):
self.target_tokenizer = AutoTokenizer.from_pretrained(self.tar... | TestUniversalSpeculativeDecoding |
python | qdrant__qdrant-client | tools/async_client_generator/transformers/local/call_transformer.py | {
"start": 126,
"end": 669
} | class ____(CallTransformer):
def visit_Call(self, node: ast.Call) -> Union[ast.AST, ast.Await]:
if isinstance(node.func, ast.Name):
if node.func.id in self.class_replace_map:
node.func.id = self.class_replace_map[node.func.id]
if isinstance(node.func, ast.Attribute):
... | LocalCallTransformer |
python | pytorch__pytorch | torch/_inductor/utils.py | {
"start": 47890,
"end": 52804
} | class ____:
tabwidth = 4
def __init__(self, initial_indent: int = 0) -> None:
self._lines: list[Union[DeferredLineBase, LineContext, str]] = []
self._indent = initial_indent
@contextlib.contextmanager
def set_tabwidth(self, tabwidth: int) -> Iterator[None]:
prev = self.tabwidth... | IndentedBuffer |
python | squidfunk__mkdocs-material | material/utilities/filter/config.py | {
"start": 1395,
"end": 1947
} | class ____(Config):
"""
A filter configuration.
"""
include = ListOfItems(Type(str), default = [])
"""
Patterns to include.
This list contains patterns that are matched against the value to filter.
If the value matches at least one pattern, it will be included.
"""
exclude = L... | FilterConfig |
python | walkccc__LeetCode | solutions/707. Design Linked List/707.py | {
"start": 107,
"end": 1216
} | class ____:
def __init__(self):
self.length = 0
self.dummy = ListNode(0)
def get(self, index: int) -> int:
if index < 0 or index >= self.length:
return -1
curr = self.dummy.next
for _ in range(index):
curr = curr.next
return curr.val
def addAtHead(self, val: int) -> None:
... | MyLinkedList |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 6870,
"end": 7107
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI Ray Cluster List link."""
name = "Ray Cluster List"
key = "ray_cluster_list_conf"
format_str = VERTEX_AI_RAY_CLUSTER_LIST_LINK
| VertexAIRayClusterListLink |
python | huggingface__transformers | src/transformers/models/phi/modular_phi.py | {
"start": 12411,
"end": 12601
} | class ____(LlamaForCausalLM):
def __init__(self, config):
super().__init__(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
| PhiForCausalLM |
python | viewflow__viewflow | tests/components/test_field_date.py | {
"start": 298,
"end": 1353
} | class ____(LiveTestCase):
def test_field_date(self):
self.browser.get(f"{self.live_server_url}/application/form/")
self.assertNoJsErrors()
input = self.browser.find_element(By.CSS_SELECTOR, "vf-field-date input")
label = self.browser.find_element(By.CSS_SELECTOR, "vf-field-date labe... | Test |
python | pypa__packaging | src/packaging/metadata.py | {
"start": 10135,
"end": 20022
} | class ____(email.message.EmailMessage):
"""
This is :class:`email.message.EmailMessage` with two small changes: it defaults to
our `RFC822Policy`, and it correctly writes unicode when being called
with `bytes()`.
"""
def __init__(self) -> None:
super().__init__(policy=RFC822Policy())
... | RFC822Message |
python | scipy__scipy | scipy/stats/tests/test_hypotests.py | {
"start": 68326,
"end": 72969
} | class ____:
@pytest.mark.parametrize('args', [([], np.arange(5)),
(np.arange(5), [1])])
@pytest.mark.skip_xp_backends("jax.numpy", reason="lazy -> no axis_nan_policy")
def test_too_small_input(self, args, xp):
args = (xp.asarray(arg, dtype=xp_default_dtype(xp)) ... | TestCvm_2samp |
python | getsentry__sentry | src/sentry/users/models/identity.py | {
"start": 6275,
"end": 7203
} | class ____(Model):
"""
A verified link between a user and a third party identity.
"""
__relocation_scope__ = RelocationScope.Excluded
idp = FlexibleForeignKey("sentry.IdentityProvider")
user = FlexibleForeignKey(settings.AUTH_USER_MODEL)
external_id = models.TextField()
data = models.J... | Identity |
python | openai__openai-python | src/openai/types/beta/threads/runs/function_tool_call_delta.py | {
"start": 240,
"end": 648
} | class ____(BaseModel):
arguments: Optional[str] = None
"""The arguments passed to the function."""
name: Optional[str] = None
"""The name of the function."""
output: Optional[str] = None
"""The output of the function.
This will be `null` if the outputs have not been
[submitted](https:... | Function |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 88572,
"end": 91880
} | class ____(fixtures.MappedTest):
"""test usages stated at
https://article.gmane.org/gmane.comp.python.sqlalchemy.user/3085
https://article.gmane.org/gmane.comp.python.sqlalchemy.user/3119
"""
@classmethod
def define_tables(cls, metadata):
Table(
"order",
metadat... | PendingOrphanTestTwoLevel |
python | TheAlgorithms__Python | graphs/boruvka.py | {
"start": 1280,
"end": 6405
} | class ____:
def __init__(self, num_of_nodes: int) -> None:
"""
Arguments:
num_of_nodes - the number of nodes in the graph
Attributes:
m_num_of_nodes - the number of nodes in the graph.
m_edges - the list of edges.
m_component - the dictionary w... | Graph |
python | eventlet__eventlet | eventlet/zipkin/_thrift/zipkinCore/ttypes.py | {
"start": 349,
"end": 722
} | class ____:
BOOL = 0
BYTES = 1
I16 = 2
I32 = 3
I64 = 4
DOUBLE = 5
STRING = 6
_VALUES_TO_NAMES = {
0: "BOOL",
1: "BYTES",
2: "I16",
3: "I32",
4: "I64",
5: "DOUBLE",
6: "STRING",
}
_NAMES_TO_VALUES = {
"BOOL": 0,
"BYTES": 1,
"I16": 2,
"I32": 3,
"I64": ... | AnnotationType |
python | huggingface__transformers | src/transformers/models/mobilevitv2/modeling_mobilevitv2.py | {
"start": 9564,
"end": 10793
} | class ____(nn.Module):
def __init__(
self,
config: MobileViTV2Config,
embed_dim: int,
ffn_latent_dim: int,
ffn_dropout: float = 0.0,
) -> None:
super().__init__()
self.conv1 = MobileViTV2ConvLayer(
config=config,
in_channels=embed_d... | MobileViTV2FFN |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_regession_8119.py | {
"start": 459,
"end": 686
} | class ____(Coordinator[int | str]):
def __init__(self) -> None:
Coordinator.__init__(self, update_interval=2)
def _async_update_data(self):
assert self.update_interval
self.update_interval = 1
| Child |
python | pandas-dev__pandas | pandas/tests/frame/test_arithmetic.py | {
"start": 16723,
"end": 30088
} | class ____:
def test_floordiv_axis0(self):
# make sure we df.floordiv(ser, axis=0) matches column-wise result
arr = np.arange(3)
ser = Series(arr)
df = DataFrame({"A": ser, "B": ser})
result = df.floordiv(ser, axis=0)
expected = DataFrame({col: df[col] // ser for co... | TestFrameFlexArithmetic |
python | Textualize__textual | src/textual/color.py | {
"start": 3454,
"end": 3803
} | class ____(Exception):
"""A color failed to parse.
Args:
message: The error message
suggested_color: A close color we can suggest.
"""
def __init__(self, message: str, suggested_color: str | None = None):
super().__init__(message)
self.suggested_color = suggested_color
... | ColorParseError |
python | django__django | tests/generic_views/views.py | {
"start": 3675,
"end": 3784
} | class ____(AuthorCreate):
post = method_decorator(login_required)(AuthorCreate.post)
| AuthorCreateRestricted |
python | django__django | django/db/models/fetch_modes.py | {
"start": 55,
"end": 235
} | class ____:
__slots__ = ()
track_peers = False
def fetch(self, fetcher, instance):
raise NotImplementedError("Subclasses must implement this method.")
| FetchMode |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass3.py | {
"start": 630,
"end": 667
} | class ____:
name: str
@final
| BFinal |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py | {
"start": 29839,
"end": 34199
} | class ____(KyutaiSpeechToTextAttention):
"""
KyutaiSpeechToText attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
`KyutaiSpeechToTextAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
SDPA API.
... | KyutaiSpeechToTextSdpaAttention |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 99416,
"end": 100198
} | class ____(IR):
"""Select a subset of columns from a dataframe."""
__slots__ = ()
_non_child = ("schema",)
def __init__(self, schema: Schema, df: IR):
self.schema = schema
self._non_child_args = (schema,)
self.children = (df,)
@classmethod
@log_do_evaluate
@nvtx_an... | Projection |
python | django__django | django/contrib/auth/views.py | {
"start": 8983,
"end": 9252
} | class ____(PasswordContextMixin, TemplateView):
template_name = "registration/password_reset_done.html"
title = _("Password reset sent")
@method_decorator(
[login_not_required, sensitive_post_parameters(), never_cache], name="dispatch"
)
| PasswordResetDoneView |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py | {
"start": 46635,
"end": 53322
} | class ____:
@pytest.mark.parametrize(
("dag_id", "run_id", "patch_body", "response_body", "note_data"),
[
(
DAG1_ID,
DAG1_RUN1_ID,
{"state": DagRunState.FAILED, "note": "new_note2"},
{"state": DagRunState.FAILED, "note": "ne... | TestPatchDagRun |
python | getsentry__sentry | src/sentry/discover/arithmetic.py | {
"start": 1061,
"end": 2566
} | class ____:
__slots__ = "operator", "lhs", "rhs"
def __init__(
self,
operator: str,
lhs: OperandType | None = None,
rhs: OperandType | None = None,
) -> None:
self.operator = operator
self.lhs: OperandType | None = lhs
self.rhs: OperandType | None = r... | Operation |
python | openai__gym | gym/error.py | {
"start": 54,
"end": 125
} | class ____(Exception):
"""Error superclass."""
# Local errors
| Error |
python | pytorch__pytorch | test/test_autocast.py | {
"start": 7910,
"end": 10910
} | class ____(TestCase):
def test_cast_cache_is_global(self):
"""
Verifies that the autocast cache is global. This is done by
mocking out cache clearing at the end of the forward pass,
running forward+backward with an explicit call to autocast in the
backward, and verifying that... | TestAutocastGPU |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_field_test.py | {
"start": 8077,
"end": 14184
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([
({
'x': 1
}, "Missing required fields: {'y'}"),
({
'x': 1,
'y': 2.0,
'z': 3
}, "Got unexpected fields: {'z'}"),
])
def testCo... | FieldValueConverterTest |
python | getsentry__sentry | tests/sentry/core/endpoints/test_project_details.py | {
"start": 1886,
"end": 12279
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_simple(self) -> None:
response = self.get_success_response(self.project.organization.slug, self.project.slug)
assert response.d... | ProjectDetailsTest |
python | falconry__falcon | examples/things_advanced.py | {
"start": 1026,
"end": 2134
} | class ____:
def process_request(self, req, resp):
token = req.get_header('Authorization')
account_id = req.get_header('Account-ID')
challenges = ['Token type="Fernet"']
if token is None:
description = 'Please provide an auth token as part of the request.'
r... | AuthMiddleware |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 10992,
"end": 11495
} | class ____(OAuth2Error):
"""
The request requires higher privileges than provided by the
access token. The resource server SHOULD respond with the HTTP
403 (Forbidden) status code and MAY include the "scope"
attribute with the scope necessary to access the protected
resource.
"""
error ... | InsufficientScopeError |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/service/server_lib.py | {
"start": 10942,
"end": 13567
} | class ____(
collections.namedtuple("WorkerConfig", [
"dispatcher_address", "worker_address", "port", "protocol",
"heartbeat_interval_ms", "dispatcher_timeout_ms",
"data_transfer_protocol", "data_transfer_address"
])):
"""Configuration class for tf.data service dispatchers.
Fields:
... | WorkerConfig |
python | django-guardian__django-guardian | example_project_custom_group/articles/tests.py | {
"start": 3831,
"end": 7414
} | class ____(TestCase):
def setUp(self):
self.article = Article.objects.create(title="foo-title", slug="foo-slug", content="bar-content")
self.factory = RequestFactory()
self.user = get_user_model().objects.create_user("joe", "joe@doe.com", "doe")
self.group = CustomGroup.objects.creat... | ViewGroupTestCase |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 41120,
"end": 41309
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("IGNORED", "SUBSCRIBED", "UNSUBSCRIBED")
| SubscriptionState |
python | kamyu104__LeetCode-Solutions | Python/delete-n-nodes-after-m-nodes-of-a-linked-list.py | {
"start": 66,
"end": 182
} | class ____(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
| ListNode |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 10803,
"end": 14554
} | class ____(nn.Module):
def __init__(self, config, position_embedding_type=None, layer_idx=None, is_cross_attention=False):
super().__init__()
self.config = config
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(... | EvollaSaProtSelfAttention |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar14.py | {
"start": 315,
"end": 2121
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 907684,
"end": 908854
} | class ____(sgqlc.types.Type, RepositoryNode, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("comments", "commit", "path", "position", "pull_request")
comments = sgqlc.types.Field(
sgqlc.types.non_null(CommitCommentConnection),
graphq... | PullRequestCommitCommentThread |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 24838,
"end": 25356
} | class ____(Pix2SkyProjection, PseudoCylindrical):
r"""
Molleweide's projection - pixel to sky.
Corresponds to the ``MOL`` projection in FITS WCS.
.. math::
\phi &= \frac{\pi x}{2 \sqrt{2 - \left(\frac{\pi}{180^\circ}y\right)^2}} \\
\theta &= \sin^{-1}\left(
\frac{1}{90^... | Pix2Sky_Molleweide |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 54275,
"end": 55295
} | class ____(BaseTestCase):
def setUp(self):
BaseTestCase.setUp(self)
self.callback_args = []
self.callback_event = threading.Event()
def test_init_immutable_default_args(self):
# Issue 17435: constructor defaults were mutable objects, they could be
# mutated via the obje... | TimerTests |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_query.py | {
"start": 3562,
"end": 9022
} | class ____(fixtures.TablesTest):
__only_on__ = "mysql", "mariadb"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"cattable",
metadata,
Column("id", Integer, primary_key=True),
Column("description", String(50)),
... | MatchTest |
python | spack__spack | lib/spack/spack/util/spack_yaml.py | {
"start": 906,
"end": 1523
} | class ____(int):
pass
#: mapping from syaml type -> primitive type
syaml_types = {syaml_str: str, syaml_int: int, syaml_dict: dict, syaml_list: list}
markable_types = set(syaml_types) | {comments.CommentedSeq, comments.CommentedMap}
def syaml_type(obj):
"""Get the corresponding syaml wrapper type for a pr... | syaml_int |
python | apache__airflow | devel-common/src/docs/build_docs.py | {
"start": 6030,
"end": 6175
} | class ____(NamedTuple):
"""Specification of single build."""
package_name: str
is_autobuild: bool
verbose: bool
| BuildSpecification |
python | walkccc__LeetCode | solutions/1287. Element Appearing More Than 25% In Sorted Array/1287.py | {
"start": 0,
"end": 202
} | class ____:
def findSpecialInteger(self, arr: list[int]) -> int:
n = len(arr)
quarter = n // 4
for i in range(n - quarter):
if arr[i] == arr[i + quarter]:
return arr[i]
| Solution |
python | python__mypy | mypyc/ir/ops.py | {
"start": 2012,
"end": 4512
} | class ____:
"""IR basic block.
Contains a sequence of Ops and ends with a ControlOp (Goto,
Branch, Return or Unreachable). Only the last op can be a
ControlOp.
All generated Ops live in basic blocks. Basic blocks determine the
order of evaluation and control flow within a function. A basic
... | BasicBlock |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1200,
"end": 1279
} | class ____(ModelExtraB):
field3 = models.CharField(max_length=30)
| ModelExtraC |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 103918,
"end": 106372
} | class ____(BaseView):
@classmethod
def create(cls, x: IRNode, *, dim: Optional[int] = None) -> IRNode:
if is_storage_and_layout(x):
storage, old_layout = as_storage_and_layout(x)
new_size = []
new_stride = []
if dim is not None:
assert isin... | SqueezeView |
python | redis__redis-py | redis/asyncio/multidb/healthcheck.py | {
"start": 602,
"end": 768
} | class ____(ABC):
@abstractmethod
async def check_health(self, database) -> bool:
"""Function to determine the health status."""
pass
| HealthCheck |
python | pypa__setuptools | setuptools/_distutils/compilers/C/tests/test_cygwin.py | {
"start": 496,
"end": 2701
} | class ____(support.TempdirManager):
def _get_config_h_filename(self):
return self.python_h
@pytest.mark.skipif('sys.platform != "cygwin"')
@pytest.mark.skipif('not os.path.exists("/usr/lib/libbash.dll.a")')
def test_find_library_file(self):
from distutils.cygwinccompiler import CygwinCC... | TestCygwinCCompiler |
python | google__jax | jax/_src/util.py | {
"start": 25709,
"end": 26329
} | class ____(abc.ABCMeta):
"""A variant of `abc.ABCMeta` which does not allow virtual subclasses.
Virtual subclasses support require `abc.ABCMeta` to roundtrip through
pure Python when doing instance/subclass checking. This if fine for ABCs
which need virtual subclasses, but is wasteful for the ones which don't.... | StrictABCMeta |
python | huggingface__transformers | src/transformers/models/sam2/modular_sam2.py | {
"start": 33692,
"end": 36498
} | class ____(SamPromptEncoder):
def __init__(self, config: Sam2PromptEncoderConfig):
nn.Module.__init__(self)
self.shared_embedding = Sam2PositionalEmbedding(config)
self.mask_embed = Sam2MaskEmbedding(config)
self.no_mask_embed = nn.Embedding(1, config.hidden_size)
self.image... | Sam2PromptEncoder |
python | getsentry__sentry | tests/sentry/hybridcloud/models/test_outbox.py | {
"start": 5177,
"end": 10998
} | class ____(TransactionTestCase):
@patch("sentry.hybridcloud.models.outbox.process_region_outbox.send")
def test_draining_with_disabled_shards(self, mock_send: Mock) -> None:
outbox1 = Organization(id=1).outbox_for_update()
outbox2 = Organization(id=1).outbox_for_update()
outbox3 = Organi... | OutboxDrainTest |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 9524,
"end": 9887
} | class ____(ValueError):
"""Raised when an error is encountered while a pickling library deserializes a pickle file."""
def __str__(self):
return (
"Error deserializing result. Note that result deserialization "
"is not supported across major Python versions. Cause: " + str(self.... | DeserializingResultError |
python | tornadoweb__tornado | tornado/test/auth_test.py | {
"start": 4524,
"end": 5516
} | class ____(RequestHandler, FacebookGraphMixin):
def initialize(self, test):
self._OAUTH_AUTHORIZE_URL = test.get_url("/facebook/server/authorize")
self._OAUTH_ACCESS_TOKEN_URL = test.get_url("/facebook/server/access_token")
self._FACEBOOK_BASE_URL = test.get_url("/facebook/server")
@gen... | FacebookClientLoginHandler |
python | django__django | tests/migrations/test_autodetector.py | {
"start": 204279,
"end": 209180
} | class ____(SimpleTestCase):
def test_no_operations(self):
class Migration(migrations.Migration):
operations = []
migration = Migration("some_migration", "test_app")
self.assertIs(migration.suggest_name().startswith("auto_"), True)
def test_no_operations_initial(self):
... | MigrationSuggestNameTests |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 268366,
"end": 268805
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "column", "deleted_card_id")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
column = sgqlc.types.Field("ProjectColumn", ... | DeleteProjectCardPayload |
python | django__django | tests/i18n/tests.py | {
"start": 80622,
"end": 81287
} | class ____(TestCase):
def test_streaming_response(self):
# Regression test for #5241
response = self.client.get("/fr/streaming/")
self.assertContains(response, "Oui/Non")
response = self.client.get("/en/streaming/")
self.assertContains(response, "Yes/No")
@override_settings... | LocaleMiddlewareTests |
python | pydata__xarray | xarray/tests/test_namedarray.py | {
"start": 1737,
"end": 3783
} | class ____(
CustomArrayBase[_ShapeType_co, _DType_co],
ExplicitlyIndexed,
Generic[_ShapeType_co, _DType_co],
):
def __getitem__(
self, key: _IndexKeyLike | CustomArrayIndexable[Any, Any], /
) -> CustomArrayIndexable[Any, _DType_co]:
if isinstance(key, CustomArrayIndexable):
... | CustomArrayIndexable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.