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 | spack__spack | lib/spack/spack/repo.py | {
"start": 78064,
"end": 78165
} | class ____(RepoError):
"""Raised when an invalid namespace is encountered."""
| InvalidNamespaceError |
python | walkccc__LeetCode | solutions/3446. Sort Matrix by Diagonals/3446.py | {
"start": 0,
"end": 446
} | class ____:
def sortMatrix(self, grid: list[list[int]]) -> list[list[int]]:
n = len(grid)
ans = [[0] * n for _ in range(n)]
diag = collections.defaultdict(list)
for i, row in enumerate(grid):
for j, num in enumerate(row):
diag[i - j].append(num)
for key in diag:
diag[key].sor... | Solution |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_view_ops.py | {
"start": 2428,
"end": 3030
} | class ____(DimSpec):
"""Flatten a set of input dimensions, ensuring right-most adjacent elements remain adjacent in the output."""
input_dims: Sequence[DimSpec]
@classmethod
def new(cls, dims: Sequence[DimSpec]) -> DimSpec:
if len(dims) == 0:
# flattening a scalar leads to a single... | Flatten |
python | pypa__pip | src/pip/_vendor/distlib/resources.py | {
"start": 3208,
"end": 6087
} | class ____(object):
"""
Resource finder for file system resources.
"""
if sys.platform.startswith('java'):
skipped_extensions = ('.pyc', '.pyo', '.class')
else:
skipped_extensions = ('.pyc', '.pyo')
def __init__(self, module):
self.module = module
self.loader = ... | ResourceFinder |
python | instagram__MonkeyType | monkeytype/stubs.py | {
"start": 9005,
"end": 9270
} | class ____(metaclass=ABCMeta):
def __eq__(self, other: Any) -> bool:
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return NotImplemented
@abstractmethod
def render(self) -> str:
pass
| Stub |
python | doocs__leetcode | solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/Solution.py | {
"start": 0,
"end": 213
} | class ____:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
f = defaultdict(int)
for x in arr:
f[x] = f[x - difference] + 1
return max(f.values())
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/functionAnnotation2.py | {
"start": 240,
"end": 550
} | class ____:
def method0(self, a, b):
# type: (str, int) -> str
return ""
# Too few annotations
def method1(self, a, b):
# type: (str) -> str
return ""
# Too many annotations
def method2(self, a, b): # type: (str, int, int, int) -> str
return ""
| ClassA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor23.py | {
"start": 417,
"end": 741
} | class ____(Generic[T, V_co]):
def fmap1(self, fn: Callable[[V_co], U]) -> "Parser[T, U]":
def fmap2(stream: Sequence[T], pos: int, bt: int) -> Result[U]:
raise NotImplementedError()
reveal_type(FnParser(fmap2), expected_text="FnParser[T@Parser, U@fmap1]")
return FnParser(fmap2)
... | Parser |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 136398,
"end": 137657
} | class ____(
TestCase,
SnubaTestCase,
CorePostProcessGroupTestMixin,
SnoozeTestSkipSnoozeMixin,
PerformanceIssueTestCase,
):
def create_event(self, data, project_id, assert_no_errors=True):
group = self.create_group(
type=PerformanceP95EndpointRegressionGroupType.type_id,
... | PostProcessGroupAggregateEventTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 58511,
"end": 58635
} | class ____(GenericFunction[float]):
"""The RANDOM() SQL function."""
_has_args = True
inherit_cache = True
| random |
python | anthropics__anthropic-sdk-python | tests/lib/test_bedrock.py | {
"start": 536,
"end": 598
} | class ____(Protocol):
request: httpx.Request
| MockRequestCall |
python | pydantic__pydantic | pydantic-core/tests/validators/test_model_fields.py | {
"start": 33152,
"end": 33307
} | class ____:
def __init__(self):
self.a = 1
self.b = 2
@property
def c(self):
return 'ham'
@dataclass
| ClassWithAttributes |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/stateful_observation.py | {
"start": 3846,
"end": 12254
} | class ____(
gym.ObservationWrapper[WrapperObsType, ActType, ObsType],
gym.utils.RecordConstructorArgs,
):
"""Augment the observation with the number of time steps taken within an episode.
The :attr:`normalize_time` if ``True`` represents time as a normalized value between [0,1]
otherwise if ``False... | TimeAwareObservation |
python | jazzband__django-waffle | waffle/models.py | {
"start": 17509,
"end": 17790
} | class ____(AbstractBaseSwitch):
"""A feature switch.
Switches are active, or inactive, globally.
"""
class Meta(AbstractBaseSwitch.Meta):
swappable = 'WAFFLE_SWITCH_MODEL'
verbose_name = _('Switch')
verbose_name_plural = _('Switches')
| Switch |
python | pypa__warehouse | warehouse/integrations/secrets/utils.py | {
"start": 2166,
"end": 2484
} | class ____:
"""
A TokenLeakMatcher is linked to a specific regex pattern. When provided
a string that matches this pattern, the matcher can extract a token-like string
from it.
"""
name: str
pattern: re.Pattern
def extract(self, text):
raise NotImplementedError
| TokenLeakMatcher |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 52208,
"end": 52998
} | class ____(TestCase):
"""Exercise dictionary creation with JIT disabled. """
def test_dict_create_no_jit_using_new_dict(self):
with override_config('DISABLE_JIT', True):
with forbid_codegen():
d = dictobject.new_dict(int32, float32)
self.assertEqual(type(d), ... | TestNoJit |
python | ansible__ansible | test/lib/ansible_test/_internal/connections.py | {
"start": 2201,
"end": 3042
} | class ____(Connection):
"""Connect to localhost."""
def __init__(self, args: EnvironmentConfig) -> None:
self.args = args
def run(
self,
command: list[str],
capture: bool,
interactive: bool = False,
data: t.Optional[str] = None,
stdin: t.Optional[t.I... | LocalConnection |
python | ansible__ansible | test/integration/targets/fork_safe_stdio/callback_plugins/spewstdio.py | {
"start": 1015,
"end": 2450
} | class ____(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_NAME = 'spewstdio'
def __init__(self):
super().__init__()
self.display = Display()
if os.environ.get('SPEWSTDIO_ENABLED', '0') != '1':
self.display.warning('spewstdio test plugin loaded but disabled; set SPEWSTDI... | CallbackModule |
python | ashishps1__awesome-system-design-resources | implementations/python/consistent_hashing/consistent-hashing.py | {
"start": 30,
"end": 3260
} | class ____:
def __init__(self, servers, num_replicas=3):
"""
Initializes the consistent hashing ring.
- servers: List of initial server names (e.g., ["S0", "S1", "S2"])
- num_replicas: Number of virtual nodes per server for better load balancing
"""
self.num_replicas... | ConsistentHashing |
python | wandb__wandb | wandb/sdk/internal/datastore.py | {
"start": 1188,
"end": 9455
} | class ____:
_index: int
_flush_offset: int
def __init__(self) -> None:
self._opened_for_scan = False
self._fp: Optional[IO[Any]] = None
self._index = 0
self._flush_offset = 0
self._size_bytes = 0
self._crc = [0] * (LEVELDBLOG_LAST + 1)
for x in range... | DataStore |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py | {
"start": 7144,
"end": 8081
} | class ____:
"""Test redact strategy."""
def test_redact_email(self):
middleware = PIIMiddleware("email", strategy="redact")
state = {"messages": [HumanMessage("Email me at test@example.com")]}
result = middleware.before_model(state, None)
assert result is not None
asse... | TestRedactStrategy |
python | psf__black | tests/data/cases/target_version_flag.py | {
"start": 97,
"end": 211
} | class ____[T: str]:
def method1(self) -> T:
...
# output
# this is invalid in versions below py312
| ClassA |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_daemon_cursor.py | {
"start": 7336,
"end": 7743
} | class ____(NamedTuple):
"""Wrapper class for the legacy AssetDaemonCursor object, which is not a serializable NamedTuple."""
serialized_cursor: str
def get_asset_daemon_cursor(self, asset_graph: Optional[BaseAssetGraph]) -> AssetDaemonCursor:
return backcompat_deserialize_asset_daemon_cursor_str(
... | LegacyAssetDaemonCursorWrapper |
python | google__pytype | pytype/pytd/optimize.py | {
"start": 14855,
"end": 15240
} | class ____(visitors.Visitor):
"""Changes the generic type from "object" to "Any"."""
def __init__(self):
super().__init__()
self.old_generic_type = pytd.ClassType("builtins.object")
self.new_generic_type = pytd.AnythingType()
def VisitClassType(self, t):
if t == self.old_generic_type:
retu... | AdjustGenericType |
python | pytorch__pytorch | torch/nn/parameter.py | {
"start": 796,
"end": 4176
} | class ____(torch.Tensor, metaclass=_ParameterMeta):
r"""A kind of Tensor that is to be considered a module parameter.
Parameters are :class:`~torch.Tensor` subclasses, that have a
very special property when used with :class:`Module` s - when they're
assigned as Module attributes they are automatically ... | Parameter |
python | numpy__numpy | numpy/f2py/symbolic.py | {
"start": 1168,
"end": 1294
} | class ____(Enum):
"""
Used as Expr.tostring language argument.
"""
Python = 0
Fortran = 1
C = 2
| Language |
python | PrefectHQ__prefect | src/prefect/utilities/asyncutils.py | {
"start": 15828,
"end": 15939
} | class ____(RuntimeError):
"""Used to indicate retrieving gather results before completion"""
| GatherIncomplete |
python | huggingface__transformers | src/transformers/models/granitemoe/modeling_granitemoe.py | {
"start": 20754,
"end": 27675
} | class ____(GraniteMoePreTrainedModel):
def __init__(self, config: GraniteMoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
... | GraniteMoeModel |
python | huggingface__transformers | src/transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py | {
"start": 1297,
"end": 3942
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"height": 224, "width": 224}
do_resize = True
do_rescale = True
do_normalize = True
# Overridden for DINOv3 to preserve order of transfo... | DINOv3ViTImageProcessorFast |
python | getsentry__sentry | src/sentry/statistical_detectors/detector.py | {
"start": 1861,
"end": 23589
} | class ____(ABC):
source: str
kind: str
regression_type: RegressionType
min_change: int
buffer_period: timedelta
resolution_rel_threshold: float
escalation_rel_threshold: float
@classmethod
@abstractmethod
def min_throughput_threshold(cls) -> int: ...
@classmethod
def co... | RegressionDetector |
python | google__jax | jax/_src/debugger/colab_debugger.py | {
"start": 3620,
"end": 5446
} | class ____(colab_lib.DynamicDOMElement):
"""Displays information about a stack frame."""
def __init__(self, frame):
super().__init__()
self._header = colab_lib.dynamic(
colab_lib.div(colab_lib.pre(colab_lib.code(""))))
self._code_view = CodeViewer("", highlights=[])
self.frame = frame
s... | FramePreview |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 1467,
"end": 2502
} | class ____(db.Model):
__tablename__ = "organization_roles"
__table_args__ = (
Index("organization_roles_user_id_idx", "user_id"),
Index("organization_roles_organization_id_idx", "organization_id"),
UniqueConstraint(
"user_id",
"organization_id",
name="... | OrganizationRole |
python | pytorch__pytorch | test/distributed/checkpoint/test_state_dict_utils.py | {
"start": 861,
"end": 11973
} | class ____(DTensorTestBase):
@property
def world_size(self):
return min(4, torch.cuda.device_count())
@with_comms
@skip_if_lt_x_gpu(2)
def test_gather_state_dict_dtensor(self):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
torch.random.manual_seed(di... | TestStateDictUtils |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/netbsd.py | {
"start": 6105,
"end": 6213
} | class ____(HardwareCollector):
_fact_class = NetBSDHardware
_platform = 'NetBSD'
| NetBSDHardwareCollector |
python | modin-project__modin | modin/core/execution/dask/implementations/pandas_on_dask/io/io.py | {
"start": 2369,
"end": 8336
} | class ____(BaseIO):
"""The class implements interface in ``BaseIO`` using Dask as an execution engine."""
frame_cls = PandasOnDaskDataframe
frame_partition_cls = PandasOnDaskDataframePartition
query_compiler_cls = PandasQueryCompiler
build_args = dict(
frame_cls=PandasOnDaskDataframe,
... | PandasOnDaskIO |
python | pytorch__pytorch | test/test_python_dispatch.py | {
"start": 26784,
"end": 98668
} | class ____(TestCase):
def test_basic(self) -> None:
with capture_logs() as logs:
x = LoggingTensor(torch.tensor([3.0]), requires_grad=True)
log_input("x", x)
y = x * x
saved_x = y.grad_fn._saved_self
grad_y = LoggingTensor(torch.tensor([1.0]))
... | TestPythonDispatch |
python | great-expectations__great_expectations | great_expectations/render/view/view.py | {
"start": 894,
"end": 1244
} | class ____:
def render(self, document, indent=2) -> None:
print(json.dumps(document, indent=indent))
# Abe 2019/06/26: This View should probably actually be called JinjaView or something similar.
# Down the road, I expect to wind up with class hierarchy along the lines of:
# View > JinjaView > GEContent... | PrettyPrintTemplate |
python | doocs__leetcode | solution/1800-1899/1822.Sign of the Product of an Array/Solution.py | {
"start": 0,
"end": 219
} | class ____:
def arraySign(self, nums: List[int]) -> int:
ans = 1
for v in nums:
if v == 0:
return 0
if v < 0:
ans *= -1
return ans
| Solution |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 5044,
"end": 5532
} | class ____(TestModelMixin, TestBase):
def testCreateRevisionManageManually(self):
with reversion.create_revision(manage_manually=True):
TestModel.objects.create()
self.assertNoRevision()
def testCreateRevisionManageManuallyNested(self):
with reversion.create_revision():
... | CreateRevisionManageManuallyTest |
python | facebook__pyre-check | client/commands/tests/daemon_querier_test.py | {
"start": 1383,
"end": 8739
} | class ____(testslide.TestCase):
@setup.async_test
async def test_get_type_coverage__happy_path(self) -> None:
with tempfile.NamedTemporaryFile(suffix=".py") as tmpfile:
tmpfile.write(b"def foo(x):\n pass\n")
tmpfile.flush()
test_path = Path(tmpfile.name)
... | DaemonQuerierTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_print_options.py | {
"start": 301,
"end": 2545
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_print_options() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_print_options_default(self):
"""Test the _write_print_... | TestWritePrintOptions |
python | PyCQA__pylint | tests/functional/e/enum_subclasses.py | {
"start": 1001,
"end": 1078
} | class ____(BaseEnum):
FOO = 1
BAR = 2
print(MyEnum.FOO.value)
| MyEnum |
python | pydata__xarray | xarray/backends/common.py | {
"start": 10924,
"end": 12340
} | class ____:
__slots__ = ("lock", "regions", "sources", "targets")
def __init__(self, lock=None):
self.sources = []
self.targets = []
self.regions = []
self.lock = lock
def add(self, source, target, region=None):
if is_chunked_array(source):
self.sources.... | ArrayWriter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_rds.py | {
"start": 6405,
"end": 10613
} | class ____:
@classmethod
def setup_class(cls):
cls.dag = DAG(
dag_id="test_dag",
schedule=None,
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
)
cls.hook = RdsHook(aws_conn_id=AWS_CONN, region_name="us-east-1")
_patch_hook_get_c... | TestRdsCreateDbSnapshotOperator |
python | django-mptt__django-mptt | mptt/managers.py | {
"start": 1108,
"end": 50192
} | class ____(models.Manager.from_queryset(TreeQuerySet)):
"""
A manager for working with trees of objects.
"""
def contribute_to_class(self, model, name):
super().contribute_to_class(model, name)
if not model._meta.abstract:
self.tree_model = _get_tree_model(model)
... | TreeManager |
python | PrefectHQ__prefect | src/prefect/settings/sources.py | {
"start": 1077,
"end": 2634
} | class ____(EnvSettingsSource):
"""
Custom pydantic settings source to filter out specific environment variables.
All validation aliases are loaded from environment variables by default. We use
`AliasPath` to maintain the ability set fields via model initialization, but those
shouldn't be loaded fro... | EnvFilterSettingsSource |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 24019,
"end": 27462
} | class ____(BaseTestCase):
founders_html = (
"<table>"
"<thead>"
"<tr><th>first_name</th><th>last_name</th><th>gpa</th></tr>"
"</thead>"
"<tbody>"
"<tr><td>John</td><td>Adams</td><td>90</td></tr>"
"<tr><td>George</td><td>Washington</td><td>67</td></tr>"
... | HTMLTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 2881,
"end": 3077
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI Model link."""
name = "Vertex AI Model"
key = "model_conf"
format_str = VERTEX_AI_MODEL_LINK
| VertexAIModelLink |
python | chroma-core__chroma | chromadb/test/property/test_persist.py | {
"start": 9490,
"end": 9627
} | class ____(EmbeddingStateMachineStates):
persist = "persist"
MIN_STATE_CHANGES_BEFORE_PERSIST = 5
| PersistEmbeddingsStateMachineStates |
python | getsentry__sentry | src/sentry/integrations/slack/views/unlink_team.py | {
"start": 1380,
"end": 1546
} | class ____(SlackLinkageView, UnlinkTeamView):
"""
Django view for unlinking team from slack channel. Deletes from ExternalActor table.
"""
| SlackUnlinkTeamView |
python | huggingface__transformers | src/transformers/models/smolvlm/video_processing_smolvlm.py | {
"start": 3510,
"end": 14850
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.LANCZOS
size = {"longest_edge": 4 * 364}
max_image_size = {"longest_edge": 364}
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = ... | SmolVLMVideoProcessor |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/audio_interface.py | {
"start": 391,
"end": 4041
} | class ____(BaseVoiceAgentInterface):
def __init__(
self,
chunk_size: int = CHUNK_SIZE,
rate: int = RATE,
format: int = FORMAT,
on_audio_callback: Optional[Callable] = None,
):
self.chunk_size = chunk_size
self.rate = rate
self.format = format
... | OpenAIVoiceAgentInterface |
python | google__pytype | pytype/tests/test_paramspec.py | {
"start": 15560,
"end": 16479
} | class ____(test_base.BaseTest):
"""Test some more complex uses of contextlib."""
def test_wrapper(self):
self.Check("""
import contextlib
import functools
from typing import Callable, ContextManager, Iterator, TypeVar
T = TypeVar("T")
class Builder:
def __init__(self, e... | ContextlibTest |
python | hynek__structlog | tests/test_contextvars.py | {
"start": 700,
"end": 7128
} | class ____:
async def test_bind(self):
"""
Binding a variable causes it to be included in the result of
merge_contextvars.
"""
event_loop = asyncio.get_running_loop()
async def coro():
bind_contextvars(a=1)
return merge_contextvars(None, None,... | TestContextvars |
python | ansible__ansible | lib/ansible/_internal/_templating/_lazy_containers.py | {
"start": 2130,
"end": 2452
} | class ____(RuntimeError):
"""Error raised when attempting to construct a lazy container with unsupported arguments."""
def __init__(self):
super().__init__("Direct construction of lazy containers is not supported.")
@t.final
@dataclasses.dataclass(frozen=True, slots=True)
| UnsupportedConstructionMethodError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass4.py | {
"start": 403,
"end": 655
} | class ____(MyCustomClass):
pass
DerivedCustomClass.do_something("hi", 3)
# This should generate an error because the second
# argument is the wrong type.
DerivedCustomClass.do_something("hi", "no")
instance = DerivedCustomClass()
| DerivedCustomClass |
python | getsentry__sentry | src/sentry/app.py | {
"start": 167,
"end": 1190
} | class ____(local):
def __init__(self) -> None:
self.request_stack: list[HttpRequest] = []
@property
def request(self) -> HttpRequest | None:
if self.request_stack:
return self.request_stack[-1]
else:
return None
@contextlib.contextmanager
def active_... | State |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 1694,
"end": 2175
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=5, name="MEMBER_REMOVE", api_name="member.remove")
def render(self, audit_log_entry: AuditLogEntry) -> str:
if audit_log_entry.target_user == audit_log_entry.actor:
return "left the organization"
... | MemberRemoveAuditLogEvent |
python | apache__airflow | providers/alibaba/src/airflow/providers/alibaba/cloud/operators/analyticdb_spark.py | {
"start": 1222,
"end": 3365
} | class ____(BaseOperator):
"""Abstract base class that defines how users develop AnalyticDB Spark."""
def __init__(
self,
*,
adb_spark_conn_id: str = "adb_spark_default",
region: str | None = None,
polling_interval: int = 0,
**kwargs: Any,
) -> None:
s... | AnalyticDBSparkBaseOperator |
python | getsentry__sentry | src/sentry/integrations/bitbucket/webhook.py | {
"start": 2431,
"end": 2616
} | class ____(SentryAPIException):
status_code = 400
code = f"{PROVIDER_NAME}.webhook.invalid-signature"
message = "Webhook signature is invalid"
| WebhookInvalidSignatureException |
python | sympy__sympy | sympy/parsing/sympy_parser.py | {
"start": 43313,
"end": 44086
} | class ____():
"""class to retrieve transformations from a given slice
EXAMPLES
========
>>> from sympy.parsing.sympy_parser import T, standard_transformations
>>> assert T[:5] == standard_transformations
"""
def __init__(self):
self.N = len(_transformation)
def __str__(self):
... | _T |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 45690,
"end": 51612
} | class ____(Wav2Vec2ConformerPreTrainedModel):
def __init__(self, config: Wav2Vec2ConformerConfig):
super().__init__(config)
self.config = config
self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config)
self.feature_projection = Wav2Vec2ConformerFeatureProjection(config)
... | Wav2Vec2ConformerModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 42950,
"end": 44836
} | class ____(test_util.TensorFlowTestCase):
"""Test varied index types and host located memory."""
def testHostVsDevice(self):
var2 = variables.Variable(
array_ops.reshape(
math_ops.cast(math_ops.range(1, 5, 1), dtypes.float32),
shape=(4, 1, 1)))
varshape = variables.Variable(... | StridedSliceGradTypeTest |
python | realpython__materials | python-class/robot.py | {
"start": 0,
"end": 472
} | class ____:
def __init__(self):
self.body = Body()
self.arm = Arm()
def rotate_body_left(self, degrees=10):
self.body.rotate_left(degrees)
def rotate_body_right(self, degrees=10):
self.body.rotate_right(degrees)
def move_arm_up(self, distance=10):
self.arm.move... | IndustrialRobot |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/deep_learning/layers.py | {
"start": 16351,
"end": 16829
} | class ____(PoolingLayer):
def _pool_forward(self, X_col):
arg_max = np.argmax(X_col, axis=0).flatten()
output = X_col[arg_max, range(arg_max.size)]
self.cache = arg_max
return output
def _pool_backward(self, accum_grad):
accum_grad_col = np.zeros((np.prod(self.pool_shape... | MaxPooling2D |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-baseten/llama_index/llms/baseten/base.py | {
"start": 905,
"end": 9385
} | class ____(OpenAI):
"""
Baseten LLM with support for both dedicated and model apis endpoints.
Args:
model_id (str): The Baseten model ID (e.g., "12a3b4c5") or model name (e.g., "deepseek-ai/DeepSeek-V3-0324").
When using model_apis=True, model availability is validated dynami... | Baseten |
python | plotly__plotly.py | plotly/graph_objs/volume/colorbar/title/_font.py | {
"start": 233,
"end": 9908
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume.colorbar.title"
_path_str = "volume.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Font |
python | sphinx-doc__sphinx | sphinx/builders/_epub_base.py | {
"start": 2263,
"end": 2322
} | class ____(NamedTuple):
idref: str
linear: bool
| Spine |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 278245,
"end": 278894
} | 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("DeploymentRequestEdge"), graphql_name="edges"
)
nodes = s... | DeploymentRequestConnection |
python | doocs__leetcode | solution/0800-0899/0842.Split Array into Fibonacci Sequence/Solution.py | {
"start": 0,
"end": 711
} | class ____:
def splitIntoFibonacci(self, num: str) -> List[int]:
def dfs(i):
if i == n:
return len(ans) > 2
x = 0
for j in range(i, n):
if j > i and num[i] == '0':
break
x = x * 10 + int(num[j])
... | Solution |
python | mlflow__mlflow | mlflow/gateway/base_models.py | {
"start": 1018,
"end": 1278
} | class ____(
BaseModel,
# Ignore extra fields for pydantic limit models, since they are unused
extra="ignore",
):
"""
A pydantic model representing Gateway Limit data, such as renewal period, limit
key, limit value, etc.
"""
| LimitModel |
python | simonw__sqlite-utils | sqlite_utils/cli.py | {
"start": 1326,
"end": 86577
} | class ____(click.Choice):
def __init__(self, choices):
super().__init__([choice.lower() for choice in choices])
def convert(self, value, param, ctx):
return super().convert(value.lower(), param, ctx)
def output_options(fn):
for decorator in reversed(
(
click.option(
... | CaseInsensitiveChoice |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 1317,
"end": 1471
} | class ____:
def __init__(self, one=None):
if one is not None:
self.one = one
def one(self): # [method-hidden]
pass
| One |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 214210,
"end": 214557
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("BypassPullRequestAllowance", graphql_name="node")
... | BypassPullRequestAllowanceEdge |
python | wandb__wandb | wandb/sdk/launch/runner/kubernetes_monitor.py | {
"start": 5578,
"end": 15442
} | class ____:
"""Monitors kubernetes resources managed by the launch agent.
Note: this class is forced to be a singleton in order to prevent multiple
threads from being created that monitor the same kubernetes resources.
"""
_instance = None # This is used to ensure only one instance is created.
... | LaunchKubernetesMonitor |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_json.py | {
"start": 711,
"end": 1996
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.is_valid_json"
filter_column_isnull = False
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasE... | ColumnValuesToBeValidJson |
python | tensorflow__tensorflow | tensorflow/python/keras/distribute/distribute_coordinator_utils.py | {
"start": 1982,
"end": 27121
} | class ____(object):
"""The worker context class.
This context object provides configuration information for each task. One
context manager with a worker context object will be created per
invocation to the `worker_fn` where `get_current_worker_context` can be called
to access the worker context object.
"""... | _WorkerContext |
python | huggingface__transformers | src/transformers/models/wav2vec2/modeling_wav2vec2.py | {
"start": 67718,
"end": 69433
} | class ____(Wav2Vec2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
warnings.warn(
"The class `Wav2Vec2ForMaskedLM` is deprecated. Please use `Wav2Vec2ForCTC` instead.", FutureWarning
)
self.wav2vec2 = Wav2Vec2Model(config)
self.dropout = n... | Wav2Vec2ForMaskedLM |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_delete_model_double_pending_app/migrations/0003_double_pending.py | {
"start": 190,
"end": 482
} | class ____(CheckedMigration):
dependencies = [
("bad_flow_delete_model_double_pending_app", "0002_delete_pending"),
]
operations = [
SafeDeleteModel(
name="TestTable",
deletion_action=DeletionAction.MOVE_TO_PENDING,
),
]
| Migration |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/transpiler_test.py | {
"start": 1095,
"end": 1415
} | class ____(transpiler.PyToPy):
def get_caching_key(self, ctx):
del ctx
return 0
def get_extra_locals(self):
return {}
def transform_ast(self, node, ctx):
return FlipSignTransformer(ctx).visit(node)
global_var_for_test_global = 1
global_var_for_test_namespace_collisions = object()
| TestTranspiler |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 6263,
"end": 6717
} | class ____(DocumentEvent):
'''
Announce when a Document is fully idle.
.. note::
To register a JS callback for this event in standalone embedding
mode, one has to either use ``curdoc()`` or an explicit ``Document``
instance, e.g.:
.. code-block:: python
from bo... | DocumentReady |
python | ansible__ansible | lib/ansible/parsing/vault/__init__.py | {
"start": 50844,
"end": 51827
} | class ____:
"""Provides context-style access to vault secrets."""
_current: t.ClassVar[t.Self | None] = None
def __init__(self, secrets: list[tuple[str, VaultSecret]]) -> None:
self.secrets = secrets
@classmethod
def initialize(cls, value: t.Self) -> None:
"""
Initialize Va... | VaultSecretsContext |
python | getsentry__sentry | src/sentry/notifications/api/endpoints/user_notification_details.py | {
"start": 803,
"end": 1728
} | class ____(Serializer):
def get_attrs(self, item_list, user, *args, **kwargs):
user_options = UserOption.objects.filter(
user__in=item_list, organization_id=None, project_id=None
).select_related("user")
keys_to_user_option_objects = {user_option.key: user_option for user_option ... | UserNotificationsSerializer |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/python_environments.py | {
"start": 7513,
"end": 12854
} | class ____(PythonEnvironment):
"""
A Conda_ environment.
.. _Conda: https://conda.io/docs/
"""
# pylint: disable=arguments-differ
def venv_bin(self, filename=None):
prefixes = ["$CONDA_ENVS_PATH", "$CONDA_DEFAULT_ENV", "bin"]
return super().venv_bin(prefixes, filename=filename)... | Conda |
python | astropy__astropy | astropy/io/fits/hdu/base.py | {
"start": 56412,
"end": 58020
} | class ____(ExtensionHDU):
"""
A Non-standard Extension HDU class.
This class is used for an Extension HDU when the ``XTENSION``
`Card` has a non-standard value. In this case, Astropy can figure
out how big the data is but not what it is. The data for this HDU
is read from the file as a byte s... | NonstandardExtHDU |
python | django__django | tests/queries/tests.py | {
"start": 96150,
"end": 100846
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.school = School.objects.create()
cls.room_1 = Classroom.objects.create(
school=cls.school, has_blackboard=False, name="Room 1"
)
cls.room_2 = Classroom.objects.create(
school=cls.school, has_bl... | QuerySetBitwiseOperationTests |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/notifications/sqs.py | {
"start": 1096,
"end": 4250
} | class ____(BaseNotifier):
"""
Amazon SQS (Simple Queue Service) Notifier.
.. seealso::
For more information on how to use this notifier, take a look at the guide:
:ref:`howto/notifier:SqsNotifier`
:param aws_conn_id: The :ref:`Amazon Web Services Connection id <howto/connection:aws>`
... | SqsNotifier |
python | numpy__numpy | numpy/distutils/tests/test_ccompiler_opt_conf.py | {
"start": 580,
"end": 977
} | class ____(CCompilerOpt):
fake_info = ("arch", "compiler", "extra_args")
def __init__(self, *args, **kwargs):
CCompilerOpt.__init__(self, None, **kwargs)
def dist_compile(self, sources, flags, **kwargs):
return sources
def dist_info(self):
return FakeCCompilerOpt.fake_info
@s... | FakeCCompilerOpt |
python | plotly__plotly.py | plotly/graph_objs/_scattersmith.py | {
"start": 215,
"end": 68176
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "scattersmith"
_valid_props = {
"cliponaxis",
"connectgaps",
"customdata",
"customdatasrc",
"fill",
"fillcolor",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
"hoveron",... | Scattersmith |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/hstore.py | {
"start": 8708,
"end": 8838
} | class ____(sqlfunc.GenericFunction):
type = ARRAY(sqltypes.Text)
name = "avals"
inherit_cache = True
| _HStoreValsFunction |
python | huggingface__transformers | src/transformers/models/mobilevit/image_processing_mobilevit.py | {
"start": 1560,
"end": 2256
} | class ____(ImagesKwargs, total=False):
"""
do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
Whether to flip the color channels from RGB to BGR or vice versa.
do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
Whether or not to red... | MobileVitImageProcessorKwargs |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 99697,
"end": 100725
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None ... | BigBirdClassificationHead |
python | django__django | tests/dbshell/test_sqlite.py | {
"start": 279,
"end": 1691
} | class ____(SimpleTestCase):
def settings_to_cmd_args_env(self, settings_dict, parameters=None):
if parameters is None:
parameters = []
return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters)
def test_path_name(self):
self.assertEqual(
self.setti... | SqliteDbshellCommandTestCase |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 68492,
"end": 69593
} | class ____(nn.Module):
"""
Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
height and width of a bounding box w.r.t. an image.
Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
Origin from https://github.com... | RTDetrMLPPredictionHead |
python | huggingface__transformers | src/transformers/models/smollm3/modeling_smollm3.py | {
"start": 13409,
"end": 15263
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: SmolLM3Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = SmolLM3Attention(config=config, layer_idx=layer_idx)
self.mlp = SmolLM3MLP(config)
self.input_layerno... | SmolLM3DecoderLayer |
python | HIPS__autograd | examples/convnet.py | {
"start": 298,
"end": 2027
} | class ____:
"""A helper class to index into a parameter vector."""
def __init__(self):
self.idxs_and_shapes = {}
self.N = 0
def add_weights(self, name, shape):
start = self.N
self.N += np.prod(shape)
self.idxs_and_shapes[name] = (slice(start, self.N), shape)
de... | WeightsParser |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 4071,
"end": 4258
} | class ____(enum.Enum):
"""this is enum class"""
@classmethod
def _missing_(cls, value):
"""docstring"""
return super()._missing_(value)
| EnumSunderMissingInClass |
python | mlflow__mlflow | mlflow/data/huggingface_dataset.py | {
"start": 855,
"end": 10390
} | class ____(Dataset, PyFuncConvertibleDatasetMixin):
"""
Represents a HuggingFace dataset for use with MLflow Tracking.
"""
def __init__(
self,
ds: "datasets.Dataset",
source: HuggingFaceDatasetSource,
targets: str | None = None,
name: str | None = None,
d... | HuggingFaceDataset |
python | chroma-core__chroma | chromadb/api/async_api.py | {
"start": 10651,
"end": 16217
} | class ____(AsyncBaseAPI, ABC):
tenant: str
database: str
@abstractmethod
async def list_collections(
self,
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> Sequence[AsyncCollection]:
"""List all collections.
Args:
limit: The maximum... | AsyncClientAPI |
python | getsentry__sentry | src/sentry/api/paginator.py | {
"start": 15013,
"end": 17882
} | class ____[T]:
def __init__(
self,
data: Iterable[tuple[int, T]],
reverse: bool = False,
max_limit: int = MAX_LIMIT,
on_results=None,
):
data = sorted(data, reverse=reverse)
self.scores = [score for score, _ in data]
self.values = [value for _, val... | SequencePaginator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.