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
openai__openai-python
src/openai/types/evals/run_cancel_response.py
{ "start": 2436, "end": 4913 }
class ____(BaseModel): type: Literal["responses"] """The type of run data source. Always `responses`.""" created_after: Optional[int] = None """Only include items created after this timestamp (inclusive). This is a query parameter used to select responses. """ created_before: Optional[int...
DataSourceResponsesSourceResponses
python
astropy__astropy
astropy/__init__.py
{ "start": 4094, "end": 6143 }
class ____(base_constants_version): """ The version of astronomical constants to use. """ # Maintainers: update when new constants are added _value = "iau2015" _versions = dict( iau2015="iau2015", iau2012="iau2012", astropyconst80="iau2015", astropyconst40="iau2...
astronomical_constants
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/formats.py
{ "start": 968, "end": 1456 }
class ____: """CENTER_XYWH contains axis indices for the CENTER_XYWH format. All values in the CENTER_XYWH format should be absolute pixel values. The CENTER_XYWH format consists of the following required indices: - X: X coordinate of the center of the bounding box - Y: Y coordinate of the center...
CENTER_XYWH
python
pytorch__pytorch
test/distributed/tensor/test_op_strategy.py
{ "start": 23886, "end": 24903 }
class ____(DTensorTestBase): @with_comms def test_call_with_different_nontensor_args(self): mesh = self.build_device_mesh() global_tensor = torch.tensor( [ [29.0, 45.0, 3.0, 61.0], [25.0, 6.0, 21.0, 0.0], [1.0, 63.0, 49.0, 38.0], ...
TestStrategyHashing
python
redis__redis-py
redis/commands/search/hybrid_query.py
{ "start": 8335, "end": 11991 }
class ____: def __init__(self) -> None: """ Create a new hybrid post processing configuration object. """ self._load_statements = [] self._apply_statements = [] self._groupby_statements = [] self._sortby_fields = [] self._filter = None self._li...
HybridPostProcessingConfig
python
aimacode__aima-python
learning4e.py
{ "start": 30538, "end": 31176 }
class ____: """Return a predictor that takes a weighted vote.""" def __init__(self, predictors, weights): self.predictors = predictors self.weights = weights def predict(self, example): return weighted_mode((predictor.predict(example) for predictor in self.predictors), self.weights...
weighted_majority
python
google__pytype
pytype/utils.py
{ "start": 4869, "end": 5844 }
class ____: """A dynamically scoped variable. This is a per-thread dynamic variable, with an initial value of None. The bind() call establishes a new value that will be in effect for the duration of the resulting context manager. This is intended to be used in conjunction with a decorator. """ def __in...
DynamicVar
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 2220, "end": 3948 }
class ____: def test_too_many_failed_logins(self, pyramid_request): exc = TooManyFailedLogins(resets_in=datetime.timedelta(seconds=600)) resp = views.failed_logins(exc, pyramid_request) assert resp.status == "429 Too Many Failed Login Attempts" assert resp.detail == ( "...
TestFailedLoginView
python
getsentry__sentry
src/sentry/notifications/notifications/missing_members_nudge.py
{ "start": 806, "end": 3032 }
class ____(BaseNotification): metrics_key = "missing_members_nudge" template_path = "sentry/emails/missing-members-nudge" def get_specific_analytics_event(self, provider: ExternalProviders) -> analytics.Event | None: return MissingMembersNudgeEvent( organization_id=self.organization.id,...
MissingMembersNudgeNotification
python
getsentry__sentry
src/sentry/projects/services/project/model.py
{ "start": 1844, "end": 3243 }
class ____(RpcModel): id: int = -1 slug: str = "" name: str = "" organization_id: int = -1 status: int = Field(default_factory=_project_status_visible) first_event: datetime | None = None platform: str | None = None external_id: str | None = None def __hash__(self) -> int: #...
RpcProject
python
joke2k__faker
tests/providers/test_file.py
{ "start": 53, "end": 3381 }
class ____(unittest.TestCase): """Tests file""" def setUp(self): self.fake = Faker() Faker.seed(0) def test_file_name(self): for _ in range(100): file_name = self.fake.file_name() assert re.search(r"\w+\.\w+", file_name) file_name = self.fake.fil...
TestFile
python
encode__django-rest-framework
rest_framework/utils/encoders.py
{ "start": 2826, "end": 3126 }
class ____: """ CustomScalar that knows how to encode timedelta that renderer can understand. """ @classmethod def represent_timedelta(cls, dumper, data): value = str(data.total_seconds()) return dumper.represent_scalar('tag:yaml.org,2002:str', value)
CustomScalar
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 89033, "end": 92095 }
class ____(Request): """ Archive tasks :param ids: IDs of the tasks to archive :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str """ _servic...
ArchiveManyRequest
python
pyinstaller__pyinstaller
bootloader/waflib/Configure.py
{ "start": 447, "end": 14831 }
class ____(Context.Context): '''configures the project''' cmd = 'configure' error_handlers = [] def __init__(self, **kw): super(ConfigurationContext, self).__init__(**kw) self.environ = dict(os.environ) self.all_envs = {} self.top_dir = None self.out_dir = None ...
ConfigurationContext
python
celery__celery
t/unit/app/test_routes.py
{ "start": 7372, "end": 7502 }
class ____: def route_for_task(self, task, args, kwargs): if task == 'celery.xaza': return 'bar'
TestRouter
python
huggingface__transformers
src/transformers/models/glm4_moe/modeling_glm4_moe.py
{ "start": 2155, "end": 9037 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Glm4MoeConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self...
Glm4MoeRotaryEmbedding
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec13.py
{ "start": 1733, "end": 2778 }
class ____: ... CheckFunc = CoroFunc[Concatenate[ClassA, _P], bool] async def my_check_func(obj: ClassA, a: int, b: str) -> bool: print(a, b) return str(a) == b async def takes_check_func( check_func: CheckFunc[_P], *args: _P.args, **kwargs: _P.kwargs ): await check_func(ClassA(), *args, **kwargs)...
ClassA
python
weaviate__weaviate-python-client
weaviate/rbac/executor.py
{ "start": 1054, "end": 12858 }
class ____(Generic[ConnectionType]): def __init__(self, connection: ConnectionType): self._connection = connection def list_all(self) -> executor.Result[Dict[str, Role]]: """Get all roles. Returns: A dictionary with user names as keys and the `Role` objects as values. ...
_RolesExecutor
python
redis__redis-py
redis/commands/cluster.py
{ "start": 25807, "end": 29094 }
class ____(DataAccessCommands): """ A class for Redis Cluster Data Access Commands The class inherits from Redis's core DataAccessCommand class and do the required adjustments to work with cluster mode """ def stralgo( self, algo: Literal["LCS"], value1: KeyT, v...
ClusterDataAccessCommands
python
encode__starlette
starlette/_utils.py
{ "start": 1377, "end": 1578 }
class ____(Protocol): async def close(self) -> None: ... # pragma: no cover SupportsAsyncCloseType = TypeVar("SupportsAsyncCloseType", bound=SupportsAsyncClose, covariant=False)
SupportsAsyncClose
python
huggingface__transformers
src/transformers/models/squeezebert/modeling_squeezebert.py
{ "start": 3177, "end": 3880 }
class ____(nn.Module): """ Wrapper for torch.matmul(). This makes flop-counting easier to implement. Note that if you directly call torch.matmul() in your code, the flop counter will typically ignore the flops of the matmul. """ def __init__(self): super().__init__() def forward(self, ...
MatMulWrapper
python
celery__celery
t/integration/test_serialization.py
{ "start": 170, "end": 1651 }
class ____: def test_accept(self, celery_app): app = celery_app # Redefine env to use in subprocess # broker_url and result backend are different for each integration test backend passenv = { **os.environ, "CELERY_BROKER_URL": app.conf.broker_url, ...
test_config_serialization
python
python__mypy
mypyc/ir/ops.py
{ "start": 31634, "end": 32596 }
class ____(RegisterOp): """dest = (reg, ...) (for fixed-length tuple)""" error_kind = ERR_NEVER def __init__(self, items: list[Value], line: int) -> None: super().__init__(line) self.items = items # Don't keep track of the fact that an int is short after it # is put into a ...
TupleSet
python
getsentry__sentry
src/sentry/core/endpoints/organization_projects.py
{ "start": 1989, "end": 8288 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } permission_classes = (OrganizationAndStaffPermission,) @extend_schema( operation_id="List an Organization's Projects", parameters=[GlobalParams.ORG_ID_OR_SLUG, CursorQueryParam], reque...
OrganizationProjectsEndpoint
python
doocs__leetcode
solution/1700-1799/1791.Find Center of Star Graph/Solution.py
{ "start": 0, "end": 144 }
class ____: def findCenter(self, edges: List[List[int]]) -> int: return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]
Solution
python
kamyu104__LeetCode-Solutions
Python/distribute-money-to-maximum-children.py
{ "start": 467, "end": 936 }
class ____(object): def distMoney(self, money, children): """ :type money: int :type children: int :rtype: int """ if money < children*1: return -1 money -= children*1 q, r = divmod(money, 7) if q > children: return chil...
Solution2
python
huggingface__transformers
tests/models/pvt/test_modeling_pvt.py
{ "start": 4660, "end": 8190 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (PvtModel, PvtForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": PvtModel, "image-classification": PvtForImageClassification} if is_torch_availab...
PvtModelTest
python
pypa__pipenv
pipenv/patched/pip/_vendor/urllib3/util/url.py
{ "start": 3003, "end": 14311 }
class ____(namedtuple("Url", url_attrs)): """ Data structure for representing an HTTP URL. Used as a return value for :func:`parse_url`. Both the scheme and host are normalized as they are both case-insensitive according to RFC 3986. """ __slots__ = () def __new__( cls, sch...
Url
python
encode__django-rest-framework
rest_framework/utils/serializer_helpers.py
{ "start": 1329, "end": 1924 }
class ____(list): """ Return object from `serializer.data` for the `SerializerList` class. Includes a backlink to the serializer instance for renderers to use if they need richer field information. """ def __init__(self, *args, **kwargs): self.serializer = kwargs.pop('serializer') ...
ReturnList
python
pandas-dev__pandas
pandas/_typing.py
{ "start": 8907, "end": 15341 }
class ____(ReadBuffer[AnyStr_co], Protocol): __module__: str = "pandas.api.typing.aliases" def __iter__(self) -> Iterator[AnyStr_co]: # for engine=python ... def fileno(self) -> int: # for _MMapWrapper ... def readline(self) -> AnyStr_co: # for engine=python ...
ReadCsvBuffer
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 57302, "end": 57588 }
class ____: "Missing __getitem__ and __iter__" def __init__(self, seqn): self.seqn = seqn self.i = 0 def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v
X
python
coleifer__peewee
examples/hexastore.py
{ "start": 107, "end": 2981 }
class ____(object): def __init__(self, database=':memory:', **options): if isinstance(database, str): self.db = SqliteDatabase(database, **options) elif isinstance(database, Database): self.db = database else: raise ValueError('Expected database filename o...
Hexastore
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/cyaml.py
{ "start": 710, "end": 1301 }
class ____(CParser, BaseConstructor, BaseResolver): # type: ignore def __init__(self, stream, version=None, preserve_quotes=None): # type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None CParser.__init__(self, stream) self._parser = self._composer = self BaseConstruc...
CBaseLoader
python
celery__celery
t/unit/utils/test_serialization.py
{ "start": 910, "end": 1283 }
class ____: def test_json_py3(self): expected = (1, "<class 'object'>") actual = ensure_serializable([1, object], encoder=json.dumps) assert expected == actual def test_pickle(self): expected = (1, object) actual = ensure_serializable(expected, encoder=pickle.dumps) ...
test_ensure_serializable
python
doocs__leetcode
solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/Solution.py
{ "start": 0, "end": 127 }
class ____: def countDistinctStrings(self, s: str, k: int) -> int: return pow(2, len(s) - k + 1) % (10**9 + 7)
Solution
python
spack__spack
lib/spack/spack/vendor/jsonschema/exceptions.py
{ "start": 3771, "end": 4014 }
class ____(_Error): """ A schema was invalid under its corresponding metaschema. """ _word_for_schema_in_error_message = "metaschema" _word_for_instance_in_error_message = "schema" @spack.vendor.attr.s(hash=True)
SchemaError
python
conda__conda
conda/plugins/reporter_backends/console.py
{ "start": 900, "end": 1165 }
class ____(ProgressBarBase): """ Progress bar class used when no output should be printed """ def update_to(self, fraction) -> None: pass def refresh(self) -> None: pass def close(self) -> None: pass
QuietProgressBar
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-operations-to-move-ones-to-the-end.py
{ "start": 413, "end": 769 }
class ____(object): def maxOperations(self, s): """ :type s: str :rtype: int """ result = curr = 0 for i in xrange(len(s)): if s[i] != '1': continue curr += 1 if i+1 < len(s) and s[i+1] == '0': result...
Solution2
python
Textualize__textual
src/textual/css/transition.py
{ "start": 32, "end": 417 }
class ____(NamedTuple): duration: float = 1.0 easing: str = "linear" delay: float = 0.0 def __str__(self) -> str: duration, easing, delay = self if delay: return f"{duration:.1f}s {easing} {delay:.1f}" elif easing != "linear": return f"{duration:.1f}s {ea...
Transition
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 532514, "end": 541431 }
class ____: def __abs__(self): if self.is_empty or self.is_infinite: return 0.0 return (self.x1 - self.x0) * (self.y1 - self.y0) def __add__(self, p): if hasattr(p, "__float__"): return Rect(self.x0 + p, self.y0 + p, self.x1 + p, self.y1 + p) if len(...
Rect
python
sphinx-doc__sphinx
sphinx/domains/python/__init__.py
{ "start": 9097, "end": 9381 }
class ____(PyMethod): """Description of a staticmethod.""" option_spec: ClassVar[OptionSpec] = PyObject.option_spec.copy() def run(self) -> list[Node]: self.name = 'py:method' self.options['staticmethod'] = True return super().run()
PyStaticMethod
python
huggingface__transformers
src/transformers/models/moshi/modeling_moshi.py
{ "start": 19545, "end": 21468 }
class ____(nn.Module): def __init__(self, config, use_flexible_linear=False): super().__init__() self.activation_fn = ACT2FN[config.hidden_act] ffn_dim = config.ffn_dim hidden_size = config.hidden_size num_layers = config.num_codebooks if use_flexible_linear else 1 i...
MoshiGatingMLP
python
uqfoundation__dill
setup.py
{ "start": 3112, "end": 4585 }
class ____(Distribution): """Distribution which forces a binary package with platform name""" def has_ext_modules(foo): return True # define dependencies ctypes_version = 'ctypes>=1.0.1' objgraph_version = 'objgraph>=1.7.2' gprof2dot_version = 'gprof2dot>=2022.7.29' pyreadline_version = 'pyreadline>=1....
BinaryDistribution
python
vyperlang__vyper
vyper/abi_types.py
{ "start": 5932, "end": 6475 }
class ____(ABIType): def __init__(self, subtyps): self.subtyps = subtyps def is_dynamic(self): return any([t.is_dynamic() for t in self.subtyps]) def static_size(self): return sum([t.embedded_static_size() for t in self.subtyps]) def dynamic_size_bound(self): return su...
ABI_Tuple
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_rds.py
{ "start": 4526, "end": 6735 }
class ____: @classmethod def setup_class(cls): cls.dag = DAG( dag_id="test_dag", schedule=None, default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, ) cls.hook = RdsHook() @classmethod def teardown_class(cls): del cls.dag ...
TestRdsSnapshotExistenceSensor
python
spack__spack
lib/spack/spack/llnl/util/lock.py
{ "start": 28546, "end": 28626 }
class ____(Exception): """Raised for any errors related to locks."""
LockError
python
pytorch__pytorch
torch/_dynamo/variables/torch.py
{ "start": 11033, "end": 18223 }
class ____(BaseTorchVariable): """Points to a context manager class in torch.* that dynamo has implementations""" def __repr__(self) -> str: return f"TorchCtxManagerClassVariable({self.value})" @staticmethod def is_matching_cls(value): # Unwrap if it's a functools.lru_cache wrapper ...
TorchCtxManagerClassVariable
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/backfill.py
{ "start": 4534, "end": 25419 }
class ____( NamedTuple( "_PartitionBackfill", [ ("backfill_id", str), ("status", BulkActionStatus), ("from_failure", bool), ("tags", Mapping[str, str]), ("backfill_timestamp", float), ("error", Optional[SerializableErrorInfo]), ...
PartitionBackfill
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_scalar_methods.py
{ "start": 4394, "end": 5363 }
class ____(TestCase): @parametrize("str_value", ["inf", "nan"]) @parametrize("code", np.typecodes["Float"]) def test_special(self, code, str_value): cls = np.dtype(code).type value = cls(str_value) assert not value.is_integer() @parametrize( "code", "efd" + "Bbhil" )...
TestIsInteger
python
walkccc__LeetCode
solutions/576. Out of Boundary Paths/576-2.py
{ "start": 0, "end": 824 }
class ____: def findPaths( self, m: int, n: int, maxMove: int, startRow: int, startColumn: int, ) -> int: DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) MOD = 1_000_000_007 ans = 0 # dp[i][j] := the number of paths to move the ball (i, j) out-of-bounds dp = [[0] * ...
Solution
python
pytorch__pytorch
torch/_higher_order_ops/schema.py
{ "start": 459, "end": 791 }
class ____: # Could give a name to the operand by default it's empty string. name: str example_value: Any # Provide an default_value default_value: Any # Whether this argument gets mutated in the hop subgraph. # For output, this should always be False is_mutated: bool kw_only: bool ...
HopArgumentInfo
python
neetcode-gh__leetcode
python/0021-merge-two-sorted-lists.py
{ "start": 624, "end": 990 }
class ____: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: if not list1: return list2 if not list2: return list1 lil, big = (list1, list2) if list1.val < list2.val else (list2, list1) lil.next = self.mergeT...
Solution
python
pytorch__pytorch
test/dynamo/test_autograd_function.py
{ "start": 3690, "end": 3945 }
class ____(torch.autograd.Function): @staticmethod def forward(ctx, foo): return torch.add(foo, foo) @staticmethod def backward(ctx, grad_output): print("graph break!") return grad_output
CustomFuncBwdPrintGraphBreak
python
plotly__plotly.py
plotly/graph_objs/splom/marker/colorbar/_tickformatstop.py
{ "start": 233, "end": 8539 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "splom.marker.colorbar" _path_str = "splom.marker.colorbar.tickformatstop" _valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"} @property def dtickrange(self): """ range [*min*, *max*], where "min",...
Tickformatstop
python
Pylons__pyramid
tests/test_security.py
{ "start": 17477, "end": 18097 }
class ____: def __init__(self, result): self.result = result def effective_principals(self, request): return self.result def unauthenticated_userid(self, request): return self.result def authenticated_userid(self, request): return self.result def remember(self, re...
DummyAuthenticationPolicy
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 747722, "end": 748983 }
class ____(Geometry): """ MultiPoint schema wrapper. MultiPoint geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.3 Parameters ---------- coordinates : Sequence[Sequence[float], :class:`Position`] type : Literal['MultiPoint'] Specifies the type of GeoJSON object. ...
MultiPoint
python
jazzband__django-formtools
tests/wizard/namedwizardtests/forms.py
{ "start": 1599, "end": 1708 }
class ____(ContactWizard): storage_name = 'formtools.wizard.storage.cookie.CookieStorage'
CookieContactWizard
python
django__django
tests/admin_views/admin.py
{ "start": 29027, "end": 29157 }
class ____(admin.ModelAdmin): def view_on_site(self, obj): return "/worker/%s/%s/" % (obj.surname, obj.name)
WorkerAdmin
python
protocolbuffers__protobuf
python/google/protobuf/internal/type_checkers.py
{ "start": 5012, "end": 6355 }
class ____(object): """Checker used for integer fields. Performs type-check and range check.""" def CheckValue(self, proposed_value): global _BoolWarningCount if type(proposed_value) == bool and _BoolWarningCount > 0: _BoolWarningCount -= 1 message = ( '%.1024r has type %s, but expe...
IntValueChecker
python
google__jax
tests/pallas/tpu_pallas_pipeline_test.py
{ "start": 3195, "end": 6861 }
class ____(parameterized.TestCase): def setUp(self): if not jtu.is_device_tpu_at_least(5): self.skipTest('Only works with TPU v5') super().setUp() def test_pipeline_without_inputs(self): def kernel(o_hbm_ref): def body(o_ref): o_ref[...] = jnp.full(o_ref.shape, 42, dtype=o_ref.dty...
PallasCallPipelineTest
python
pandas-dev__pandas
asv_bench/benchmarks/sparse.py
{ "start": 2962, "end": 3836 }
class ____: params = ([0.1, 0.01], [0, np.nan]) param_names = ["dense_proportion", "fill_value"] def setup(self, dense_proportion, fill_value): N = 10**6 arr1 = make_array(N, dense_proportion, fill_value, np.int64) self.array1 = SparseArray(arr1, fill_value=fill_value) arr2 ...
Arithmetic
python
modin-project__modin
modin/pandas/accessor.py
{ "start": 5920, "end": 6305 }
class ____(ClassLogger): def __init__(self, name: str, accessor) -> None: self._name = name self._accessor = accessor def __get__(self, obj, cls): # noqa: GL08 if obj is None: return self._accessor accessor_obj = self._accessor(obj) object.__setattr__(obj, s...
CachedAccessor
python
readthedocs__readthedocs.org
readthedocs/organizations/views/public.py
{ "start": 1373, "end": 2264 }
class ____(FilterContextMixin, OrganizationView, DetailView): """Display information about an organization.""" template_name = "organizations/organization_detail.html" admin_only = False filterset_class = OrganizationProjectListFilterSet strict = True def get_context_data(self, **kwargs): ...
DetailOrganization
python
allegroai__clearml
clearml/backend_api/services/v2_9/models.py
{ "start": 99540, "end": 103062 }
class ____(Response): """ Response of models.update_for_task endpoint. :param id: ID of the model :type id: str :param created: Was the model created :type created: bool :param updated: Number of models updated (0 or 1) :type updated: int :param fields: Updated fields names and valu...
UpdateForTaskResponse
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 1979, "end": 5483 }
class ____(TestCase): def setUp(self): """ Create 3 BasicModel instances. """ items = ['foo', 'bar', 'baz'] for item in items: BasicModel(text=item).save() self.objects = BasicModel.objects self.data = [ {'id': obj.id, 'text': obj.text}...
TestRootView
python
pytorch__pytorch
tools/code_coverage/package/util/setting.py
{ "start": 613, "end": 681 }
class ____(Enum): CPP = "cxx_test" PY = "python_test"
TestType
python
allegroai__clearml
clearml/storage/callbacks.py
{ "start": 199, "end": 4972 }
class ____(object): report_upload_chunk_size_mb = None report_download_chunk_size_mb = None def __init__( self, verbose: bool, total_size: float, log: logging.Logger, report_chunk_size_mb: float, description_prefix: Optional[str] = None, description_s...
ProgressReport
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 18461, "end": 18558 }
class ____(BasePlace): serves_hot_dogs = models.BooleanField(default=False)
InheritedRestaurant
python
pytorch__pytorch
torch/ao/quantization/observer.py
{ "start": 37859, "end": 54863 }
class ____(UniformQuantizationObserverBase): r""" The module records the running histogram of tensor values along with min/max values. ``calculate_qparams`` will calculate scale and zero_point. Args: bins: Number of bins to use for the histogram dtype: dtype argument to the `quantize` n...
HistogramObserver
python
sympy__sympy
sympy/core/tests/test_expr.py
{ "start": 4458, "end": 5255 }
class ____(DummyNumber): number = 1.1 def __float__(self): return self.number i5 = I5() f1_1 = F1_1() # basic SymPy objects basic_objs = [ Rational(2), Float("1.3"), x, y, pow(x, y)*y, ] # all supported objects all_objs = basic_objs + [ 5, 5.5, i5, f1_1 ] def do...
F1_1
python
django__django
tests/model_inheritance_regress/models.py
{ "start": 1185, "end": 1236 }
class ____(Place, ParkingLot4): pass
ParkingLot4B
python
getsentry__sentry
tests/sentry/ratelimits/test_leaky_bucket.py
{ "start": 281, "end": 6518 }
class ____(TestCase): def setUp(self) -> None: self.limiter = LeakyBucketRateLimiter(burst_limit=5, drip_rate=2) @pytest.fixture(autouse=True) def inject_fixtures(self, caplog: pytest.LogCaptureFixture) -> None: self._caplog = caplog def test_basic(self) -> None: with freeze_ti...
LeakyBucketRateLimiterTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/repository.py
{ "start": 1197, "end": 109601 }
class ____(ReadableDeploymentStorage): """ Interact with files stored on GitHub repositories. """ _block_type_name = "GitHub Repository" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/41971cfecfea5f79ff334164f06ecb34d1038dd4-250x250.png" # noqa: E501 _documentation_url = "https:...
GitHubRepository
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2.py
{ "start": 3909, "end": 5633 }
class ____(Initializer): """Initializer that generates tensors initialized to 0. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Examples: >>> def make_variables(k, initializer): ...
Zeros
python
getsentry__sentry
src/sentry/issues/endpoints/group_similar_issues.py
{ "start": 586, "end": 2156 }
class ____(GroupEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, group: Group) -> Response: features = similarity.features limit_s = request.GET.get("limit", None) if limit_s is not None: limit: int | None = int(li...
GroupSimilarIssuesEndpoint
python
kamyu104__LeetCode-Solutions
Python/prefix-and-suffix-search.py
{ "start": 245, "end": 1411 }
class ____(object): def __init__(self, words): """ :type words: List[str] """ _trie = lambda: collections.defaultdict(_trie) self.__trie = _trie() for weight, word in enumerate(words): word += '#' for i in xrange(len(word)): c...
WordFilter
python
facebook__pyre-check
pyre_extensions/tests/safe_json_test.py
{ "start": 507, "end": 583 }
class ____(Movie): dictionary: Dict[str, Any]
MovieWithArbitraryDictionary
python
pydata__xarray
asv_bench/benchmarks/accessors.py
{ "start": 144, "end": 634 }
class ____: def setup(self, calendar): np.random.randn(NTIME) time = xr.date_range("2000", periods=30 * 365, calendar=calendar) data = np.ones((NTIME,)) self.da = xr.DataArray(data, dims="time", coords={"time": time}) def time_dayofyear(self, calendar): _ = self.da.time....
DateTimeAccessor
python
mahmoud__glom
glom/core.py
{ "start": 65197, "end": 67102 }
class ____(_ObjStyleKeysMeta('_AbstractKeys', (object,), {})): __metaclass__ = _ObjStyleKeysMeta @staticmethod def get_keys(obj): ret = obj.__dict__.keys() return ret def _get_sequence_item(target, index): return target[int(index)] # handlers are 3-arg callables, with args (spec, ta...
_ObjStyleKeys
python
pytorch__pytorch
test/distributed/checkpoint/test_file_system_checkpoint.py
{ "start": 2633, "end": 2965 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear_1 = torch.nn.Linear(5, 5) self.linear_2 = torch.nn.Linear(5, 1) self.emb = torch.nn.EmbeddingBag(5, 10) # The ShardedModels are borrowed from test/distributed/_sharded_tensor/test_sharded_tensor...
MyTestModule
python
coleifer__peewee
tests/regressions.py
{ "start": 44284, "end": 45160 }
class ____(ModelTestCase): requires = [Bits] def assertBits(self, bf, expected): b1_1, b1_2, b2_1, b2_2 = expected self.assertEqual(bf.b1_1, b1_1) self.assertEqual(bf.b1_2, b1_2) self.assertEqual(bf.b2_1, b2_1) self.assertEqual(bf.b2_2, b2_2) def test_bit_field_name...
TestBitFieldName
python
ray-project__ray
python/ray/dashboard/modules/reporter/gpu_providers.py
{ "start": 745, "end": 1077 }
class ____(TypedDict): """GPU utilization information for a single GPU device.""" index: int name: str uuid: str utilization_gpu: Optional[Percentage] memory_used: Megabytes memory_total: Megabytes processes_pids: Optional[Dict[int, ProcessGPUInfo]] # tpu utilization for google tpu
GpuUtilizationInfo
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 9729, "end": 9860 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): pass @dataclasses.dataclass(frozen=True)
ShowStatusRequestClientCapabilities
python
huggingface__transformers
src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py
{ "start": 2543, "end": 4863 }
class ____(nn.Module): def __init__(self, input_size, output_size, num_layers): super().__init__() # Stack the weights for N layers into a single tensor (num_layers, output_size, input_size) self.weight = nn.Parameter(torch.randn(num_layers, output_size, input_size)) def forward(self, x...
KyutaiSpeechToTextFlexibleLinear
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 45879, "end": 47106 }
class ____(nn.Module): def __init__(self, config: PatchTSTConfig): super().__init__() if config.scaling == "mean" or config.scaling is True: self.scaler = PatchTSTMeanScaler(config) elif config.scaling == "std": self.scaler = PatchTSTStdScaler(config) else: ...
PatchTSTScaler
python
psf__black
tests/data/miscellaneous/force_pyi.py
{ "start": 270, "end": 468 }
class ____ (A , C): ... def spam() -> None: ... @overload def spam(arg: str) -> str: ... var : int = 1 def eggs() -> Union[str, int]: ... # output from typing import Union @bird def zoo(): ...
F
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass3.py
{ "start": 446, "end": 490 }
class ____(metaclass=SubMeta3): pass
Base5
python
langchain-ai__langchain
libs/core/langchain_core/tools/base.py
{ "start": 44881, "end": 45134 }
class ____: """Annotation for tool arguments that are injected at runtime. Tool arguments annotated with this class are not included in the tool schema sent to language models and are instead injected during execution. """
InjectedToolArg
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 287670, "end": 291907 }
class ____(AssignmentNode): # An assignment with multiple left hand sides: # # a = b = c # # lhs_list [ExprNode] Left hand sides # rhs ExprNode Right hand sides # # Used internally: # # coerced_values [ExprNode] RHS coerced to all distinct LHS types...
CascadedAssignmentNode
python
PyCQA__pylint
tests/functional/u/undefined/undefined_variable.py
{ "start": 4939, "end": 5096 }
class ____: myattr = 1 mylambda = lambda: LambdaClass.myattr # Need different classes to make sure # consumed variables don't get in the way
LambdaClass
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 77063, "end": 84763 }
class ____(ReturnsRows): """Sub-base of ReturnsRows for elements that deliver rows directly, namely SELECT and INSERT/UPDATE/DELETE..RETURNING""" _label_style: SelectLabelStyle = LABEL_STYLE_NONE def _generate_columns_plus_names( self, anon_for_dupe_key: bool, cols: Optional[_S...
SelectsRows
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 10455, "end": 11430 }
class ____(HtmlRenderer): """ Renderer to display interactive figures in the classic Jupyter Notebook. This renderer is also useful for notebooks that will be converted to HTML using nbconvert/nbviewer as it will produce standalone HTML files that include interactive figures. This renderer auto...
NotebookRenderer
python
huggingface__transformers
src/transformers/models/flaubert/modeling_flaubert.py
{ "start": 65477, "end": 70993 }
class ____(FlaubertPreTrainedModel): def __init__(self, config): super().__init__(config) self.transformer = FlaubertModel(config) self.qa_outputs = FlaubertSQuADHead(config) # Initialize weights and apply final processing self.post_init() @auto_docstring def forwa...
FlaubertForQuestionAnswering
python
scipy__scipy
scipy/optimize/_numdiff.py
{ "start": 31862, "end": 35820 }
class ____: # Permits pickling of a wrapped function def __init__(self, fun, x0, args, kwargs): self.fun = fun self.x0 = x0 self.args = args self.kwargs = kwargs def __call__(self, x): # send user function same fp type as x0. (but only if cs is not being # us...
_Fun_Wrapper
python
kubernetes-client__python
kubernetes/client/api/internal_apiserver_v1alpha1_api.py
{ "start": 543, "end": 123682 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client ...
InternalApiserverV1alpha1Api
python
kamyu104__LeetCode-Solutions
Python/count-number-of-nice-subarrays.py
{ "start": 29, "end": 608 }
class ____(object): def numberOfSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def atMost(nums, k): result, left, count = 0, 0, 0 for right, x in enumerate(nums): count += x%2 wh...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 48735, "end": 49276 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("project_column_id", "content_id", "note", "client_mutation_id") project_column_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="projectColumnId" ) ...
AddProjectCardInput
python
kamyu104__LeetCode-Solutions
Python/construct-binary-tree-from-preorder-and-postorder-traversal.py
{ "start": 154, "end": 766 }
class ____(object): def constructFromPrePost(self, pre, post): """ :type pre: List[int] :type post: List[int] :rtype: TreeNode """ stack = [TreeNode(pre[0])] j = 0 for i in xrange(1, len(pre)): node = TreeNode(pre[i]) while stac...
Solution
python
huggingface__transformers
src/transformers/models/jamba/modeling_jamba.py
{ "start": 14842, "end": 27737 }
class ____(nn.Module): """ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) ∆, B, C are input-dependent (this is a key difference between Mamba and ...
JambaMambaMixer
python
spack__spack
lib/spack/spack/modules/common.py
{ "start": 37685, "end": 37858 }
class ____(AttributeError, ModulesError): """Raised if the attribute ``hide_cmd_format`` has not been specified in the derived classes. """
HideCmdFormatNotDefined