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 | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass8.py | {
"start": 133,
"end": 203
} | class ____(ABC):
@abstractmethod
def foo(self):
pass
| Foo |
python | walkccc__LeetCode | solutions/2404. Most Frequent Even Element/2404.py | {
"start": 0,
"end": 359
} | class ____:
def mostFrequentEven(self, nums: list[int]) -> int:
ans = -1
count = collections.Counter()
for num in nums:
if num % 2 == 1:
continue
count[num] += 1
newCount = count[num]
maxCount = count[ans]
if newCount > maxCount or newCount == maxCount and num < ans:... | Solution |
python | ansible__ansible | test/lib/ansible_test/_internal/config.py | {
"start": 8091,
"end": 8701
} | class ____(EnvironmentConfig):
"""Configuration for the shell command."""
def __init__(self, args: t.Any) -> None:
super().__init__(args, 'shell')
self.cmd: list[str] = args.cmd
self.raw: bool = args.raw
self.check_layout = self.delegate # allow shell to be used without a vali... | ShellConfig |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/simple_standalone_test/package.py | {
"start": 217,
"end": 956
} | class ____(Package):
"""This package has simple stand-alone test features."""
homepage = "http://www.example.com/simple_test"
url = "http://www.unit-test-should-replace-this-url/simple_test-1.0.tar.gz"
version("1.0", md5="123456789abcdef0123456789abcdefg")
version("0.9", md5="0123456789abcdef01234... | SimpleStandaloneTest |
python | doocs__leetcode | solution/0200-0299/0290.Word Pattern/Solution.py | {
"start": 0,
"end": 389
} | class ____:
def wordPattern(self, pattern: str, s: str) -> bool:
ws = s.split()
if len(pattern) != len(ws):
return False
d1 = {}
d2 = {}
for a, b in zip(pattern, ws):
if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
return False... | Solution |
python | kamyu104__LeetCode-Solutions | Python/two-sum-iii-data-structure-design.py | {
"start": 66,
"end": 755
} | class ____(object):
def __init__(self):
"""
initialize your data structure here
"""
self.lookup = defaultdict(int)
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
self.lookup[number] += 1
... | TwoSum |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 122436,
"end": 123132
} | class ____:
def setup_method(self):
self.x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5
def test_mle(self):
maxlog = stats.yeojohnson_normmax(self.x)
assert_allclose(maxlog, 1.876393, rtol=1e-6)
def test_darwin_example(self):
# test from original paper "A new fam... | TestYeojohnsonNormmax |
python | pytorch__pytorch | test/dynamo/test_flat_apply.py | {
"start": 805,
"end": 3664
} | class ____(torch._dynamo.test_case.TestCase):
def test_simple(self):
tensor = torch.tensor
a = Point(tensor(0.0), tensor(0.0))
b = Point(tensor(3.0), tensor(4.0))
norm = Norm("l2")
args = (a, b)
kwargs = {"norm": norm}
empty_list, func_spec = func_to_grapha... | FlatApplyTests |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 7077,
"end": 7839
} | class ____(
mixins.NodeDetailMixin,
mixins.NodeCancelMixin,
mixins.NodeUndoMixin,
mixins.NodeReviveMixin,
nodes.Handle,
):
"""
Represents a task executed from the other parts of code
Usage:
To define a handle in a flow and run it:
.. code-block:: python
class MyFlow(fl... | Handle |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 8619,
"end": 8738
} | class ____(OverrideSampleTestsMixin, TestCase):
"""
Run tests with Django TestCase
"""
| OverrideSampleTestCase |
python | pytest-dev__pytest-asyncio | tests/test_simple.py | {
"start": 2157,
"end": 3119
} | class ____:
@pytest.fixture
async def loop(self):
return asyncio.get_event_loop()
@staticmethod
def foo():
return 1
@pytest.mark.asyncio
async def test_no_event_loop(self, loop):
assert await loop.run_in_executor(None, self.foo) == 1
@pytest.mark.asyncio
async ... | TestEventLoopStartedBeforeFixtures |
python | google__pytype | pytype/tests/test_operators2.py | {
"start": 82,
"end": 3321
} | class ____(test_base.BaseTest):
"""Operator tests."""
@test_base.skip("Needs __radd__ on all builtins")
def test_add1(self):
"""Test that __add__, __radd__ are working."""
ty = self.Infer("""
def t_testAdd1(x):
return x + 2.0
""")
self.assertTypesMatchPytd(
ty,
"""
... | OperatorsWithAnyTests |
python | getsentry__sentry | tests/sentry/models/test_groupsnooze.py | {
"start": 655,
"end": 18915
} | class ____(
TestCase,
SnubaTestCase,
SearchIssueTestMixin,
PerformanceIssueTestCase,
):
sequence = itertools.count() # generates unique values, class scope doesn't matter
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.group.times_seen... | GroupSnoozeTest |
python | ray-project__ray | python/ray/tune/integration/xgboost.py | {
"start": 368,
"end": 3484
} | class ____(RayReportCallback):
"""XGBoost callback to save checkpoints and report metrics for Ray Tune.
Args:
metrics: Metrics to report. If this is a list,
each item describes the metric key reported to XGBoost,
and it will be reported under the same name.
This can ... | TuneReportCheckpointCallback |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 10667,
"end": 16730
} | class ____(TestCase):
"""Run a set of generic tests to verify that self.func acts like a
reduction operation.
Specifically, this class checks axis=... and keepdims=... parameters.
To check the out=... parameter, see the _GenericHasOutTestMixin class below.
To use: subclass, define self.func and se... | TestGenericReductions |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 2436,
"end": 2580
} | class ____(str, Enum):
"""Encoding type for the serve logs."""
TEXT = "TEXT"
JSON = "JSON"
@PublicAPI(stability="alpha")
| EncodingType |
python | spyder-ide__spyder | spyder/widgets/browser.py | {
"start": 2455,
"end": 13731
} | class ____(QWebEngineView, SpyderWidgetMixin):
"""
Web view.
"""
sig_focus_in_event = Signal()
"""
This signal is emitted when the widget receives focus.
"""
sig_focus_out_event = Signal()
"""
This signal is emitted when the widget loses focus.
"""
def __init__(self, pa... | WebView |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 7052,
"end": 9732
} | class ____(BaseEntitySubscription, ABC):
def __init__(
self,
aggregate: str,
time_window: int,
extra_fields: _EntitySpecificParams | None = None,
):
super().__init__(aggregate, time_window, extra_fields)
self.aggregate = aggregate
self.event_types = None
... | BaseEventsAndTransactionEntitySubscription |
python | bokeh__bokeh | tests/unit/bokeh/protocol/messages/test_patch_doc.py | {
"start": 1685,
"end": 6272
} | class ____:
def _sample_doc(self):
doc = document.Document()
another = AnotherModelInTestPatchDoc()
doc.add_root(SomeModelInTestPatchDoc(child=another))
doc.add_root(SomeModelInTestPatchDoc())
doc.to_json() # clear new model queue
return doc
def test_create_no_ev... | TestPatchDocument |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/interfaces.py | {
"start": 6522,
"end": 7470
} | class ____(ConnectionError):
"""
Raised if `.test_connection()` fails to connect to the datasource.
"""
def __init__(
self,
message: str = "Attempt to connect to datasource failed",
*,
cause: Exception | None = None,
addendum: str | None = None,
):
""... | TestConnectionError |
python | pallets__click | src/click/parser.py | {
"start": 7005,
"end": 19010
} | class ____:
"""The option parser is an internal class that is ultimately used to
parse options and arguments. It's modelled after optparse and brings
a similar but vastly simplified API. It should generally not be used
directly as the high level Click classes wrap it for you.
It's not nearly as e... | _OptionParser |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py | {
"start": 69,
"end": 2275
} | class ____(ValidationRule):
__slots__ = 'errors', 'visited_frags', 'spread_path', 'spread_path_index_by_name'
def __init__(self, context):
super(NoFragmentCycles, self).__init__(context)
self.errors = []
self.visited_frags = set()
self.spread_path = []
self.spread_path_i... | NoFragmentCycles |
python | google__pytype | pytype/abstract/_function_base.py | {
"start": 15792,
"end": 16928
} | class ____(
BoundFunction["_interpreter_function.InterpreterFunction"]
):
"""The method flavor of InterpreterFunction."""
@contextlib.contextmanager
def record_calls(self) -> Generator[None, None, None]:
with self.underlying.record_calls():
yield
# TODO: b/350643999 - figure out the return type
... | BoundInterpreterFunction |
python | pydantic__pydantic | pydantic/deprecated/parse.py | {
"start": 468,
"end": 2511
} | class ____(str, Enum):
json = 'json'
pickle = 'pickle'
@deprecated('`load_str_bytes` is deprecated.', category=None)
def load_str_bytes(
b: str | bytes,
*,
content_type: str | None = None,
encoding: str = 'utf8',
proto: Protocol | None = None,
allow_pickle: bool = False,
json_loads... | Protocol |
python | pypa__warehouse | tests/unit/legacy/api/test_json.py | {
"start": 15415,
"end": 17669
} | class ____:
def test_missing_release(self, db_request):
project = ProjectFactory.create()
db_request.matchdict = {"name": project.normalized_name, "version": "3.0"}
resp = json.release_factory(db_request)
assert isinstance(resp, HTTPNotFound)
_assert_has_cors_headers(resp.hea... | TestReleaseFactory |
python | pypa__pip | src/pip/_vendor/dependency_groups/_implementation.py | {
"start": 1017,
"end": 1072
} | class ____:
include_group: str
| DependencyGroupInclude |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_stats_mep.py | {
"start": 768,
"end": 44983
} | class ____(
MetricsEnhancedPerformanceTestCase
):
endpoint = "sentry-api-0-organization-events-stats"
METRIC_STRINGS = [
"foo_transaction",
"d:transactions/measurements.datacenter_memory@pebibyte",
]
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.us... | OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest |
python | numba__numba | numba/tests/test_firstlinefinder.py | {
"start": 197,
"end": 6831
} | class ____(TestCase):
"""
The following methods contains tests that are sensitive to the source
locations w.r.t. the beginning of each method.
"""
def _get_grandparent_caller_code(self):
frame = inspect.currentframe()
caller_frame = inspect.getouterframes(frame)
return calle... | TestFirstLineFinder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/workflows.py | {
"start": 6440,
"end": 9723
} | class ____(GoogleCloudBaseOperator):
"""
Updates an existing workflow.
Running this method has no impact on already running
executions of the workflow. A new revision of the
workflow may be created as a result of a successful
update operation. In that case, such revision will be
used in new... | WorkflowsUpdateWorkflowOperator |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/resolvers.py | {
"start": 1763,
"end": 2105
} | class ____(RegionResolutionStrategy):
"""Resolve from a `str` parameter representing an organization slug."""
parameter_name: str = "slug"
def resolve(self, arguments: ArgumentDict) -> Region:
slug = arguments[self.parameter_name]
return self._get_from_mapping(slug=slug)
@dataclass(froze... | ByOrganizationSlug |
python | crytic__slither | slither/core/declarations/custom_error_top_level.py | {
"start": 295,
"end": 611
} | class ____(CustomError, TopLevel):
def __init__(self, compilation_unit: "SlitherCompilationUnit", scope: "FileScope") -> None:
super().__init__(compilation_unit)
self.file_scope: "FileScope" = scope
@property
def canonical_name(self) -> str:
return self.full_name
| CustomErrorTopLevel |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 16791,
"end": 20614
} | class ____(nn.Module):
def __init__(self, config: GitVisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(torch.randn(sel... | GitVisionEmbeddings |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/conftest/request_builder.py | {
"start": 1636,
"end": 2241
} | class ____:
@classmethod
def get_token_endpoint(cls) -> AuthBuilder:
return cls(resource="token")
def __init__(self, resource):
self._body = ""
self._resource = resource
self._query_params = ""
def with_body(self, body: str):
self._body = body
return sel... | AuthBuilder |
python | facebook__pyre-check | client/commands/tests/statistics_test.py | {
"start": 2941,
"end": 3951
} | class ____(testslide.TestCase):
maxDiff = 2000
def assert_counts(
self,
source: str,
expected_codes: Dict[int, List[int]],
expected_no_codes: List[int],
) -> None:
source_module = parse_code(source.replace("IGNORE", "pyre-ignore"))
result = statistics.IgnoreC... | IgnoreCountCollectorTest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_contain_valid_email.py | {
"start": 395,
"end": 1622
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_email"
condition_value_keys = ()
# This method defines the business logic for evaluating your metric when using a PandasExecutionEngine
@column_condi... | ColumnValuesContainValidEmail |
python | conda__conda | conda/gateways/repodata/__init__.py | {
"start": 2022,
"end": 2188
} | class ____(Exception):
"""
Indicate that RepoInterface.repodata() successfully wrote repodata to disk,
instead of returning a string.
"""
| RepodataOnDisk |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/11_Dyna_Q/RL_brain.py | {
"start": 1996,
"end": 3068
} | class ____:
"""Similar to the memory buffer in DQN, you can store past experiences in here.
Alternatively, the model can generate next state and reward signal accurately."""
def __init__(self, actions):
# the simplest case is to think about the model is a memory which has all past transition informa... | EnvModel |
python | pytorch__pytorch | torch/_inductor/test_case.py | {
"start": 394,
"end": 1475
} | class ____(DynamoTestCase):
"""
A base TestCase for inductor tests. Enables FX graph caching and isolates
the cache directory for each test.
"""
def setUp(self) -> None:
super().setUp()
self._inductor_test_stack = contextlib.ExitStack()
self._inductor_test_stack.enter_contex... | TestCase |
python | MongoEngine__mongoengine | mongoengine/document.py | {
"start": 3540,
"end": 41607
} | class ____(BaseDocument, metaclass=TopLevelDocumentMetaclass):
"""The base class used for defining the structure and properties of
collections of documents stored in MongoDB. Inherit from this class, and
add fields as class attributes to define a document's structure.
Individual documents may then be cr... | Document |
python | django__django | django/forms/fields.py | {
"start": 34594,
"end": 35822
} | class ____(MultipleChoiceField):
def __init__(self, *, coerce=lambda val: val, **kwargs):
self.coerce = coerce
self.empty_value = kwargs.pop("empty_value", [])
super().__init__(**kwargs)
def _coerce(self, value):
"""
Validate that the values are in self.choices and can b... | TypedMultipleChoiceField |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 488,
"end": 758
} | class ____:
"""Base model for Prefect filters that combines criteria with a user-provided operator"""
operator: Operator = Field(
default=Operator.and_,
description="Operator for combining filter criteria. Defaults to 'and_'.",
)
| OperatorMixin |
python | kamyu104__LeetCode-Solutions | Python/count-special-quadruplets.py | {
"start": 52,
"end": 651
} | class ____(object):
def countQuadruplets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
lookup = collections.defaultdict(int)
lookup[nums[-1]] = 1
for c in reversed(xrange(2, len(nums)-1)):
for b in xrange(1, c):
... | Solution |
python | RaRe-Technologies__gensim | gensim/test/test_similarity_metrics.py | {
"start": 4866,
"end": 7457
} | class ____(unittest.TestCase):
def setUp(self):
self.corpus = MmCorpus(datapath('testcorpus.mm'))
self.class_ = ldamodel.LdaModel
self.model = self.class_(common_corpus, id2word=common_dictionary, num_topics=2, passes=100)
def test_inputs(self):
# checking empty inputs
... | TestKL |
python | django-mptt__django-mptt | tests/myapp/tests.py | {
"start": 55464,
"end": 55936
} | class ____(TreeTestCase):
fixtures = ["genres.json"]
template = re.sub(
r"(?m)^[\s]+",
"",
"""
{% load mptt_tags %}
{% full_tree_for_model myapp.Genre as tree %}
{% for node in tree %}{{ node.pk }},{% endfor %}
""",
)
def test_full_tree_html(self)... | FullTreeTestCase |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/hot_reloading_app_with_screen_css.py | {
"start": 715,
"end": 889
} | class ____(App[None]):
def on_mount(self) -> None:
self.push_screen(MyScreen())
if __name__ == "__main__":
HotReloadingApp(watch_css=True).run()
| HotReloadingApp |
python | networkx__networkx | networkx/readwrite/text.py | {
"start": 927,
"end": 1310
} | class ____(BaseGlyphs):
# Notes on available box and arrow characters
# https://en.wikipedia.org/wiki/Box-drawing_character
# https://stackoverflow.com/questions/2701192/triangle-arrow
empty: str = "╙"
newtree_last: str = "╙── "
newtree_mid: str = "╟── "
endof_forest: str = " "
within... | UtfBaseGlyphs |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 25631,
"end": 25808
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("POSITION",)
| ProjectV2ItemFieldValueOrderField |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/ray.py | {
"start": 9798,
"end": 11532
} | class ____(RayBaseOperator):
"""
List Ray clusters under the currently authenticated project.
: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 gcp_conn_id: Th... | ListRayClustersOperator |
python | justquick__django-activity-stream | actstream/tests/test_drf.py | {
"start": 265,
"end": 1299
} | class ____(DataTestCase):
def setUp(self):
from rest_framework.test import APIClient
super().setUp()
self.auth_user = self.user1
self.client = APIClient()
self.auth_client = APIClient()
self.auth_client.login(username=self.user1.username, password='admin')
def g... | BaseDRFTestCase |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 8617,
"end": 11729
} | class ____:
"""Represents a live websocket connection to the Realtime API"""
session: AsyncRealtimeSessionResource
response: AsyncRealtimeResponseResource
input_audio_buffer: AsyncRealtimeInputAudioBufferResource
conversation: AsyncRealtimeConversationResource
output_audio_buffer: AsyncRealtime... | AsyncRealtimeConnection |
python | numpy__numpy | numpy/lib/tests/test_io.py | {
"start": 1948,
"end": 5527
} | class ____:
def roundtrip(self, save_func, *args, **kwargs):
"""
save_func : callable
Function used to save arrays to file.
file_on_disk : bool
If true, store the file on disk, instead of in a
string buffer.
save_kwds : dict
Parameters ... | RoundtripTest |
python | numpy__numpy | tools/swig/test/testFlat.py | {
"start": 4443,
"end": 4704
} | class ____(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "ulong"
self.typeCode = "L"
######################################################################
| ulongTestCase |
python | getsentry__sentry | src/sentry/api/serializers/models/team.py | {
"start": 13101,
"end": 14689
} | class ____(Serializer):
def __init__(
self,
expand: Sequence[str] | None = None,
) -> None:
self.expand = expand or []
def get_attrs(
self, item_list: Sequence[Team], user: User | RpcUser | AnonymousUser, **kwargs: Any
) -> dict[Team, dict[str, Any]]:
result: di... | TeamSCIMSerializer |
python | lazyprogrammer__machine_learning_examples | pytorch/rl_trader.py | {
"start": 7177,
"end": 11873
} | class ____(object):
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.memory = ReplayBuffer(state_size, action_size, size=500)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.... | DQNAgent |
python | django__django | django/core/paginator.py | {
"start": 12204,
"end": 15267
} | class ____:
def __init__(self, object_list, number, paginator):
self.object_list = object_list
self.number = number
self.paginator = paginator
def __repr__(self):
return "<Async Page %s>" % self.number
async def __aiter__(self):
if hasattr(self.object_list, "__aiter... | AsyncPage |
python | google__pytype | pytype/rewrite/convert.py | {
"start": 297,
"end": 5508
} | class ____:
"""Pytd -> abstract converter."""
def __init__(self, ctx: abstract.ContextType):
self._ctx = ctx
self._cache = _Cache()
overlays.initialize()
def pytd_class_to_value(self, cls: pytd.Class) -> abstract.SimpleClass:
"""Converts a pytd class to an abstract class."""
if cls in self._... | AbstractConverter |
python | django__django | tests/auth_tests/test_admin_multidb.py | {
"start": 244,
"end": 685
} | class ____:
target_db = None
def db_for_read(self, model, **hints):
return self.target_db
db_for_write = db_for_read
def allow_relation(self, obj1, obj2, **hints):
return True
site = admin.AdminSite(name="test_adminsite")
site.register(User, admin_class=UserAdmin)
urlpatterns = [
... | Router |
python | django__django | tests/model_fields/tests.py | {
"start": 10458,
"end": 12967
} | class ____(SimpleTestCase):
def test_choices_and_field_display(self):
"""
get_choices() interacts with get_FIELD_display() to return the expected
values.
"""
self.assertEqual(Whiz(c=1).get_c_display(), "First") # A nested value
self.assertEqual(Whiz(c=0).get_c_displa... | GetFieldDisplayTests |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 7628,
"end": 8203
} | class ____(LocalizableStreamlitException):
"""Exception raised when an invalid value is specified for vertical_alignment."""
def __init__(self, vertical_alignment: str, element_type: str) -> None:
super().__init__(
"The `vertical_alignment` argument to `{element_type}` must be "
... | StreamlitInvalidVerticalAlignmentError |
python | kamyu104__LeetCode-Solutions | Python/maximum-genetic-difference-query.py | {
"start": 95,
"end": 930
} | class ____(object):
def __init__(self, bit_count):
self.__root = {}
self.__bit_count = bit_count
def insert(self, num, v):
node = self.__root
for i in reversed(xrange(self.__bit_count)):
curr = (num>>i) & 1
new_node = node.setdefault(curr, collect... | Trie |
python | pytorch__pytorch | test/test_sort_and_select.py | {
"start": 651,
"end": 55367
} | class ____(TestCase):
def assertIsOrdered(self, order, x, mxx, ixx, task):
SIZE = x.size(1)
if order == "descending":
def check_order(a, b):
# `a != a` because we put NaNs
# at the end of ascending sorted lists,
# and the beginning of desc... | TestSortAndSelect |
python | scipy__scipy | scipy/sparse/_dok.py | {
"start": 21162,
"end": 23387
} | class ____(spmatrix, _dok_base):
"""
Dictionary Of Keys based sparse matrix.
This is an efficient structure for constructing sparse
matrices incrementally.
This can be instantiated in several ways:
dok_matrix(D)
where D is a 2-D ndarray
dok_matrix(S)
with a... | dok_matrix |
python | chroma-core__chroma | chromadb/segment/impl/manager/distributed.py | {
"start": 622,
"end": 2986
} | class ____(SegmentManager):
_sysdb: SysDB
_system: System
_instances: Dict[UUID, SegmentImplementation]
_segment_directory: SegmentDirectory
_lock: Lock
def __init__(self, system: System):
super().__init__(system)
self._sysdb = self.require(SysDB)
self._segment_directory... | DistributedSegmentManager |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/normal_test.py | {
"start": 1736,
"end": 21729
} | class ____(test.TestCase):
def setUp(self):
self._rng = np.random.RandomState(123)
def assertAllFinite(self, tensor):
is_finite = np.isfinite(self.evaluate(tensor))
all_true = np.ones_like(is_finite, dtype=np.bool_)
self.assertAllEqual(all_true, is_finite)
def _testParamShapes(self, sample_shap... | NormalTest |
python | PrefectHQ__prefect | tests/runtime/test_flow_run.py | {
"start": 22805,
"end": 23407
} | class ____:
async def test_job_variables_is_attribute(self):
assert "job_variables" in dir(flow_run)
async def test_job_variables_is_none_when_not_set(self):
assert flow_run.job_variables is None
async def test_job_variables_returns_variables_when_present_dynamically(self):
assert ... | TestJobVariables |
python | facebook__pyre-check | tools/incremental_test/tests/runner_tests.py | {
"start": 990,
"end": 29661
} | class ____(unittest.TestCase):
@patch("os.stat", new=mock_stat)
@patch("tempfile.NamedTemporaryFile", new=mock_temp_file_class)
def assert_run(
self,
mock_execute: MockExecuteCallable,
specification: Specification,
expected_commands: List[CommandInput],
expected_discr... | RunnerTest |
python | getsentry__sentry | src/sentry/web/frontend/twofactor.py | {
"start": 1778,
"end": 9931
} | class ____(BaseView):
auth_required = False
def perform_signin(self, request: HttpRequest, user, interface=None):
assert auth.login(request, user, passed_2fa=True)
rv = HttpResponseRedirect(auth.get_login_redirect(request))
if interface is not None:
interface.authenticator.m... | TwoFactorAuthView |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/core.py | {
"start": 49166,
"end": 55730
} | class ____(Layer):
"""Wraps TF API symbols in a `Layer` object.
It is inserted by the Functional API construction whenever users call
a supported TF symbol on KerasTensors.
Like Lambda layers, this layer tries to raise warnings when it detects users
explicitly use variables in the call. (To let them know
... | TFOpLambda |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType13.py | {
"start": 110,
"end": 278
} | class ____: ...
T = TypeVar("T")
def func1(x: Type[Any], y: Type[T]) -> T:
v1: Type[Any] = x
v2: Type[Any] = ClassA
v3: Type[Any] = y
return y()
| ClassA |
python | anthropics__anthropic-sdk-python | tests/api_resources/test_models.py | {
"start": 3622,
"end": 7147
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_retrieve(self, async_client: AsyncAnthropic) -> None:
model = await async_client.models.re... | TestAsyncModels |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_stackdriver.py | {
"start": 4187,
"end": 4697
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook")
def test_execute(self, mock_hook):
operator = StackdriverEnableAlertPoliciesOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER)
operator.execute(context=mock.MagicMock())
mock_hook.return_valu... | TestStackdriverEnableAlertPoliciesOperator |
python | kubernetes-client__python | kubernetes/client/models/v1_iscsi_persistent_volume_source.py | {
"start": 383,
"end": 14704
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1ISCSIPersistentVolumeSource |
python | ipython__ipython | IPython/core/error.py | {
"start": 886,
"end": 1081
} | class ____(IPythonCoreError):
"""Try next hook exception.
Raise this in your hook function to indicate that the next hook handler
should be used to handle the operation.
"""
| TryNext |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 5753,
"end": 8549
} | class ____(fixtures.TablesTest):
__only_on__ = "mssql"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"rv_t",
metadata,
Column("data", String(50)),
Column("rv", ROWVERSION),
)
Table(
"ts_t",
... | RowVersionTest |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 38764,
"end": 44960
} | class ____(MBartPreTrainedModel):
_tied_weights_keys = {
"decoder.embed_tokens.weight": "shared.weight",
"encoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: MBartConfig):
super().__init__(config)
padding_idx, vocab_size = config.pad_token_id, config... | MBartModel |
python | mkdocs__mkdocs | mkdocs/exceptions.py | {
"start": 457,
"end": 717
} | class ____(MkDocsException):
"""
This error is raised by configuration validation when a validation error
is encountered. This error should be raised by any configuration options
defined in a plugin's [config_scheme][].
"""
| ConfigurationError |
python | streamlit__streamlit | lib/tests/streamlit/runtime/state/query_params_test.py | {
"start": 1119,
"end": 17403
} | class ____(DeltaGeneratorTestCase):
def setUp(self):
super().setUp()
self.query_params = QueryParams()
self.query_params._query_params = {"foo": "bar", "two": ["x", "y"]}
def test__iter__doesnt_include_embed_keys(self):
self.query_params._query_params = QUERY_PARAMS_DICT_WITH_EM... | QueryParamsMethodTests |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 67018,
"end": 67691
} | class ____(gdb.Function):
def _get_pycurframe_attr(self, attr):
frame = Frame(gdb.selected_frame())
if is_evalframeex(frame):
pyframe = frame.get_pyop()
if pyframe is None:
warnings.warn("Use a Python debug build, Python breakpoints "
... | PyNameEquals |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_sys.py | {
"start": 53183,
"end": 60199
} | class ____(__TestCase):
def test_original_unraisablehook(self):
_testcapi = import_helper.import_module('_testcapi')
from _testcapi import err_writeunraisable, err_formatunraisable
obj = hex
with support.swap_attr(sys, 'unraisablehook',
sys.__unra... | UnraisableHookTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 85841,
"end": 89784
} | class ____(GoogleCloudBaseOperator):
"""
Creates an Asset resource.
:param project_id: Required. The ID of the Google Cloud project that the task belongs to.
:param region: Required. The ID of the Google Cloud region that the task belongs to.
:param lake_id: Required. The ID of the Google Cloud lak... | DataplexCreateAssetOperator |
python | faif__python-patterns | tests/test_hsm.py | {
"start": 234,
"end": 1475
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.hsm = HierachicalStateMachine()
def test_initial_state_shall_be_standby(cls):
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
def test_unsupported_state_shall_raise_exception(cls):
with cls.... | HsmMethodTest |
python | great-expectations__great_expectations | great_expectations/render/renderer/observed_value_renderer.py | {
"start": 194,
"end": 343
} | class ____(str, Enum):
EXPECTED = "expected"
UNEXPECTED = "unexpected"
MISSING = "missing"
@dataclass(frozen=True)
| ObservedValueRenderState |
python | numba__numba | numba/core/pythonapi.py | {
"start": 67123,
"end": 69621
} | class ____:
"""Internal utils for calling objmode dispatcher from within NPM code.
"""
def __init__(self, pyapi):
self.pyapi = pyapi
def load_dispatcher(self, fnty, argtypes):
builder = self.pyapi.builder
tyctx = self.pyapi.context
m = builder.module
# Add a glo... | ObjModeUtils |
python | huggingface__transformers | src/transformers/models/tvp/modeling_tvp.py | {
"start": 5362,
"end": 7107
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.backbone = load_backbone(config)
if config.backbone_config is not None:
in_channels = config.backbone_config.hidden_sizes[-1]
elif hasattr(self.backbone, "config") and hasattr(self.backbone.config... | TvpVisionModel |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/runnable_exec_date_dep.py | {
"start": 977,
"end": 2326
} | class ____(BaseTIDep):
"""Determines whether a task's logical date is valid."""
NAME = "Logical Date"
IGNORABLE = True
@provide_session
def _get_dep_statuses(self, ti, session, dep_context):
logical_date = ti.get_dagrun(session).logical_date
if logical_date is None:
ret... | RunnableExecDateDep |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/llama_index/vector_stores/bigquery/base.py | {
"start": 1173,
"end": 1288
} | class ____(str, Enum):
EUCLIDEAN = "EUCLIDEAN"
COSINE = "COSINE"
DOT_PRODUCT = "DOT_PRODUCT"
| DistanceType |
python | pypa__pip | src/pip/_vendor/rich/syntax.py | {
"start": 7967,
"end": 36369
} | class ____(JupyterMixin):
"""Construct a Syntax object to render syntax highlighted code.
Args:
code (str): Code to highlight.
lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/... | Syntax |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/schedule_definition.py | {
"start": 16904,
"end": 18771
} | class ____(
NamedTuple(
"_ScheduleExecutionData",
[
("run_requests", Optional[Sequence[RunRequest]]),
("skip_message", Optional[str]),
("log_key", Optional[Sequence[str]]),
],
)
):
def __new__(
cls,
run_requests: Optional[Sequence[R... | ScheduleExecutionData |
python | ray-project__ray | python/ray/serve/task_processor.py | {
"start": 988,
"end": 12922
} | class ____(TaskProcessorAdapter):
"""
Celery-based task processor adapter.
This adapter does NOT support any async operations.
All operations must be performed synchronously.
"""
_app: Celery
_config: TaskProcessorConfig
_worker_thread: Optional[threading.Thread] = None
_worker_host... | CeleryTaskProcessorAdapter |
python | getsentry__sentry | tests/sentry/apidocs/test_extensions.py | {
"start": 717,
"end": 931
} | class ____(BasicSerializerOptional):
b: str
c: bool
d: list[int]
e: NestedDict
f: Literal[3]
g: str | bool
h: str | None
i: int | float | None
excluded: str
| BasicSerializerResponse |
python | matplotlib__matplotlib | lib/matplotlib/backend_tools.py | {
"start": 20353,
"end": 22704
} | class ____(ToolToggleBase):
"""Base class for `ToolZoom` and `ToolPan`."""
def __init__(self, *args):
super().__init__(*args)
self._button_pressed = None
self._xypress = None
self._idPress = None
self._idRelease = None
self._idScroll = None
self.base_scale... | ZoomPanBase |
python | lazyprogrammer__machine_learning_examples | rl2/cartpole/pg_tf.py | {
"start": 3465,
"end": 7857
} | class ____:
def __init__(self, D, hidden_layer_sizes):
# create the graph
self.layers = []
M1 = D
for M2 in hidden_layer_sizes:
layer = HiddenLayer(M1, M2)
self.layers.append(layer)
M1 = M2
# final layer
layer = HiddenLayer(M1, 1, lambda x: x)
self.layers.append(layer)
... | ValueModel |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_str_returned.py | {
"start": 829,
"end": 1002
} | class ____:
""" __str__ returns node which does not have 'value' in AST """
def __str__(self): # [invalid-str-returned]
return lambda: "some str"
| ThirdBadStr |
python | keras-team__keras | examples/demo_custom_layer_backend_agnostic.py | {
"start": 947,
"end": 1458
} | class ____(layers.Layer):
def __init__(self, rate, name=None):
super().__init__(name=name)
self.rate = rate
# Use seed_generator for managing RNG state.
# It is a state element and its seed variable is
# tracked as part of `layer.variables`.
self.seed_generator = kera... | MyDropout |
python | kamyu104__LeetCode-Solutions | Python/divide-nodes-into-the-maximum-number-of-groups.py | {
"start": 52,
"end": 1663
} | class ____(object):
def magnificentSets(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs(u):
group = []
stk = [u]
lookup[u] = 0
while stk:
u = stk.pop()
... | Solution |
python | huggingface__transformers | src/transformers/models/bit/modeling_bit.py | {
"start": 16477,
"end": 18610
} | class ____(nn.Module):
"""
A ResNet v2 stage composed by stacked layers.
"""
def __init__(
self,
config,
in_channels,
out_channels,
stride,
dilation,
depth,
bottle_ratio=0.25,
layer_dropout=None,
):
super().__init__()
... | BitStage |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 3684,
"end": 3760
} | class ____(date):
"""test derived instance of date"""
pass
| CustomDate |
python | Pylons__pyramid | tests/test_location.py | {
"start": 99,
"end": 783
} | class ____(unittest.TestCase):
def _callFUT(self, one, two):
from pyramid.location import inside
return inside(one, two)
def test_inside(self):
o1 = Location()
o2 = Location()
o2.__parent__ = o1
o3 = Location()
o3.__parent__ = o2
o4 = Location()
... | TestInside |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 37064,
"end": 38666
} | class ____(TestCase):
def test_repr_date_field_not_included(self):
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = HiddenFieldUniqueForDateModel
fields = ('id', 'slug')
serializer = TestSerializer()
expected = dedent("""
... | TestHiddenFieldUniquenessForDateValidation |
python | anthropics__anthropic-sdk-python | src/anthropic/_exceptions.py | {
"start": 3202,
"end": 3339
} | class ____(APIStatusError):
status_code: Literal[413] = 413 # pyright: ignore[reportIncompatibleVariableOverride]
| RequestTooLargeError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.