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 | Pylons__pyramid | tests/test_authentication.py | {
"start": 8943,
"end": 16847
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.authentication import RepozeWho1AuthenticationPolicy
return RepozeWho1AuthenticationPolicy
def _makeOne(self, identifier_name='auth_tkt', callback=None):
return self._getTargetClass()(identifier_name, callback)
... | TestRepozeWho1AuthenticationPolicy |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 2191,
"end": 2604
} | class ____(collector.BaseFactCollector):
name = 'exc_throwing'
def __init__(self, collectors=None, namespace=None, exception=None):
super(ExceptionThrowingCollector, self).__init__(collectors, namespace)
self._exception = exception or CollectorException('collection failed')
def collect(sel... | ExceptionThrowingCollector |
python | apache__airflow | providers/smtp/src/airflow/providers/smtp/notifications/smtp.py | {
"start": 1232,
"end": 7023
} | class ____(BaseNotifier):
"""
SMTP Notifier.
Accepts keyword arguments. The only required arguments are `from_email` and `to`. Examples:
.. code-block:: python
EmptyOperator(task_id="task", on_failure_callback=SmtpNotifier(from_email=None, to="my@mail.com"))
EmptyOperator(
... | SmtpNotifier |
python | walkccc__LeetCode | solutions/785. Is Graph Bipartite?/785.py | {
"start": 79,
"end": 778
} | class ____:
def isBipartite(self, graph: list[list[int]]) -> bool:
colors = [Color.WHITE] * len(graph)
for i in range(len(graph)):
# This node has been colored, so do nothing.
if colors[i] != Color.WHITE:
continue
# Always paint red for a white node.
colors[i] = Color.RED
... | Solution |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_latest_only_operator.py | {
"start": 2375,
"end": 13634
} | class ____:
@staticmethod
def clean_db():
clear_db_runs()
clear_db_xcom()
def setup_class(self):
self.clean_db()
def setup_method(self):
self.freezer = time_machine.travel(FROZEN_NOW, tick=False)
self.freezer.start()
def teardown_method(self):
self.... | TestLatestOnlyOperator |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 1563,
"end": 1778
} | class ____(pydantic.BaseModel):
column_names: List[str]
sort_ascending: bool = True
method_name: Literal["partition_on_multi_column_values"] = "partition_on_multi_column_values"
| PartitionerMultiColumnValue |
python | openai__openai-python | src/openai/cli/_tools/migrate.py | {
"start": 1098,
"end": 4497
} | class ____(BaseModel):
# internal
unknown_args: List[str] = []
def migrate(args: MigrateArgs) -> None:
grit_path = install()
try:
subprocess.check_call([grit_path, "apply", "openai", *args.unknown_args])
except subprocess.CalledProcessError:
# stdout and stderr are forwarded by su... | MigrateArgs |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 77420,
"end": 78796
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
Sequence of hidden-states at the last layer of the model.
`num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
co... | ReformerModelOutput |
python | ahupp__python-magic | test/python_magic_test.py | {
"start": 517,
"end": 5086
} | class ____:
file_name: str
mime_results: List[str]
text_results: List[str]
no_check_elf_results: Union[List[str], None]
buf_equals_file: bool = True
# magic_descriptor is broken (?) in centos 7, so don't run those tests
SKIP_FROM_DESCRIPTOR = bool(os.environ.get("SKIP_FROM_DESCRIPTOR"))
COMMON_P... | TestFile |
python | Netflix__metaflow | metaflow/_vendor/click/types.py | {
"start": 21391,
"end": 25045
} | class ____(CompositeParamType):
"""The default behavior of Click is to apply a type on a value directly.
This works well in most cases, except for when `nargs` is set to a fixed
count and different types should be used for different items. In this
case the :class:`Tuple` type can be used. This type ca... | Tuple |
python | catalyst-team__catalyst | catalyst/contrib/layers/se.py | {
"start": 84,
"end": 1384
} | class ____(nn.Module): # noqa: N801
"""
The channel-wise SE (Squeeze and Excitation) block from the
`Squeeze-and-Excitation Networks`__ paper.
Adapted from
https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/65939
and
https://www.kaggle.com/c/tgs-salt-identification-chall... | cSE |
python | celery__celery | t/unit/tasks/test_chord.py | {
"start": 8078,
"end": 9710
} | class ____(ChordCase):
def test_eager(self):
from celery import chord
@self.app.task(shared=False)
def addX(x, y):
return x + y
@self.app.task(shared=False)
def sumX(n):
return sum(n)
self.app.conf.task_always_eager = True
x = chord... | test_chord |
python | google__jax | jax/experimental/jax2tf/tests/call_tf_test.py | {
"start": 40538,
"end": 62204
} | class ____(tf_test_util.JaxToTfTestCase):
"""Reloading output of call_tf into TF with jax2tf."""
def setUp(self):
if tf is None:
raise unittest.SkipTest("Test requires tensorflow")
# TODO(b/171320191): this line works around a missing context initialization
# bug in TensorFlow.
_ = tf.add(1, ... | RoundTripToTfTest |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 5095,
"end": 5256
} | class ____(Screen):
"""A screen with a simple low-priority alpha key binding."""
BINDINGS = [Binding("a", "a", "a", priority=False)]
| ScreenWithLowBindings |
python | huggingface__transformers | tests/models/sam3_tracker/test_modeling_sam3_tracker.py | {
"start": 8163,
"end": 21034
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SAM's vision encoder does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (Sam3TrackerModel,) if is_torch_availa... | Sam3TrackerModelTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 376744,
"end": 377497
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateTeamDiscussionComment"""
__schema__ = github_schema
__field_names__ = ("id", "body", "body_version", "client_mutation_id")
id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id")
"""The ID of the comment to modify."""
... | UpdateTeamDiscussionCommentInput |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/common/db/test_dags.py | {
"start": 1322,
"end": 13822
} | class ____:
"""Unit tests for generate_dag_with_latest_run_query function."""
@staticmethod
def _clear_db():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
@pytest.fixture(autouse=True)
def setup_teardown(self):
"""Setup and teardown for each test."""
... | TestGenerateDagWithLatestRunQuery |
python | keras-team__keras | keras/src/saving/saving_lib_test.py | {
"start": 478,
"end": 1675
} | class ____(keras.layers.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self.nested_layer = keras.layers.Dense(self.units, name="dense")
def build(self, input_shape):
self.additional_weights = [
self.add_weight(
... | MyDense |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-google/llama_index/vector_stores/google/genai_extension.py | {
"start": 4732,
"end": 14141
} | class ____(credentials.Credentials):
"""
Credentials that do not provide any authentication information.
Useful for unit tests where the credentials are not used.
"""
@property
def expired(self) -> bool:
"""Returns `False`, test credentials never expire."""
return False
@p... | TestCredentials |
python | kamyu104__LeetCode-Solutions | Python/clear-digits.py | {
"start": 457,
"end": 759
} | class ____(object):
def clearDigits(self, s):
"""
:type s: str
:rtype: str
"""
result = []
for x in s:
if x.isdigit():
result.pop()
continue
result.append(x)
return "".join(result)
| Solution2 |
python | kamyu104__LeetCode-Solutions | Python/array-partition-i.py | {
"start": 549,
"end": 849
} | class ____(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
result = 0
for i in xrange(0, len(nums), 2):
result += nums[i]
return result
# Time: O(nlogn)
# Space: O(n)
| Solution2 |
python | django-extensions__django-extensions | tests/management/commands/test_describe_form.py | {
"start": 1208,
"end": 1668
} | class ____(forms.Form):
title = forms.CharField(label='Title', max_length=50)
body = forms.CharField(label='Body')"""
call_command("describe_form", "testapp.BaseModel", stdout=self.out)
self.assertIn(expected_result, self.out.getvalue())
def test_should_print_form_definition_for_TestModel... | BaseModelForm |
python | cython__cython | tests/run/qualname.py | {
"start": 3218,
"end": 4238
} | class ____:
"""
>>> print(CdefModifyNames.qn_reassigned, CdefModifyNames.m_reassigned)
I'm not a qualname I'm not a module
# TODO - enable when https://github.com/cython/cython/issues/4815 is fixed
#>>> hasattr(CdefModifyNames, "qn_deleted")
#False
#>>> hasattr(CdefModifyNames, "m_deleted")... | CdefModifyNames |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 2686,
"end": 6845
} | class ____:
path: Path
client_id: str
def to_json(self) -> List[object]:
return [
"FileClosed",
{
"path": f"{self.path}",
"client_id": self.client_id,
},
]
def invalid_response(response: str, raw_request: str) -> ErrorRes... | FileClosed |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/pipes/context_injectors.py | {
"start": 1943,
"end": 2282
} | class ____(PipesEnvContextInjector):
"""Injects context via AWS Lambda event input.
Should be paired with :py:class`~dagster_pipes.PipesMappingParamsLoader` on the Lambda side.
"""
def no_messages_debug_text(self) -> str:
return "Attempted to inject context via the lambda event input."
| PipesLambdaEventContextInjector |
python | pytorch__pytorch | benchmarks/dynamo/dist_util.py | {
"start": 953,
"end": 1170
} | class ____(torch.nn.Module):
def __init__(self, a, b):
super().__init__()
self.weight = nn.Parameter(torch.randn(a, b))
def forward(self, x):
return torch.mm(x, self.weight)
| CustomLinear |
python | joke2k__faker | faker/providers/address/en_CA/__init__.py | {
"start": 129,
"end": 9037
} | class ____(AddressProvider):
# Source: https://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1449294
#
# 'W' and 'Z' are valid in non-initial position (easily verified in the
# wild), but online official documentation is hard to find, so just ignore
# them for now.
postal_code_letters = ... | Provider |
python | sympy__sympy | sympy/polys/numberfields/modules.py | {
"start": 8293,
"end": 23783
} | class ____:
"""
Generic finitely-generated module.
This is an abstract base class, and should not be instantiated directly.
The two concrete subclasses are :py:class:`~.PowerBasis` and
:py:class:`~.Submodule`.
Every :py:class:`~.Submodule` is derived from another module, referenced
by its ... | Module |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 25978,
"end": 29366
} | class ____(ManagedKafkaBaseOperator):
"""
List the topics in a given cluster.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param cluster_id: Required. The ID of... | ManagedKafkaListTopicsOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_events.py | {
"start": 501,
"end": 1834
} | class ____(StreamTestCase):
_STREAM_NAME = "events"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
req = self.stream_request().with_limit(250).with_created_min(START_DATE).build()
http_mocker.get(
req,
get_... | TestFullRefresh |
python | cherrypy__cherrypy | cherrypy/test/helper.py | {
"start": 1017,
"end": 2918
} | class ____(Supervisor):
"""Base for modeling/controlling servers which run in the same process.
When the server side runs in a different process, start/stop can
dump all state between each test module easily. When the server side
runs in the same process as the client, however, we have to do a bit
... | LocalSupervisor |
python | doocs__leetcode | solution/0100-0199/0141.Linked List Cycle/Solution2.py | {
"start": 136,
"end": 390
} | class ____:
def hasCycle(self, head: ListNode) -> bool:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
return True
return False
| Solution |
python | tensorflow__tensorflow | third_party/xla/build_tools/configure/configure.py | {
"start": 10026,
"end": 21241
} | class ____:
"""Represents XLA configuration options."""
backend: Backend
os: OS
python_bin_path: str
host_compiler: HostCompiler
compiler_options: list[str]
# CUDA specific
cuda_compiler: CudaCompiler
using_nccl: bool
# ROCM specific
rocm_compiler: RocmCompiler
# SYCL specific
sycl_compile... | XLAConfigOptions |
python | readthedocs__readthedocs.org | readthedocs/api/v2/models.py | {
"start": 1786,
"end": 2370
} | class ____(AbstractAPIKey):
"""
API key for securely interacting with the API from the builders.
The key is attached to a single project,
it can be used to have write access to the API V2.
"""
project = models.ForeignKey(
Project,
on_delete=models.CASCADE,
related_name=... | BuildAPIKey |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/constant.py | {
"start": 212,
"end": 4982
} | class ____(Operator):
"""Operator for generating constants."""
def __init__(self):
super().__init__("constant")
self.template = "default" # Track template for DTensor compatibility
@property
def torch_op_name(self) -> str | None:
"""Constant is not a torch operation, it genera... | ConstantOperator |
python | python__mypy | mypy/plugin.py | {
"start": 31554,
"end": 36250
} | class ____(Plugin):
"""A plugin that represents a sequence of chained plugins.
Each lookup method returns the hook for the first plugin that
reports a match.
This class should not be subclassed -- use Plugin as the base class
for all plugins.
"""
# TODO: Support caching of lookup results ... | ChainedPlugin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 2521,
"end": 2674
} | class ____[**P = [1, int]]: ...
# This should generate an error because it combines a traditional ParamSpec
# with a new-style (PEP 695) ParamSpec.
| ClassP8 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/execution.py | {
"start": 2817,
"end": 4607
} | class ____(graphene.ObjectType):
key = graphene.NonNull(graphene.String)
inputs = non_null_list(GrapheneExecutionStepInput)
outputs = non_null_list(GrapheneExecutionStepOutput)
solidHandleID = graphene.NonNull(graphene.String)
kind = graphene.NonNull(GrapheneStepKind)
metadata = non_null_list(Gr... | GrapheneExecutionStep |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx2_sgskip.py | {
"start": 462,
"end": 1495
} | class ____(wx.Frame):
def __init__(self):
super().__init__(None, -1, 'CanvasFrame', size=(550, 350))
self.figure = Figure()
self.axes = self.figure.add_subplot()
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)
self.canvas = Figur... | CanvasFrame |
python | facelessuser__pymdown-extensions | tests/util.py | {
"start": 625,
"end": 3307
} | class ____(unittest.TestCase):
"""Markdown unittest test case base."""
extension = []
extension_configs = {}
base = CURRENT_DIR
def setUp(self):
"""Setup."""
for k1, v1 in self.extension_configs.items():
if v1 is not None:
for k2, v2 in v1.items():
... | MdCase |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/rich_jupyter_widget.py | {
"start": 1106,
"end": 1174
} | class ____(Exception):
"""Exception for Latex errors"""
| LatexError |
python | mlflow__mlflow | dev/clint/src/clint/rules/isinstance_union_syntax.py | {
"start": 48,
"end": 1749
} | class ____(Rule):
def _message(self) -> str:
return (
"Use `isinstance(obj, (X, Y))` instead of `isinstance(obj, X | Y)`. "
"The union syntax with `|` is slower than using a tuple of types."
)
@staticmethod
def check(node: ast.Call) -> bool:
"""
Retur... | IsinstanceUnionSyntax |
python | django-import-export__django-import-export | tests/core/forms.py | {
"start": 407,
"end": 553
} | class ____(AuthorFormMixin, ConfirmImportForm):
"""Customized ConfirmImportForm, with author field required"""
pass
| CustomConfirmImportForm |
python | donnemartin__system-design-primer | solutions/object_oriented_design/call_center/call_center.py | {
"start": 1833,
"end": 1977
} | class ____(object):
def __init__(self, rank):
self.state = CallState.READY
self.rank = rank
self.employee = None
| Call |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/advanced_models.py | {
"start": 1695,
"end": 2188
} | class ____(nn.Module):
def __init__(self, img_shape: tuple):
super().__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(img_shape)), 512),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(512, 256),
nn.LeakyReLU(0.2, inplace=True),
nn.... | Discriminator |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 23296,
"end": 23958
} | class ____(TearDownLocalEventsFixture, fixtures.TestBase):
"""test that ad-hoc subclasses are garbage collected."""
def setup_test(self):
class TargetEvents(event.Events):
def some_event(self, x, y):
pass
class Target:
dispatch = event.dispatcher(TargetE... | SubclassGrowthTest |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 28388,
"end": 28540
} | class ____(ProjectRedirectsMixin, ListView):
template_name = "redirects/redirect_list.html"
context_object_name = "redirects"
| ProjectRedirectsList |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/dagster_types.py | {
"start": 4146,
"end": 4329
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneDagsterType, GrapheneWrappingDagsterType)
name = "NullableDagsterType"
| GrapheneNullableDagsterType |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/rag.py | {
"start": 3697,
"end": 6421
} | class ____(BaseLlamaDataset[BaseQueryEngine]):
"""RagDataset class."""
_example_type = LabelledRagDataExample
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
"pandas i... | LabelledRagDataset |
python | pypa__setuptools | setuptools/_vendor/platformdirs/macos.py | {
"start": 112,
"end": 5580
} | class ____(PlatformDirsABC):
"""
Platform directories for the macOS operating system.
Follows the guidance from
`Apple documentation <https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html>`_.
Makes use... | MacOS |
python | keras-team__keras | keras/src/layers/pooling/global_max_pooling_test.py | {
"start": 174,
"end": 2788
} | class ____(testing.TestCase):
@parameterized.parameters(
("channels_last", False, (3, 5, 4), (3, 4)),
("channels_last", True, (3, 5, 4), (3, 1, 4)),
("channels_first", False, (3, 5, 4), (3, 5)),
)
def test_global_max_pooling1d(
self,
data_format,
keepdims,
... | GlobalMaxPoolingBasicTest |
python | getsentry__sentry | src/sentry/sentry_metrics/aggregation_option_registry.py | {
"start": 187,
"end": 316
} | class ____(Enum):
HIST = "hist"
TEN_SECOND = "ten_second"
DISABLE_PERCENTILES = "disable_percentiles"
| AggregationOption |
python | walkccc__LeetCode | solutions/442. Find All Duplicates in an Array/442.py | {
"start": 0,
"end": 218
} | class ____:
def findDuplicates(self, nums: list[int]) -> list[int]:
ans = []
for num in nums:
nums[abs(num) - 1] *= -1
if nums[abs(num) - 1] > 0:
ans.append(abs(num))
return ans
| Solution |
python | ipython__ipython | IPython/external/pickleshare.py | {
"start": 1504,
"end": 8042
} | class ____(collections_abc.MutableMapping):
"""The main 'connection' object for PickleShare database"""
def __init__(self, root):
"""Return a db object that will manage the specied directory"""
if not isinstance(root, str):
root = str(root)
root = os.path.abspath(os.path.exp... | PickleShareDB |
python | walkccc__LeetCode | solutions/692. Top K Frequent Words/692-2.py | {
"start": 225,
"end": 568
} | class ____:
def topKFrequent(self, words: list[str], k: int) -> list[str]:
ans = []
heap = []
for word, freq in collections.Counter(words).items():
heapq.heappush(heap, T(word, freq))
if len(heap) > k:
heapq.heappop(heap)
while heap:
ans.append(heapq.heappop(heap).word)
... | Solution |
python | pola-rs__polars | py-polars/tests/unit/io/database/test_async.py | {
"start": 996,
"end": 1814
} | class ____:
"""Mock SurrealDB connection/client object."""
__module__ = "surrealdb"
def __init__(self, url: str, mock_data: list[dict[str, Any]]) -> None:
self._mock_data = mock_data.copy()
self.url = url
async def __aenter__(self) -> Any:
await self.connect()
return s... | MockSurrealConnection |
python | zarr-developers__zarr-python | tests/test_store/test_logging.py | {
"start": 443,
"end": 5226
} | class ____(StoreTests[LoggingStore[LocalStore], cpu.Buffer]):
# store_cls is needed to do an isintsance check, so can't be a subscripted generic
store_cls = LoggingStore # type: ignore[assignment]
buffer_cls = cpu.Buffer
async def get(self, store: LoggingStore[LocalStore], key: str) -> Buffer:
... | TestLoggingStore |
python | getsentry__sentry | tests/sentry/api/helpers/test_deprecation.py | {
"start": 912,
"end": 1508
} | class ____(Endpoint):
permission_classes = ()
@deprecated(test_date, suggested_api=replacement_api)
def get(self, request):
return Response({"ok": True})
def head(self, request):
return Response({"ok": True})
@deprecated(test_date, suggested_api=replacement_api, key="override")
... | DummyEndpoint |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 89882,
"end": 97249
} | class ____(CNumericType):
is_complex = 1
has_attributes = 1
scope = None
@property
def to_py_function(self):
return "__pyx_PyComplex_FromComplex%s" % self.implementation_suffix
def __init__(self, real_type):
if real_type.is_typedef:
real_type = real_type.resolve_kn... | CComplexType |
python | django-haystack__django-haystack | haystack/inputs.py | {
"start": 73,
"end": 571
} | class ____:
"""
The base input type. Doesn't do much. You want ``Raw`` instead.
"""
input_type_name = "base"
post_process = True
def __init__(self, query_string, **kwargs):
self.query_string = query_string
self.kwargs = kwargs
def __repr__(self):
return "<%s '%s'>"... | BaseInput |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 3655,
"end": 3729
} | class ____(TextareaRenderer):
tag = "vf-field-editor"
| TrixEditorRenderer |
python | joke2k__faker | faker/providers/address/en_PH/__init__.py | {
"start": 181,
"end": 43225
} | class ____(AddressProvider):
"""
Provider for addresses for en_PH locale
Like many things in the Philippines, even addresses are more complicated than necessary. This provider is already
a gross oversimplification, and it is still a lot more complicated VS providers from other locales despite taking
... | Provider |
python | spack__spack | lib/spack/spack/mirrors/utils.py | {
"start": 5864,
"end": 8312
} | class ____:
def __init__(self):
# Counter is used to easily merge mirror stats for one spec into mirror stats for all specs
self.present = Counter()
self.new = Counter()
self.errors = Counter()
def merge(self, ext_mirror_stat: MirrorStatsForOneSpec):
# For the sake of pa... | MirrorStatsForAllSpecs |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_union.py | {
"start": 3815,
"end": 18359
} | class ____(ModelB):
pass
@pytest.mark.parametrize('input_value', [ModelB(b'bite', 2.3456), SubclassB(b'bite', 2.3456)])
def test_model_b(model_serializer: SchemaSerializer, input_value):
assert model_serializer.to_python(input_value) == {'c': b'bite', 'd': '2.35'}
assert model_serializer.to_python(input_v... | SubclassB |
python | django-compressor__django-compressor | compressor/filters/css_default.py | {
"start": 4502,
"end": 6010
} | class ____(CssAbsoluteFilter):
"""
Do similar to ``CssAbsoluteFilter`` URL processing
but add a *relative URL prefix* instead of ``settings.COMPRESS_URL``.
"""
run_with_compression_disabled = True
def post_process_url(self, url):
"""
Replace ``settings.COMPRESS_URL`` URL prefix... | CssRelativeFilter |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-azure-cv/llama_index/tools/azure_cv/base.py | {
"start": 258,
"end": 1694
} | class ____(BaseToolSpec):
"""Azure Cognitive Vision tool spec."""
spec_functions = ["process_image"]
def __init__(
self,
resource: str,
api_key: str,
language: Optional[str] = "en",
api_version: Optional[str] = "2023-04-01-preview",
) -> None:
"""Initial... | AzureCVToolSpec |
python | huggingface__transformers | src/transformers/models/internvl/modular_internvl.py | {
"start": 17456,
"end": 24137
} | class ____(LlavaModel):
def pixel_shuffle(self, vision_features: torch.Tensor, scale_factor: float = 0.5):
"""Perform pixel shuffle downsampling on vision features.
Args:
vision_features (`torch.Tensor`):
Input tensor of shape (batch_size, width, height, channels).
... | InternVLModel |
python | django__django | tests/staticfiles_tests/test_finders.py | {
"start": 1926,
"end": 2600
} | class ____(TestFinders, StaticFilesTestCase):
"""
Test DefaultStorageFinder.
"""
def setUp(self):
super().setUp()
self.finder = finders.DefaultStorageFinder(
storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT)
)
test_file_path = os.path.join(sett... | TestDefaultStorageFinder |
python | pyparsing__pyparsing | pyparsing/testing.py | {
"start": 200,
"end": 15260
} | class ____:
"""
namespace class for classes useful in writing unit tests
"""
class reset_pyparsing_context:
"""
Context manager to be used when writing unit tests that modify pyparsing config values:
- packrat parsing
- bounded recursion parsing
- default whitesp... | pyparsing_test |
python | vyperlang__vyper | vyper/venom/passes/machinery/inst_updater.py | {
"start": 255,
"end": 4877
} | class ____:
"""
A helper class for updating instructions which also updates the
basic block and dfg in place
"""
def __init__(self, dfg: DFGAnalysis):
self.dfg = dfg
def update_operands(
self, inst: IRInstruction, replace_dict: dict[IROperand, IROperand], annotation: str = ""
... | InstUpdater |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 27760,
"end": 29029
} | class ____:
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
max_message_size: int,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self._max_message_size = max_message_size
if max_wbits is None:
max_wbits = zlib... | _PerMessageDeflateDecompressor |
python | pyparsing__pyparsing | examples/test_bibparse.py | {
"start": 149,
"end": 9006
} | class ____(unittest.TestCase):
def test_names(self):
# check various types of names
# All names can contains alphas, but not some special chars
bad_chars = "\"#%'(),={}"
for name_type, dig1f in (
(bp.macro_def, False),
(bp.field_name, False),
(bp.e... | TestBibparse |
python | dagster-io__dagster | python_modules/libraries/dagster-dlt/dagster_dlt/components/dlt_load_collection/component.py | {
"start": 1732,
"end": 2528
} | class ____(Resolvable):
"""Represents a single dlt load, a combination of pipeline and source."""
pipeline: Annotated[
Pipeline,
Resolver(lambda ctx, path: _load_object_from_python_path(ctx, path), model_field_type=str),
]
source: Annotated[
DltSource,
Resolver(
... | DltLoadSpecModel |
python | ray-project__ray | python/ray/serve/_private/build_app.py | {
"start": 1330,
"end": 8228
} | class ____:
# Name of the application.
name: str
route_prefix: Optional[str]
logging_config: Optional[LoggingConfig]
# Name of the application's 'ingress' deployment
# (the one exposed over gRPC/HTTP/handle).
ingress_deployment_name: str
# List of unique deployments comprising the app.
... | BuiltApplication |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graph/Python/kahn_algorithm.py | {
"start": 104,
"end": 2150
} | class ____:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
def topological_sort(self):
#initialise in... | Graph |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-vectara-query/llama_index/tools/vectara_query/base.py | {
"start": 435,
"end": 10846
} | class ____(BaseToolSpec):
"""Vectara Query tool spec."""
spec_functions = ["semantic_search", "rag_query"]
def __init__(
self,
vectara_corpus_key: Optional[str] = None,
vectara_api_key: Optional[str] = None,
num_results: int = 5,
offset: int = 0,
lambda_val:... | VectaraQueryToolSpec |
python | ray-project__ray | python/ray/data/llm.py | {
"start": 13565,
"end": 24457
} | class ____(_ServeDeploymentProcessorConfig):
"""The configuration for the serve deployment processor.
This processor enables sharing serve deployments across multiple processors. This is useful
for sharing the same LLM engine across multiple processors.
Args:
deployment_name: The name of the s... | ServeDeploymentProcessorConfig |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 15092,
"end": 15517
} | class ____:
"""Test ro_RO currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.ro_RO import Provider as RoRoCurrencyProvider
cls.provider = RoRoCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(... | TestRoRo |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 11726,
"end": 12121
} | class ____(NoReferenceError):
"""Raised by ``ForeignKey`` when the referred ``Table`` cannot be
located.
"""
def __init__(self, message: str, tname: str):
NoReferenceError.__init__(self, message)
self.table_name = tname
def __reduce__(self) -> Union[str, Tuple[Any, ...]]:
... | NoReferencedTableError |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 52586,
"end": 52872
} | class ____(BaseModel):
"""
DAG Stats serializer for responses.
"""
dag_id: Annotated[str, Field(title="Dag Id")]
dag_display_name: Annotated[str, Field(title="Dag Display Name")]
stats: Annotated[list[DagStatsStateResponse], Field(title="Stats")]
| DagStatsResponse |
python | dask__dask | dask/array/cupy_entry_point.py | {
"start": 735,
"end": 2114
} | class ____(ArrayBackendEntrypoint):
def __init__(self):
"""Register data-directed dispatch functions"""
if _cupy(strict=False):
register_cupy()
@classmethod
def to_backend_dispatch(cls):
return to_cupy_dispatch
@classmethod
def to_backend(cls, data: Array, **kwa... | CupyBackendEntrypoint |
python | pyodide__pyodide | benchmark/benchmarks/pystone_benchmarks/pystone.py | {
"start": 1892,
"end": 7311
} | class ____:
def __init__(self, PtrComp=None, Discr=0, EnumComp=0, IntComp=0, StringComp=0):
self.PtrComp = PtrComp
self.Discr = Discr
self.EnumComp = EnumComp
self.IntComp = IntComp
self.StringComp = StringComp
def copy(self):
return Record(
self.PtrC... | Record |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/graphql_client.py | {
"start": 947,
"end": 6634
} | class ____:
def __init__(
self,
session: requests.Session,
headers: Optional[dict[str, Any]] = None,
verify: bool = True,
timeout: int = DEFAULT_TIMEOUT,
cookies: Optional[dict[str, Any]] = None,
proxies: Optional[dict[str, Any]] = None,
max_retries: i... | DagsterCloudAgentHttpClient |
python | getsentry__sentry | src/sentry/snuba/models.py | {
"start": 4045,
"end": 4627
} | class ____(Model):
__relocation_scope__ = RelocationScope.Organization
class EventType(Enum):
ERROR = 0
DEFAULT = 1
TRANSACTION = 2
TRACE_ITEM_SPAN = 3
TRACE_ITEM_LOG = 4
snuba_query = FlexibleForeignKey("sentry.SnubaQuery")
type = models.SmallIntegerField()
... | SnubaQueryEventType |
python | getsentry__sentry | tests/sentry/issues/test_issue_search.py | {
"start": 8830,
"end": 10119
} | class ____(TestCase):
def test_valid(self) -> None:
for status_string, status_val in STATUS_QUERY_CHOICES.items():
filters = [SearchFilter(SearchKey("status"), "=", SearchValue([status_string]))]
result = convert_query_values(filters, [self.project], self.user, None)
asse... | ConvertStatusValueTest |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 48496,
"end": 48542
} | class ____(ssl2_info):
pass
| lapack_ssl2_info |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py | {
"start": 1123,
"end": 1472
} | class ____(Generic[T1, T2, T3]): ...
h1 = ClassH()
reveal_type(h1, expected_text="ClassH[str, str, list[str]]")
h2 = ClassH[int]()
reveal_type(h2, expected_text="ClassH[int, int, list[int]]")
h3 = ClassH[int, float]()
reveal_type(h3, expected_text="ClassH[int, float, list[float]]")
# This should generate an error... | ClassH |
python | django__django | tests/migrations/test_migrations_squashed_loop/2_auto.py | {
"start": 35,
"end": 233
} | class ____(migrations.Migration):
replaces = [("migrations", "2_squashed")]
dependencies = [("migrations", "1_auto")]
operations = [migrations.RunPython(migrations.RunPython.noop)]
| Migration |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/aggregate.py | {
"start": 6586,
"end": 7255
} | class ____(GenericBase):
@staticmethod
def visit_eq(expression: Expression, value: UUID) -> Condition:
return contains(UUIDArray.visit_eq(expression, value))
@staticmethod
def visit_neq(expression: Expression, value: UUID) -> Condition:
return does_not_contain(UUIDArray.visit_eq(express... | SumOfUUIDArray |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/latest_release_handler.py | {
"start": 4385,
"end": 5242
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.ACTION_FILTER
subgroup = DataConditionHandler.Subgroup.EVENT_ATTRIBUTES
comparison_json_schema = {"type": "boolean"}
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
... | LatestReleaseConditionHandler |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_utils.py | {
"start": 1148,
"end": 1480
} | class ____(TestCase):
def test_simple(self) -> None:
fn = {
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
}
assert get_latest_layer_for_function(fn) == "arn:aws:lambda:us-east-2:1234:layer:my-layer:3"
| GetLatestLayerForFunctionTest |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 42729,
"end": 43817
} | class ____(Token):
""" Attribute (possibly parametrized)
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
``Attribute`` as ``attrs``).
Parameters
==========
name : str
parameters : Tuple
Examples
========
>>> from sympy.codegen.ast import Attribute
... | Attribute |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 26547,
"end": 28071
} | class ____(nn.Module):
def __init__(self, config: CLIPVisionConfig):
super().__init__()
self.config = config
embed_dim = config.hidden_size
self.embeddings = CLIPVisionEmbeddings(config)
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.enco... | CLIPVisionTransformer |
python | PrefectHQ__prefect | src/prefect/workers/base.py | {
"start": 2972,
"end": 12774
} | class ____(BaseModel):
command: Optional[str] = Field(
default=None,
description=(
"The command to use when starting a flow run. "
"In most cases, this should be left blank and the command "
"will be automatically generated by the worker."
),
)
env... | BaseJobConfiguration |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 4226,
"end": 4765
} | class ____(Filter):
"""
Create a mode filter. Picks the most frequent pixel value in a box with the
given size. Pixel values that occur only once or twice are ignored; if no
pixel value occurs more than twice, the original pixel value is preserved.
:param size: The kernel size, in pixels.
"""
... | ModeFilter |
python | numba__numba | numba/tests/test_dispatcher.py | {
"start": 36893,
"end": 38046
} | class ____(SerialMixin, unittest.TestCase):
def run_fc_multiproc(self, fc):
try:
ctx = multiprocessing.get_context('spawn')
except AttributeError:
ctx = multiprocessing
# RE: issue #5973, this doesn't use multiprocessing.Pool.map as doing so
# causes the TBB ... | TestMultiprocessingDefaultParameters |
python | huggingface__transformers | src/transformers/models/deit/modeling_deit.py | {
"start": 14214,
"end": 14750
} | class ____(nn.Module):
def __init__(self, config: DeiTConfig):
super().__init__()
self.config = config
self.layer = nn.ModuleList([DeiTLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, hidden_states: torch.Tensor) -> B... | DeiTEncoder |
python | encode__django-rest-framework | tests/test_request.py | {
"start": 13184,
"end": 13341
} | class ____(TestCase):
def test_deepcopy_works(self):
request = Request(factory.get('/', secure=False))
copy.deepcopy(request)
| TestDeepcopy |
python | pytorch__pytorch | test/distributed/_composable/test_replicate_with_compiler.py | {
"start": 2493,
"end": 13679
} | class ____(MultiProcessInductorTestCase):
@property
def world_size(self) -> int:
return min(2, torch.get_device_module(device_type).device_count())
def _test_compile(
self,
*,
no_sync: bool,
setup_func: Optional[Callable] = None,
no_inductor: bool = False,
... | ReplicateTest |
python | ansible__ansible | lib/ansible/utils/context_objects.py | {
"start": 1907,
"end": 2794
} | class ____(ImmutableDict):
"""
Hold a parsed copy of cli arguments
We have both this non-Singleton version and the Singleton, GlobalCLIArgs, version to leave us
room to implement a Context object in the future. Whereas there should only be one set of args
in a global context, individual Context ob... | CLIArgs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.