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
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_line04.py
{ "start": 315, "end": 1375 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_line04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
apache__airflow
helm-tests/tests/helm_tests/other/test_pgbouncer.py
{ "start": 15965, "end": 24677 }
class ____: """Tests PgBouncer config.""" def test_config_not_created_by_default(self): docs = render_chart( show_only=["templates/secrets/pgbouncer-config-secret.yaml"], ) assert docs == [] def test_should_add_annotations_to_pgbouncer_config_secret(self): docs...
TestPgbouncerConfig
python
getsentry__sentry
src/sentry/db/models/fields/array.py
{ "start": 400, "end": 2715 }
class ____(models.Field): def __init__(self, of=models.TextField, **kwargs): # Arrays in PostgreSQL are arrays of a particular type. # Save the subtype in our field class. if isinstance(of, type): of = of() self.of = of # Set "null" to True. Arrays don't have nul...
ArrayField
python
pydata__xarray
xarray/core/indexing.py
{ "start": 14716, "end": 15331 }
class ____: """Provide getitem and setitem syntax for callable objects.""" __slots__ = ("getter", "setter") def __init__( self, getter: Callable[..., Any], setter: Callable[..., Any] | None = None ): self.getter = getter self.setter = setter def __getitem__(self, key: Any)...
IndexCallable
python
kamyu104__LeetCode-Solutions
Python/minimum-time-difference.py
{ "start": 33, "end": 394 }
class ____(object): def findMinDifference(self, timePoints): """ :type timePoints: List[str] :rtype: int """ minutes = map(lambda x: int(x[:2]) * 60 + int(x[3:]), timePoints) minutes.sort() return min((y - x) % (24 * 60) \ for x, y in zip(m...
Solution
python
facebook__pyre-check
client/configuration/tests/search_path_test.py
{ "start": 581, "end": 9258 }
class ____(testslide.TestCase): def test_create_raw_element(self) -> None: self.assertEqual(create_raw_element("foo"), SimpleRawElement("foo")) self.assertEqual( create_raw_element({"root": "foo", "subdirectory": "bar"}), SubdirectoryRawElement("foo", "bar"), ) ...
SearchPathTest
python
pytorch__pytorch
test/test_cpp_extensions_aot.py
{ "start": 10719, "end": 14464 }
class ____(common.TestCase): def test_unregistered(self): torch.arange(0, 10, device="cpu") with self.assertRaisesRegex(RuntimeError, "Could not run"): torch.arange(0, 10, device="maia") @skipIfTorchDynamo("dynamo cannot model maia device") def test_zeros(self): a = torc...
TestMAIATensor
python
fastai__fastai
fastai/data/transforms.py
{ "start": 9967, "end": 11122 }
class ____(CollBase): "Collection of categories with the reverse mapping in `o2i`" def __init__(self, col, sort=True, add_na=False, strict=False): if hasattr(col, 'dtype') and isinstance(col.dtype, CategoricalDtype): items = L(col.cat.categories, use_list=True) #Remove non-used c...
CategoryMap
python
doocs__leetcode
solution/0000-0099/0069.Sqrt(x)/Solution.py
{ "start": 0, "end": 247 }
class ____: def mySqrt(self, x: int) -> int: l, r = 0, x while l < r: mid = (l + r + 1) >> 1 if mid > x // mid: r = mid - 1 else: l = mid return l
Solution
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_synapse.py
{ "start": 5612, "end": 15359 }
class ____: @pytest.fixture(autouse=True) def setup_test_cases(self, create_mock_connection): self.mock_ti = MagicMock() self.mock_context = {"ti": self.mock_ti} self.config = { "task_id": AZURE_SYNAPSE_PIPELINE_TASK_ID, "azure_synapse_conn_id": AZURE_SYNAPSE_CONN...
TestAzureSynapseRunPipelineOperator
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_integration_details.py
{ "start": 3728, "end": 4942 }
class ____(OrganizationIntegrationDetailsTest): method = "delete" def test_removal(self) -> None: self.get_success_response(self.organization.slug, self.integration.id) assert Integration.objects.filter(id=self.integration.id).exists() org_integration = OrganizationIntegration.objects....
OrganizationIntegrationDetailsDeleteTest
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 94754, "end": 96647 }
class ____(nn.Module): def __init__(self, hidden_size: int, num_heads: int, mask_feature_size: torch.Tensor): """ This class is used to get the predicted mask for a given Mask2FormerMaskedAttentionDecoder layer. It also generates the binarized attention mask associated with the given predict...
Mask2FormerMaskPredictor
python
Lightning-AI__lightning
src/lightning/fabric/_graveyard/tpu.py
{ "start": 3243, "end": 4355 }
class ____(XLABf16Precision): """Legacy class. Use :class:`~lightning.fabric.plugins.precision.xla.XLAPrecision` instead. """ def __init__(self, *args: Any, **kwargs: Any) -> None: rank_zero_deprecation( "The `TPUBf16Precision` class is deprecated. Use `lightning.fabric.plugins.pr...
TPUBf16Precision
python
python__mypy
mypyc/test/test_optimizations.py
{ "start": 750, "end": 1870 }
class ____(MypycDataSuite): """Base class for IR optimization test suites. To use this, add a base class and define "files" and "do_optimizations". """ base_path = test_temp_dir def run_case(self, testcase: DataDrivenTestCase) -> None: with use_custom_builtins(os.path.join(self.data_prefi...
OptimizationSuite
python
doocs__leetcode
solution/3000-3099/3004.Maximum Subtree of the Same Color/Solution.py
{ "start": 0, "end": 684 }
class ____: def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int: def dfs(a: int, fa: int) -> bool: ok = True for b in g[a]: if b != fa: t = dfs(b, a) ok = ok and colors[a] == colors[b] and t ...
Solution
python
keras-team__keras
keras/src/utils/file_utils_test.py
{ "start": 28691, "end": 29106 }
class ____(test_case.TestCase): def test_raise_if_no_gfile_raises_correct_message(self): path = "gs://bucket/some/file.txt" expected_error_msg = ( "Handling remote paths requires installing TensorFlow " f".*Received path: {path}" ) with self.assertRaisesRegex(...
TestRaiseIfNoGFile
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 991244, "end": 991445 }
class ____(VegaLiteSchema): """ProjectionType schema wrapper.""" _schema = {"$ref": "#/definitions/ProjectionType"} def __init__(self, *args): super().__init__(*args)
ProjectionType
python
getsentry__sentry
tests/sentry/db/models/fields/test_picklefield.py
{ "start": 106, "end": 1327 }
class ____(models.Model): id = models.AutoField(primary_key=True) data = picklefield.PickledObjectField() class Meta: app_label = "fixtures" @pytest.mark.django_db def test_json_by_default() -> None: obj = JsonWritingPickleModel.objects.create( data={"foo": "bar2"}, ) obj = Js...
JsonWritingPickleModel
python
python-openxml__python-docx
src/docx/oxml/xmlchemy.py
{ "start": 23582, "end": 25458 }
class ____(etree.ElementBase, metaclass=MetaOxmlElement): """Effective base class for all custom element classes. Adds standardized behavior to all classes in one place. """ def __repr__(self): return "<%s '<%s>' at 0x%0x>" % ( self.__class__.__name__, self._nsptag, ...
BaseOxmlElement
python
ipython__ipython
IPython/testing/plugin/pytest_ipdoctest.py
{ "start": 16667, "end": 19883 }
class ____(pytest.Module): obj = None def collect(self) -> Iterable[IPDoctestItem]: import doctest from .ipdoctest import IPDocTestParser # Inspired by doctest.testfile; ideally we would use it directly, # but it doesn't support passing a custom checker. encoding = self...
IPDoctestTextfile
python
numba__numba
numba/core/types/npytypes.py
{ "start": 8955, "end": 9442 }
class ____(SimpleIteratorType): """ Type class for `np.ndenumerate()` objects. """ def __init__(self, arrty): from . import Tuple, UniTuple, intp self.array_type = arrty yield_type = Tuple((UniTuple(intp, arrty.ndim), arrty.dtype)) name = "ndenumerate({arrayty})".format(...
NumpyNdEnumerateType
python
airbytehq__airbyte
airbyte-integrations/connectors/source-s3/source_s3/source_files_abstract/source.py
{ "start": 1083, "end": 5112 }
class ____(AbstractSource, ABC): @property @abstractmethod def stream_class(self) -> type: """ :return: reference to the relevant FileStream class e.g. IncrementalFileStreamS3 """ @property @abstractmethod def spec_class(self) -> type: """ :return: refere...
SourceFilesAbstract
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 1100259, "end": 1109910 }
class ____(FieldChannelMixin, core.SecondaryFieldDef): r""" Y2 schema wrapper. A field definition of a secondary channel that shares a scale with another primary channel. For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``. Parameters ---------- shorthand : str,...
Y2
python
mlflow__mlflow
mlflow/lightgbm/__init__.py
{ "start": 16565, "end": 36743 }
class ____: def __init__(self, lgb_model): self.lgb_model = lgb_model def get_raw_model(self): """ Returns the underlying model. """ return self.lgb_model def predict(self, dataframe, params: dict[str, Any] | None = None): """ Args: dataf...
_LGBModelWrapper
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 14996, "end": 15129 }
class ____(PydanticTypeError): code = 'int_enum_instance' msg_template = '{value} is not a valid IntEnum instance'
IntEnumError
python
pytest-dev__pytest
src/_pytest/capture.py
{ "start": 12927, "end": 13413 }
class ____(SysCaptureBase[str]): EMPTY_BUFFER = "" def snap(self) -> str: self._assert_state("snap", ("started", "suspended")) assert isinstance(self.tmpfile, CaptureIO) res = self.tmpfile.getvalue() self.tmpfile.seek(0) self.tmpfile.truncate() return res de...
SysCapture
python
scipy__scipy
scipy/stats/_distribution_infrastructure.py
{ "start": 24414, "end": 32129 }
class ____(ABC): r""" Representation of a distribution parameter or variable. A `_Parameter` object is responsible for storing information about a parameter or variable, providing input validation/standardization of values passed for that parameter, providing a text/mathematical representation of t...
_Parameter
python
chroma-core__chroma
chromadb/db/mixins/embeddings_queue.py
{ "start": 1365, "end": 19325 }
class ____(SqlDB, Producer, Consumer): """A SQL database that stores embeddings, allowing a traditional RDBMS to be used as the primary ingest queue and satisfying the top level Producer/Consumer interfaces. Note that this class is only suitable for use cases where the producer and consumer are in the ...
SqlEmbeddingsQueue
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 109933, "end": 116242 }
class ____: @pytest.mark.parametrize( ("is_primary", "confirm_message"), [ (True, "This is your primary address."), (False, "You can now set this email as your primary address."), ], ) def test_verify_email( self, mocker, db_request, ratelimit_service,...
TestVerifyEmail
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/slice1.py
{ "start": 53, "end": 381 }
class ____: def __getitem__[T](self, item: T) -> T: return item a1 = ClassA() reveal_type(a1[::], expected_text="slice[None, None, None]") reveal_type( a1[1:"a":False], expected_text="slice[Literal[1], Literal['a'], Literal[False]]" ) reveal_type(a1[:3:5.0], expected_text="slice[None, Literal[3], flo...
ClassA
python
ray-project__ray
python/ray/tune/tests/test_convergence.py
{ "start": 318, "end": 4412 }
class ____(unittest.TestCase): """Test convergence in gaussian process.""" @classmethod def setUpClass(cls) -> None: ray.init(local_mode=False, num_cpus=1, num_gpus=0) @classmethod def tearDownClass(cls) -> None: ray.shutdown() def _testConvergence(self, searcher, top=3, patie...
ConvergenceTest
python
mlflow__mlflow
mlflow/utils/import_hooks/__init__.py
{ "start": 8631, "end": 13050 }
class ____: def __init__(self): self.in_progress = {} @synchronized(_post_import_hooks_lock) @synchronized(_import_error_hooks_lock) def find_module(self, fullname, path=None): # If the module being imported is not one we have registered # import hooks for, we can return immedia...
ImportHookFinder
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 9479, "end": 9602 }
class ____: arg: Annotated[TensorArgument, 10] user_input_name: Annotated[str, 20] @dataclass
GradientToUserInputSpec
python
doocs__leetcode
solution/1000-1099/1002.Find Common Characters/Solution.py
{ "start": 0, "end": 262 }
class ____: def commonChars(self, words: List[str]) -> List[str]: cnt = Counter(words[0]) for w in words: t = Counter(w) for c in cnt: cnt[c] = min(cnt[c], t[c]) return list(cnt.elements())
Solution
python
jazzband__django-pipeline
pipeline/compressors/__init__.py
{ "start": 15171, "end": 15311 }
class ____(CompressorBase): def compress_js(self, js): return js def compress_css(self, css): return css
NoopCompressor
python
plotly__plotly.py
plotly/graph_objs/volume/_spaceframe.py
{ "start": 233, "end": 3741 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "volume" _path_str = "volume.spaceframe" _valid_props = {"fill", "show"} @property def fill(self): """ Sets the fill ratio of the `spaceframe` elements. The default fill value is 1 meaning that they are entirely shaded....
Spaceframe
python
getsentry__sentry
src/sentry/grouping/variants.py
{ "start": 2855, "end": 2990 }
class ____(BaseVariant): type = "fallback" def get_hash(self) -> str | None: return hash_from_values([])
FallbackVariant
python
xlwings__xlwings
xlwings/constants.py
{ "start": 12033, "end": 12168 }
class ____: xlColumnThenRow = 2 # from enum XlApplyNamesOrder xlRowThenColumn = 1 # from enum XlApplyNamesOrder
ApplyNamesOrder
python
scipy__scipy
scipy/odr/_odrpack.py
{ "start": 2068, "end": 2243 }
class ____(Exception): """ Exception indicating an error in fitting. This is raised by `~scipy.odr.odr` if an error occurs during fitting. """ pass
OdrError
python
Pylons__pyramid
docs/quick_tutorial/databases/tutorial/views.py
{ "start": 363, "end": 3001 }
class ____: def __init__(self, request): self.request = request @property def wiki_form(self): schema = WikiPage() return deform.Form(schema, buttons=('submit',)) @property def reqts(self): return self.wiki_form.get_widget_resources() @view_config(route_name='w...
WikiViews
python
sqlalchemy__sqlalchemy
examples/asyncio/async_orm_writeonly.py
{ "start": 716, "end": 1099 }
class ____(Base): __tablename__ = "a" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[Optional[str]] create_date: Mapped[datetime.datetime] = mapped_column( server_default=func.now() ) # collection relationships are declared with WriteOnlyMapped. There # is no separ...
A
python
pytorch__pytorch
torch/nn/modules/instancenorm.py
{ "start": 7754, "end": 9528 }
class ____(_LazyNormBase, _InstanceNorm): r"""A :class:`torch.nn.InstanceNorm1d` module with lazy initialization of the ``num_features`` argument. The ``num_features`` argument of the :class:`InstanceNorm1d` is inferred from the ``input.size(1)``. The attributes that will be lazily initialized are `weight`...
LazyInstanceNorm1d
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py
{ "start": 10059, "end": 12462 }
class ____(unittest.TestCase): def setUp(self): self.mock_index = MagicMock() self.mock_index.dimension = 2 self.mock_index.query.return_value = [ { "id": "1", "similarity": 0.9, "meta": {"text": "mock text"}, "vecto...
TestVectorXAdvanced
python
getsentry__sentry
tests/sentry/backup/test_imports.py
{ "start": 111485, "end": 118279 }
class ____(TestCase): """ Ensure large lists of a single model type are batched properly, and that this batching does not disrupt pk mapping. These tests do not inherit from `ImportTestCase` because they do not require a completely clean database. """ def import_n_users_with_options(self, import_uuid: ...
BatchingTests
python
facebook__pyre-check
client/commands/tests/start_test.py
{ "start": 1288, "end": 6054 }
class ____(testslide.TestCase): def test_serialize_critical_file(self) -> None: self.assertDictEqual( start.CriticalFile( policy=start.MatchPolicy.BASE_NAME, path="foo" ).serialize(), {"base_name": "foo"}, ) self.assertDictEqual( ...
ArgumentTest
python
PrefectHQ__prefect
tests/server/schemas/test_schedules.py
{ "start": 11224, "end": 12622 }
class ____: def test_create_cron_schedule(self): clock = CronSchedule(cron="5 4 * * *") assert clock.cron == "5 4 * * *" @pytest.mark.parametrize( "cron_string", [ "@yearly", "@weekly", "@daily", "@hourly", "* * * * MON...
TestCreateCronSchedule
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 38711, "end": 39602 }
class ____(sqltypes.Date): def bind_processor(self, dialect): def process(value): if type(value) == datetime.date: return datetime.datetime(value.year, value.month, value.day) else: return value return process _reg = re.compile(r"(\d+)-(\...
_MSDate
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-spread-stones-over-grid.py
{ "start": 2650, "end": 3444 }
class ____(object): def minimumMoves(self, grid): """ :type grid: List[List[int]] :rtype: int """ def dist(a, b): return abs(a[0]-b[0])+abs(a[1]-b[1]) src, dst = [], [] for i in xrange(len(grid)): for j in xrange(len(grid[0])): ...
Solution2
python
numpy__numpy
numpy/f2py/tests/test_f2cmap.py
{ "start": 41, "end": 387 }
class ____(util.F2PyTest): sources = [ util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90"), util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap") ] # gh-15095 def test_gh15095(self): inp = np.ones(3) out = self.module.func1(inp) exp_out = 3 as...
TestF2Cmap
python
apache__airflow
airflow-core/src/airflow/api_fastapi/common/parameters.py
{ "start": 6732, "end": 10592 }
class ____(BaseParam[list[str]]): """Order result by the attribute.""" MAX_SORT_PARAMS = 10 def __init__( self, allowed_attrs: list[str], model: Base, to_replace: dict[str, str | Column] | None = None ) -> None: super().__init__() self.allowed_attrs = allowed_attrs self...
SortParam
python
kamyu104__LeetCode-Solutions
Python/sort-array-by-moving-items-to-empty-space.py
{ "start": 44, "end": 873 }
class ____(object): def sortArray(self, nums): """ :type nums: List[int] :rtype: int """ def min_moves(d): def index(x): return d*(len(nums)-1) if x == 0 else x-d lookup = [False]*len(nums) result = len(nums) fo...
Solution
python
ray-project__ray
rllib/models/torch/recurrent_net.py
{ "start": 5223, "end": 12224 }
class ____(RecurrentNetwork, nn.Module): """An LSTM wrapper serving as an interface for ModelV2s that set use_lstm.""" def __init__( self, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, num_outputs: int, model_config: ModelConfigDict, name: str, ...
LSTMWrapper
python
scikit-learn__scikit-learn
sklearn/gaussian_process/tests/_mini_sequence_kernel.py
{ "start": 185, "end": 1571 }
class ____(GenericKernelMixin, StationaryKernelMixin, Kernel): """ A minimal (but valid) convolutional kernel for sequences of variable length. """ def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)): self.baseline_similarity = baseline_similarity self....
MiniSeqKernel
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/observers/test_ecs_observer.py
{ "start": 29544, "end": 33759 }
class ____: @pytest.fixture def sample_event(self): return { "id": str(uuid.uuid4()), "time": "2024-01-01T12:00:00Z", "detail": { "taskArn": "arn:aws:ecs:us-east-1:123456789:task/cluster/task-id", "clusterArn": "arn:aws:ecs:us-east-1:12...
TestReplicateEcsEvent
python
pandas-dev__pandas
asv_bench/benchmarks/strings.py
{ "start": 6482, "end": 6820 }
class ____(Dtypes): params = (Dtypes.params, [True, False]) param_names = ["dtype", "expand"] def setup(self, dtype, expand): super().setup(dtype) def time_extract_single_group(self, dtype, expand): with warnings.catch_warnings(record=True): self.s.str.extract("(\\w*)A", ex...
Extract
python
doocs__leetcode
solution/2700-2799/2717.Semi-Ordered Permutation/Solution.py
{ "start": 0, "end": 211 }
class ____: def semiOrderedPermutation(self, nums: List[int]) -> int: n = len(nums) i = nums.index(1) j = nums.index(n) k = 1 if i < j else 2 return i + n - j - k
Solution
python
pytorch__pytorch
torch/_inductor/dtype_propagation.py
{ "start": 464, "end": 2236 }
class ____(Protocol): @property def dtype(self) -> torch.dtype: ... DTypeArg = Union[DTypeVar, torch.types.Number, str, OpsValue] # Inputs need to be cacheable (e.g., not a CSEVar) in order for the cache to be effective # So first decompose CSEVars -> tuple before calling this @functools.cache def get_pro...
DTypeVar
python
networkx__networkx
networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py
{ "start": 46638, "end": 66703 }
class ____: def test_const_covered_neighbors(self): G1 = nx.MultiGraph( [(0, 1), (0, 1), (1, 2), (3, 0), (3, 0), (3, 0), (3, 2), (3, 2)] ) G2 = nx.MultiGraph( [ ("a", "b"), ("a", "b"), ("b", "c"), ("k", "...
TestMultiGraphISOFeasibility
python
getsentry__sentry
src/sentry/types/grouphash_metadata.py
{ "start": 3121, "end": 3769 }
class ____(TypedDict): """ Data gathered when grouping browser-based security (Content Security Policy, Certifcate Transparency, Online Certificate Status Protocol Stapling, or HTTP Public Key Pinning) reports """ # Either "csp", "expect_ct", "expect_staple", or "hpkp" security_report_type: str...
SecurityHashingMetadata
python
astropy__astropy
astropy/time/formats.py
{ "start": 78513, "end": 78732 }
class ____(TimeEpochDateString): """Besselian Epoch year as string value(s) like 'B1950.0'.""" name = "byear_str" epoch_to_jd = "epb2jd" jd_to_epoch = "epb" epoch_prefix = "B"
TimeBesselianEpochString
python
eventlet__eventlet
tests/queue_test.py
{ "start": 237, "end": 7988 }
class ____(tests.LimitedTestCase): def test_send_first(self): q = eventlet.Queue() q.put('hi') self.assertEqual(q.get(), 'hi') def test_send_last(self): q = eventlet.Queue() def waiter(q): self.assertEqual(q.get(), 'hi2') gt = eventlet.spawn(eventle...
TestQueue
python
plotly__plotly.py
plotly/graph_objs/_deprecations.py
{ "start": 13715, "end": 14409 }
class ____(dict): """ plotly.graph_objs.Scene is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.layout.Scene """ def __init__(self, *args, **kwargs): """ plotly.graph_objs.Scene is deprecated. Please replace...
Scene
python
python__mypy
mypy/checker_state.py
{ "start": 286, "end": 858 }
class ____: # Wrap this in a class since it's faster that using a module-level attribute. def __init__(self, type_checker: TypeCheckerSharedApi | None) -> None: # Value varies by file being processed self.type_checker = type_checker @contextmanager def set(self, value: TypeCheckerShare...
TypeCheckerState
python
spack__spack
lib/spack/spack/util/spack_yaml.py
{ "start": 10111, "end": 11384 }
class ____(emitter.Emitter): saved = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del _ANNOTATIONS[:] self.colors = "KgrbmcyGRBMCY" self.filename_colors = {} def process_scalar(self): super().process_scalar() if marked(self.eve...
LineAnnotationEmitter
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/ecs.py
{ "start": 1776, "end": 1996 }
class ____(_StringCompareEnum): """Contains the possible State values of an ECS Task Definition.""" ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" DELETE_IN_PROGRESS = "DELETE_IN_PROGRESS"
EcsTaskDefinitionStates
python
doocs__leetcode
solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/Solution.py
{ "start": 192, "end": 1005 }
class ____: def countPairs(self, root: TreeNode, distance: int) -> int: def dfs(root, cnt, i): if root is None or i >= distance: return if root.left is None and root.right is None: cnt[i] += 1 return dfs(root.left, cnt, i + ...
Solution
python
pytorch__pytorch
torch/autograd/graph.py
{ "start": 994, "end": 6154 }
class ____(abc.ABC): @abc.abstractmethod def name(self) -> str: r"""Return the name. Example:: >>> import torch >>> a = torch.tensor([0., 0., 0.], requires_grad=True) >>> b = a.clone() >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node) ...
Node
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 74467, "end": 78243 }
class ____(BasePostProgressGroupMixin): @with_feature("organizations:sdk-crash-detection") @override_options( { "issues.sdk_crash_detection.cocoa.project_id": 1234, "issues.sdk_crash_detection.cocoa.sample_rate": 1.0, "issues.sdk_crash_detection.react-native.project_i...
SDKCrashMonitoringTestMixin
python
getsentry__sentry
tests/sentry/sentry_apps/tasks/test_sentry_apps.py
{ "start": 2873, "end": 4242 }
class ____: def __init__(self): self.body = "blah blah" headers = {"Sentry-Hook-Error": "d5111da2c28645c5889d072017e3445d", "Sentry-Hook-Project": "1"} html_content = "a bunch of garbage HTML" json_content = '{"error": "bad request"}' MockResponse = namedtuple( "MockResponse", ["headers", "conten...
RequestMock
python
huggingface__transformers
src/transformers/models/regnet/modeling_regnet.py
{ "start": 5654, "end": 6945 }
class ____(nn.Module): """ RegNet's Y layer: an X layer with Squeeze and Excitation. """ def __init__(self, config: RegNetConfig, in_channels: int, out_channels: int, stride: int = 1): super().__init__() should_apply_shortcut = in_channels != out_channels or stride != 1 groups =...
RegNetYLayer
python
doocs__leetcode
solution/1300-1399/1316.Distinct Echo Substrings/Solution.py
{ "start": 0, "end": 724 }
class ____: def distinctEchoSubstrings(self, text: str) -> int: def get(l, r): return (h[r] - h[l - 1] * p[r - l + 1]) % mod n = len(text) base = 131 mod = int(1e9) + 7 h = [0] * (n + 10) p = [1] * (n + 10) for i, c in enumerate(text): ...
Solution
python
google__jax
docs/the-training-cookbook.py
{ "start": 2476, "end": 7264 }
class ____(dict): __setattr__ = dict.__setitem__ __getattr__ = dict.__getitem__ def tree_flatten_with_keys(self): keys = tuple(sorted(self)) return tuple((jax.tree_util.DictKey(k), self[k]) for k in keys), keys @classmethod def tree_unflatten(cls, keys, values): return cls(zip(keys, values)) #...
dot_dict
python
ansible__ansible
lib/ansible/_internal/_encryption/_crypt.py
{ "start": 1060, "end": 5994 }
class ____: """ Provide an interface for various crypt libraries that might be available. """ def __init__(self) -> None: self._crypt_impl: t.Callable | None = None self._crypt_gensalt_impl: t.Callable | None = None self._use_crypt_r = False self._use_crypt_gensalt_rn = ...
CryptFacade
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py
{ "start": 6850, "end": 6907 }
class ____[ T ]: pass type X[T,] = T def f[T,](): pass
C
python
huggingface__transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
{ "start": 25710, "end": 32488 }
class ____(JetMoePreTrainedModel): def __init__(self, config: JetMoeConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.lay...
JetMoeModel
python
sympy__sympy
sympy/stats/frv.py
{ "start": 15927, "end": 16874 }
class ____(IndependentProductPSpace, FinitePSpace): """ A collection of several independent finite probability spaces """ @property def domain(self): return ProductFiniteDomain(*[space.domain for space in self.spaces]) @property # type: ignore @cacheit def _density(self): ...
ProductFinitePSpace
python
ApeWorX__ape
src/ape/types/coverage.py
{ "start": 12440, "end": 15160 }
class ____(BaseModel): """ A project with coverage collected. """ name: str """ The name of the project being covered. """ sources: list[ContractSourceCoverage] = [] """ Coverage for each source in the project. """ @property def statements(self) -> list[CoverageSta...
CoverageProject
python
realpython__materials
python-bitwise-operators/src/stegano/encoder.py
{ "start": 153, "end": 1605 }
class ____: """Convenience class for serializing secret data.""" def __init__(self, path: pathlib.Path): self.path = path self.filename = path.name.encode("utf-8") + b"\x00" self.size_bytes = path.stat().st_size @property def num_secret_bytes(self) -> int: """Total numb...
SecretFile
python
miyuchina__mistletoe
mistletoe/span_token.py
{ "start": 3068, "end": 3884 }
class ____(SpanToken): """ Inline code token. ("`some code`") This is an inline token with a single child of type RawText. """ pattern = re.compile(r"(?<!\\|`)(?:\\\\)*(`+)(?!`)(.+?)(?<!`)\1(?!`)", re.DOTALL) parse_inner = False parse_group = 2 def __init__(self, match): content...
InlineCode
python
run-llama__llama_index
llama-index-integrations/observability/llama-index-observability-otel/llama_index/observability/otel/base.py
{ "start": 1408, "end": 5367 }
class ____(SimpleSpanHandler): """OpenTelemetry-compatible span handler.""" _tracer: trace.Tracer = PrivateAttr() _events_by_span: Dict[str, List[OTelEventAttributes]] = PrivateAttr( default_factory=dict, ) all_spans: Dict[str, Union[trace.Span, _Span]] = Field( default_factory=dict...
OTelCompatibleSpanHandler
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 2278, "end": 3839 }
class ____(greentest.TestCase): def test_link_to_asyncresult(self): p = gevent.spawn(lambda: 100) event = AsyncResult() p.link(event) self.assertEqual(event.get(), 100) for _ in range(3): event2 = AsyncResult() p.link(event2) self.assertE...
TestLink
python
django__django
tests/httpwrappers/tests.py
{ "start": 21105, "end": 25284 }
class ____(SimpleTestCase): def test_redirect(self): response = HttpResponseRedirect("/redirected/") self.assertEqual(response.status_code, 302) # Standard HttpResponse init args can be used response = HttpResponseRedirect( "/redirected/", content="The resourc...
HttpResponseSubclassesTests
python
getsentry__sentry
tests/sentry/issues/endpoints/test_organization_group_search_view_details.py
{ "start": 11164, "end": 14993 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-group-search-view-details" def setUp(self) -> None: super().setUp() self.user_1 = self.user self.user_2 = self.create_user() self.create_member(organization=self.organization, user=self.user_2) self.user_1_...
OrganizationGroupSearchViewsDeleteStarredAndLastVisitedTest
python
pytorch__pytorch
torch/_inductor/custom_graph_pass.py
{ "start": 1995, "end": 3820 }
class ____(ABC): """ Implement this interface for custom Graph passes: 1) The __call__() method contains the implementation of the custom pass. 2) The uuid() method enables inductor to cache compiled graphs when your custom passes are applied. This method can return any identifier as long as it un...
CustomGraphModulePass
python
mwaskom__seaborn
seaborn/_core/plot.py
{ "start": 2072, "end": 4222 }
class ____(TypedDict, total=False): variables: dict[str, VariableSpec] structure: dict[str, list[str]] cross: bool wrap: int | None # --- Local helpers ---------------------------------------------------------------- # @contextmanager def theme_context(params: dict[str, Any]) -> Generator: """T...
PairSpec
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 83118, "end": 83439 }
class ____(str, Enum): """ All possible names of payload types """ def __str__(self) -> str: return str(self.value) KEYWORD = "keyword" INTEGER = "integer" FLOAT = "float" GEO = "geo" TEXT = "text" BOOL = "bool" DATETIME = "datetime" UUID = "uuid"
PayloadSchemaType
python
getsentry__sentry
src/sentry/api/serializers/models/project.py
{ "start": 46931, "end": 47266 }
class ____(Serializer): def serialize(self, obj, attrs, user, **kwargs): return { "slug": obj.slug, "name": obj.name, "color": obj.color, "features": [], "organization": {"slug": obj.organization.slug, "name": obj.organization.name}, }
SharedProjectSerializer
python
facelessuser__pymdown-extensions
tests/test_extensions/test_snippets.py
{ "start": 18909, "end": 20698 }
class ____(util.MdCase): """Test snippet file case.""" extension = [ 'pymdownx.snippets', ] extension_configs = { 'pymdownx.snippets': { 'base_path': [os.path.join(BASE, '_snippets')], 'check_paths': True } } def test_good(self): """Test...
TestSnippetsMissing
python
dagster-io__dagster
python_modules/dagster/dagster_tests/freshness_tests/test_internal_freshness.py
{ "start": 9872, "end": 15725 }
class ____: def test_cron_freshness_policy_validation_basic(self) -> None: """Can we define a cron freshness policy with valid parameters?""" # Valid cron string and lower bound delta policy = FreshnessPolicy.cron( deadline_cron="0 10 * * *", lower_bound_delta=timedel...
TestCronFreshnessPolicy
python
kamyu104__LeetCode-Solutions
Python/filter-characters-by-frequency.py
{ "start": 48, "end": 340 }
class ____(object): def filterCharacters(self, s, k): """ :type s: str :type k: int :rtype: str """ cnt = [0]*26 for x in s: cnt[ord(x)-ord('a')] += 1 return "".join(x for x in s if cnt[ord(x)-ord('a')] < k)
Solution
python
ray-project__ray
rllib/policy/view_requirement.py
{ "start": 381, "end": 6294 }
class ____: """Single view requirement (for one column in an SampleBatch/input_dict). Policies and ModelV2s return a Dict[str, ViewRequirement] upon calling their `[train|inference]_view_requirements()` methods, where the str key represents the column name (C) under which the view is available in the ...
ViewRequirement
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 611, "end": 1305 }
class ____(Operation): def call(self, x): return backend.nn.relu(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.relu", "keras.ops.nn.relu"]) def relu(x): """Rectified linear unit activation function. It is defined as `f(x) = ...
Relu
python
doocs__leetcode
solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/Solution.py
{ "start": 0, "end": 392 }
class ____: def areSimilar(self, mat: List[List[int]], k: int) -> bool: n = len(mat[0]) for i, row in enumerate(mat): for j, x in enumerate(row): if i % 2 == 1 and x != mat[i][(j + k) % n]: return False if i % 2 == 0 and x != mat[i][(j ...
Solution
python
joke2k__faker
faker/providers/address/ne_NP/__init__.py
{ "start": 45, "end": 13318 }
class ____(AddressProvider): building_number_formats = ("#", "##", "###") street_name_formats = ("{{last_name}} {{street_suffix}}",) street_address_formats = ("{{street_name}}",) city_formats = ("{{city}}",) # http://www.nepalpost.gov.np/index.php/postal-codes-of-nepal postcode_formats = ("#####...
Provider
python
ansible__ansible
test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
{ "start": 4366, "end": 4484 }
class ____: def __init__(self, thing) -> None: self.module = thing # type: AnsibleModule
MyTypeCommentWrapper
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/ticket_forms_response_builder.py
{ "start": 228, "end": 488 }
class ____(HttpResponseBuilder): @classmethod def ticket_forms_response(cls) -> "TicketFormsResponseBuilder": return cls(find_template("ticket_forms", __file__), FieldPath("ticket_forms"), CursorBasedPaginationStrategy())
TicketFormsResponseBuilder
python
dask__distributed
distributed/comm/ws.py
{ "start": 9070, "end": 9589 }
class ____(WS): prefix = "wss://" def _read_extra(self): WS._read_extra(self) sock = self.sock.stream.socket if sock is not None: self._extra.update(peercert=sock.getpeercert(), cipher=sock.cipher()) cipher, proto, bits = self._extra["cipher"] logger....
WSS
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 16818, "end": 17725 }
class ____(TorchDistributionWrapper): """Action distribution that returns the input values directly. This is similar to DiagGaussian with standard deviation zero (thus only requiring the "mean" values as NN output). """ @override(ActionDistribution) def deterministic_sample(self) -> TensorType...
TorchDeterministic
python
pytorch__pytorch
test/test_proxy_tensor.py
{ "start": 81292, "end": 83521 }
class ____(TestCase): @ops(op_db + filtered_hop_db + custom_op_db, allowed_dtypes=(torch.float,)) @skipOps('TestProxyTensorOpInfo', 'test_make_fx_exhaustive', make_fx_failures.union(only_real_tensor_failures)) def test_make_fx_exhaustive(self, device, dtype, op): _test_make_fx_helper(self, device, d...
TestProxyTensorOpInfo
python
sqlalchemy__sqlalchemy
test/sql/test_update.py
{ "start": 53997, "end": 59167 }
class ____(_UpdateFromTestBase, fixtures.TablesTest): __sparse_driver_backend__ = True @testing.requires.update_from def test_exec_two_table(self, connection): users, addresses = self.tables.users, self.tables.addresses connection.execute( addresses.update() .values...
UpdateFromRoundTripTest