language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
kamyu104__LeetCode-Solutions
Python/bus-routes.py
{ "start": 66, "end": 1071 }
class ____(object): def numBusesToDestination(self, routes, S, T): """ :type routes: List[List[int]] :type S: int :type T: int :rtype: int """ if S == T: return 0 to_route = collections.defaultdict(set) for i, route in enumerate(ro...
Solution
python
cherrypy__cherrypy
cherrypy/test/test_iterator.py
{ "start": 467, "end": 1068 }
class ____(IteratorBase): started = False closed_off = False count = 0 def increment(self): self.incr() def decrement(self): if not self.closed_off: self.closed_off = True self.decr() def __iter__(self): return self def __next__(self): ...
OurIterator
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-box/llama_index/readers/box/BoxReaderAIExtraction/base.py
{ "start": 503, "end": 4189 }
class ____(BoxReaderBase): """ A reader class for loading data from Box files using Box AI Extract. This class inherits from the `BaseReader` class and specializes in processing data from Box files using Box AI Extract. It utilizes the provided BoxClient object to interact with the Box API and extr...
BoxReaderAIExtract
python
walkccc__LeetCode
solutions/1188. Design Bounded Blocking Queue/1188.py
{ "start": 34, "end": 564 }
class ____: def __init__(self, capacity: int): self.q = collections.deque() self.enqueueSemaphore = Semaphore(capacity) self.dequeueSemaphore = Semaphore(0) def enqueue(self, element: int) -> None: self.enqueueSemaphore.acquire() self.q.append(element) self.dequeueSemaphore.release() def...
BoundedBlockingQueue
python
PrefectHQ__prefect
src/prefect/utilities/dispatch.py
{ "start": 143, "end": 241 }
class ____: @classmethod def __dispatch_key__(cls): return cls.__name__.lower()
Base
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 3740, "end": 3900 }
class ____(_TestSchema): _schema = {"anyOf": [{"$ref": "#/definitions/Foo"}, {"$ref": "#/definitions/Bar"}]} _rootschema = Derived._schema
DefinitionUnion
python
ray-project__ray
doc/source/rllib/doc_code/custom_gym_env.py
{ "start": 137, "end": 1152 }
class ____(gym.Env): def __init__(self, config): self.end_pos = config["corridor_length"] self.cur_pos = 0.0 self.action_space = gym.spaces.Discrete(2) # right/left self.observation_space = gym.spaces.Box(0.0, self.end_pos, shape=(1,)) def reset(self, *, seed=None, options=None...
SimpleCorridor
python
falconry__falcon
falcon/inspect.py
{ "start": 14150, "end": 14639 }
class ____(_Traversable): """Describes a middleware tree entry. Args: name (str): The name of the method. class_name (str): The class name of the method. """ __visit_name__ = 'middleware_tree_item' _symbols = { 'process_request': '→', 'process_resource': '↣', ...
MiddlewareTreeItemInfo
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 94817, "end": 94956 }
class ____(torch.nn.Module): def calculate_qparams(self): return 1.0, 0 def forward(self, x): return x
DummyObserver
python
kamyu104__LeetCode-Solutions
Python/minimum-incompatibility.py
{ "start": 3643, "end": 6189 }
class ____(object): def minimumIncompatibility(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def greedy(nums, k, is_reversed): count = collections.Counter(nums) if max(count.itervalues()) > k: return -1 ...
Solution_Wrong_Greedy_SortedList
python
huggingface__transformers
src/transformers/models/vjepa2/modeling_vjepa2.py
{ "start": 36007, "end": 37737 }
class ____(PreTrainedModel): config: VJEPA2Config base_model_prefix = "vjepa2" main_input_name = "pixel_values_videos" input_modalities = "video" supports_gradient_checkpointing = True _no_split_modules = [ "VJEPA2Layer", "VJEPA2PoolerSelfAttentionLayer", "VJEPA2PoolerCro...
VJEPA2PreTrainedModel
python
Netflix__metaflow
metaflow/plugins/datatools/s3/s3.py
{ "start": 3034, "end": 3118 }
class ____(MetaflowException): headline = "S3 object not found"
MetaflowS3NotFound
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 63183, "end": 63678 }
class ____(OrderedSetAgg[_T]): """Implement the ``percentile_cont`` ordered-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, o...
percentile_cont
python
walkccc__LeetCode
solutions/2384. Largest Palindromic Number/2384.py
{ "start": 0, "end": 396 }
class ____: def largestPalindromic(self, num: str) -> str: count = collections.Counter(num) firstHalf = ''.join(count[i] // 2 * i for i in '9876543210').lstrip('0') mid = self._getMid(count) return (firstHalf + mid + firstHalf[::-1]) or '0' def _getMid(self, count: dict[str, int]) -> str: for c...
Solution
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 176904, "end": 177777 }
class ____(test.TestCase): def testOnesLike(self): for dtype in [ dtypes.float32, dtypes.float64, dtypes.int32, dtypes.uint8, dtypes.int16, dtypes.int8, dtypes.complex64, dtypes.complex128, dtypes.int64, ]: numpy_dtype = dtype.as_n...
MPSOnesLikeTest
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_backend.py
{ "start": 5266, "end": 5692 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(model_attr="foo", document=True) name = indexes.CharField(model_attr="author") pub_date = indexes.DateTimeField(model_attr="pub_date") text_auto = indexes.EdgeNgramField(model_attr="foo") name_auto = indexes.EdgeNgramField(...
SolrAutocompleteMockModelSearchIndex
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 2502, "end": 5872 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
PatchTSTAttention
python
dagster-io__dagster
.buildkite/buildkite-shared/buildkite_shared/step_builders/group_step_builder.py
{ "start": 684, "end": 1205 }
class ____: _step: GroupStepConfiguration def __init__(self, name, steps, key=None, skip=None): if all(step["agents"]["queue"] == BuildkiteQueue.KUBERNETES_GKE.value for step in steps): name = ":gcp: " + name self._step = { "group": name, "label": name, ...
GroupStepBuilder
python
h5py__h5py
h5py/_hl/base.py
{ "start": 12450, "end": 13053 }
class ____(ItemsView): """ Wraps e.g. a Group or AttributeManager to provide an items view. """ def __contains__(self, item): with phil: key, val = item if key in self._mapping: return val == self._mapping.get(key) return False def _...
ItemsViewHDF5
python
django__django
tests/i18n/contenttypes/tests.py
{ "start": 387, "end": 750 }
class ____(TestCase): def test_verbose_name(self): company_type = ContentType.objects.get(app_label="i18n", model="company") with translation.override("en"): self.assertEqual(str(company_type), "I18N | Company") with translation.override("fr"): self.assertEqual(str(co...
ContentTypeTests
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 34420, "end": 34963 }
class ____(Callback): """Callback that terminates training when a NaN loss is encountered. """ def __init__(self): super(TerminateOnNaN, self).__init__() self._supports_tf_logs = True def on_batch_end(self, batch, logs=None): logs = logs or {} loss = logs.get('loss') if loss is not None: ...
TerminateOnNaN
python
django__django
tests/admin_changelist/models.py
{ "start": 88, "end": 227 }
class ____(models.Model): # Oracle can have problems with a column named "date" date = models.DateField(db_column="event_date")
Event
python
getsentry__sentry
tests/sentry/api/serializers/rest_framework/test_rule.py
{ "start": 1876, "end": 2624 }
class ____: def test_updates_actions(self) -> None: bad_action = { "id": "whatever", } good_action_uuid = str(uuid.uuid4()) good_action = { "id": "whatever", "uuid": good_action_uuid, } actions = [good_action, bad_action] a...
TestValidateActions
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/models.py
{ "start": 653, "end": 818 }
class ____(models.Model): name = models.CharField(max_length=100, unique=True) company = models.ForeignKey(Company, null=False, on_delete=models.CASCADE)
Store
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0100_move_is_single_written_to_pending.py
{ "start": 239, "end": 1573 }
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
streamlit__streamlit
lib/streamlit/runtime/caching/cache_data_api.py
{ "start": 22122, "end": 24587 }
class ____(Cache[R]): """Manages cached values for a single st.cache_data function.""" def __init__( self, key: str, storage: CacheStorage, persist: CachePersistType, max_entries: int | None, ttl_seconds: float | None, display_name: str, ) -> None: ...
DataCache
python
Delgan__loguru
tests/test_interception.py
{ "start": 102, "end": 5443 }
class ____(logging.Handler): def emit(self, record): # Get corresponding Loguru level if it exists. try: level = logger.level(record.levelname).name except ValueError: level = record.levelno # Find caller from where originated the logged message. fram...
InterceptHandler
python
sympy__sympy
sympy/functions/special/error_functions.py
{ "start": 25525, "end": 27507 }
class ____ (DefinedFunction): r""" Inverse Complementary Error Function. The erfcinv function is defined as: .. math :: \mathrm{erfc}(x) = y \quad \Rightarrow \quad \mathrm{erfcinv}(y) = x Examples ======== >>> from sympy import erfcinv >>> from sympy.abc import x Several spe...
erfcinv
python
google__jax
jax/experimental/jax2tf/call_tf.py
{ "start": 16517, "end": 28745 }
class ____(effects.Effect): __str__ = lambda _: "CallTfOrderedEffect" call_tf_ordered_effect = CallTfOrderedEffect() effects.lowerable_effects.add_type(CallTfOrderedEffect) effects.control_flow_allowed_effects.add_type(CallTfOrderedEffect) effects.remat_allowed_effects.add_type(CallTfOrderedEffect) effects.custom_...
CallTfOrderedEffect
python
getsentry__sentry
tests/acceptance/test_issue_tag_values.py
{ "start": 349, "end": 1713 }
class ____(AcceptanceTestCase, SnubaTestCase): page: IssueDetailsPage def setUp(self) -> None: super().setUp() self.user = self.create_user("foo@example.com") self.org = self.create_organization(owner=self.user, name="Rowdy Tiger") self.team = self.create_team(organization=self....
IssueTagValuesTest
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_auth_index.py
{ "start": 1665, "end": 2143 }
class ____(APITestCase): path = "/api/0/auth/" def test_logged_in(self) -> None: user = self.create_user("foo@example.com") self.login_as(user) response = self.client.get(self.path) assert response.status_code == 200 assert response.data["id"] == str(user.id) def te...
AuthDetailsEndpointTest
python
kamyu104__LeetCode-Solutions
Python/maximum-height-of-a-triangle.py
{ "start": 628, "end": 1000 }
class ____(object): def maxHeightOfTriangle(self, red, blue): """ :type red: int :type blue: int :rtype: int """ def f(x, y): h = 0 while x >= h+1: h += 1 x -= h x, y = y, x return h ...
Solution2
python
dagster-io__dagster
python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/resource.py
{ "start": 856, "end": 6997 }
class ____(ConfigurableResource): """Represents a workspace in Databricks and provides utilities to interact with the Databricks SDK. """ host: str = Field(description="The host used to connect to the Databricks Workspace.") token: str = Field(description="The token used to connect to Databricks Wo...
DatabricksWorkspace
python
lepture__authlib
authlib/oauth2/rfc8628/device_code.py
{ "start": 500, "end": 7900 }
class ____(BaseGrant, TokenEndpointMixin): """This OAuth 2.0 [RFC6749] protocol extension enables OAuth clients to request user authorization from applications on devices that have limited input capabilities or lack a suitable browser. Such devices include smart TVs, media consoles, picture frames, and...
DeviceCodeGrant
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 98540, "end": 103290 }
class ____(ThreadSafeCleanupTestCase): # Base class for sendmsg()/recvmsg() tests. # Time in seconds to wait before considering a test failed, or # None for no timeout. Not all tests actually set a timeout. fail_timeout = support.LOOPBACK_TIMEOUT def setUp(self): self.misc_event = threadi...
SendrecvmsgBase
python
walkccc__LeetCode
solutions/3422. Minimum Operations to Make Subarray Elements Equal/3422.py
{ "start": 0, "end": 669 }
class ____: def minOperations(self, nums: list[int], k: int) -> int: window = SortedList(nums[:k]) median = window[(k - 1) // 2] ops = sum(abs(median - nums[j]) for j in range(k)) ans = ops for i in range(k, len(nums)): window.remove(nums[i - k]) window.add(nums[i]) ops -= abs(m...
Solution
python
faif__python-patterns
patterns/creational/lazy_evaluation.py
{ "start": 806, "end": 1654 }
class ____: def __init__(self, function: Callable) -> None: self.function = function functools.update_wrapper(self, function) def __get__(self, obj: "Person", type_: Type["Person"]) -> str: if obj is None: return self val = self.function(obj) obj.__dict__[sel...
lazy_property
python
rq__rq
rq/worker.py
{ "start": 73156, "end": 73870 }
class ____(BaseWorker): def execute_job(self, job: 'Job', queue: 'Queue'): """Execute job in same thread/process, do not fork()""" self.prepare_execution(job) self.perform_job(job, queue) self.set_state(WorkerStatus.IDLE) def get_heartbeat_ttl(self, job: 'Job') -> int: "...
SimpleWorker
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/regular_languages/regex_parser.py
{ "start": 559, "end": 869 }
class ____: """ Base class for all the grammar nodes. (You don't initialize this one.) """ def __add__(self, other_node: Node) -> NodeSequence: return NodeSequence([self, other_node]) def __or__(self, other_node: Node) -> AnyNode: return AnyNode([self, other_node])
Node
python
astropy__astropy
astropy/extern/ply/yacc.py
{ "start": 5349, "end": 5539 }
class ____(object): def __getattribute__(self, name): return self def __call__(self, *args, **kwargs): return self # Exception raised for yacc-related errors
NullLogger
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk4.py
{ "start": 16722, "end": 20189 }
class ____(ToolContainerBase, Gtk.Box): _icon_extension = '-symbolic.svg' def __init__(self, toolmanager): ToolContainerBase.__init__(self, toolmanager) Gtk.Box.__init__(self) self.set_property('orientation', Gtk.Orientation.HORIZONTAL) # Tool items are created later, but must ...
ToolbarGTK4
python
walkccc__LeetCode
solutions/300. Longest Increasing Subsequence/300.py
{ "start": 0, "end": 324 }
class ____: def lengthOfLIS(self, nums: list[int]) -> int: if not nums: return 0 # dp[i] := the length of LIS ending in nums[i] dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 87880, "end": 89033 }
class ____(Response): """ Response of tasks.archive endpoint. :param archived: Indicates number of archived tasks :type archived: int """ _service = "tasks" _action = "archive" _version = "2.20" _schema = { "definitions": {}, "properties": { "archived": ...
ArchiveResponse
python
readthedocs__readthedocs.org
readthedocs/search/api/v3/tests/test_api.py
{ "start": 19572, "end": 32943 }
class ____(SearchTestBase): def setUp(self): super().setUp() self.user = get(User) self.member = get(User) self.project = get(Project, slug="project") self.project.versions.update(built=True, active=True, privacy_level=PRIVATE) self.version = self.project.versions.fi...
SearchAPIWithOrganizationsTest
python
sphinx-doc__sphinx
sphinx/domains/cpp/__init__.py
{ "start": 22330, "end": 27966 }
class ____(SphinxTransform): default_priority = ReferencesResolver.default_priority - 1 def _render_symbol( self, s: Symbol, maxdepth: int, skip_this: bool, alias_options: dict[str, bool], render_options: dict[str, bool], document: Any, ) -> list[Node...
AliasTransform
python
django__django
tests/mail/tests.py
{ "start": 4482, "end": 8976 }
class ____: def assertMessageHasHeaders(self, message, headers): """ Asserts that the `message` has all `headers`. message: can be an instance of an email.Message subclass or bytes with the contents of an email message. headers: should be a set of (header-name, head...
MailTestsMixin
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/util.py
{ "start": 183, "end": 594 }
class ____(graphene.ResolveInfo): @property def context(self) -> WorkspaceRequestContext: return cast("WorkspaceRequestContext", super().context) def non_null_list(of_type): return graphene.NonNull(graphene.List(graphene.NonNull(of_type))) def get_compute_log_manager(graphene_info: ResolveInfo) ...
ResolveInfo
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external.py
{ "start": 37079, "end": 42393 }
class ____: def __init__(self, sensor_snap: SensorSnap, handle: RepositoryHandle): self._sensor_snap = check.inst_param(sensor_snap, "sensor_snap", SensorSnap) self._handle = InstigatorHandle( self._sensor_snap.name, check.inst_param(handle, "handle", RepositoryHandle) ) @pr...
RemoteSensor
python
scrapy__scrapy
scrapy/http/headers.py
{ "start": 634, "end": 4260 }
class ____(CaselessDict): """Case insensitive http headers dictionary""" def __init__( self, seq: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None, encoding: str = "utf-8", ): self.encoding: str = encoding super().__init__(seq) def update( # ty...
Headers
python
huggingface__transformers
src/transformers/models/hunyuan_v1_dense/modular_hunyuan_v1_dense.py
{ "start": 6045, "end": 6293 }
class ____(LlamaForSequenceClassification): pass __all__ = [ "HunYuanDenseV1ForCausalLM", "HunYuanDenseV1Model", "HunYuanDenseV1PreTrainedModel", "HunYuanDenseV1ForSequenceClassification", ]
HunYuanDenseV1ForSequenceClassification
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/executable_component_tests/test_executable_component_in_memory.py
{ "start": 4394, "end": 9686 }
class ____(dg.Config): config_value: str def execute_fn_with_config(context, config: MyConfig): return dg.MaterializeResult(metadata={"config_value": config.config_value}) def test_singular_asset_with_config() -> None: component = FunctionComponent.from_attributes_dict( attributes={ ...
MyConfig
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_day_count_to_be_close_to_equivalent_week_day_mean.py
{ "start": 3025, "end": 11517 }
class ____(ColumnAggregateExpectation): """Expect No missing days in date column""" # Default values default_kwarg_values = {"threshold": 0.25} example_days_ago_dict = get_days_ago_dict(TODAY_EXAMPLE) examples = [ { # column a - good counts - 3 rows for every day "da...
ExpectDayCountToBeCloseToEquivalentWeekDayMean
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 97570, "end": 113626 }
class ____: """Wrap an actual or potential sys.path entry w/metadata""" PKG_INFO = 'PKG-INFO' def __init__( self, location: str | None = None, metadata: _MetadataType = None, project_name: str | None = None, version: str | None = None, py_version: str | None...
Distribution
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 65651, "end": 65761 }
class ____(spack.error.FetchError): """Raised when there is no cached archive for a package."""
NoCacheError
python
pytorch__pytorch
torch/nn/modules/loss.py
{ "start": 69613, "end": 72772 }
class ____(_Loss): r"""Creates a criterion that measures the loss given inputs :math:`x1`, :math:`x2`, two 1D mini-batch or 0D `Tensors`, and a label 1D mini-batch or 0D `Tensor` :math:`y` (containing 1 or -1). If :math:`y = 1` then it assumed the first input should be ranked higher (have a larger ...
MarginRankingLoss
python
keras-team__keras
keras/src/callbacks/callback.py
{ "start": 148, "end": 10831 }
class ____: """Base class used to build new callbacks. Callbacks can be passed to keras methods such as `fit()`, `evaluate()`, and `predict()` in order to hook into the various stages of the model training, evaluation, and inference lifecycle. To create a custom callback, subclass `keras.callbacks...
Callback
python
kamyu104__LeetCode-Solutions
Python/minimum-swaps-to-arrange-a-binary-grid.py
{ "start": 50, "end": 758 }
class ____(object): def minSwaps(self, grid): """ :type grid: List[List[int]] :rtype: int """ result = 0 for target in reversed(xrange(1, len(grid))): row_idx = len(grid)-1-target while row_idx < len(grid): row = grid[row_idx] ...
Solution
python
coleifer__peewee
tests/model_sql.py
{ "start": 38832, "end": 40130 }
class ____(ModelDatabaseTestCase): database = get_in_memory_db() requires = [Note, Person, Relationship] def test_insert(self): qkwargs = Person.insert(first='huey', last='kitty') qliteral = Person.insert({'first': 'huey', 'last': 'kitty'}) for query in (qkwargs, qliteral): ...
TestStringsForFieldsa
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type_test.py
{ "start": 5812, "end": 5901 }
class ____(extension_type.ExtensionType): z: 'ForwardRefB' n: tensor.Tensor
ForwardRefB
python
pypa__warehouse
tests/unit/search/test_tasks.py
{ "start": 5720, "end": 5965 }
class ____: def test_is_subclass_of_redis_lock(self, mockredis): search_lock = SearchLock(redis_client=mockredis) assert isinstance(search_lock, redis.lock.Lock) assert search_lock.name == "search-index"
TestSearchLock
python
google__jax
jax/_src/interpreters/batching.py
{ "start": 2378, "end": 2490 }
class ____: aval: JumbleTy data: Array # To vmap over a jumble, one must specify the axis as JumbleAxis.
Jumble
python
ansible__ansible
test/units/module_utils/facts/test_facts.py
{ "start": 6953, "end": 7142 }
class ____(BaseTestFactsPlatform): platform_id = 'OpenBSD' fact_class = virtual.openbsd.OpenBSDVirtual collector_class = virtual.openbsd.OpenBSDVirtualCollector
TestOpenBSDVirtual
python
run-llama__llama_index
llama-index-core/tests/program/test_function_program.py
{ "start": 538, "end": 610 }
class ____(BaseModel): """Mock Song class.""" title: str
MockSong
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/combined_nms_test.py
{ "start": 7370, "end": 7902 }
class ____(CombinedNmsTest): def setUp(self): super().setUp() self.num_boxes = 5000 os.environ['TF_TRT_ALLOW_NMS_TOPK_OVERRIDE'] = '1' def tearDown(self): super().tearDown() os.environ['TF_TRT_ALLOW_NMS_TOPK_OVERRIDE'] = '0' def GetMaxBatchSize(self, run_params): """Returns the max_batc...
CombinedNmsTopKOverride
python
numpy__numpy
numpy/polynomial/tests/test_symbol.py
{ "start": 3099, "end": 3437 }
class ____: p = poly.Polynomial([1, 2, 3], symbol='x') other = poly.Polynomial([4, 5, 6], symbol='y') ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__) @pytest.mark.parametrize('f', ops) def test_binops_fails(self, f): assert_raises(ValueError, f, self.other)
TestBinaryOperatorsDifferentSymbol
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 143349, "end": 144563 }
class ____(FixedLayout): """ A layout that signifies the buffer is a comm buffer. In terms of striding, the layout is identical to `FixedLayout`. Buffers with this layout do not participate in in-place reuse - it can be neither the source nor the target for in-place reuse. For detailed motivat...
CommBufferLayout
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 346394, "end": 346711 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("GistComment", graphql_name="node")
GistCommentEdge
python
coleifer__peewee
tests/reflection.py
{ "start": 1553, "end": 1645 }
class ____(TestModel): data = CharField() class Meta: primary_key = False
NoPK
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/matrix_solve_ls_op_test.py
{ "start": 2903, "end": 10246 }
class ____(test_lib.TestCase): def _verifySolve(self, x, y, dtype, use_placeholder, fast, l2_regularizer, batch_shape=()): if not fast and l2_regularizer != 0: # The slow pat...
MatrixSolveLsOpTest
python
pallets__quart
src/quart/datastructures.py
{ "start": 265, "end": 1623 }
class ____(WerkzeugFileStorage): """A thin wrapper over incoming files.""" def __init__( self, stream: IO[bytes] | None = None, filename: str | None = None, name: str | None = None, content_type: str | None = None, content_length: int | None = None, heade...
FileStorage
python
PrefectHQ__prefect
src/prefect/context.py
{ "start": 6182, "end": 8660 }
class ____(BaseModel): """ A base model for context data that forbids mutation and extra data while providing a context manager """ if TYPE_CHECKING: # subclasses can pass through keyword arguments to the pydantic base model def __init__(self, **kwargs: Any) -> None: ... # The ...
ContextModel
python
numba__numba
numba/core/typing/arraydecl.py
{ "start": 25974, "end": 26287 }
class ____(AttributeTemplate): key = types.ArrayFlags def resolve_contiguous(self, ctflags): return types.boolean def resolve_c_contiguous(self, ctflags): return types.boolean def resolve_f_contiguous(self, ctflags): return types.boolean @infer_getattr
ArrayFlagsAttribute
python
django__django
tests/get_earliest_or_latest/tests.py
{ "start": 7223, "end": 9988 }
class ____(TestCase): def test_first(self): p1 = Person.objects.create(name="Bob", birthday=datetime(1950, 1, 1)) p2 = Person.objects.create(name="Alice", birthday=datetime(1961, 2, 3)) self.assertEqual(Person.objects.first(), p1) self.assertEqual(Person.objects.order_by("name").firs...
TestFirstLast
python
getsentry__sentry
src/sentry/workflow_engine/handlers/detector/stateful.py
{ "start": 11829, "end": 27885 }
class ____( Generic[DataPacketType, DataPacketEvaluationType], DetectorHandler[DataPacketType, DataPacketEvaluationType], abc.ABC, ): """ Stateful Detectors are provided as a base class for new detectors that need to track state. """ def __init__(self, detector: Detector, thresholds: Detect...
StatefulDetectorHandler
python
huggingface__transformers
src/transformers/models/dpt/modeling_dpt.py
{ "start": 33798, "end": 34396 }
class ____(nn.Module): def __init__(self, config: DPTConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.pooler_output_size) self.activation = ACT2FN[config.pooler_act] def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the mode...
DPTViTPooler
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/keys.py
{ "start": 103, "end": 4916 }
class ____(str, Enum): """ List of keys for use in key bindings. Note that this is an "StrEnum", all values can be compared against strings. """ value: str Escape = "escape" # Also Control-[ ShiftEscape = "s-escape" ControlAt = "c-@" # Also Control-Space. ControlA = "c-a" ...
Keys
python
lepture__mistune
tests/test_syntax.py
{ "start": 64, "end": 342 }
class ____(BaseTestCase): def assert_case(self, n, text, html): result = mistune.html(text) self.assertEqual(normalize_html(result), normalize_html(html)) TestSyntax.load_fixtures("fix-commonmark.txt") TestSyntax.load_fixtures("diff-commonmark.txt")
TestSyntax
python
sympy__sympy
sympy/polys/fields.py
{ "start": 3748, "end": 10866 }
class ____(DefaultPrinting, Generic[Er]): """Multivariate distributed rational function field. """ ring: PolyRing[Er] gens: tuple[FracElement[Er], ...] symbols: tuple[Expr, ...] ngens: int domain: Domain[Er] order: MonomialOrder zero: FracElement[Er] one: FracElement[Er] dtype: ...
FracField
python
PyCQA__pylint
tests/functional/i/invalid/invalid_format_returned.py
{ "start": 960, "end": 1161 }
class ____: """ __format__ returns node which does not have 'value' in AST """ def __format__(self, format_spec): # [invalid-format-returned] return lambda: "some format"
ThirdBadFormat
python
getsentry__sentry
src/sentry/data_export/models.py
{ "start": 5683, "end": 6074 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded data_export = FlexibleForeignKey("sentry.ExportedData") blob_id = BoundedBigIntegerField(db_index=True) offset = BoundedBigIntegerField() class Meta: app_label = "sentry" db_table = "sentry_exporteddatablob" ...
ExportedDataBlob
python
jina-ai__jina
jina/resources/project-template/deployment/executor1/executor.py
{ "start": 106, "end": 321 }
class ____(Executor): @requests def foo(self, docs: DocList[TextDoc], **kwargs) -> DocList[TextDoc]: docs[0].text = 'hello, world!' docs[1].text = 'goodbye, world!' return docs
MyExecutor
python
scikit-learn__scikit-learn
sklearn/utils/_testing.py
{ "start": 43860, "end": 51527 }
class ____: """Minimal transformer implementation without inheriting from BaseEstimator. This estimator should be tested with: * `check_estimator` in `test_estimator_checks.py`; * within a `Pipeline` in `test_pipeline.py`; * within a `SearchCV` in `test_search.py`. """ def __init__(se...
MinimalTransformer
python
redis__redis-py
redis/commands/search/reducers.py
{ "start": 1798, "end": 2078 }
class ____(FieldOnlyReducer): """ Calculate the number of distinct values contained in all the results in the group for the given field. This uses a faster algorithm than `count_distinct` but is less accurate """ NAME = "COUNT_DISTINCTISH"
count_distinctish
python
scrapy__scrapy
scrapy/core/downloader/handlers/http2.py
{ "start": 1695, "end": 4369 }
class ____: _Agent = H2Agent _ProxyAgent = ScrapyProxyH2Agent def __init__( self, context_factory: IPolicyForHTTPS, pool: H2ConnectionPool, connect_timeout: int = 10, bind_address: bytes | None = None, crawler: Crawler | None = None, ) -> None: se...
ScrapyH2Agent
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
{ "start": 4027, "end": 4614 }
class ____: """MarkedManagers are passed to GraphQLContextVariants. They contain a contextmanager function "manager_fn" that yield the relevant instance, and it includes marks that will be applied to any context-variant-driven test case that includes this MarkedManager. See InstanceManagers for an ...
MarkedManager
python
dagster-io__dagster
python_modules/libraries/dagster-omni/dagster_omni/translation.py
{ "start": 4344, "end": 4820 }
class ____(AssetSpecUpdateKwargs, Resolvable): """Model used to allow per-object-type translation of an Omni object.""" for_document: Optional[ResolvedTargetedOmniTranslationFn] = None for_query: Optional[ResolvedTargetedKeyOnlyOmniTranslationFn] = None ResolvedOmniTranslationFn = Annotated[ OmniTran...
OmniTranslationArgs
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 980258, "end": 981761 }
class ____(sgqlc.types.relay.Connection): """The connection type for Sponsorship.""" __schema__ = github_schema __field_names__ = ( "edges", "nodes", "page_info", "total_count", "total_recurring_monthly_price_in_cents", "total_recurring_monthly_price_in_dolla...
SponsorshipConnection
python
getsentry__sentry
tests/sentry/issues/test_run.py
{ "start": 5937, "end": 20685 }
class ____( TransactionTestCase, OccurrenceTestMixin, StatusChangeTestMixin ): def build_mock_message( self, data: MutableMapping[str, Any] | None, topic: ArroyoTopic | None = None ) -> mock.Mock: message = mock.Mock() message.value.return_value = json.dumps(data) if topic: ...
TestBatchedOccurrenceConsumer
python
django__django
tests/postgres_tests/test_array.py
{ "start": 3352, "end": 7609 }
class ____(PostgreSQLTestCase): def test_integer(self): instance = IntegerArrayModel(field=[1, 2, 3]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_char(self): instance = CharArrayModel(field=["hello", "g...
TestSaveLoad
python
huggingface__transformers
src/transformers/models/deberta_v2/configuration_deberta_v2.py
{ "start": 781, "end": 7245 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DebertaV2Model`]. It is used to instantiate a DeBERTa-v2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar ...
DebertaV2Config
python
dagster-io__dagster
python_modules/libraries/dagster-powerbi/dagster_powerbi/resource.py
{ "start": 1799, "end": 2097 }
class ____(ConfigurableResource): """Authenticates with PowerBI directly using an API access token.""" api_token: str = Field(..., description="An API access token used to connect to PowerBI.") MICROSOFT_LOGIN_URL = "https://login.microsoftonline.com/{tenant_id}/oauth2/token"
PowerBIToken
python
walkccc__LeetCode
solutions/2970. Count the Number of Incremovable Subarrays I/2970-2.py
{ "start": 0, "end": 1154 }
class ____: def incremovableSubarrayCount(self, nums: list[int]) -> int: n = len(nums) startIndex = self._getStartIndexOfSuffix(nums) # If the complete array is strictly increasing, the total number of ways we # can remove elements equals the total number of possible subarrays. if startIndex == 0:...
Solution
python
pytransitions__transitions
transitions/extensions/factory.py
{ "start": 1373, "end": 2252 }
class ____(object): """Convenience factory for machine class retrieval.""" # get one of the predefined classes which fulfill the criteria @staticmethod def get_predefined(graph=False, nested=False, locked=False, asyncio=False): """A function to retrieve machine classes by required functionality...
MachineFactory
python
huggingface__transformers
src/transformers/models/led/modeling_led.py
{ "start": 48671, "end": 51286 }
class ____(ModelOutput): r""" attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x + attention_window +...
LEDEncoderBaseModelOutput
python
pytorch__pytorch
torch/_inductor/runtime/caching/implementations.py
{ "start": 1224, "end": 3507 }
class ____(ABC): """Abstract base class for cache implementations. This class defines the interface that all cache implementations must follow. It provides thread-safe operations through a locking mechanism and supports both get and insert operations. Note: We don't use generics here as doing so w...
_CacheImpl
python
sqlalchemy__sqlalchemy
test/ext/declarative/test_deprecations.py
{ "start": 317, "end": 2202 }
class ____(fixtures.TestBase): def _expect_warning(self, name): return expect_deprecated_20( r"The ``%s\(\)`` function is now available as " r"sqlalchemy.orm.%s\(\)" % (name, name) ) def test_declarative_base(self): with self._expect_warning("declarative_base"): ...
DeprecatedImportsTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_opensearch_serverless.py
{ "start": 1277, "end": 1534 }
class ____: @pytest.fixture(autouse=True) def mock_conn(self, monkeypatch): self.client = boto3.client("opensearchserverless") monkeypatch.setattr(OpenSearchServerlessHook, "conn", self.client)
TestOpenSearchServerlessCustomWaitersBase
python
django-import-export__django-import-export
tests/core/tests/test_mixins.py
{ "start": 12991, "end": 14503 }
class ____(TestCase): class TestBaseExportMixin(mixins.BaseExportMixin): def get_export_resource_kwargs(self, request, **kwargs): self.kwargs = kwargs return super().get_resource_kwargs(request, **kwargs) def test_get_data_for_export_sets_kwargs(self): """ issue ...
BaseExportMixinTest
python
ray-project__ray
rllib/models/tf/complex_input_net.py
{ "start": 742, "end": 8352 }
class ____(TFModelV2): """TFModelV2 concat'ing CNN outputs to flat input(s), followed by FC(s). Note: This model should be used for complex (Dict or Tuple) observation spaces that have one or more image components. The data flow is as follows: `obs` (e.g. Tuple[img0, img1, discrete0]) -> `CNN0 + ...
ComplexInputNetwork
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 58448, "end": 58668 }
class ____(_TestCopying, __TestCase): def setUp(self): self.set = set(["zero", 0, None]) super().setUp() #------------------------------------------------------------------------------
TestCopyingTriple