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
gevent__gevent
src/greentest/3.14/test_smtplib.py
{ "start": 28876, "end": 29421 }
class ____(unittest.TestCase): def setUp(self): smtplib.socket = mock_socket mock_socket.reply_with(b"199 no hello for you!") self.old_stdout = sys.stdout self.output = io.StringIO() sys.stdout = self.output self.port = 25 def tearDown(self): smtplib.soc...
BadHELOServerTests
python
tensorflow__tensorflow
tensorflow/compiler/tests/float_ops_test.py
{ "start": 868, "end": 17917 }
class ____(xla_test.XLATestCase): def test_float_ops(self): with self.session() as session: for dtype in self.float_types: x = np.arange(-0.90, 0.90, 0.25) self.assert_op_output_matches_expected( math_ops.acos, x.astype(dtype), expected=np.arccos(x).astyp...
FloatOpsTest
python
pytorch__pytorch
torch/onnx/_internal/torchscript_exporter/_type_utils.py
{ "start": 1086, "end": 13980 }
class ____(enum.IntEnum): """Scalar types defined in torch. Use ``JitScalarType`` to convert from torch and JIT scalar types to ONNX scalar types. Examples: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_ONNX) >>> # xdoctest: +IGNORE_WANT("win32 has different output") >>> JitScalarTyp...
JitScalarType
python
arrow-py__arrow
tests/test_locales.py
{ "start": 75041, "end": 75696 }
class ____: def test_ordinal_number(self): assert self.locale._ordinal_number(0) == "0তম" assert self.locale._ordinal_number(1) == "1ম" assert self.locale._ordinal_number(3) == "3য়" assert self.locale._ordinal_number(4) == "4র্থ" assert self.locale._ordinal_number(5) == "5ম"...
TestBengaliLocale
python
tornadoweb__tornado
tornado/test/tcpserver_test.py
{ "start": 3814, "end": 7711 }
class ____(unittest.TestCase): # These tests verify that the two multiprocess examples from the # TCPServer docs work. Both tests start a server with three worker # processes, each of which prints its task id to stdout (a single # byte, so we don't have to worry about atomicity of the shared # stdou...
TestMultiprocess
python
ray-project__ray
python/ray/data/preprocessors/discretizer.py
{ "start": 2285, "end": 7217 }
class ____(_AbstractKBinsDiscretizer): """Bin values into discrete intervals using custom bin edges. Columns must contain numerical values. Examples: Use :class:`CustomKBinsDiscretizer` to bin continuous features. >>> import pandas as pd >>> import ray >>> from ray.data.pr...
CustomKBinsDiscretizer
python
pytorch__pytorch
torchgen/api/lazy.py
{ "start": 11456, "end": 17053 }
class ____: # The name of the operator this function schema describes. name: OperatorName positional_args: tuple[LazyArgument, ...] keyword_args: tuple[LazyArgument, ...] # TODO: Need to handle collisions with argument names at some point returns: tuple[Return, ...] # if this schema has a...
LazyIrSchema
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type.py
{ "start": 3908, "end": 15230 }
class ____( composite_tensor.CompositeTensor, metaclass=ExtensionTypeMetaclass ): """Base class for TensorFlow `ExtensionType` classes. Tensorflow `ExtensionType` classes are specialized Python classes that can be used transparently with TensorFlow -- e.g., they can be used with ops such as `tf.cond` or `t...
ExtensionType
python
modin-project__modin
modin/pandas/groupby.py
{ "start": 3090, "end": 70034 }
class ____(ClassLogger, QueryCompilerCaster): # noqa: GL08 _pandas_class = pandas.core.groupby.DataFrameGroupBy _return_tuple_when_iterating = False _df: Union[DataFrame, Series] _query_compiler: BaseQueryCompiler _extensions: EXTENSION_DICT_TYPE = EXTENSION_DICT_TYPE(dict) def __init__( ...
DataFrameGroupBy
python
huggingface__transformers
tests/models/altclip/test_modeling_altclip.py
{ "start": 14616, "end": 16674 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (AltCLIPModel,) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": AltCLIPModel} if is_torch_available() else {} test_resize_embeddings = False test_attention_outputs = False # TO...
AltCLIPModelTest
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 8339, "end": 9017 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'pkg_mgr'] valid_subsets = ['pkg_mgr'] fact_namespace = 'ansible_pkgmgr' collector_class = PkgMgrFactCollector collected_facts = { "ansible_distribution": "Fedora", "ansible_distribution_major_version": "28", ...
TestPkgMgrFacts
python
cython__cython
Cython/Debugger/Tests/test_libcython_in_gdb.py
{ "start": 13564, "end": 13922 }
class ____(DebugTestCase): def test_updown(self): self.break_and_run('os.path.join("foo", "bar")') gdb.execute('cy step') self.assertRaises(RuntimeError, gdb.execute, 'cy down') result = gdb.execute('cy up', to_string=True) assert 'spam()' in result assert 'os.path....
TestUpDown
python
pallets__jinja
tests/test_inheritance.py
{ "start": 12198, "end": 13504 }
class ____: def test_fixed_macro_scoping_bug(self, env): assert Environment( loader=DictLoader( { "test.html": """\ {% extends 'details.html' %} {% macro my_macro() %} my_macro {% endmacro %} {% block inner_box %} ...
TestBugFix
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/gmake/package.py
{ "start": 217, "end": 847 }
class ____(Package): """Dummy GMake Package""" homepage = "https://www.gnu.org/software/make" url = "https://ftpmirror.gnu.org/make/make-4.4.tar.gz" tags = ["build-tools"] version("4.4", sha256="ce35865411f0490368a8fc383f29071de6690cbadc27704734978221f25e2bed") version("3.0", sha256="ce358654...
Gmake
python
weaviate__weaviate-python-client
weaviate/aliases/alias.py
{ "start": 63, "end": 248 }
class ____(BaseModel): """Returned aliases from Weaviate.""" alias: str collection: str _WeaviateAlias = TypedDict("_WeaviateAlias", {"alias": str, "class": str})
AliasReturn
python
getsentry__sentry
src/sentry/conf/types/topic_definition.py
{ "start": 67, "end": 225 }
class ____(TypedDict): cluster: str # The topic name may be overridden from the default via KAFKA_TOPIC_OVERRIDES real_topic_name: str
TopicDefinition
python
boto__boto3
boto3/resources/action.py
{ "start": 3546, "end": 6333 }
class ____(ServiceAction): """ An action which operates on a batch of items in a collection, typically a single page of results from the collection's underlying service operation call. For example, this allows you to delete up to 999 S3 objects in a single operation rather than calling ``.delete()``...
BatchAction
python
django__django
tests/m2m_regress/tests.py
{ "start": 268, "end": 5102 }
class ____(TestCase): def test_multiple_m2m(self): # Multiple m2m references to model must be distinguished when # accessing the relations through an instance attribute. s1 = SelfRefer.objects.create(name="s1") s2 = SelfRefer.objects.create(name="s2") s3 = SelfRefer.objects....
M2MRegressionTests
python
dagster-io__dagster
examples/project_fully_featured/project_fully_featured/resources/hn_resource.py
{ "start": 632, "end": 1037 }
class ____(HNClient): def fetch_item_by_id(self, item_id: int) -> Optional[HNItemRecord]: item_url = f"{HN_BASE_URL}/item/{item_id}.json" item = requests.get(item_url, timeout=5).json() return item def fetch_max_item_id(self) -> int: return requests.get(f"{HN_BASE_URL}/maxitem.j...
HNAPIClient
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 7005, "end": 8226 }
class ____(ModelOutput): r""" audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*): Discret code embeddings computed using `model.encode`. encoder_past_key_values (`Cache`, *optional*): Pre-computed hidden-states (key and values in the self-atte...
MimiEncoderOutput
python
conda__conda
conda/common/configuration.py
{ "start": 5497, "end": 6354 }
class ____(metaclass=ABCMeta): def __init__(self, source, key, raw_value): self.source = source self.key = key try: self._raw_value = raw_value.decode("utf-8") except AttributeError: # AttributeError: raw_value is not encoded self._raw_value = raw_...
RawParameter
python
kamyu104__LeetCode-Solutions
Python/number-of-good-paths.py
{ "start": 54, "end": 1026 }
class ____(object): # Time: O(n * alpha(n)), Space: O(n) def __init__(self, vals): self.set = range(len(vals)) self.rank = [0]*len(vals) self.cnt = [collections.Counter({v:1}) for v in vals] # added def find_set(self, x): stk = [] while self.set[x] != x: # path compr...
UnionFind
python
kubernetes-client__python
kubernetes/client/models/v1_priority_level_configuration.py
{ "start": 383, "end": 7676 }
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...
V1PriorityLevelConfiguration
python
urllib3__urllib3
test/with_dummyserver/test_connectionpool.py
{ "start": 57321, "end": 57742 }
class ____(HypercornDummyServerTestCase): def test_pool_size_retry(self) -> None: retries = Retry(total=1, raise_on_status=False, status_forcelist=[404]) with HTTPConnectionPool( self.host, self.port, maxsize=10, retries=retries, block=True ) as pool: pool.urlopen("GE...
TestRetryPoolSize
python
joke2k__faker
faker/providers/color/ar_PS/__init__.py
{ "start": 80, "end": 5782 }
class ____(ColorProvider): """Implement color provider for ``ar_PS`` locale.""" all_colors = OrderedDict( ( ("أزرق أليس", "#F0F8FF"), ("أبيض عتيق", "#FAEBD7"), ("مائي", "#00FFFF"), ("زبرجدي", "#7FFFD4"), ("لازوردي", "#F0FFFF"), ("ص...
Provider
python
davidhalter__jedi
test/completion/classes.py
{ "start": 4054, "end": 4142 }
class ____(object): def sum(self, a, b): self.xxx = 3 return a + b
Calc
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_comprehensions/C420_3.py
{ "start": 333, "end": 884 }
class ____: a = None def func(): {(C.a,): None for (C.a,) in "abc"} # OK def func(): obj = type('obj', (), {'attr': 1})() {(obj.attr,): None for (obj.attr,) in "abc"} # OK def func(): lst = [1, 2, 3] {(lst[0],): None for (lst[0],) in "abc"} # OK def func(): lst = [1, 2, 3, 4, 5] ...
C
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/python_connectors.py
{ "start": 8923, "end": 11077 }
class ____(Step): """Validate the connector can be installed and invoked via Python, using PyAirbyte. When this fails, it generally signals that the connector is not installable or not runnable in a Python environment. The most common reasons for this are: 1. Conflicting dependencies. 2. Missing de...
PyAirbyteValidation
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 47494, "end": 49051 }
class ____(ASTBase): def __init__( self, exprs: list[ASTExpression | ASTBracedInitList], trailingComma: bool ) -> None: self.exprs = exprs self.trailingComma = trailingComma def __eq__(self, other: object) -> bool: if not isinstance(other, ASTBracedInitList): ret...
ASTBracedInitList
python
ApeWorX__ape
src/ape_pm/dependency.py
{ "start": 3026, "end": 9031 }
class ____(DependencyAPI): """ A dependency from GitHub. Use the ``github`` key in your ``dependencies:`` section of your ``ape-config.yaml`` file to declare a dependency from GitHub. Config example:: dependencies: - name: OpenZeppelin github: OpenZeppelin/openzeppelin-co...
GithubDependency
python
doocs__leetcode
solution/2300-2399/2301.Match Substring After Replacement/Solution2.py
{ "start": 0, "end": 433 }
class ____: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: d = [[False] * 128 for _ in range(128)] for a, b in mappings: d[ord(a)][ord(b)] = True for i in range(len(s) - len(sub) + 1): if all( a == b or d[ord(b)][ord(a...
Solution
python
pytorch__pytorch
.github/scripts/test_filter_test_configs.py
{ "start": 7855, "end": 35353 }
class ____(TestCase): def setUp(self) -> None: os.environ["GITHUB_TOKEN"] = "GITHUB_TOKEN" if os.getenv("GITHUB_OUTPUT"): del os.environ["GITHUB_OUTPUT"] def tearDown(self) -> None: if os.getenv("GITHUB_OUTPUT"): os.remove(str(os.getenv("GITHUB_OUTPUT"))) @m...
TestConfigFilter
python
getsentry__sentry
src/sentry/core/endpoints/team_projects.py
{ "start": 5330, "end": 5488 }
class ____(TypedDict): request: Request organization: Organization target_object: int @extend_schema(tags=["Teams"]) @region_silo_endpoint
AuditData
python
tensorflow__tensorflow
tensorflow/python/autograph/core/converter_test.py
{ "start": 1111, "end": 1157 }
class ____(converter.Base): pass
TestConverter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_array_formula03.py
{ "start": 315, "end": 1572 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("array_formula03.xlsx") self.ignore_files = [ "xl/calcChain.xml", "[Content_Types].xml", "xl/_rels/workbook....
TestCompareXLSXFiles
python
openai__openai-python
tests/api_resources/uploads/test_parts.py
{ "start": 2114, "end": 4032 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: part = await async_client.uploads.parts.c...
TestAsyncParts
python
Pylons__pyramid
tests/test_viewderivers.py
{ "start": 70982, "end": 71170 }
class ____: def __init__(self, permitted=True): self.permitted = permitted def permits(self, request, context, permission): return self.permitted
DummySecurityPolicy
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_overlap_exceptions.py
{ "start": 350, "end": 3369 }
class ____(unittest.TestCase): """ Test overlapping merge and table ranges. """ def setUp(self): fh = StringIO() workbook = Workbook() workbook._set_filehandle(fh) self.workbook = workbook def test_overlaps01(self): """Test Worksheet range overlap exception...
TestOverlapRanges
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/login.py
{ "start": 1343, "end": 2627 }
class ____: """Login Service for FABAuthManager.""" @classmethod def create_token( cls, body: LoginBody, expiration_time_in_seconds: int = conf.getint("api_auth", "jwt_expiration_time") ) -> LoginResponse: """Create a new token.""" if not body.username or not body.password: ...
FABAuthManagerLogin
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc.py
{ "start": 84777, "end": 94144 }
class ____(GoogleCloudBaseOperator): """ Submit a job to a cluster. :param project_id: Optional. The ID of the Google Cloud project that the job belongs to. :param region: Required. The Cloud Dataproc region in which to handle the request. :param job: Required. The job resource. If a dict i...
DataprocSubmitJobOperator
python
scikit-learn__scikit-learn
sklearn/gaussian_process/_gpc.py
{ "start": 1303, "end": 20701 }
class ____(BaseEstimator): """Binary Gaussian process classification based on Laplace approximation. The implementation is based on Algorithm 3.1, 3.2, and 5.1 from [RW2006]_. Internally, the Laplace approximation is used for approximating the non-Gaussian posterior by a Gaussian. Currently, the ...
_BinaryGaussianProcessClassifierLaplace
python
openai__openai-python
src/openai/types/realtime/realtime_response.py
{ "start": 1198, "end": 3826 }
class ____(BaseModel): id: Optional[str] = None """The unique ID of the response, will look like `resp_1234`.""" audio: Optional[Audio] = None """Configuration for audio output.""" conversation_id: Optional[str] = None """ Which conversation the response is added to, determined by the `con...
RealtimeResponse
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_dataplex.py
{ "start": 8647, "end": 9769 }
class ____: @pytest.mark.db_test def test_get_link(self, create_task_instance_of_operator, session, mock_supervisor_comms): expected_url = EXPECTED_DATAPLEX_CATALOG_ENTRY_GROUPS_LINK link = DataplexCatalogEntryGroupsLink() ti = create_task_instance_of_operator( DataplexCatalo...
TestDataplexCatalogEntryGroupsLink
python
apache__airflow
providers/presto/src/airflow/providers/presto/hooks/presto.py
{ "start": 2893, "end": 11537 }
class ____(DbApiHook): """ Interact with Presto through prestodb. >>> ph = PrestoHook() >>> sql = "SELECT count(1) AS num FROM airflow.static_babynames" >>> ph.get_records(sql) [[340698]] """ conn_name_attr = "presto_conn_id" default_conn_name = "presto_default" conn_type = "pr...
PrestoHook
python
instagram__MonkeyType
tests/test_typing.py
{ "start": 17660, "end": 20175 }
class ____: @pytest.mark.parametrize( 'typ, expected', [ (TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': int}), True), (Dict[str, int], False), # Regression test. (lambda x: x, False), ], ) def test_is_typed_dict(self, typ, expected):...
TestTypedDictHelpers
python
pytorch__pytorch
torch/ao/quantization/observer.py
{ "start": 64180, "end": 64530 }
class ____(Granularity): """ Represents per-block granularity in quantization. See :func:`~torchao.quantization.quant_primitives.quantize_affine` for docs for `block_size` Attributes: block_size (Tuple[int, ...]): The size of each quantization group """ block_size: tuple[int, ...] ...
PerBlock
python
encode__django-rest-framework
tests/test_routers.py
{ "start": 10579, "end": 11105 }
class ____(TestCase): def setUp(self): class NoteViewSet(viewsets.ModelViewSet): queryset = RouterTestModel.objects.all() self.router = SimpleRouter() self.router.register(r'notes', NoteViewSet) self.urls = self.router.urls def test_urls_have_trailing_slash_by_defau...
TestTrailingSlashIncluded
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 62000, "end": 63613 }
class ____(nn.Module): def __init__(self, config, layer_id=0): super().__init__() self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id] self.out_conv_dim = config.tdnn_dim[layer_id] self.kernel_size = config.tdnn_kernel[layer_id] self...
TDNNLayer
python
ansible__ansible
lib/ansible/module_utils/facts/hardware/darwin.py
{ "start": 5828, "end": 5936 }
class ____(HardwareCollector): _fact_class = DarwinHardware _platform = 'Darwin'
DarwinHardwareCollector
python
numpy__numpy
benchmarks/benchmarks/bench_app.py
{ "start": 1436, "end": 2669 }
class ____(Benchmark): def setup(self): np.random.seed(1) nsubj = 5 nfeat = 100 ntime = 200 self.arrays = [np.random.normal(size=(ntime, nfeat)) for i in range(nsubj)] def maxes_of_dots(self, arrays): """ A magical feature score fo...
MaxesOfDots
python
sqlalchemy__sqlalchemy
test/ext/test_indexable.py
{ "start": 726, "end": 4951 }
class ____(fixtures.TestBase): def test_array(self): Base = declarative_base() class A(Base): __tablename__ = "a" id = Column("id", Integer, primary_key=True) array = Column("_array", ARRAY(Integer), default=[]) first = index_property("array", 0) ...
IndexPropertyTest
python
kubernetes-client__python
kubernetes/client/models/v1_persistent_volume.py
{ "start": 383, "end": 7376 }
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...
V1PersistentVolume
python
spack__spack
var/spack/test_repos/spack_repo/flags_test/packages/x/package.py
{ "start": 216, "end": 480 }
class ____(Package): version("1.1") version("1.0") variant("activatemultiflag", default=False) depends_on('y cflags="-d1"', when="~activatemultiflag") depends_on('y cflags="-d1 -d2"', when="+activatemultiflag") depends_on("c", type="build")
X
python
sympy__sympy
sympy/printing/latex.py
{ "start": 4521, "end": 124935 }
class ____(Printer): printmethod = "_latex" _default_settings: dict[str, Any] = { "full_prec": False, "fold_frac_powers": False, "fold_func_brackets": False, "fold_short_frac": None, "inv_trig_style": "abbreviated", "itex": False, "ln_notation": False, ...
LatexPrinter
python
dask__dask
dask/dataframe/dask_expr/_collection.py
{ "start": 173404, "end": 237513 }
class ____(FrameBase): """Scalar Expr Collection""" def __repr__(self): return f"<dask_expr.expr.Scalar: expr={self.expr}, dtype={self.dtype}>" def __bool__(self): raise TypeError( f"Trying to convert {self} to a boolean value. Because Dask objects are " "lazily eva...
Scalar
python
networkx__networkx
networkx/algorithms/centrality/tests/test_degree_centrality.py
{ "start": 82, "end": 4101 }
class ____: def setup_method(self): self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.K5 = nx.complete_graph(5) F = nx.Graph() # Florentine families F.add_edge("Acciaiuoli", "Medici") F.add_edge("Castellani", "Peruzzi") F.add_edge("Castella...
TestDegreeCentrality
python
getsentry__sentry
tests/sentry/uptime/endpoints/test_project_uptime_alert_details.py
{ "start": 411, "end": 550 }
class ____(UptimeAlertBaseEndpointTest): endpoint = "sentry-api-0-project-uptime-alert-details"
ProjectUptimeAlertDetailsBaseEndpointTest
python
realpython__materials
wordcount/tests/realpython/resources.py
{ "start": 1650, "end": 1797 }
class ____(Resource): @property def url(self) -> str: return f"https://realpython.com/learning-paths/{self.slug_clean}/"
LearningPath
python
langchain-ai__langchain
libs/partners/prompty/langchain_prompty/core.py
{ "start": 346, "end": 683 }
class ____(BaseModel): """Property settings for a prompty model.""" model_config = ConfigDict(arbitrary_types_allowed=True) type: Literal["string", "number", "array", "object", "boolean"] default: str | int | float | list | dict | bool | None = Field(default=None) description: str = Field(default="...
PropertySettings
python
doocs__leetcode
solution/1800-1899/1805.Number of Different Integers in a String/Solution.py
{ "start": 0, "end": 442 }
class ____: def numDifferentIntegers(self, word: str) -> int: s = set() i, n = 0, len(word) while i < n: if word[i].isdigit(): while i < n and word[i] == '0': i += 1 j = i while j < n and word[j].isdigit(): ...
Solution
python
pydata__xarray
xarray/core/indexes.py
{ "start": 54523, "end": 61803 }
class ____(Index): """Helper class for creating Xarray indexes based on coordinate transforms. - wraps a :py:class:`CoordinateTransform` instance - takes care of creating the index (lazy) coordinates - supports point-wise label-based selection - supports exact alignment only, by comparing indexes b...
CoordinateTransformIndex
python
PrefectHQ__prefect
src/prefect/events/actions.py
{ "start": 1928, "end": 2823 }
class ____(DeploymentAction): """Runs the given deployment with the given parameters""" type: Literal["run-deployment"] = "run-deployment" parameters: Optional[Dict[str, Any]] = Field( None, description=( "The parameters to pass to the deployment, or None to use the " ...
RunDeployment
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_algorithm.py
{ "start": 7308, "end": 7995 }
class ____(_CalibrationAlgorithmBase): """MinMaxCalibrationAlgorithm for calculating min and max values of calibration result. MinMax calibration calculates the global min and global max values. global min = min of given sample inputs global max = max of given sample inputs """ def get_min_max_value(self...
_MinMax
python
django__django
tests/lookup/test_lookups.py
{ "start": 1779, "end": 2345 }
class ____(SimpleTestCase): def test_get_bound_params(self): look_up = YearLookup( lhs=Value(datetime(2010, 1, 1, 0, 0, 0), output_field=DateTimeField()), rhs=Value(datetime(2010, 1, 1, 23, 59, 59), output_field=DateTimeField()), ) msg = "subclasses of YearLookup must...
YearLookupTests
python
kamyu104__LeetCode-Solutions
Python/find-valid-pair-of-adjacent-digits-in-string.py
{ "start": 42, "end": 461 }
class ____(object): def findValidPair(self, s): """ :type s: str :rtype: str """ cnt = [0]*9 for x in s: cnt[ord(x)-ord('1')] += 1 for i in xrange(len(s)-1): if s[i] != s[i+1] and cnt[ord(s[i])-ord('1')] == ord(s[i])-ord('0') and cnt[or...
Solution
python
python-visualization__folium
folium/plugins/pattern.py
{ "start": 214, "end": 2347 }
class ____(JSCSSMixin, MacroElement): """Fill Pattern for polygon composed of alternating lines. Add these to the 'fillPattern' field in GeoJson style functions. Parameters ---------- angle: float, default 0.5 Angle of the line pattern (degrees). Should be between -360 and 360. weight:...
StripePattern
python
pytorch__pytorch
torch/package/package_importer.py
{ "start": 28948, "end": 29600 }
class ____(_PathNode): pass # A private global registry of all modules that have been package-imported. _package_imported_modules: WeakValueDictionary = WeakValueDictionary() # `inspect` by default only looks in `sys.modules` to find source files for classes. # Patch it to check our private registry of package-i...
_ExternNode
python
apache__airflow
providers/celery/tests/unit/celery/cli/test_celery_command.py
{ "start": 10666, "end": 16946 }
class ____: @classmethod def setup_class(cls): with conf_vars({("core", "executor"): "CeleryExecutor"}): importlib.reload(cli_parser) cls.parser = cli_parser.get_parser() @mock.patch("airflow.providers.celery.executors.celery_executor.app") def test_run_command(self, moc...
TestFlowerCommand
python
django__django
tests/utils_tests/test_autoreload.py
{ "start": 17116, "end": 18948 }
class ____(SimpleTestCase): @mock.patch("django.utils.autoreload._exception", None) def test_no_exception(self): # Should raise no exception if _exception is None autoreload.raise_last_exception() def test_raises_exception(self): class MyException(Exception): pass ...
TestRaiseLastException
python
celery__celery
t/unit/utils/test_collections.py
{ "start": 9845, "end": 11755 }
class ____: def assert_size_and_first(self, buf, size, expected_first_item): assert len(buf) == size assert buf.take() == expected_first_item def test_append_limited(self): b = Messagebuffer(10) for i in range(20): b.put(i) self.assert_size_and_first(b, 10, ...
test_Messagebuffer
python
numba__numba
numba/tests/test_dyn_array.py
{ "start": 1642, "end": 15631 }
class ____(NrtRefCtTest, TestCase): def test_empty_0d(self): @nrtjit def foo(): arr = np.empty(()) arr[()] = 42 return arr arr = foo() self.assert_array_nrt_refct(arr, 1) np.testing.assert_equal(42, arr) self.assertEqual(arr.size,...
TestDynArray
python
langchain-ai__langchain
libs/partners/anthropic/tests/unit_tests/test_chat_models.py
{ "start": 40276, "end": 44066 }
class ____(BaseModel): """Get the current weather in a given location.""" location: str = Field(..., description="The city and state, e.g. San Francisco, CA") def test_anthropic_bind_tools_tool_choice() -> None: chat_model = ChatAnthropic( # type: ignore[call-arg, call-arg] model=MODEL_NAME, ...
GetWeather
python
streamlit__streamlit
lib/streamlit/testing/v1/app_test.py
{ "start": 2600, "end": 38351 }
class ____: """ A simulated Streamlit app to check the correctness of displayed\ elements and outputs. An instance of ``AppTest`` simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to...
AppTest
python
django__django
tests/m2m_and_m2o/models.py
{ "start": 255, "end": 581 }
class ____(models.Model): num = models.IntegerField() cc = models.ManyToManyField(User, blank=True, related_name="test_issue_cc") client = models.ForeignKey(User, models.CASCADE, related_name="test_issue_client") class Meta: ordering = ("num",) def __str__(self): return str(self.nu...
Issue
python
FactoryBoy__factory_boy
tests/djapp/models.py
{ "start": 949, "end": 993 }
class ____(AbstractBase): pass
ConcreteSon
python
tensorflow__tensorflow
tensorflow/compiler/tests/sharding_util_ops_test.py
{ "start": 2241, "end": 13625 }
class ____(xla_test.XLATestCase, parameterized.TestCase): @parameterized.named_parameters(('Tensor', create_tensor_split_graph), ('Resource', create_resource_split_graph)) def testSplitDimensionZero(self, graph_fn): for dtype in self.numeric_types: with self.session() as...
XlaSplitNDOpTest
python
mitmproxy__pdoc
pdoc/doc_ast.py
{ "start": 1973, "end": 11345 }
class ____: """The information extracted from walking the syntax tree.""" var_docstrings: dict[str, str] """A qualname -> docstring mapping.""" func_docstrings: dict[str, str] """A qualname -> docstring mapping for functions.""" annotations: dict[str, str | type[pdoc.doc_types.empty]] """A ...
AstInfo
python
fluentpython__example-code-2e
03-dict-set/missing.py
{ "start": 2085, "end": 2421 }
class ____(SimpleMappingSub): def __getitem__(self, key): try: return self._data[key] except KeyError: return self[_upper(key)] def get(self, key, default=None): return self._data.get(key, default) def __contains__(self, key): return key in self._dat...
DictLikeMappingSub
python
pypa__hatch
backend/src/hatchling/builders/sdist.py
{ "start": 3102, "end": 5496 }
class ____(BuilderConfig): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.__core_metadata_constructor: Callable[..., str] | None = None self.__strict_naming: bool | None = None self.__support_legacy: bool | None = None @property ...
SdistBuilderConfig
python
openai__openai-python
tests/test_transform.py
{ "start": 2235, "end": 2287 }
class ____(TypedDict): foo: Union[Bar4, Baz4]
Foo4
python
google__jax
jax/_src/tpu/linalg/eigh.py
{ "start": 11156, "end": 26537 }
class ____(NamedTuple): """Describes a subproblem of _eigh_work. Each subproblem is a `size` x `size` Hermitian matrix, starting at `offset` in the workspace. """ # The row offset of the block in the matrix of blocks. offset: Array # The size of the block. size: Array @api.jit(static_argnames=('term...
_Subproblem
python
Farama-Foundation__Gymnasium
gymnasium/vector/vector_env.py
{ "start": 23645, "end": 24534 }
class ____(VectorWrapper): """Wraps the vectorized environment to allow a modular transformation of the reward. Equivalent of :class:`gymnasium.RewardWrapper` for vectorized environments. """ def step( self, actions: ActType ) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, An...
VectorRewardWrapper
python
doocs__leetcode
solution/0200-0299/0218.The Skyline Problem/Solution.py
{ "start": 34, "end": 821 }
class ____: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: skys, lines, pq = [], [], PriorityQueue() for build in buildings: lines.extend([build[0], build[1]]) lines.sort() city, n = 0, len(buildings) for line in lines: while city...
Solution
python
google__pytype
pytype/tests/test_base_test.py
{ "start": 5490, "end": 6495 }
class ____(test_base.BaseTest): @test_utils.skipUnlessPy((3, 10), reason="testing skipUnlessPy") def test_skip_unless_py(self): # This test will fail if run in a version other than 3.10. self.Check(""" import sys if sys.version_info.minor != 10: name_error """) @test_utils.skipIf...
SkipTest
python
pytorch__pytorch
torch/_subclasses/_fake_tensor_utils.py
{ "start": 3114, "end": 5458 }
class ____: """ Represents a SymInt in the cached key. Needed because SymInt doesn't support __eq__ or __hash__ directly. """ # value can be: # PySymType: This is the 'normal' SymInt value, wrapped so we can use # hash/eq as value hash/eq (normally SymInt does object # ...
_PySymInputStub
python
buildout__buildout
src/zc/buildout/easy_install.py
{ "start": 66505, "end": 67641 }
class ____(zc.buildout.UserError): def __init__(self, req, ws): ws = list(ws) ws.sort() self.data = req, ws def __str__(self): req, ws = self.data return "Couldn't find a distribution for %r." % str(req) def _constrained_requirement(constraint, requirement): assert...
MissingDistribution
python
MongoEngine__mongoengine
tests/queryset/test_pickable.py
{ "start": 185, "end": 1315 }
class ____(MongoDBTestCase): """ Test for adding pickling support for QuerySet instances See issue https://github.com/MongoEngine/mongoengine/issues/442 """ def setUp(self): super().setUp() self.john = Person.objects.create(name="John", age=21) def test_picke_simple_qs(self): ...
TestQuerysetPickable
python
google__jax
tests/cache_key_test.py
{ "start": 1266, "end": 15285 }
class ____(jtu.JaxTestCase): def test_serialized_compile_options(self): compile_options = compiler.get_compile_options( num_replicas=1, num_partitions=1 ) hash1 = self.get_hashed_value( cache_key._hash_serialized_compile_options, compile_options ) debug_options = compile_options.e...
CacheKeyTest
python
realpython__materials
asterioids-pygame-project/source_code_step_3/space_rocks/game.py
{ "start": 46, "end": 856 }
class ____: def __init__(self): self._init_pygame() self.screen = pygame.display.set_mode((800, 600)) self.background = load_sprite("space", False) def main_loop(self): while True: self._handle_input() self._process_game_logic() self._draw() ...
SpaceRocks
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 28733, "end": 31146 }
class ____(GradientCheckpointingLayer): """Cross-attention transformer block with tanh-gated attention and feedforward.""" def __init__(self, config: MllamaTextConfig, layer_idx: int) -> None: super().__init__() self.layer_idx = layer_idx self.cross_attn = MllamaTextCrossAttention(confi...
MllamaCrossAttentionDecoderLayer
python
pyinstaller__pyinstaller
PyInstaller/utils/osx.py
{ "start": 12847, "end": 12999 }
class ____(Exception): """ Exception raised by `get_binary_architectures` when it is passed an invalid binary. """ pass
InvalidBinaryError
python
encode__django-rest-framework
rest_framework/fields.py
{ "start": 46414, "end": 48649 }
class ____(Field): default_error_messages = { 'invalid': _('Time has wrong format. Use one of these formats instead: {format}.'), } datetime_parser = datetime.datetime.strptime def __init__(self, format=empty, input_formats=None, **kwargs): if format is not empty: self.forma...
TimeField
python
facebook__pyre-check
scripts/callgraph_utilities.py
{ "start": 796, "end": 2355 }
class ____(abc.ABC): call_graph: Dict[str, Set[str]] original_call_graph: Dict[str, JSON] def __init__(self, call_graph: JSON) -> None: self.original_call_graph = self.validate_top_level_dict(call_graph) self.call_graph = self._to_call_graph() @staticmethod def validate_top_level_d...
InputFormat
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 70853, "end": 71108 }
class ____(BaseModel): """ Schema for a collection of Human-in-the-loop details. """ hitl_details: Annotated[list[HITLDetail], Field(title="Hitl Details")] total_entries: Annotated[int, Field(title="Total Entries")]
HITLDetailCollection
python
getsentry__sentry
src/sentry/web/forms/accounts.py
{ "start": 7552, "end": 8676 }
class ____(PasswordlessRegistrationForm): password = forms.CharField( required=True, widget=forms.PasswordInput(attrs={"placeholder": "something super secret"}) ) def clean_password(self): password = self.cleaned_data["password"] user = ( User(username=self.cleaned_data[...
RegistrationForm
python
tensorflow__tensorflow
tensorflow/python/data/util/random_seed_test.py
{ "start": 3622, "end": 4758 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def _checkEqual(self, tinput, toutput): random_seed.set_random_seed(tinput[0]) g_seed, op_seed = data_random_seed.get_seed(tinput[1]) g_seed = self.evaluate(g_seed) op_seed = self.evaluate(op_seed) msg = "test_case = {0}, got {1}, wan...
RandomSeedTest
python
huggingface__transformers
src/transformers/models/dia/processing_dia.py
{ "start": 1073, "end": 1239 }
class ____(AudioKwargs, total=False): bos_token_id: int eos_token_id: int pad_token_id: int delay_pattern: list[int] generation: bool
DiaAudioKwargs
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_hashtag.py
{ "start": 1589, "end": 3762 }
class ____(ColumnMapExpectation): """Expect column values to be valid #hashtags.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_hashtag": [ ...
ExpectColumnValuesToBeValidHashtag
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-upstage/llama_index/embeddings/upstage/base.py
{ "start": 1148, "end": 7455 }
class ____(OpenAIEmbedding): """ Class for Upstage embeddings. """ additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the Upstage API." ) api_key: str = Field(description="The Upstage API key.") api_base: Optional[str] = Field( ...
UpstageEmbedding
python
tensorflow__tensorflow
tensorflow/python/feature_column/sequence_feature_column_test.py
{ "start": 8425, "end": 9983 }
class ____( test.TestCase, parameterized.TestCase): @parameterized.named_parameters( {'testcase_name': '2D', 'inputs_args': { 'indices': ((0, 0), (1, 0), (1, 1)), 'values': ('omar', 'stringer', 'marlo'), 'dense_shape': (2, 2)}, 'expected_args': { 'i...
SequenceCategoricalColumnWithHashBucketTest