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
pytorch__pytorch
test/torch_np/test_basic.py
{ "start": 14076, "end": 14333 }
class ____(TestCase): def test_nimpl_basic(self): # smoke test that the "NotImplemented" annotation is picked up with assert_raises(NotImplementedError): w.empty(3, like="ooops") @instantiate_parametrized_tests
TestSmokeNotImpl
python
kamyu104__LeetCode-Solutions
Python/smallest-palindromic-rearrangement-ii.py
{ "start": 86, "end": 1510 }
class ____(object): def smallestPalindrome(self, s, k): """ :type s: str :type k: int :rtype: str """ cnt = [0]*26 for i in xrange(len(s)//2): cnt[ord(s[i])-ord('a')] += 1 total, count, remain = 0, 1, 0 for i in reversed(xrange(len(...
Solution
python
mlflow__mlflow
mlflow/exceptions.py
{ "start": 5947, "end": 6279 }
class ____(MlflowException): """Exception thrown when multipart upload is unsupported by an artifact repository""" MESSAGE = "Multipart upload is not supported for the current artifact repository" def __init__(self): super().__init__(self.MESSAGE, error_code=NOT_IMPLEMENTED)
_UnsupportedMultipartUploadException
python
ijl__orjson
test/test_error.py
{ "start": 2536, "end": 2964 }
class ____(Exception): pass def default_typeerror(obj): raise TypeError def default_notimplementederror(obj): raise NotImplementedError def default_systemerror(obj): raise SystemError def default_importerror(obj): import doesnotexist # noqa: PLC0415 assert doesnotexist CUSTOM_ERROR_M...
CustomException
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py
{ "start": 3279, "end": 4072 }
class ____(BaseGoogleLink): """Helper class for constructing Vertex AI Model Export Link.""" name = "Export Model" key = "export_conf" format_str = VERTEX_AI_MODEL_EXPORT_LINK @staticmethod def extract_bucket_name(config): """Return bucket name from output configuration.""" ret...
VertexAIModelExportLink
python
mlflow__mlflow
mlflow/genai/judges/tools/types.py
{ "start": 1070, "end": 1332 }
class ____: """Expectation for a trace (simplified for judge tools).""" name: str source: str rationale: str | None span_id: str | None assessment_id: str | None value: Any @experimental(version="3.5.0") @dataclass
JudgeToolExpectation
python
PyCQA__pylint
tests/functional/n/no/no_member_assign_same_line.py
{ "start": 672, "end": 861 }
class ____(ClassWithMember): """This assignment is valid due to inheritance.""" def __init__(self): self.member = self.member super().__init__()
AssignMemberFromSuper1
python
getsentry__sentry
src/sentry/integrations/github/blame.py
{ "start": 730, "end": 860 }
class ____(TypedDict): commit: GitHubFileBlameCommit startingLine: int endingLine: int age: int
GitHubFileBlameRange
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 133836, "end": 136412 }
class ____(test.TestCase): def _npRelu6(self, np_features): sixes = np.copy(np_features) sixes.fill(6.0) return np.minimum( np.maximum(np_features, np.zeros(np_features.shape)), sixes ) def testNpRelu6(self): self.assertAllClose( np.array([[0.0, 0.7, 0.0, 0.3, 6.0], [0.1, 0.0, ...
Relu6Test
python
getsentry__sentry
src/sentry/replays/lib/new_query/fields.py
{ "start": 6414, "end": 6502 }
class ____(ColumnField[UUID]): """UUID-type condition column field."""
UUIDColumnField
python
tensorflow__tensorflow
tensorflow/python/tpu/feature_column_v2.py
{ "start": 44496, "end": 47960 }
class ____(_TPUSharedEmbeddingColumnV2): """TPUSharedEmbeddingColumnV2 which allows serving on TensorCore.""" def __new__(cls, *args, **kwargs): # For __new__, just capture the inference dense shape and call parent. if 'tensor_core_shape' in kwargs: cls._tensor_core_shape = kwargs['tensor_core_shape'...
_TPUSharedDeviceSpecificEmbeddingColumnV2
python
nedbat__coveragepy
tests/test_plugins.py
{ "start": 23483, "end": 37527 }
class ____(FileTracerTest): """Test error handling around file tracer plugins.""" def run_plugin(self, module_name: str) -> Coverage: """Run a plugin with the given module_name. Uses a few fixed Python files. Returns the Coverage object. """ self.make_file( ...
BadFileTracerTest
python
django__django
django/db/migrations/operations/models.py
{ "start": 26463, "end": 28994 }
class ____(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = "order_with_respect_to" def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): ...
AlterOrderWithRespectTo
python
huggingface__transformers
tests/models/gemma/test_modeling_gemma.py
{ "start": 2226, "end": 22174 }
class ____(unittest.TestCase): input_text = ["Hello I am doing", "Hi today"] # This variable is used to determine which accelerator are we using for our runners (e.g. A10 or T4) # Depending on the hardware we get different logits / generations device_properties: DeviceProperties = (None, None, None) ...
GemmaIntegrationTest
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 93097, "end": 99398 }
class ____(Response): """ Response of models.get_by_id endpoint. :param model: Model info :type model: Model """ _service = "models" _action = "get_by_id" _version = "2.20" _schema = { "definitions": { "metadata_item": { "properties": { ...
GetByIdResponse
python
tensorflow__tensorflow
tensorflow/python/keras/engine/sequential.py
{ "start": 1978, "end": 23345 }
class ____(functional.Functional): """`Sequential` groups a linear stack of layers into a `tf.keras.Model`. `Sequential` provides training and inference features on this model. Examples: >>> # Optionally, the first layer can receive an `input_shape` argument: >>> model = tf.keras.Sequential() >>> model.a...
Sequential
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/records/groups_records_builder.py
{ "start": 196, "end": 492 }
class ____(ZendeskSupportRecordBuilder): @classmethod def groups_record(cls) -> "GroupsRecordBuilder": record_template = cls.extract_record("groups", __file__, NestedPath(["groups", 0])) return cls(record_template, FieldPath("id"), FieldPath("updated_at"))
GroupsRecordBuilder
python
scikit-image__scikit-image
benchmarks/benchmark_peak_local_max.py
{ "start": 437, "end": 1103 }
class ____: def setup(self): mask = np.zeros([500, 500], dtype=bool) x, y = np.indices((500, 500)) x_c = x // 20 * 20 + 10 y_c = y // 20 * 20 + 10 mask[(x - x_c) ** 2 + (y - y_c) ** 2 < 8**2] = True # create a mask, label each disk, self.labels, num_objs = nd...
PeakLocalMaxSuite
python
sqlalchemy__sqlalchemy
test/orm/test_mapper.py
{ "start": 82658, "end": 86296 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "cartographers", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), ...
MagicNamesTest
python
huggingface__transformers
src/transformers/models/dac/modeling_dac.py
{ "start": 10054, "end": 11153 }
class ____(nn.Module): """Decoder block used in DAC decoder.""" def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1): super().__init__() input_dim = config.decoder_hidden_size // 2**stride_index output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)...
DacDecoderBlock
python
langchain-ai__langchain
libs/core/langchain_core/tracers/event_stream.py
{ "start": 1466, "end": 2342 }
class ____(TypedDict): """Information about a run. This is used to keep track of the metadata associated with a run. """ name: str """The name of the run.""" tags: list[str] """The tags associated with the run.""" metadata: dict[str, Any] """The metadata associated with the run."""...
RunInfo
python
ZoranPandovski__al-go-rithms
data_structures/Linked_list/Python/linked_list.py
{ "start": 40, "end": 3521 }
class ____: class Node: next_node = None data = None def compare_to(self, node): return node.data == self.data def __init__(self, data, next_node): self.data = data self.next_node = next_node class NoSuchNodeException(Exception): pa...
LinkedList
python
scipy__scipy
scipy/stats/tests/test_sampling.py
{ "start": 12246, "end": 16126 }
class ____: def test_input_validation(self, method): match = "`qmc_engine` must be an instance of..." with pytest.raises(ValueError, match=match): Method = getattr(stats.sampling, method) gen = Method(StandardNormal()) gen.qrvs(qmc_engine=0) # issues with...
TestQRVS
python
weaviate__weaviate-python-client
weaviate/users/base.py
{ "start": 7165, "end": 9534 }
class ____(Generic[ConnectionType], _BaseExecutor[ConnectionType]): @overload def get_assigned_roles( self, *, user_id: str, include_permissions: Literal[False] = False ) -> executor.Result[Dict[str, RoleBase]]: ... @overload def get_assigned_roles( self, *, user_id: str, include_pe...
_UsersOIDCExecutor
python
protocolbuffers__protobuf
python/google/protobuf/internal/well_known_types_test.py
{ "start": 1392, "end": 1942 }
class ____(parameterized.TestCase): def CheckTimestampConversion(self, message, text): self.assertEqual(text, message.ToJsonString()) parsed_message = timestamp_pb2.Timestamp() parsed_message.FromJsonString(text) self.assertEqual(message, parsed_message) def CheckDurationConversion(self, message, ...
TimeUtilTestBase
python
PrefectHQ__prefect
src/integrations/prefect-docker/tests/test_containers.py
{ "start": 273, "end": 1012 }
class ____: async def test_create_kwargs(self, mock_docker_host: MagicMock): create_kwargs = dict( image="test_image", command="test_command", name="test_name", detach=False, ports={"2222/tcp": 3333}, entrypoint=None, enviro...
TestCreateDockerContainer
python
openai__openai-python
src/openai/types/beta/realtime/input_audio_buffer_append_event.py
{ "start": 233, "end": 662 }
class ____(BaseModel): audio: str """Base64-encoded audio bytes. This must be in the format specified by the `input_audio_format` field in the session configuration. """ type: Literal["input_audio_buffer.append"] """The event type, must be `input_audio_buffer.append`.""" event_id: Opt...
InputAudioBufferAppendEvent
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001_py310.py
{ "start": 468, "end": 588 }
class ____(SQLModel): id: int | None = None name: str | None = None headquarters: str | None = None
TeamUpdate
python
pypa__warehouse
warehouse/banners/models.py
{ "start": 235, "end": 1039 }
class ____(db.Model): __tablename__ = "banners" __repr__ = make_repr("text") DEFAULT_FA_ICON = "fa-comment-alt" DEFAULT_BTN_LABEL = "See more" # internal name name: Mapped[str] # banner display configuration text: Mapped[str] link_url: Mapped[str] link_label: Mapped[str] = mapp...
Banner
python
pytorch__pytorch
test/distributed/test_control_collectives.py
{ "start": 621, "end": 7398 }
class ____(TestCase): def test_barrier(self) -> None: store = dist.HashStore() world_size = 2 def f(rank: int) -> None: collectives = dist._StoreCollectives(store, rank, world_size) collectives.barrier("foo", timedelta(seconds=10), True) with ThreadPool(wor...
TestCollectives
python
ansible__ansible
lib/ansible/plugins/connection/psrp.py
{ "start": 10819, "end": 30847 }
class ____(ConnectionBase): transport = 'psrp' module_implementation_preferences = ('.ps1', '.exe', '') allow_executable = False has_pipelining = True # Satisfies mypy as this connection only ever runs with this plugin _shell: PowerShellPlugin def __init__(self, *args: t.Any, **kwargs: t....
Connection
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 29808, "end": 484566 }
class ____: def is_dtype_supported(self, dtype: torch.dtype) -> bool: device_interface = get_interface_for_device(self.device) return device_interface.is_dtype_supported(dtype) def test_bool(self): def fn(a, b): return ( a + b, a * b, ...
CommonTemplate
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial002_py310.py
{ "start": 78, "end": 369 }
class ____(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: list[str] = [] @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
Item
python
has2k1__plotnine
plotnine/scales/scale_manual.py
{ "start": 1967, "end": 2478 }
class ____(_scale_manual): """ Custom discrete shape scale See Also -------- [](`matplotlib.markers`) """ _aesthetics = ["shape"] values: InitVar[Sequence[Any] | dict[Any, Any]] """ Shapes that make up the palette. See [](`matplotlib.markers`) for list of all possible shape...
scale_shape_manual
python
pydantic__pydantic
tests/test_validate_call.py
{ "start": 36588, "end": 37300 }
class ____[T]: @validate_call(validate_return=True) def f(self, a: T) -> T: return str(a) """ ) A = module.A a = A[int]() # these two are undesired behavior, but it's what happens now assert a.f(1) == '1' assert a.f('1') == '1' @pytest.mark.s...
A
python
ipython__ipython
tests/test_interactivshell.py
{ "start": 3311, "end": 4870 }
class ____(object): """Machinery for tests of the main interact loop. Used by the mock_input decorator. """ def __init__(self, testgen): self.testgen = testgen self.exception = None self.ip = get_ipython() def __enter__(self): self.orig_prompt_for_code = self.ip.pr...
mock_input_helper
python
pypa__virtualenv
src/virtualenv/run/session.py
{ "start": 2248, "end": 2487 }
class ____: """lazily populate debug.""" def __init__(self, creator) -> None: self.creator = creator def __repr__(self) -> str: return json.dumps(self.creator.debug, indent=2) __all__ = [ "Session", ]
_Debug
python
pytorch__pytorch
torch/_inductor/codegen/memory_planning.py
{ "start": 6122, "end": 6376 }
class ____(Protocol): get_live_ranges: CachedMethod[[], LiveRanges] get_size_hint: CachedMethod[[], int] get_symbolic_size: CachedMethod[[], sympy.Expr] def _allocate(self, block: Allocation, is_last: bool) -> bool: ...
MemorySplitProtocol
python
kubernetes-client__python
kubernetes/client/models/v1_stateful_set.py
{ "start": 383, "end": 7226 }
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...
V1StatefulSet
python
pytorch__pytorch
test/inductor/test_cutlass_evt.py
{ "start": 2526, "end": 2697 }
class ____(BaseSchedulerNode): def __init__(self, node, last_usage=None): self.node = node self.last_usage = last_usage or OrderedSet()
MockSchedulerNode
python
pydata__xarray
xarray/tests/test_utils.py
{ "start": 1438, "end": 1816 }
class ____: def test_0d(self): # verify our work around for pd.isnull not working for 0-dimensional # object arrays assert duck_array_ops.array_equiv(0, np.array(0, dtype=object)) assert duck_array_ops.array_equiv(np.nan, np.array(np.nan, dtype=object)) assert not duck_array_...
TestArrayEquiv
python
ansible__ansible
hacking/create-bulk-issues.py
{ "start": 3936, "end": 4199 }
class ____(metaclass=abc.ABCMeta): @staticmethod @abc.abstractmethod def parse(message: str) -> Deprecation: pass @abc.abstractmethod def create_bug_report(self) -> BugReport: pass @dataclasses.dataclass(frozen=True)
Deprecation
python
langchain-ai__langchain
libs/core/tests/unit_tests/language_models/llms/test_cache.py
{ "start": 2083, "end": 3834 }
class ____(BaseCache): """In-memory cache used for testing purposes.""" def __init__(self) -> None: """Initialize with empty cache.""" self._cache: dict[tuple[str, str], RETURN_VAL_TYPE] = {} def lookup(self, prompt: str, llm_string: str) -> RETURN_VAL_TYPE | None: """Look up based...
InMemoryCacheBad
python
chroma-core__chroma
chromadb/telemetry/product/posthog.py
{ "start": 340, "end": 2176 }
class ____(ProductTelemetryClient): def __init__(self, system: System): if not system.settings.anonymized_telemetry or "pytest" in sys.modules: posthog.disabled = True else: logger.info( "Anonymized telemetry enabled. See \ https://docs.try...
Posthog
python
ansible__ansible
lib/ansible/_internal/_templating/_datatag.py
{ "start": 527, "end": 752 }
class ____(AnsibleSingletonTagBase): # deprecated: description='embedded Jinja constant string template support' core_version='2.23' pass @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
_JinjaConstTemplate
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/cholesky_op_test.py
{ "start": 11928, "end": 15230 }
class ____(test.Benchmark): shapes = [ (4, 4), (10, 10), (16, 16), (101, 101), (256, 256), (1000, 1000), (1024, 1024), (2048, 2048), (513, 2, 2), (513, 8, 8), (513, 256, 256), (4, 513, 2, 2), ] def _GenerateMatrix(self, shape): batch_sh...
CholeskyBenchmark
python
huggingface__transformers
tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py
{ "start": 1495, "end": 14344 }
class ____: def __init__( self, parent, input_modality="speech", batch_size=2, seq_length=4, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, hidden_act="gelu", hidden_dropout_prob=0.1, at...
SeamlessM4Tv2ModelTester
python
getsentry__sentry
tests/sentry/tasks/test_commit_context.py
{ "start": 39352, "end": 58554 }
class ____(IntegrationTestCase, TestCommitContextIntegration): provider = GitHubIntegrationProvider base_url = "https://api.github.com" def setUp(self) -> None: super().setUp() self.pull_request = PullRequest.objects.create( organization_id=self.commit.organization_id, ...
TestGHCommentQueuing
python
doocs__leetcode
solution/0500-0599/0565.Array Nesting/Solution2.py
{ "start": 0, "end": 331 }
class ____: def arrayNesting(self, nums: List[int]) -> int: ans, n = 0, len(nums) for i in range(n): cnt = 0 while nums[i] != n: j = nums[i] nums[i] = n i = j cnt += 1 ans = max(ans, cnt) retu...
Solution
python
fluentpython__example-code
21-class-metaprog/bulkfood/bulkfood_v8.py
{ "start": 1787, "end": 2124 }
class ____(model.Entity): description = model.NonBlank() weight = model.Quantity() price = model.Quantity() def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight ...
LineItem
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 10612, "end": 11869 }
class ____(BaseField): """32-bit integer field.""" def __init__(self, min_value=None, max_value=None, **kwargs): """ :param min_value: (optional) A min value that will be applied during validation :param max_value: (optional) A max value that will be applied during validation :p...
IntField
python
Textualize__textual
src/textual/binding.py
{ "start": 5594, "end": 6053 }
class ____(NamedTuple): """Information about an active binding (returned from [active_bindings][textual.screen.Screen.active_bindings]).""" node: DOMNode """The node where the binding is defined.""" binding: Binding """The binding information.""" enabled: bool """Is the binding enabled? (en...
ActiveBinding
python
PyCQA__pylint
doc/data/messages/a/arguments-differ/good/no_inheritance.py
{ "start": 517, "end": 646 }
class ____: def mix(self, fluid_one, fluid_two, alcoholic_fluid): return fluid_one + fluid_two + alcoholic_fluid
Cocktail
python
jazzband__django-waffle
waffle/tests/test_admin.py
{ "start": 4517, "end": 7197 }
class ____(TestCase): def setUp(self): super().setUp() self.site = AdminSite() self.switch_admin = SwitchAdmin(Switch, self.site) def test_enable_switches(self): s1 = Switch.objects.create(name="switch1", active=False) request = FakeRequest() enable_switches(Non...
SwitchAdminTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels16.py
{ "start": 315, "end": 1355 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels16.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
pytorch__pytorch
test/distributed/tensor/test_dtensor.py
{ "start": 25540, "end": 41860 }
class ____(DTensorTestBase): @property def world_size(self): return 8 def sub_mesh_assert_equal(self, mesh, exp_in_mesh, exp_out_of_mesh, tensor): if self.rank in mesh: self.assertEqual(tensor, exp_in_mesh) else: self.assertEqual(tensor, exp_out_of_mesh) ...
DTensorMeshTest
python
kamyu104__LeetCode-Solutions
Python/minimum-garden-perimeter-to-collect-enough-apples.py
{ "start": 43, "end": 1535 }
class ____(object): def minimumPerimeter(self, neededApples): """ :type neededApples: int :rtype: int """ # find min r, s.t. 4r^3+6r^2+2r-neededApples >= 0 # => by depressed cubic (https://en.wikipedia.org/wiki/Cubic_equation#Depressed_cubic) # let x = r+(6...
Solution
python
huggingface__transformers
src/transformers/models/speech_to_text/modeling_speech_to_text.py
{ "start": 3707, "end": 8218 }
class ____(nn.Module): """This module produces sinusoidal positional embeddings of any length.""" def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None): super().__init__() self.offset = 2 self.embedding_dim = embedding_dim self.padding_idx...
Speech2TextSinusoidalPositionalEmbedding
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_math_ops_test.py
{ "start": 1321, "end": 1920 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters( [dict(original=['a b'.split(), 'c d e'.split()], expected='a b c d e')]) @test_util.run_in_graph_and_eager_modes def testStringReduceJoin(self, original, expected, separator=' ', axis=None): original_rt = ragge...
RaggedReduceTest
python
sympy__sympy
sympy/polys/domains/fractionfield.py
{ "start": 555, "end": 6225 }
class ____(Field, CompositeDomain, Generic[Er]): """A class for representing multivariate rational function fields. """ is_FractionField = is_Frac = True has_assoc_Ring = True has_assoc_Field = True def __init__(self, domain_or_field: FracField[Er] | Domain[Er], symbols=None, order=None): ...
FractionField
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_cmath.py
{ "start": 2691, "end": 23818 }
class ____(__TestCase): # list of all functions in cmath test_functions = [getattr(cmath, fname) for fname in [ 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'exp', 'log', 'log10', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']] # test first and second argument...
CMathTests
python
huggingface__transformers
tests/models/flaubert/test_tokenization_flaubert.py
{ "start": 942, "end": 3375 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "flaubert/flaubert_base_cased" tokenizer_class = FlaubertTokenizer test_rust_tokenizer = False # Copied from transformers.tests.models.xlm.test_tokenization_xlm.XLMTokenizationTest.test_full_tokenizer def test_full_tokenizer(...
FlaubertTokenizationTest
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_custom_business_month.py
{ "start": 573, "end": 1442 }
class ____: @pytest.mark.parametrize("offset2", [CBMonthBegin(2), CBMonthEnd(2)]) def test_eq(self, offset2): assert offset2 == offset2 @pytest.mark.parametrize("offset2", [CBMonthBegin(2), CBMonthEnd(2)]) def test_hash(self, offset2): assert hash(offset2) == hash(offset2) @pytest....
TestCommonCBM
python
scikit-learn__scikit-learn
sklearn/pipeline.py
{ "start": 3009, "end": 59192 }
class ____(_BaseComposition): """ A sequence of data transformers with an optional final predictor. `Pipeline` allows you to sequentially apply a list of transformers to preprocess the data and, if desired, conclude the sequence with a final :term:`predictor` for predictive modeling. Intermedi...
Pipeline
python
pallets__flask
tests/test_async.py
{ "start": 289, "end": 444 }
class ____(View): methods = ["GET", "POST"] async def dispatch_request(self): await asyncio.sleep(0) return request.method
AsyncView
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/test_environment_validation.py
{ "start": 1077, "end": 8291 }
class ____: def __init__(self, command: tuple[str, ...], *args: str): self.command = command self.args = args def to_cli_args(self) -> tuple[str, ...]: return (*self.command, *self.args) DEFAULT_COMPONENT_TYPE = "dagster_test.components.SimpleAssetComponent" NO_REQUIRED_CONTEXT_COMMA...
CommandSpec
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/test_project/test_jobs/pending_repo.py
{ "start": 304, "end": 1488 }
class ____(CacheableAssetsDefinition): _cacheable_data = AssetsDefinitionCacheableData(keys_by_output_name={"result": AssetKey("bar")}) def compute_cacheable_data(self): # make sure this never gets called in the normal course of a run assert os.getenv("IN_EXTERNAL_PROCESS") == "yes" ret...
MyCacheableAssetsDefinition
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 5953, "end": 7092 }
class ____(DashboardComponent): """How many tasks are on each worker""" @log_errors def __init__(self, scheduler, **kwargs): self.last = 0 self.scheduler = scheduler self.source = ColumnDataSource( {"left": [1, 2], "right": [10, 10], "top": [0, 0]} ) sel...
ProcessingHistogram
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 134642, "end": 142115 }
class ____(Layout): """ A Tensor layout that we are allowed to change Assumption: layout change should NOT add or remove free symbols """ allow_indexing = False # WARNING! This doesn't handle zero size tensors correctly @staticmethod def contiguous_strides(sizes: Sequence[int]) -> li...
FlexibleLayout
python
numba__numba
numba/parfors/array_analysis.py
{ "start": 40140, "end": 124117 }
class ____(object): aa_count = 0 """Analyzes Numpy array computations for properties such as shape/size equivalence, and keeps track of them on a per-block basis. The analysis should only be run once because it modifies the incoming IR by inserting assertion statements that safeguard parfor opt...
ArrayAnalysis
python
prabhupant__python-ds
data_structures/trie/trie.py
{ "start": 112, "end": 2020 }
class ____(): def __init__(self): self.root = TrieNode() self.word_list = [] def formTrie(self, keys): for key in keys: self.insert(key) def insert(self, key): node = self.root for a in list(key): ...
Trie
python
encode__httpx
httpx/_auth.py
{ "start": 11744, "end": 11891 }
class ____(typing.NamedTuple): realm: bytes nonce: bytes algorithm: str opaque: bytes | None qop: bytes | None
_DigestAuthChallenge
python
ethereum__web3.py
tests/core/middleware/test_formatting_middleware.py
{ "start": 385, "end": 7029 }
class ____(BaseProvider): def make_request(self, method, params): raise NotImplementedError(f"Cannot make request for {method}:{params}") @pytest.fixture def w3(): return Web3(provider=DummyProvider(), middleware=[]) def test_formatting_middleware(w3, request_mocker): # No formatters by default ...
DummyProvider
python
airbytehq__airbyte
airbyte-integrations/connectors/source-intercom/components.py
{ "start": 845, "end": 6150 }
class ____: """ Define timings for RateLimits. Adjust timings if needed. :: on_unknown_load = 1.0 sec - Intercom recommended time to hold between each API call. :: on_low_load = 0.01 sec (10 miliseconds) - ideal ratio between hold time and api call, also the standard hold time between each API call. ...
IntercomRateLimiter
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 33247, "end": 37649 }
class ____: def _create_arrays(self): a = np.arange(5) nd_a = np.arange(5).repeat(2).reshape(1, 5, 2) return a, nd_a def _check_inverse_of_slicing(self, indices): a, nd_a = self._create_arrays() a_del = delete(a, indices) nd_a_del = delete(nd_a, indices, axis=1)...
TestDelete
python
xlwings__xlwings
xlwings/constants.py
{ "start": 71737, "end": 71910 }
class ____: xlCompactRow = 0 # from enum XlLayoutRowType xlOutlineRow = 2 # from enum XlLayoutRowType xlTabularRow = 1 # from enum XlLayoutRowType
LayoutRowType
python
sympy__sympy
sympy/polys/domains/mpelements.py
{ "start": 567, "end": 861 }
class ____(_mpf, DomainElement): """An element of a real domain. """ __slots__ = ('__mpf__',) def _set_mpf(self, val): self.__mpf__ = val _mpf_ = property(lambda self: self.__mpf__, _set_mpf) def parent(self): return self.context._parent @public
RealElement
python
django__django
tests/sitemaps_tests/models.py
{ "start": 63, "end": 261 }
class ____(models.Model): name = models.CharField(max_length=100) lastmod = models.DateTimeField(null=True) def get_absolute_url(self): return "/testmodel/%s/" % self.id
TestModel
python
rapidsai__cudf
python/cudf/cudf/core/udf/masked_typing.py
{ "start": 2775, "end": 6053 }
class ____(types.Type): """ A Numba type consisting of a value of some primitive type and a validity boolean, over which we can define math ops """ def __init__(self, value): # MaskedType in Numba shall be parameterized # with a value type if default_manager[value].has_nrt_m...
MaskedType
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 39589, "end": 42305 }
class ____: """ The Tensor metadata relevant to hashing FakeTensors when caching. """ dtype: torch.dtype shape: tuple[_MetadataIntLike, ...] stride: tuple[_MetadataIntLike, ...] device: torch.device layout: torch.layout memory_format: Optional[torch.memory_format] storage_offset...
TensorMetadata
python
kamyu104__LeetCode-Solutions
Python/design-movie-rental-system.py
{ "start": 202, "end": 1685 }
class ____(object): def __init__(self, n, entries): """ :type n: int :type entries: List[List[int]] """ self.__movie_to_ordered_price_shop = collections.defaultdict(SortedList) self.__shop_movie_to_price = {} self.__rented_ordered_price_shop_movie = SortedLi...
MovieRentingSystem
python
getsentry__sentry
src/sentry/hybridcloud/outbox/base.py
{ "start": 18095, "end": 19861 }
class ____(Protocol): """ Helps cover the interface of ReplicatedControlModel and User (which cannot subclass) that allows them to use OutboxCategory.connect_control_model_updates. """ @classmethod def handle_async_deletion( cls, identifier: int, region_name: str, ...
HasControlReplicationHandlers
python
pytorch__pytorch
torch/ao/nn/intrinsic/qat/modules/conv_fused.py
{ "start": 692, "end": 15481 }
class ____(nn.modules.conv._ConvNd, nni._FusedModule): _version = 2 _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]] def __init__( self, # ConvNd args in_channels, out_channels, kernel_size, stride, padding, dilation, transposed,...
_ConvBnNd
python
kubernetes-client__python
kubernetes/base/config/dateutil.py
{ "start": 628, "end": 2745 }
class ____(datetime.tzinfo): def __init__(self, h, m): self._name = "UTC" if h != 0 and m != 0: self._name += "%+03d:%2d" % (h, m) self._delta = datetime.timedelta(hours=h, minutes=math.copysign(m, h)) def utcoffset(self, dt): return self._delta def tzname(self,...
TimezoneInfo
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 5479, "end": 6477 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__(event_id=51, name="PROJECTKEY_EDIT", api_name="projectkey.edit") def render(self, audit_log_entry: AuditLogEntry) -> str: items_strings = [] if "prev_rate_limit_count" in audit_log_entry.data: items_stri...
ProjectKeyEditAuditLogEvent
python
tiangolo__fastapi
fastapi/security/http.py
{ "start": 557, "end": 968 }
class ____(BaseModel): """ The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). """ username: Annotated[str, Doc("The HTTP Basic us...
HTTPBasicCredentials
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/request_builders/api.py
{ "start": 1398, "end": 1587 }
class ____(AbstractRequestBuilder): URL = "https://api.hubapi.com/crm/v3/schemas" def build(self) -> HttpRequest: return HttpRequest(url=self.URL)
CustomObjectsRequestBuilder
python
getsentry__sentry
src/sentry/relay/config/__init__.py
{ "start": 14343, "end": 14559 }
class ____(TypedDict): op: Literal["http"] """Top scope to match on. Subscopes match all top scopes; for example, the scope `http` matches `http.client` and `http.server` operations."""
SpanDescriptionScope
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/eventloop/async_generator.py
{ "start": 1562, "end": 3933 }
class ____: pass async def generator_to_async_generator( get_iterable: Callable[[], Iterable[_T]], buffer_size: int = DEFAULT_BUFFER_SIZE, ) -> AsyncGenerator[_T, None]: """ Turn a generator or iterable into an async generator. This works by running the generator in a background thread. ...
_Done
python
sqlalchemy__sqlalchemy
test/dialect/sqlite/test_types.py
{ "start": 10774, "end": 12200 }
class ____(fixtures.TestBase, AssertsCompiledSQL): def test_time_microseconds(self): dt = datetime.datetime(2008, 6, 27, 12, 0, 0, 125) eq_(str(dt), "2008-06-27 12:00:00.000125") sldt = sqlite.DATETIME() bp = sldt.bind_processor(None) eq_(bp(dt), "2008-06-27 12:00:00.000125")...
DateTimeTest
python
sqlalchemy__sqlalchemy
test/orm/test_cascade.py
{ "start": 5784, "end": 7763 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(30), nullable=False), ...
CasadeWithRaiseloadTest
python
scrapy__scrapy
scrapy/cmdline.py
{ "start": 762, "end": 7647 }
class ____(argparse.ArgumentParser): def _parse_optional( self, arg_string: str ) -> tuple[argparse.Action | None, str, str | None] | None: # Support something like ‘-o -:json’, where ‘-:json’ is a value for # ‘-o’, not another parameter. if arg_string.startswith("-:"): ...
ScrapyArgumentParser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/partial5.py
{ "start": 199, "end": 721 }
class ____: def __init__(self, x: int, y: int) -> None: ... # This should generate an error because "y" has the wrong type. v1 = partial(A, x=1, y="a") v2 = partial(A, x=1, y=2) reveal_type(v2, expected_text="partial[A]") v2() v2(x=2) T = TypeVar("T", bound=A) def func1(x: type[T]): # This should generat...
A
python
walkccc__LeetCode
solutions/3042. Count Prefix and Suffix Pairs I/3042.py
{ "start": 0, "end": 115 }
class ____: def __init__(self): self.children: dict[tuple[str, str], TrieNode] = {} self.count = 0
TrieNode
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/vector/vectorize_observation.py
{ "start": 13747, "end": 14634 }
class ____(VectorizeTransformObservation): """Resizes image observations using OpenCV to shape. Example: >>> import gymnasium as gym >>> envs = gym.make_vec("CarRacing-v3", num_envs=3, vectorization_mode="sync") >>> obs, info = envs.reset(seed=123) >>> obs.shape (3, 96, ...
ResizeObservation
python
django__django
tests/inspectdb/models.py
{ "start": 5478, "end": 5936 }
class ____(models.Model): fk_do_nothing = models.ForeignKey(UniqueTogether, on_delete=models.DO_NOTHING) fk_db_cascade = models.ForeignKey(ColumnTypes, on_delete=models.DB_CASCADE) fk_set_null = models.ForeignKey( DigitsInColumnName, on_delete=models.DB_SET_NULL, null=True ) class Meta: ...
DbOnDeleteModel
python
apache__airflow
providers/celery/tests/unit/celery/cli/test_celery_command.py
{ "start": 16946, "end": 21959 }
class ____: @classmethod def setup_class(cls): with conf_vars({("core", "executor"): "CeleryExecutor"}): importlib.reload(executor_loader) importlib.reload(cli_parser) cls.parser = cli_parser.get_parser() @pytest.mark.db_test @mock.patch("airflow.providers.ce...
TestRemoteCeleryControlCommands
python
pytorch__pytorch
test/fx/quantization.py
{ "start": 3263, "end": 6103 }
class ____(MinMaxObserver): def __init__(self, quantizer, node): super().__init__(quantizer, node) self.relu_node, self.bn_node = None, None if isinstance(quantizer.modules[node.target], torch.nn.ReLU): self.relu_node = node node = node.args[0] if isinstance(q...
ConvNormRelu
python
kamyu104__LeetCode-Solutions
Python/data-stream-as-disjoint-intervals.py
{ "start": 201, "end": 1353 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.__intervals = [] def addNum(self, val): """ :type val: int :rtype: void """ def upper_bound(nums, target): left, right = 0, len(nums) - ...
SummaryRanges
python
django__django
tests/template_tests/syntax_tests/test_comment.py
{ "start": 68, "end": 3685 }
class ____(SimpleTestCase): @setup({"comment-syntax01": "{# this is hidden #}hello"}) def test_comment_syntax01(self): output = self.engine.render_to_string("comment-syntax01") self.assertEqual(output, "hello") @setup({"comment-syntax02": "{# this is hidden #}hello{# foo #}"}) def test_...
CommentSyntaxTests