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 | pandas-dev__pandas | pandas/io/parsers/arrow_parser_wrapper.py | {
"start": 666,
"end": 11952
} | class ____(ParserBase):
"""
Wrapper for the pyarrow engine for read_csv()
"""
def __init__(self, src: ReadBuffer[bytes], **kwds) -> None:
super().__init__(kwds)
self.kwds = kwds
self.src = src
self._parse_kwds()
def _parse_kwds(self) -> None:
"""
Va... | ArrowParserWrapper |
python | pypa__hatch | src/hatch/index/core.py | {
"start": 251,
"end": 786
} | class ____:
def __init__(self, repo: str):
self.repo = hyperlink.parse(repo).normalize()
# PyPI
if self.repo.host.endswith("pypi.org"): # no cov
repo_url = self.repo.replace(host="pypi.org") if self.repo.host == "upload.pypi.org" else self.repo
self.simple = repo_u... | IndexURLs |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1203201,
"end": 1203385
} | class ____(sgqlc.types.Type, Contribution):
"""Represents a user signing up for a GitHub account."""
__schema__ = github_schema
__field_names__ = ()
| JoinedGitHubContribution |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 21773,
"end": 22288
} | class ____(ExplicitlyIndexedNDArrayMixin):
"""Marker class for indexing adapters.
These classes translate between Xarray's indexing semantics and the underlying array's
indexing semantics.
"""
def get_duck_array(self):
key = BasicIndexer((slice(None),) * self.ndim)
return self[key]... | IndexingAdapter |
python | wandb__wandb | wandb/sdk/artifacts/exceptions.py | {
"start": 1042,
"end": 1524
} | class ____(ArtifactStatusError):
"""Raised for Artifact methods or attributes only available after logging."""
def __init__(self, fullname: str, obj: ArtifactT):
*_, name = fullname.split(".")
msg = (
f"{fullname!r} used prior to logging artifact or while in offline mode. "
... | ArtifactNotLoggedError |
python | chardet__chardet | chardet/enums.py | {
"start": 322,
"end": 712
} | class ____(Flag):
"""
This enum represents the different language filters we can apply to a
``UniversalDetector``.
"""
NONE = 0x00
CHINESE_SIMPLIFIED = 0x01
CHINESE_TRADITIONAL = 0x02
JAPANESE = 0x04
KOREAN = 0x08
NON_CJK = 0x10
ALL = 0x1F
CHINESE = CHINESE_SIMPLIFIED | ... | LanguageFilter |
python | Netflix__metaflow | metaflow/_vendor/v3_7/typing_extensions.py | {
"start": 54718,
"end": 70473
} | class ____(metaclass=_TypeVarLikeMeta):
"""Type variable."""
_backported_typevarlike = typing.TypeVar
def __new__(cls, name, *constraints, bound=None,
covariant=False, contravariant=False,
default=_marker, infer_variance=False):
if hasattr(typing, "TypeAliasType"):
... | TypeVar |
python | has2k1__plotnine | plotnine/stats/stat_unique.py | {
"start": 67,
"end": 449
} | class ____(stat):
"""
Remove duplicates
{usage}
Parameters
----------
{common_parameters}
See Also
--------
plotnine.geom_point : The default `geom` for this `stat`.
"""
DEFAULT_PARAMS = {"geom": "point", "position": "identity", "na_rm": False}
def compute_panel(self... | stat_unique |
python | PyCQA__pylint | doc/data/messages/i/invalid-overridden-method/bad.py | {
"start": 74,
"end": 178
} | class ____(Fruit):
def bore(self, insect): # [invalid-overridden-method]
insect.eat(self)
| Apple |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/featureflags.py | {
"start": 5199,
"end": 5539
} | class ____(SearchStrategy[FeatureFlags]):
def __init__(self, at_least_one_of: Iterable[Hashable] = ()):
super().__init__()
self._at_least_one_of = frozenset(at_least_one_of)
def do_draw(self, data: ConjectureData) -> FeatureFlags:
return FeatureFlags(data, at_least_one_of=self._at_least... | FeatureStrategy |
python | agronholm__apscheduler | src/apscheduler/_events.py | {
"start": 4895,
"end": 5158
} | class ____(SchedulerEvent):
"""
Signals that a scheduler has stopped.
:ivar exception: the exception that caused the scheduler to stop, if any
"""
exception: BaseException | None = None
@attrs.define(kw_only=True, frozen=True)
| SchedulerStopped |
python | google__pytype | pytype/vm_test.py | {
"start": 3217,
"end": 3692
} | class ____(VmTestBase):
"""Tests for recording annotations."""
def test_record_local_ops(self):
self.ctx.vm.run_program("v: int = None", "", maximum_depth=10)
self.assertEqual(
self.ctx.vm.local_ops,
{
"<module>": [
vm.LocalOp(name="v", op=vm.LocalOp.Op.ASSIGN),
... | AnnotationsTest |
python | etianen__django-reversion | tests/test_app/tests/test_admin.py | {
"start": 8823,
"end": 9320
} | class ____(LoginMixin, AdminMixin, TestBase):
def testHistorylistView(self):
with reversion.create_revision():
obj = TestModelParent.objects.create()
response = self.client.get(resolve_url("admin:test_app_testmodelparent_history", obj.pk))
self.assertContains(response, resolve_u... | AdminHistoryViewTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1540110,
"end": 1570919
} | class ____(
sgqlc.types.Type,
Node,
Actor,
PackageOwner,
ProjectOwner,
ProjectV2Owner,
ProjectV2Recent,
RepositoryDiscussionAuthor,
RepositoryDiscussionCommentAuthor,
RepositoryOwner,
UniformResourceLocatable,
ProfileOwner,
Sponsorable,
):
"""A user is an individu... | User |
python | pypa__pip | tests/data/packages/HackedEggInfo/setup.py | {
"start": 88,
"end": 303
} | class ____(orig_egg_info.egg_info):
def run(self):
orig_egg_info.egg_info.run(self)
setup(
name="hackedegginfo",
version="0.0.0",
cmdclass={"egg_info": egg_info},
zip_safe=False,
)
| egg_info |
python | pypa__pipenv | pipenv/patched/pip/_internal/req/__init__.py | {
"start": 587,
"end": 3126
} | class ____:
name: str
def _validate_requirements(
requirements: List[InstallRequirement],
) -> Generator[Tuple[str, InstallRequirement], None, None]:
for req in requirements:
assert req.name, f"invalid to-be-installed requirement: {req}"
yield req.name, req
def install_given_reqs(
re... | InstallationResult |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 11197,
"end": 12911
} | class ____(ContextWrappingVariable):
"""represents torch.func.jvp increment/decrement nesting"""
# A guard is needed as the grad level is baked into the torch FX graph
# This is fine if jvp is only called from within the function
# being compiled. But the FX graph may be invalid in the case of a jvp
... | JvpIncrementNestingCtxManagerVariable |
python | PrefectHQ__prefect | tests/client/test_prefect_client.py | {
"start": 62652,
"end": 64033
} | class ____:
@pytest.fixture
async def test_app(self):
app = FastAPI()
basic = HTTPBasic()
# Returns given credentials if an Authorization
# header is passed, otherwise raises 403
@app.get("/api/check_for_auth_header")
async def check_for_auth_header(credentials=D... | TestClientAuthString |
python | jina-ai__jina | tests/integration/networking/__init__.py | {
"start": 84,
"end": 195
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
docs[0].text = 'dummy'
| DummyExecutor |
python | getsentry__sentry | tests/sentry/middleware/test_access_log_middleware.py | {
"start": 920,
"end": 1070
} | class ____(Endpoint):
permission_classes = (SentryIsAuthenticated,)
def get(self, request):
return Response({"ok": True})
| DummyEndpoint |
python | charliermarsh__ruff | scripts/check_ecosystem.py | {
"start": 819,
"end": 6002
} | class ____(NamedTuple):
"""A GitHub repository at a specific ref."""
org: str
repo: str
ref: str | None
select: str = ""
ignore: str = ""
exclude: str = ""
# Generating fixes is slow and verbose
show_fixes: bool = False
@asynccontextmanager
async def clone(self: Self, check... | Repository |
python | django__django | tests/aggregation_regress/models.py | {
"start": 1466,
"end": 1674
} | class ____(models.Model):
EntryID = models.AutoField(primary_key=True, db_column="Entry ID")
Entry = models.CharField(unique=True, max_length=50)
Exclude = models.BooleanField(default=False)
| Entries |
python | pytest-dev__pytest | testing/_py/test_local.py | {
"start": 40690,
"end": 42696
} | class ____:
pytestmark = win32only
def test_owner_group_not_implemented(self, path1):
with pytest.raises(NotImplementedError):
_ = path1.stat().owner
with pytest.raises(NotImplementedError):
_ = path1.stat().group
def test_chmod_simple_int(self, path1):
mode... | TestWINLocalPath |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/pg_tf.py | {
"start": 792,
"end": 1361
} | class ____:
def __init__(self, M1, M2, f=tf.nn.tanh, use_bias=True, zeros=False):
if zeros:
W = np.zeros((M1, M2), dtype=np.float32)
else:
W = tf.random_normal(shape=(M1, M2)) * np.sqrt(2. / M1, dtype=np.float32)
self.W = tf.Variable(W)
self.use_bias = use_bias
if use_bias:
self... | HiddenLayer |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 14591,
"end": 14748
} | class ____(NoReturnType):
choices = ["a", "b"]
def draw(self) -> str: # [useless-parent-delegation]
return super().draw()
| ReturnTypeSpecified |
python | realpython__materials | dwitter-part-1/source_code_final/dwitter/models.py | {
"start": 159,
"end": 690
} | class ____(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follows = models.ManyToManyField(
"self", related_name="followed_by", symmetrical=False, blank=True
)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_profile... | Profile |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_deepspeed.py | {
"start": 1653,
"end": 1998
} | class ____(BoringModel):
def __init__(self):
super().__init__()
self.layer = None
def configure_model(self) -> None:
if self.layer is None:
self.layer = torch.nn.Linear(32, 2)
def on_load_checkpoint(self, checkpoint: dict[str, Any]) -> None:
self.configure_model... | ModelParallelBoringModel |
python | apache__airflow | airflow-core/tests/unit/ti_deps/deps/test_task_not_running_dep.py | {
"start": 1046,
"end": 1389
} | class ____:
def test_not_running_state(self):
ti = Mock(state=State.QUEUED, end_date=datetime(2016, 1, 1))
assert TaskNotRunningDep().is_met(ti=ti)
def test_running_state(self):
ti = Mock(state=State.RUNNING, end_date=datetime(2016, 1, 1))
assert not TaskNotRunningDep().is_met(t... | TestTaskNotRunningDep |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/spanner.py | {
"start": 22044,
"end": 25409
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a Cloud Spanner database.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SpannerDeleteDatabaseInstanceOperator`
:param instance_id: Cloud Spanner instance ID.
:param data... | SpannerDeleteDatabaseInstanceOperator |
python | falconry__falcon | falcon/inspect.py | {
"start": 12035,
"end": 12478
} | class ____(_Traversable):
"""Describes a sink.
Args:
prefix (str): The prefix of the sink.
name (str): The name of the sink function or class.
source_info (str): The source path where this sink was defined.
"""
__visit_name__ = 'sink'
def __init__(self, prefix: str, name: ... | SinkInfo |
python | python-poetry__poetry | src/poetry/utils/threading.py | {
"start": 328,
"end": 2420
} | class ____(functools.cached_property[T]):
def __init__(self, func: Callable[[C], T]) -> None:
super().__init__(func)
self._semaphore = threading.BoundedSemaphore()
self._locks: WeakKeyDictionary[object, threading.Lock] = WeakKeyDictionary()
@overload
def __get__(
self, insta... | AtomicCachedProperty |
python | mlflow__mlflow | mlflow/langchain/chat_agent_langgraph.py | {
"start": 11007,
"end": 13120
} | class ____(ToolNode):
"""
Helper class to make ToolNodes be compatible with
:py:class:`ChatAgentState <mlflow.langchain.chat_agent_langgraph.ChatAgentState>`.
Parse ``attachments`` and ``custom_outputs`` keys from the string output of a
LangGraph tool.
"""
def __init__(self, *args, **kwargs... | ChatAgentToolNode |
python | pytorch__pytorch | test/inductor/test_cudagraph_trees.py | {
"start": 2740,
"end": 179933
} | class ____(InductorTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._stack = contextlib.ExitStack()
cls._stack.enter_context(
config.patch(
{
"debug": True,
"cpp.min_chunk_size": 1,
... | TestCase |
python | huggingface__transformers | src/transformers/models/glm/modeling_glm.py | {
"start": 15421,
"end": 15952
} | class ____(PreTrainedModel):
config: GlmConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["GlmDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_c... | GlmPreTrainedModel |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 26327,
"end": 34261
} | class ____(UniformQuantizationObserverBase):
r"""Observer module for computing the quantization parameters based on the
running per channel min and max values.
This observer uses the tensor min/max statistics to compute the per channel
quantization parameters. The module records the running minimum and... | PerChannelMinMaxObserver |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 14884,
"end": 15331
} | class ____:
id: str
start_timestamp: float
finish_timestamp: float
exclusive_time: float
trace_id: str
def serialize(self) -> Any:
return {
"id": self.id,
"startTimestamp": self.start_timestamp,
"finishTimestamp": self.finish_timestamp,
"e... | ExampleSpan |
python | pytorch__pytorch | .github/scripts/generate_ci_workflows.py | {
"start": 1397,
"end": 2956
} | class ____:
os: str
build_configs: list[dict[str, str]]
package_type: str
# Optional fields
build_environment: str = ""
ciflow_config: CIFlowConfig = field(default_factory=CIFlowConfig)
is_scheduled: str = ""
branches: str = "nightly"
# Mainly for macos
macos_runner: str = "maco... | BinaryBuildWorkflow |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 5501,
"end": 5577
} | class ____(DurationPercentiles, UserCounts):
pass
| UserCountsAndPercentiles |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/mssql.py | {
"start": 608,
"end": 1400
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "mssql"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.mssql
@override
def create_batch_setup(
self,
request: pytest.FixtureReques... | MSSQLDatasourceTestConfig |
python | doocs__leetcode | solution/0900-0999/0932.Beautiful Array/Solution.py | {
"start": 0,
"end": 310
} | class ____:
def beautifulArray(self, n: int) -> List[int]:
if n == 1:
return [1]
left = self.beautifulArray((n + 1) >> 1)
right = self.beautifulArray(n >> 1)
left = [x * 2 - 1 for x in left]
right = [x * 2 for x in right]
return left + right
| Solution |
python | ray-project__ray | doc/source/ray-core/doc_code/direct_transport_nixl.py | {
"start": 1601,
"end": 2480
} | class ____:
def __init__(self):
self.tensor1 = torch.tensor([1, 2, 3])
self.tensor2 = torch.tensor([4, 5, 6])
self.tensor3 = torch.tensor([7, 8, 9])
@ray.method(tensor_transport="nixl")
def send_dict1(self):
return {"round1-1": self.tensor1, "round1-2": self.tensor2}
@r... | Actor |
python | mlflow__mlflow | tests/utils/test_annotations.py | {
"start": 1139,
"end": 1273
} | class ____:
a: int
b: int
def add(self):
return self.a + self.b
@deprecated()
@dataclass
| AnotherDeprecatedDataClass |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 22536,
"end": 24339
} | class ____(models.Model):
class Meta:
abstract = True
constraints = [
models.UniqueConstraint(
fields=["device_code"],
name="%(app_label)s_%(class)s_unique_device_code",
),
]
AUTHORIZED = "authorized"
AUTHORIZATION_PENDING = "a... | AbstractDeviceGrant |
python | wandb__wandb | wandb/vendor/pygments/lexers/asm.py | {
"start": 5511,
"end": 5856
} | class ____(DelegatingLexer):
"""
For the output of 'objdump -Sr on compiled D files'
"""
name = 'd-objdump'
aliases = ['d-objdump']
filenames = ['*.d-objdump']
mimetypes = ['text/x-d-objdump']
def __init__(self, **options):
super(DObjdumpLexer, self).__init__(DLexer, ObjdumpLexe... | DObjdumpLexer |
python | spulec__freezegun | tests/test_datetimes.py | {
"start": 14632,
"end": 14776
} | class ____: # type: ignore
def __call__(self, *args: Any, **kws: Any) -> Any:
return (args, kws)
@freeze_time("2012-01-14")
| Callable |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/ingress.py | {
"start": 268,
"end": 434
} | class ____(BaseModel):
enabled: bool
secretName: str
# Enforce as HTTPIngressPath: see https://github.com/dagster-io/dagster/issues/3184
| IngressTLSConfiguration |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/pg_theano.py | {
"start": 1262,
"end": 1813
} | class ____:
def __init__(self, M1, M2, f=T.nnet.relu, use_bias=True, zeros=False):
if zeros:
W = np.zeros((M1, M2))
else:
W = np.random.randn(M1, M2) * np.sqrt(2. / M1)
self.W = theano.shared(W)
self.params = [self.W]
self.use_bias = use_bias
if use_bias:
self.b = theano.shar... | HiddenLayer |
python | TheAlgorithms__Python | graphs/bidirectional_a_star.py | {
"start": 1661,
"end": 4805
} | class ____:
"""
>>> astar = AStar((0, 0), (len(grid) - 1, len(grid[0]) - 1))
>>> (astar.start.pos_y + delta[3][0], astar.start.pos_x + delta[3][1])
(0, 1)
>>> [x.pos for x in astar.get_successors(astar.start)]
[(1, 0), (0, 1)]
>>> (astar.start.pos_y + delta[2][0], astar.start.pos_x + delta[2... | AStar |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_common_errors.py | {
"start": 10633,
"end": 12494
} | class ____:
"""Test detection of structural issues in docstrings."""
# Using function-based validation approach
def test_empty_sections(self):
"""Test detection of empty sections."""
docstring = '''"""Function with empty sections.
Args:
# Empty section - no parameters ... | TestStructuralErrors |
python | sphinx-doc__sphinx | sphinx/util/nodes.py | {
"start": 1093,
"end": 26567
} | class ____(Generic[N]):
"""A helper class for Node.findall().
It checks that the given node is an instance of the specified node-classes and
has the specified node-attributes.
For example, following example searches ``reference`` node having ``refdomain``
and ``reftype`` attributes::
matc... | NodeMatcher |
python | sphinx-doc__sphinx | sphinx/testing/util.py | {
"start": 3007,
"end": 8684
} | class ____(sphinx.application.Sphinx):
"""A subclass of :class:`~sphinx.application.Sphinx` for tests.
The constructor uses some better default values for the initialization
parameters and supports arbitrary keywords stored in the :attr:`extras`
read-only mapping.
It is recommended to use::
... | SphinxTestApp |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/discover.py | {
"start": 162,
"end": 541
} | class ____(BlockSlackMessageBuilder):
def __init__(self, title: str, chart_url: str) -> None:
super().__init__()
self.title = title
self.chart_url = chart_url
def build(self) -> SlackBody:
return self._build_blocks(
self.get_image_block(self.chart_url, title=self.tit... | SlackDiscoverMessageBuilder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/unit_tests/integration/test_bulk_stream.py | {
"start": 3323,
"end": 29836
} | class ____(TestCase):
def setUp(self) -> None:
self._config = ConfigBuilder().client_id(_CLIENT_ID).client_secret(_CLIENT_SECRET).refresh_token(_REFRESH_TOKEN)
self._http_mocker = HttpMocker()
self._http_mocker.__enter__()
given_authentication(self._http_mocker, _CLIENT_ID, _CLIENT... | BulkStreamTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 20946,
"end": 22141
} | class ____(Processor):
"""
Make trailing whitespace visible.
:param get_char: Callable that returns one character.
"""
def __init__(
self,
get_char: Callable[[], str] | None = None,
style: str = "class:training-whitespace",
) -> None:
def default_get_char() -> s... | ShowTrailingWhiteSpaceProcessor |
python | neetcode-gh__leetcode | python/0236-lowest-common-ancestor-of-a-binary-tree.py | {
"start": 163,
"end": 653
} | class ____:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right... | Solution |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_profiling_profiles.py | {
"start": 30643,
"end": 33221
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-profiling-chunks"
features = {
"organizations:continuous-profiling": True,
}
def setUp(self) -> None:
self.login_as(user=self.user)
self.url = reverse(self.endpoint, args=(self.organization.slug,))
def test_forb... | OrganizationProfilingChunksTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/sensor.py | {
"start": 3806,
"end": 3987
} | class ____(NamedTuple):
"""Placeholder for runs that are skipped during the run_key idempotence check."""
run_key: Optional[str]
existing_run: DagsterRun
| SkippedSensorRun |
python | huggingface__transformers | tests/models/wav2vec2_phoneme/test_tokenization_wav2vec2_phoneme.py | {
"start": 1082,
"end": 19737
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/wav2vec2-lv-60-espeak-cv-ft"
tokenizer_class = Wav2Vec2PhonemeCTCTokenizer
test_rust_tokenizer = False
@classmethod
def setUpClass(cls):
super().setUpClass()
vocab = (
"<s> <pad> </s> <u... | Wav2Vec2PhonemeCTCTokenizerTest |
python | tensorflow__tensorflow | tensorflow/python/eager/core.py | {
"start": 1848,
"end": 2258
} | class ____(Exception):
"""Exception class to handle fallback from the fastpath.
The fastpath that we refer to here is the one implemented to reduce per-op
overheads (TFE_Py_FastPathExecute_C). If the conditions for executing the op
on the fastpath are not met, we fallback to a safer (and more complete)
slowp... | _FallbackException |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_tridiag_test.py | {
"start": 1255,
"end": 4022
} | class ____(object):
def build_operator_and_matrix(
self, build_info, dtype, use_placeholder,
ensure_self_adjoint_and_pd=False,
diagonals_format='sequence'):
shape = list(build_info.shape)
# Ensure that diagonal has large enough values. If we generate a
# self adjoint PD matrix, then th... | _LinearOperatorTriDiagBase |
python | gevent__gevent | src/greentest/3.14/test_socket.py | {
"start": 16342,
"end": 17649
} | class ____(unittest.TestCase, ThreadableTest):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def setUp(self):
self.serv = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
self.addCleanup(self.se... | ThreadedVSOCKSocketStreamTest |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 652,
"end": 814
} | class ____(TestModel):
tweet = ForeignKeyField(Tweet)
tag = ForeignKeyField(Tag)
class Meta:
primary_key = CompositeKey('tweet', 'tag')
| TweetTag |
python | ansible__ansible | test/integration/targets/tasks/action_plugins/action_that_fails.py | {
"start": 84,
"end": 566
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
args = self.validate_argument_spec(argument_spec=dict(
fail_mode=dict(default='raise', choices=['raise', 'result_dict'], type='str')
))
if args[0].validated_parameters['fail_mode'] == 'raise':
raise Exce... | ActionModule |
python | realpython__materials | arcade-platformer/arcade_platformer/15_moving_platforms.py | {
"start": 7820,
"end": 22145
} | class ____(arcade.View):
def __init__(self) -> None:
super().__init__()
# These lists will hold different sets of sprites
self.coins = None
self.background = None
self.walls = None
self.ladders = None
self.goals = None
self.enemies = None
# O... | PlatformerView |
python | matplotlib__matplotlib | lib/matplotlib/animation.py | {
"start": 25895,
"end": 26227
} | class ____(ImageMagickBase, MovieWriter):
"""
Pipe-based animated gif writer.
Frames are streamed directly to ImageMagick via a pipe and written
in a single pass.
"""
input_names = "-" # stdin
# Combine ImageMagick options with temp file-based writing
@writers.register('imagemagick_file')
| ImageMagickWriter |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/data-modeling/asset-factories/advanced-yaml-asset-factory.py | {
"start": 1020,
"end": 1703
} | class ____(pydantic.BaseModel):
aws: AwsConfig
etl_jobs: list[JobConfig]
def to_definitions(self) -> dg.Definitions:
s3_resource = self.aws.to_resource()
return dg.Definitions.merge(
*[job.to_etl_job(s3_resource) for job in self.etl_jobs]
)
def load_etl_jobs_from_yaml(... | EtlJobsConfig |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 1162,
"end": 2177
} | class ____:
@classmethod
def create(cls, **kwargs):
instance = cls(**kwargs)
instance.id = 1
return instance
class FakeModelManager:
def get_or_create(self, **kwargs):
defaults = kwargs.pop('defaults', {})
kwargs.update(defaults)
instance ... | FakeModel |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 12745,
"end": 14076
} | class ____(TestCase):
def test_divmod_out(self):
x1 = w.arange(8, 15)
x2 = w.arange(4, 11)
out = (w.empty_like(x1), w.empty_like(x1))
quot, rem = w.divmod(x1, x2, out=out)
assert_equal(quot, x1 // x2)
assert_equal(rem, x1 % x2)
out1, out2 = out
ass... | TestDivmod |
python | gevent__gevent | src/greentest/3.14/test_smtplib.py | {
"start": 29421,
"end": 31019
} | class ____(unittest.TestCase):
respdata = b'250 OK' + (b'.' * smtplib._MAXLINE * 2) + b'\n'
def setUp(self):
self.thread_key = threading_helper.threading_setup()
self.old_stdout = sys.stdout
self.output = io.StringIO()
sys.stdout = self.output
self.evt = threading.Event... | TooLongLineTests |
python | getsentry__sentry | src/sentry/issue_detection/detectors/mn_plus_one_db_span_detector.py | {
"start": 1507,
"end": 4060
} | class ____(MNPlusOneState):
"""
The initial state for the MN+1 DB Query detector, and the state we return to
whenever there is no active repeating pattern being checked.
Keeps a list of recently seen spans until a repeat is found, at which point
it transitions to the ContinuingMNPlusOne state.
... | SearchingForMNPlusOne |
python | sympy__sympy | sympy/assumptions/predicates/common.py | {
"start": 166,
"end": 898
} | class ____(Predicate):
"""
Commutative predicate.
Explanation
===========
``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other
object with respect to multiplication operation.
Examples
========
>>> from sympy import Q, ask, Symbol
>>> x = Symbol('x')
>>> as... | CommutativePredicate |
python | PyCQA__pylint | tests/checkers/base/unittest_multi_naming_style.py | {
"start": 436,
"end": 5164
} | class ____(CheckerTestCase):
CHECKER_CLASS = base.NameChecker
MULTI_STYLE_RE = re.compile("(?:(?P<UP>[A-Z]+)|(?P<down>[a-z]+))$")
@set_config(class_rgx=MULTI_STYLE_RE)
def test_multi_name_detection_majority(self) -> None:
classes = astroid.extract_node(
"""
class classb(obj... | TestMultiNamingStyle |
python | networkx__networkx | networkx/algorithms/centrality/flow_matrix.py | {
"start": 1252,
"end": 2397
} | class ____:
def __init__(self, L, width=None, dtype=None):
global np
import numpy as np
(n, n) = L.shape
self.dtype = dtype
self.n = n
if width is None:
self.w = self.width(L)
else:
self.w = width
self.C = np.zeros((self.w, n),... | InverseLaplacian |
python | getsentry__sentry | tests/sentry/integrations/test_issues.py | {
"start": 1271,
"end": 20842
} | class ____(TestCase):
def test_status_sync_inbound_resolve(self) -> None:
group = self.group
assert group.status == GroupStatus.UNRESOLVED
with assume_test_silo_mode(SiloMode.CONTROL):
integration = self.create_provider_integration(provider="example", external_id="123456")
... | IssueSyncIntegration |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/secrets/test_systems_manager.py | {
"start": 1615,
"end": 14819
} | class ____:
@mock.patch(
"airflow.providers.amazon.aws.secrets.systems_manager."
"SystemsManagerParameterStoreBackend.get_conn_value"
)
def test_aws_ssm_get_connection(self, mock_get_value):
mock_get_value.return_value = "scheme://user:pass@host:100"
conn = SystemsManagerPara... | TestSsmSecrets |
python | tensorflow__tensorflow | tensorflow/python/grappler/cluster.py | {
"start": 1010,
"end": 4362
} | class ____(object):
"""Grappler Clusters."""
def __init__(self,
allow_soft_placement=True,
disable_detailed_stats=True,
disable_timeline=True,
devices=None):
"""Creates a Cluster.
Args:
allow_soft_placement: If True, TF will automatically f... | Cluster |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-gitbook/tests/test_gitbook_client.py | {
"start": 163,
"end": 3943
} | class ____(unittest.TestCase):
def setUp(self):
"""Sets up test environment before each test case."""
self.client = GitbookClient("test_token")
self.space_id = "test_space"
self.page_id = "test_page"
self.fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures")
... | TestGitbookClient |
python | apache__airflow | providers/apache/pinot/tests/unit/apache/pinot/hooks/test_pinot.py | {
"start": 10151,
"end": 14885
} | class ____:
def setup_method(self):
self.conn = conn = mock.MagicMock()
self.conn.host = "host"
self.conn.port = "1000"
self.conn.login = "user"
self.conn.password = "pwd"
self.conn.extra_dejson = {}
class PinotAdminHookTest(PinotAdminHook):
def g... | TestPinotAdminHookWithAuth |
python | sympy__sympy | sympy/matrices/expressions/blockmatrix.py | {
"start": 18864,
"end": 31906
} | class ____(BlockMatrix):
"""A sparse matrix with block matrices along its diagonals
Examples
========
>>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols
>>> n, m, l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> BlockDiagMatrix(X, Y)
... | BlockDiagMatrix |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 51963,
"end": 52331
} | class ____(MathTextGlyph):
""" Render mathematical content using `MathML <https://www.w3.org/Math/>`_
notation.
See :ref:`ug_styling_mathtext` in the |user guide| for more information.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
... | MathMLGlyph |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 45160,
"end": 46465
} | class ____(graphene.Interface):
name = graphene.NonNull(graphene.String)
description = graphene.String()
owners = non_null_list(GrapheneDefinitionOwner)
pipeline_snapshot_id = graphene.NonNull(graphene.String)
dagster_types = non_null_list(GrapheneDagsterType)
dagster_type_or_error = graphene.Fi... | GrapheneIPipelineSnapshot |
python | lepture__authlib | tests/django_helper.py | {
"start": 128,
"end": 554
} | class ____(RequestFactory):
@property
def session(self):
engine = import_module(settings.SESSION_ENGINE)
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
if cookie:
return engine.SessionStore(cookie.value)
session = engine.SessionStore()
session.save()... | RequestClient |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 2560,
"end": 2717
} | class ____(Exception):
def __init__(self, msg: str, oid: ObjectIdentifier) -> None:
super().__init__(msg)
self.oid = oid
| DuplicateExtension |
python | sympy__sympy | sympy/physics/quantum/operator.py | {
"start": 9809,
"end": 14728
} | class ____(Operator):
"""An unevaluated outer product between a ket and bra.
This constructs an outer product between any subclass of ``KetBase`` and
``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
operators in quantum expressions. For reference see [1]_.
Para... | OuterProduct |
python | getsentry__sentry | src/sentry/preprod/pull_request/types.py | {
"start": 1980,
"end": 2218
} | class ____(BaseModel):
"""
Complete pull request data including file changes.
"""
pull_request: PullRequestDetails
files: list[PullRequestFileChange]
build_details: list[BuildDetailsApiResponse]
| PullRequestWithFiles |
python | pytorch__pytorch | test/inductor/test_group_batch_fusion.py | {
"start": 8531,
"end": 9537
} | class ____(torch.nn.Module):
def __init__(self, device):
super().__init__()
self.device = device
def forward(self, x):
inputs = torch.ops.aten.split(x.to(self.device), 500, dim=1)
x_split = torch.ops.aten.split(inputs[0].to(self.device), 50, dim=1)
y_split = torch.ops.at... | TestPoitwiseOpsPostGrad |
python | astropy__astropy | astropy/nddata/tests/test_nddata.py | {
"start": 17400,
"end": 22202
} | class ____(NDData):
@property
def wcs(self):
return WCS()
def test_overriden_wcs():
# Check that a sub-class that overrides `.wcs` without providing a setter
# works
NDDataCustomWCS(np.ones((5, 5)))
# set up parameters for test_collapse:
np.random.seed(42)
collapse_units = [None, u.Jy]
c... | NDDataCustomWCS |
python | getsentry__sentry | src/sentry/preprod/migrations/0012_installablepreprod.py | {
"start": 269,
"end": 2538
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | google__pytype | pytype/directors/directors_test.py | {
"start": 22838,
"end": 23958
} | class ____(DirectorTestCase):
"""Test pragmas."""
def test_valid(self):
self._create("""
def f(x) -> str: # pytype: pragma=cache-return
...
""")
self.assertTrue(self._director.has_pragma("cache-return", 2))
self.assertFalse(self._director.has_pragma("cache-return", 3))
def test_inv... | PragmaDirectivesTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 20590,
"end": 64330
} | class ____:
"""Use this factory class to create the correct object for the `vectorizer_config` argument in the `collections.create()` method.
Each staticmethod provides options specific to the named vectorizer in the function's name. Under-the-hood data validation steps
will ensure that any mis-specificati... | _Vectorizer |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_generators.py | {
"start": 8656,
"end": 10731
} | class ____(__TestCase):
iterables = [
range(0),
range(20),
[1, 2, 3],
(2,),
{13, 48, 211},
frozenset((15, 8, 6)),
{1: 2, 3: 4},
]
non_iterables = [
None,
42,
3.0,
2j,
]
def genexpr(self):
return (x for ... | ModifyUnderlyingIterableTest |
python | joke2k__faker | faker/providers/date_time/de_AT/__init__.py | {
"start": 46,
"end": 778
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "Sonntag",
"1": "Montag",
"2": "Dienstag",
"3": "Mittwoch",
"4": "Donnerstag",
"5": "Freitag",
"6": "Samstag",
}
MONTH_NAMES = {
"01": "Jänner",
"02": "Februar",
"03": "März",
... | Provider |
python | conda__conda | conda/exceptions.py | {
"start": 12163,
"end": 12325
} | class ____(CondaError, OSError):
def __init__(self, path: PathType):
message = "%(path)s"
super().__init__(message, path=path)
| PathNotFoundError |
python | apache__avro | lang/py/avro/test/test_io.py | {
"start": 9501,
"end": 10575
} | class ____(unittest.TestCase):
def __init__(self, test_schema: str, test_datum: object) -> None:
"""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 autoloader
ignores this class. The autoloader will ... | IoValidateTestCase |
python | ansible__ansible | lib/ansible/module_utils/errors.py | {
"start": 2030,
"end": 2119
} | class ____(AnsibleValidationError):
"""Error with parameter value"""
| ArgumentValueError |
python | docker__docker-py | tests/unit/api_test.py | {
"start": 14613,
"end": 19391
} | class ____(unittest.TestCase):
stdout_data = b'''
Now, those children out there, they're jumping through the
flames in the hope that the god of the fire will make them fruitful.
Really, you can't blame them. After all, what girl would not prefer the
child of a god to that of some acne-scarred artisa... | TCPSocketStreamTest |
python | sympy__sympy | sympy/physics/quantum/cartesian.py | {
"start": 2785,
"end": 3679
} | class ____(HermitianOperator):
"""1D cartesian momentum operator."""
@classmethod
def default_args(self):
return ("Px",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PxKet(self, ket, **options):
... | PxOp |
python | ansible__ansible | test/units/plugins/action/test_action.py | {
"start": 33334,
"end": 35682
} | class ____(unittest.TestCase):
def test_fail_no_json(self):
action_base = _action_base()
rc = 0
stdout = 'foo\nbar\n'
err = 'oopsy'
returned_data = {'rc': rc,
'stdout': stdout,
'stdout_lines': stdout.splitlines(),
... | TestActionBaseParseReturnedData |
python | huggingface__transformers | src/transformers/models/doge/modeling_doge.py | {
"start": 24485,
"end": 32433
} | class ____(DogePreTrainedModel):
def __init__(self, config: DogeConfig):
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)
self.layers ... | DogeModel |
python | coleifer__peewee | tests/models.py | {
"start": 155411,
"end": 155536
} | class ____(TestModel):
filename = CharField(primary_key=True)
data = TextField()
timestamp = TimestampField()
| CFile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.