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
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_http_status_code.py
{ "start": 1681, "end": 3978 }
class ____(ColumnMapExpectation): """Expect column values to be valid HTTP status codes.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_http_status_code":...
ExpectColumnValuesToBeValidHttpStatusCode
python
kamyu104__LeetCode-Solutions
Python/count-substrings-that-satisfy-k-constraint-i.py
{ "start": 60, "end": 514 }
class ____(object): def countKConstraintSubstrings(self, s, k): """ :type s: str :type k: int :rtype: int """ result = cnt = left = 0 for right in xrange(len(s)): cnt += int(s[right] == '1') while not (cnt <= k or (right-left+1)-cnt <= ...
Solution
python
pytorch__pytorch
torch/_inductor/template_heuristics/contiguous_mm.py
{ "start": 719, "end": 1149 }
class ____(TemplateConfigHeuristics): """empty heuristics to skip contiguous mm on not cuda""" @register_template_heuristic( mm_contiguous_subgraph_template.uid, "cuda", register=torch.version.hip is not None, op_name="mm", ) @register_template_heuristic( addmm_contiguous_subgraph_template.uid...
EmptyContiguousMMConfigHeuristics
python
ijl__orjson
test/test_enum.py
{ "start": 202, "end": 249 }
class ____(enum.IntEnum): ONE = 1
IntEnumEnum
python
google__jax
jax/_src/debugger/colab_lib.py
{ "start": 1046, "end": 1176 }
class ____(metaclass=abc.ABCMeta): @abc.abstractmethod def render(self): pass Element = Union[DOMElement, str]
DOMElement
python
django__django
django/core/management/commands/makemessages.py
{ "start": 1857, "end": 5995 }
class ____: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, translatable): self.command = command self.domain = domain self.translatable = translatable @cached_property def is_templatized(self): if...
BuildFile
python
pytorch__pytorch
test/test_bundled_images.py
{ "start": 1727, "end": 3310 }
class ____(TestCase): def test_single_tensors(self): class SingleTensorModel(torch.nn.Module): def forward(self, arg): return arg im = cv2.imread("caffe2/test/test_img/p1.jpg") tensor = torch.from_numpy(im) inflatable_arg = bundle_jpeg_image(tensor, 90) ...
TestBundledImages
python
weaviate__weaviate-python-client
integration/conftest.py
{ "start": 2224, "end": 6778 }
class ____(Protocol): """Typing for fixture.""" def __call__( self, headers: Optional[Dict[str, str]] = None, ports: Tuple[int, int] = (8080, 50051), auth_credentials: Optional[weaviate.auth.AuthCredentials] = None, ) -> weaviate.WeaviateClient: """Typing for fixture...
ClientFactory
python
Lightning-AI__lightning
src/lightning/fabric/plugins/environments/kubeflow.py
{ "start": 774, "end": 2362 }
class ____(ClusterEnvironment): """Environment for distributed training using the `PyTorchJob`_ operator from `Kubeflow`_. This environment, unlike others, does not get auto-detected and needs to be passed to the Fabric/Trainer constructor manually. .. _PyTorchJob: https://www.kubeflow.org/docs/compon...
KubeflowEnvironment
python
numpy__numpy
numpy/_core/arrayprint.py
{ "start": 50195, "end": 51229 }
class ____: """ Formatter for subtypes of np.complexfloating """ def __init__(self, x, precision, floatmode, suppress_small, sign=False, *, legacy=None): # for backcompatibility, accept bools if isinstance(sign, bool): sign = '+' if sign else '-' floatmode_r...
ComplexFloatingFormat
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 2104, "end": 19848 }
class ____: """Common interface for performing matrix vector products Many iterative methods (e.g. `cg`, `gmres`) do not need to know the individual entries of a matrix to solve a linear system ``A@x = b``. Such solvers only require the computation of matrix vector products, ``A@v`` where ``v`` is ...
LinearOperator
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-get-a-peaceful-board.py
{ "start": 512, "end": 981 }
class ____(object): def minMoves(self, rooks): """ :type rooks: List[List[int]] :rtype: int """ def count(arr): cnt = [0]*len(arr) for x in arr: cnt[x] += 1 result = bal = 0 for i in xrange(len(rooks)): ...
Solution2
python
kamyu104__LeetCode-Solutions
Python/count-primes.py
{ "start": 717, "end": 1332 }
class ____(object): def countPrimes(self, n): """ :type n: int :rtype: int """ def linear_sieve_of_eratosthenes(n): primes = [] spf = [-1]*(n+1) # the smallest prime factor for i in xrange(2, n+1): if spf[i] == -1: ...
Solution_TLE
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/component_tree_tests/test_get_all_components.py
{ "start": 254, "end": 400 }
class ____(dg.Component): def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: return dg.Definitions()
FooComponent
python
pallets__click
src/click/core.py
{ "start": 4265, "end": 5110 }
class ____(enum.Enum): """This is an :class:`~enum.Enum` that indicates the source of a parameter's value. Use :meth:`click.Context.get_parameter_source` to get the source for a parameter by name. .. versionchanged:: 8.0 Use :class:`~enum.Enum` and drop the ``validate`` method. .. ver...
ParameterSource
python
django__django
django/contrib/postgres/validators.py
{ "start": 2568, "end": 2801 }
class ____(MinValueValidator): def compare(self, a, b): return a.lower is None or a.lower < b message = _( "Ensure that the lower bound of the range is not less than %(limit_value)s." )
RangeMinValueValidator
python
sympy__sympy
sympy/physics/secondquant.py
{ "start": 38831, "end": 40370 }
class ____: """ A single state, variable particle number basis set. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(5) >>> b [FockState((0,)), FockState((1,)), FockState((2,)), FockState((3,)), FockState((4,))] """ def _...
VarBosonicBasis
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/sql_to_gcs.py
{ "start": 1368, "end": 22550 }
class ____(BaseOperator): """ Copy data from SQL to Google Cloud Storage in JSON, CSV, or Parquet format. :param sql: The SQL to execute. :param bucket: The bucket to upload to. :param filename: The filename to use as the object name when uploading to Google Cloud Storage. A ``{}`` should b...
BaseSQLToGCSOperator
python
Pylons__pyramid
tests/test_integration.py
{ "start": 7413, "end": 7528 }
class ____(StaticAppBase, unittest.TestCase): package = 'tests.pkgs.static_assetspec'
TestStaticAppUsingAssetSpec
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/logs.py
{ "start": 951, "end": 1608 }
class ____(BaseAwsLink): """Helper class for constructing AWS CloudWatch Events Link.""" name = "CloudWatch Events" key = "cloudwatch_events" format_str = ( BASE_AWS_CONSOLE_LINK + "/cloudwatch/home?region={awslogs_region}#logsV2:log-groups/log-group/{awslogs_group}" + "/log-eve...
CloudWatchEventsLink
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ROI.py
{ "start": 69957, "end": 71165 }
class ____(ROI): r""" Rectangular ROI subclass with a single scale handle at the top-right corner. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI origin. See ROI(). size ...
RectROI
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor18.py
{ "start": 887, "end": 1019 }
class ____(Generic[_T2]): value: _T2 c1: ClassC[int] | ClassC[str] = ClassC("hi") c2: ClassC[int] | ClassC[str] = ClassC(1)
ClassC
python
getsentry__sentry
src/sentry/seer/anomaly_detection/types.py
{ "start": 153, "end": 261 }
class ____(TypedDict): timestamp: float value: float anomaly: NotRequired[Anomaly]
TimeSeriesPoint
python
catalyst-team__catalyst
catalyst/runners/supervised.py
{ "start": 775, "end": 5503 }
class ____(Runner): """IRunner for experiments with supervised model. Args: input_key: key in ``runner.batch`` dict mapping for model input output_key: key for ``runner.batch`` to store model output target_key: key in ``runner.batch`` dict mapping for target loss_key: key for ``...
ISupervisedRunner
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/cluster_coordinator_test.py
{ "start": 3019, "end": 15383 }
class ____(test.TestCase): def testBasic(self): queue = coordinator_lib._CoordinatedClosureQueue() closure1 = self._create_closure(queue._cancellation_mgr) queue.put(closure1) self.assertIs(closure1, queue.get()) self.assertFalse(queue.done()) queue.put_back(closure1) self.assertEqual(clo...
CoordinatedClosureQueueTest
python
pytorch__pytorch
test/torch_np/test_scalars_0D_arrays.py
{ "start": 2500, "end": 3823 }
class ____(TestCase): # # np.isscalar(...) checks that its argument is a numeric object with exactly one element. # # This differs from NumPy which also requires that shape == (). # scalars = [ subtest(42, "literal"), subtest(int(42.0), "int"), subtest(np.float32(42), "fl...
TestIsScalar
python
aimacode__aima-python
agents.py
{ "start": 12953, "end": 15360 }
class ____: """A direction class for agents that want to move in a 2D plane Usage: d = Direction("down") To change directions: d = d + "right" or d = d + Direction.R #Both do the same thing Note that the argument to __add__ must be a string and not a Direction...
Direction
python
doocs__leetcode
solution/0400-0499/0496.Next Greater Element I/Solution.py
{ "start": 0, "end": 348 }
class ____: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: stk = [] d = {} for x in nums2[::-1]: while stk and stk[-1] < x: stk.pop() if stk: d[x] = stk[-1] stk.append(x) return [d.get...
Solution
python
psf__black
tests/data/cases/no_blank_line_before_docstring.py
{ "start": 312, "end": 402 }
class ____: """I'm so far and on so many lines... """
MultilineDocstringsAsWell
python
pydata__xarray
xarray/tests/test_datatree.py
{ "start": 21685, "end": 27872 }
class ____: def test_properties(self) -> None: # use int64 for repr consistency on windows ds = Dataset( data_vars={ "foo": (["x", "y"], np.random.randn(2, 3)), }, coords={ "x": ("x", np.array([-1, -2], "int64")), "y...
TestCoords
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/information_schema.py
{ "start": 8324, "end": 8963 }
class ____(TypeDecorator): """This type casts sql_variant columns in the extended_properties view to nvarchar. This is required because pyodbc does not support sql_variant """ impl = Unicode cache_ok = True def column_expression(self, colexpr): return cast(colexpr, NVARCHAR) extended...
NVarcharSqlVariant
python
Netflix__metaflow
metaflow/plugins/aws/step_functions/step_functions_deployer_objects.py
{ "start": 300, "end": 1529 }
class ____(TriggeredRun): """ A class representing a triggered AWS Step Functions state machine execution. """ def terminate(self, **kwargs) -> bool: """ Terminate the running state machine execution. Parameters ---------- authorize : str, optional, default None...
StepFunctionsTriggeredRun
python
modin-project__modin
modin/core/execution/ray/common/deferred_execution.py
{ "start": 18277, "end": 19292 }
class ____(MaterializationHook): """ Used by MetaList.__getitem__() for lazy materialization and getting a single value from the list. Parameters ---------- meta : MetaList Non-materialized list to get the value from. idx : int The value index in the list. """ def __ini...
MetaListHook
python
weaviate__weaviate-python-client
weaviate/cluster/models.py
{ "start": 514, "end": 960 }
class ____: """Class representing the status of a replication operation.""" state: ReplicateOperationState errors: List[str] @classmethod def _from_weaviate(cls, data: dict) -> "ReplicateOperationStatus": return cls( state=ReplicateOperationState(data["state"]), err...
ReplicateOperationStatus
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/redshift_data.py
{ "start": 1893, "end": 11841 }
class ____(AwsGenericHook["RedshiftDataAPIServiceClient"]): """ Interact with Amazon Redshift Data API. Provide thin wrapper around :external+boto3:py:class:`boto3.client("redshift-data") <RedshiftDataAPIService.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are ...
RedshiftDataHook
python
django__django
tests/staticfiles_tests/test_handlers.py
{ "start": 207, "end": 401 }
class ____: """ASGI application that returns a string indicating that it was called.""" async def __call__(self, scope, receive, send): return "Application called"
MockApplication
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_sparse_tensor_slices_test.py
{ "start": 1280, "end": 7767 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( combinations.combine(tf_api_version=1, mode=["graph"]), combinations.combine(slices=[[ [1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], ...
FromSparseTensorSlicesTest
python
joke2k__faker
tests/providers/test_job.py
{ "start": 2269, "end": 2458 }
class ____: """Test de_DE job provider""" def test_job(self, faker, num_samples): for _ in range(num_samples): assert faker.job() in DeDeJobProvider.jobs
TestDeDe
python
tiangolo__fastapi
docs_src/path_operation_configuration/tutorial003.py
{ "start": 109, "end": 517 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: Set[str] = set() @app.post( "/items/", response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, pri...
Item
python
sympy__sympy
sympy/assumptions/assume.py
{ "start": 2107, "end": 4723 }
class ____(Boolean): """ The class of expressions resulting from applying ``Predicate`` to the arguments. ``AppliedPredicate`` merely wraps its argument and remain unevaluated. To evaluate it, use the ``ask()`` function. Examples ======== >>> from sympy import Q, ask >>> Q.integer(1) ...
AppliedPredicate
python
PyCQA__pylint
tests/input/similar_lines_b.py
{ "start": 861, "end": 1110 }
class ____: def similar_function_3_lines(self, tellus): # line same #1 agittis = 10 # line same #2 tellus *= 300 # line same #3 laoreet = "commodo " # line diff return agittis, tellus, laoreet # line diff
Commodo
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 11337, "end": 14137 }
class ____(Benchmark): param_names = ['sparse_type', 'density', 'format'] params = [ ['spmatrix', 'sparray'], [0.05, 0.01], ['csr', 'csc', 'lil'], ] def _setup(self, sparse_type, density, format): n = 100000 k = 1000 # faster version of sparse.rand(n, k,...
NullSlice
python
ray-project__ray
python/ray/dashboard/modules/job/tests/test_backwards_compatibility.py
{ "start": 916, "end": 4029 }
class ____: @pytest.mark.skipif( sys.platform == "darwin", reason="ray 2.0.1 runs differently on apple silicon than today's.", ) def test_cli(self): """ Test that the current commit's CLI works with old server-side Ray versions. 1) Create a new conda environment with...
TestBackwardsCompatibility
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/base.py
{ "start": 10717, "end": 11691 }
class ____: """ Join information. Notes ----- This class is used to track mappings between joined-on columns and joined-on keys (groups of columns). We need these mappings to calculate equivalence sets and make join-based unique-count and row-count estimates. """ __slots__ = ("...
JoinInfo
python
fluentpython__example-code-2e
23-descriptor/bulkfood/bulkfood_v4.py
{ "start": 1366, "end": 1670 }
class ____: weight = Quantity() # <5> price = Quantity() def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.price # end::LINEITEM_V4[]
LineItem
python
numpy__numpy
numpy/_core/tests/test_defchararray.py
{ "start": 24472, "end": 28306 }
class ____: def A(self): return np.array([['abc', '123'], ['789', 'xyz']]).view(np.char.chararray) def B(self): return np.array([['efg', '456'], ['051', 'tuv']]).view(np.char.chararray) def test_argsort(self): arr = np.array(['abc']...
TestOperations
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 29222, "end": 29811 }
class ____(AdminScriptTestCase): """ reverse_lazy can be used in settings without causing a circular import error. """ def setUp(self): super().setUp() self.write_settings( "settings.py", extra=( "from django.urls import reverse_lazy\n" ...
ReverseLazySettingsTest
python
getsentry__sentry
tests/sentry/middleware/integrations/test_classifications.py
{ "start": 1079, "end": 2447 }
class ____(BaseClassificationTestCase): get_response = MagicMock() plugin_cls = PluginClassification(response_handler=get_response) plugin_paths = [ "/plugins/github/installations/webhook/", "/plugins/github/organizations/1/webhook/", "/plugins/bitbucket/organizations/1/webhook/", ...
PluginClassifiationTest
python
huggingface__transformers
src/transformers/models/tapas/modeling_tapas.py
{ "start": 29590, "end": 34903 }
class ____(TapasPreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "tapas.embeddings.word_embeddings.weight", } config: TapasConfig base_model_prefix = "tapas" def __init__(self, config): super()...
TapasForMaskedLM
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 14859, "end": 21319 }
class ____(TestCase): def setUp(self): self.device = torch.device("cpu") self.pg = MagicMock() self.timeout = timedelta(seconds=10) # Mock Work object self.mock_work = MagicMock() self.mock_work.wait = MagicMock() # Setup process group mock to return mock_wo...
TestPGTransportMocked
python
huggingface__transformers
src/transformers/activations.py
{ "start": 4674, "end": 5712 }
class ____(nn.Module): """ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to https://huggingface.co/papers/2004.09602. Gaussi...
ClippedGELUActivation
python
doocs__leetcode
solution/2700-2799/2707.Extra Characters in a String/Solution.py
{ "start": 0, "end": 354 }
class ____: def minExtraChar(self, s: str, dictionary: List[str]) -> int: ss = set(dictionary) n = len(s) f = [0] * (n + 1) for i in range(1, n + 1): f[i] = f[i - 1] + 1 for j in range(i): if s[j:i] in ss and f[j] < f[i]: f[...
Solution
python
apache__airflow
airflow-core/src/airflow/models/asset.py
{ "start": 16036, "end": 17689 }
class ____(Base): """Reference from a DAG to an asset URI reference of which it is a consumer.""" uri: Mapped[str] = mapped_column( String(length=1500).with_variant( String( length=1500, # latin1 allows for more indexed length in mysql # and t...
DagScheduleAssetUriReference
python
huggingface__transformers
src/transformers/trainer_utils.py
{ "start": 12978, "end": 14441 }
class ____(ExplicitEnum): """ Scheduler names for the parameter `lr_scheduler_type` in [`TrainingArguments`]. By default, it uses "linear". Internally, this retrieves `get_linear_schedule_with_warmup` scheduler from [`Trainer`]. Scheduler types: - "linear" = [`get_linear_schedule_with_warmup`] ...
SchedulerType
python
google__pytype
pytype/pytd/base_visitor_test.py
{ "start": 87, "end": 897 }
class ____(unittest.TestCase): def test_get_ancestor_map(self): ancestors = base_visitor._GetAncestorMap() # TypeDeclUnit is the top of the food chain - no ancestors other than # itself. self.assertEqual({"TypeDeclUnit"}, ancestors["TypeDeclUnit"]) # NamedType can appear in quite a few places, sp...
TestAncestorMap
python
pydantic__pydantic
pydantic/v1/class_validators.py
{ "start": 484, "end": 5879 }
class ____: __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields', 'skip_on_failure' def __init__( self, func: AnyCallable, pre: bool = False, each_item: bool = False, always: bool = False, check_fields: bool = False, skip_on_failure: bool = Fa...
Validator
python
google__pytype
pytype/imports/module_loader.py
{ "start": 314, "end": 3087 }
class ____: """Find a filepath for a module.""" def __init__(self, options: config.Options): self.options = options self.accessed_imports_paths: set[str] = set() def find_import(self, module_name: str) -> tuple[str, bool] | None: """Search through pythonpath for a module. Loops over self.option...
_PathFinder
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
{ "start": 986, "end": 1130 }
class ____(BaseInfoResponse): """Scheduler info serializer for responses.""" latest_scheduler_heartbeat: str | None
SchedulerInfoResponse
python
huggingface__transformers
tests/models/xmod/test_modeling_xmod.py
{ "start": 26921, "end": 34328 }
class ____(unittest.TestCase): @slow def test_xmod_base(self): model = XmodModel.from_pretrained("facebook/xmod-base") # language en_XX model.set_default_language("en_XX") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The d...
XmodModelIntegrationTest
python
sympy__sympy
sympy/core/numbers.py
{ "start": 74180, "end": 92450 }
class ____(Expr): r""" Class for representing algebraic numbers in SymPy. Symbolically, an instance of this class represents an element $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the algebraic number $\alpha$ is represented as an element of a particular number field $\...
AlgebraicNumber
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 10160, "end": 10253 }
class ____(ParameterBase): name: str in_: ParameterInType = Field(alias="in")
Parameter
python
mlflow__mlflow
mlflow/tracking/fluent.py
{ "start": 132585, "end": 141664 }
class ____(LoggedModel): """ Wrapper around :py:class:`mlflow.entities.LoggedModel` to enable using Python ``with`` syntax. """ def __init__(self, logged_model: LoggedModel, set_by_user: bool): super().__init__(**logged_model.to_dictionary()) self.last_active_model_context = _ACTIVE_MOD...
ActiveModel
python
doocs__leetcode
solution/0700-0799/0773.Sliding Puzzle/Solution2.py
{ "start": 0, "end": 1578 }
class ____: def slidingPuzzle(self, board: List[List[int]]) -> int: m, n = 2, 3 seq = [] start, end = '', '123450' for i in range(m): for j in range(n): if board[i][j] != 0: seq.append(board[i][j]) start += str(board[i][...
Solution
python
astropy__astropy
astropy/utils/masked/tests/test_containers.py
{ "start": 2222, "end": 4399 }
class ____: def setup_class(self): self.ra = np.array([3.0, 5.0, 0.0]) << u.hourangle self.dec = np.array([4.0, 12.0, 1.0]) << u.deg self.sc = SkyCoord(self.ra, self.dec) self.mask = np.array([False, False, True]) self.mra = Masked(self.ra, self.mask) self.mdec = Mask...
TestSkyCoord
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 43924, "end": 46959 }
class ____: def test_invalid_shapes(self, convapproach, xp): a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) with assert_raises(ValueError, match="For 'valid' mode, one must be at least " "as large as the other i...
TestAllFreqConvolves
python
google__pytype
pytype/tools/xref/parse_args_test.py
{ "start": 127, "end": 1340 }
class ____(unittest.TestCase): """Test parse_args.parse_args.""" def test_parse_filename(self): _, _, pytype_opts = parse_args.parse_args(["a.py"]) self.assertEqual(pytype_opts.input, "a.py") def test_parse_no_filename(self): with self.assertRaises(SystemExit): parse_args.parse_args([]) def...
TestParseArgs
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_name04.py
{ "start": 315, "end": 1827 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_font04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 569397, "end": 570181 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "edges", "nodes", "page_info", "total_count", "viewer_has_reacted", ) edges = sgqlc.types.Field(sgqlc.types.list_of("React...
ReactionConnection
python
getsentry__sentry
src/sentry/sentry_apps/metrics.py
{ "start": 626, "end": 1310 }
class ____(EventLifecycleMetric): """An event under the Sentry App umbrella""" operation_type: SentryAppInteractionType event_type: str def get_metric_key(self, outcome: EventLifecycleOutcome) -> str: tokens = ("sentry_app", self.operation_type, str(outcome)) return ".".join(tokens) ...
SentryAppInteractionEvent
python
walkccc__LeetCode
solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py
{ "start": 0, "end": 590 }
class ____: def maxNonOverlapping(self, nums: list[int], target: int) -> int: # Ending the subarray ASAP always has a better result. ans = 0 prefix = 0 prefixes = {0} # Greedily find the subarrays that equal to the target. for num in nums: # Check if there is a subarray ends in here and...
Solution
python
astropy__astropy
astropy/units/function/logarithmic.py
{ "start": 6409, "end": 15195 }
class ____(FunctionQuantity): """A representation of a (scaled) logarithm of a number with a unit. Parameters ---------- value : number, `~astropy.units.Quantity`, `~astropy.units.LogQuantity`, or sequence of quantity-like. The numerical value of the logarithmic quantity. If a number or ...
LogQuantity
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar05.py
{ "start": 315, "end": 1350 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_f...
TestCompareXLSXFiles
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_vector/query/async_.py
{ "start": 312, "end": 461 }
class ____( Generic[Properties, References], _NearVectorQueryExecutor[ConnectionAsync, Properties, References], ): pass
_NearVectorQueryAsync
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_manytomany.py
{ "start": 6218, "end": 10658 }
class ____(fixtures.MappedTest): """deals with inheritance and many-to-many relationships""" @classmethod def define_tables(cls, metadata): global foo, bar, blub, bar_foo, blub_bar, blub_foo # the 'data' columns are to appease SQLite which can't handle a blank # INSERT foo ...
InheritTest3
python
ansible__ansible
lib/ansible/module_utils/facts/network/hurd.py
{ "start": 780, "end": 2962 }
class ____(Network): """ This is a GNU Hurd specific subclass of Network. It use fsysopts to get the ip address and support only pfinet. """ platform = 'GNU' _socket_dir = '/servers/socket/' def assign_network_facts(self, network_facts, fsysopts_path, socket_path): rc, out, err = se...
HurdPfinetNetwork
python
kamyu104__LeetCode-Solutions
Python/minimum-discards-to-balance-inventory.py
{ "start": 93, "end": 792 }
class ____(object): def minArrivalsToDiscard(self, arrivals, w, m): """ :type arrivals: List[int] :type w: int :type m: int :rtype: int """ result = 0 cnt = collections.defaultdict(int) for i in xrange(len(arrivals)): cnt[arrivals[i...
Solution
python
joke2k__faker
tests/providers/test_phone_number.py
{ "start": 14019, "end": 15030 }
class ____: def test_phone_number(self, faker, num_samples): pattern_no_whitespaces: Pattern = re.compile( r"^0\d{9}$", ) pattern_no_country_prefix: Pattern = re.compile( r"^0\d \d{2} \d{2} \d{2} \d{2}$", ) pattern_country_prefix_1: Pattern = re.compil...
TestFrFr
python
getsentry__sentry
src/sentry/releases/endpoints/project_release_file_details.py
{ "start": 2296, "end": 7258 }
class ____: """Shared functionality of ProjectReleaseFileDetails and OrganizationReleaseFileDetails Only has class methods, but keep it as a class to be consistent with ReleaseFilesMixin. """ @staticmethod def download(releasefile): file = releasefile.file fp = file.getfile() ...
ReleaseFileDetailsMixin
python
huggingface__transformers
tests/models/t5gemma/test_modeling_t5gemma.py
{ "start": 1589, "end": 22698 }
class ____: config_class = T5GemmaConfig module_config_class = T5GemmaModuleConfig if is_torch_available(): model_class = T5GemmaModel causal_lm_class = T5GemmaForConditionalGeneration sequence_classification_class = T5GemmaForSequenceClassification token_classification_clas...
T5GemmaModelTester
python
dask__dask
dask/multiprocessing.py
{ "start": 1576, "end": 8519 }
class ____(Exception): """Remote Exception Contains the exception and traceback from a remotely run task """ def __init__(self, exception, traceback): self.exception = exception self.traceback = traceback def __str__(self): return f"{self.exception}\n\nTraceback\n---------...
RemoteException
python
sphinx-doc__sphinx
sphinx/builders/linkcheck.py
{ "start": 11864, "end": 11952 }
class ____(NamedTuple): next_check: float hyperlink: Hyperlink | None
CheckRequest
python
run-llama__llama_index
llama-index-core/llama_index/core/base/llms/types.py
{ "start": 20564, "end": 21045 }
class ____(BaseModel): """Chat response.""" message: ChatMessage raw: Optional[Any] = None delta: Optional[str] = None logprobs: Optional[List[List[LogProb]]] = None additional_kwargs: dict = Field(default_factory=dict) def __str__(self) -> str: return str(self.message) ChatRespo...
ChatResponse
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0009_added_external_version_type.py
{ "start": 150, "end": 1252 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0008_remove-version-tags"), ] operations = [ migrations.AlterField( model_name="version", name="type", field=models.CharField( choices=[ ...
Migration
python
huggingface__transformers
src/transformers/models/informer/modeling_informer.py
{ "start": 3437, "end": 5178 }
class ____(nn.Module): """ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by subtracting from the mean and dividing by the standard deviation. """ def __init__(self, config: InformerConfig): super().__init__() self.dim = co...
InformerStdScaler
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/dataflow.py
{ "start": 23479, "end": 29380 }
class ____(BaseTrigger): """ Trigger that checks for autoscaling events associated with a Dataflow job. :param job_id: Required. ID of the job. :param project_id: Required. The Google Cloud project ID in which the job was started. :param location: Optional. The location where the job is executed. I...
DataflowJobAutoScalingEventTrigger
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/python.py
{ "start": 329, "end": 416 }
class ____(PackageBase): def test_imports(self) -> None: pass
PythonExtension
python
ethereum__web3.py
web3/_utils/threads.py
{ "start": 3352, "end": 4235 }
class ____(threading.Thread): def __init__(self, interval: int, callback: Callable[..., Any], *args: Any) -> None: threading.Thread.__init__(self) self.callback = callback self.terminate_event = threading.Event() self.interval = interval self.args = args def run(self) ->...
TimerClass
python
ray-project__ray
rllib/policy/policy_map.py
{ "start": 492, "end": 10247 }
class ____(dict): """Maps policy IDs to Policy objects. Thereby, keeps n policies in memory and - when capacity is reached - writes the least recently used to disk. This allows adding 100s of policies to a Algorithm for league-based setups w/o running out of memory. """ def __init__( s...
PolicyMap
python
django-haystack__django-haystack
test_haystack/elasticsearch5_tests/test_backend.py
{ "start": 1356, "end": 1673 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr="author", faceted=True) pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel
Elasticsearch5MockSearchIndex
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/stats.py
{ "start": 4108, "end": 4668 }
class ____(IHaveNew): start_time: Optional[float] end_time: Optional[float] key: Optional[str] def __new__( cls, start_time: Optional[float] = None, end_time: Optional[float] = None, key: Optional[str] = None, ): return super().__new__( cls, ...
RunStepMarker
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/translate.py
{ "start": 69327, "end": 74744 }
class ____(GoogleCloudBaseOperator): """ Get a list of translation glossaries in a project. List the translation glossaries, using translation API V3. For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:TranslateListGlossariesOperator`. :param proj...
TranslateListGlossariesOperator
python
spack__spack
lib/spack/spack/detection/common.py
{ "start": 10892, "end": 17427 }
class ____: @staticmethod def find_windows_kit_roots() -> List[str]: """Return Windows kit root, typically %programfiles%\\Windows Kits\\10|11\\""" if sys.platform != "win32": return [] program_files = os.environ["PROGRAMFILES(x86)"] kit_base = os.path.join(program_fi...
WindowsKitExternalPaths
python
pydata__xarray
xarray/core/types.py
{ "start": 3434, "end": 9720 }
class ____(Protocol): """Represents any Xarray type that supports alignment. It may be ``Dataset``, ``DataArray`` or ``Coordinates``. This protocol class is needed since those types do not all have a common base class. """ @property def dims(self) -> Frozen[Hashable, int] | tuple[Hashable, .....
Alignable
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py
{ "start": 2928, "end": 3182 }
class ____: thing: G | H def method1(self) -> None: if self.thing.type == 1: reveal_type(self.thing, expected_text="H") local = self.thing if local.type == 1: reveal_type(local, expected_text="H")
I
python
pandas-dev__pandas
pandas/core/window/rolling.py
{ "start": 113732, "end": 116027 }
class ____(BaseWindowGroupby, Rolling): """ Provide a rolling groupby implementation. """ _attributes = Rolling._attributes + BaseWindowGroupby._attributes def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds...
RollingGroupby
python
Textualize__textual
src/textual/events.py
{ "start": 22565, "end": 22922 }
class ____(Event, bubble=True, verbose=True): """Sent when a child widget is focussed. - [X] Bubbles - [X] Verbose """ widget: Widget """The widget that was focused.""" @property def control(self) -> Widget: """The widget that was focused (alias of `widget`).""" return...
DescendantFocus
python
apache__airflow
airflow-core/tests/unit/models/test_dagrun.py
{ "start": 109756, "end": 113965 }
class ____: """Test the handle_dag_callback method (only uses in dag.test).""" def test_handle_dag_callback_success(self, dag_maker, session): """Test handle_dag_callback executes success callback with RuntimeTaskInstance context""" called = False context_received = None def on...
TestDagRunHandleDagCallback
python
facebookresearch__faiss
faiss/gpu/test/torch_test_contrib_gpu.py
{ "start": 17611, "end": 18495 }
class ____(unittest.TestCase): def test_python_kmeans(self): """ Test the python implementation of kmeans """ ds = datasets.SyntheticDataset(32, 10000, 0, 0) x = ds.get_train() # bad distribution to stress-test split code xt = x[:10000].copy() xt[:5000] = x[0] ...
TestClustering
python
apache__airflow
airflow-core/tests/unit/jobs/test_triggerer_job.py
{ "start": 28460, "end": 31993 }
class ____(TriggerRunnerSupervisor): """ Make sure that the Supervisor stops after handling the events and do not keep running forever so the test can continue. """ def handle_events(self): self.stop = bool(self.events) super().handle_events() @pytest.mark.asyncio @pytest.mark.exe...
DummyTriggerRunnerSupervisor
python
astropy__astropy
astropy/io/ascii/ipac.py
{ "start": 1809, "end": 11568 }
class ____(fixedwidth.FixedWidthHeader): """IPAC table header.""" splitter_class = IpacHeaderSplitter # Defined ordered list of possible types. Ordering is needed to # distinguish between "d" (double) and "da" (date) as defined by # the IPAC standard for abbreviations. This gets used in get_col_...
IpacHeader