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
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/base_streams.py
{ "start": 30841, "end": 41594 }
class ____(IncrementalShopifyStream): filter_field = "updated_at" cursor_field = "updated_at" data_field = "graphql" parent_stream_class: Optional[Union[ShopifyStream, IncrementalShopifyStream]] = None def __init__(self, config: Dict) -> None: super().__init__(config) # define BULK...
IncrementalShopifyGraphQlBulkStream
python
rapidsai__cudf
python/cudf_polars/cudf_polars/utils/config.py
{ "start": 33434, "end": 35362 }
class ____(str, enum.Enum): """ The policy to use for acquiring new CUDA streams. * ``CUDAStreamPolicy.DEFAULT`` : Use the default CUDA stream. * ``CUDAStreamPolicy.NEW`` : Create a new CUDA stream. """ DEFAULT = "default" NEW = "new" def _convert_cuda_stream_policy( user_cuda_stream...
CUDAStreamPolicy
python
huggingface__transformers
src/transformers/models/conditional_detr/image_processing_conditional_detr.py
{ "start": 29363, "end": 80160 }
class ____(BaseImageProcessor): r""" Constructs a Conditional Detr image processor. Args: format (`str`, *optional*, defaults to `"coco_detection"`): Data format of the annotations. One of "coco_detection" or "coco_panoptic". do_resize (`bool`, *optional*, defaults to `True`): ...
ConditionalDetrImageProcessor
python
ray-project__ray
rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py
{ "start": 374, "end": 3880 }
class ____(ConnectorV2): """Adds the NEXT_OBS column with the correct episode observations to train batch. - Operates on a list of Episode objects. - Gets all observation(s) from all the given episodes (except the very first ones) and adds them to the batch under construction in the NEXT_OBS column (as...
AddNextObservationsFromEpisodesToTrainBatch
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_storage_version_migration_list.py
{ "start": 383, "end": 7360 }
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...
V1alpha1StorageVersionMigrationList
python
mlflow__mlflow
tests/pyfunc/test_chat_model.py
{ "start": 4236, "end": 4551 }
class ____(mlflow.pyfunc.ChatModel): @mlflow.trace def predict( self, context, messages: list[ChatMessage], params: ChatParams ) -> ChatCompletionResponse: mock_response = get_mock_response(messages, params) return ChatCompletionResponse.from_dict(mock_response)
ChatModelWithTrace
python
getsentry__sentry
tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_crash_free_rate_healthy.py
{ "start": 5523, "end": 12943 }
class ____(TestCase): def setUp(self) -> None: self.project1 = self.create_project(name="foo", organization=self.organization) self.release1 = Release.objects.create(version="v1", organization=self.organization) self.sessions_data = mock_sessions_data @patch( "sentry.api.endpoin...
CrashFreeRateThresholdCheckTest
python
getsentry__sentry
tests/sentry/seer/autofix/test_autofix.py
{ "start": 18661, "end": 26085 }
class ____(APITestCase, SnubaTestCase): @patch("sentry.seer.explorer.utils.get_from_profiling_service") def test_get_profile_from_trace_tree_basic(self, mock_get_from_profiling_service) -> None: """Test finding a profile for a matching transaction in trace tree.""" # Setup mock event with transa...
TestGetProfileFromTraceTree
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 485250, "end": 485759 }
class ____(sgqlc.types.Type): """Autogenerated return type of CancelSponsorship""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "sponsors_tier") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing th...
CancelSponsorshipPayload
python
kamyu104__LeetCode-Solutions
Python/count-triplets-with-even-xor-set-bits-i.py
{ "start": 93, "end": 742 }
class ____(object): def tripletCount(self, a, b, c): """ :type a: List[int] :type b: List[int] :type c: List[int] :rtype: int """ def popcount(x): return bin(x).count('1') def count(a): odd = sum(popcount(x)&1 for x in a) ...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/decorator4.py
{ "start": 406, "end": 628 }
class ____: def __init__(self, a, b, c): pass v1 = ClassA(1, 2, 3) reveal_type(v1, expected_text="ClassA") @decorator1 def func1() -> int: return 3 v2 = func1() reveal_type(v2, expected_text="int")
ClassA
python
ansible__ansible
test/units/module_utils/basic/test_no_log.py
{ "start": 1694, "end": 6085 }
class ____: OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' dataset_no_remove = ( ('string', frozenset(['nope'])), (1234, frozenset(['4321'])), (False, frozenset(['4321'])), (1.0, frozenset(['4321'])), (['string', 'strang', 'strung'], frozenset(['nope'])), ({'one': 1...
TestRemoveValues
python
ray-project__ray
python/ray/_private/event/export_event_logger.py
{ "start": 1096, "end": 3006 }
class ____(Enum): """Enum class representing different types of export event logs. Each enum value contains a log type name and a set of supported event data types. Attributes: TRAIN_STATE: Export events related to training state, supporting train run and attempt events. SUBMISSION_JOB: Ex...
EventLogType
python
openai__openai-python
src/openai/types/responses/response_reasoning_item_param.py
{ "start": 520, "end": 744 }
class ____(TypedDict, total=False): text: Required[str] """The reasoning text from the model.""" type: Required[Literal["reasoning_text"]] """The type of the reasoning text. Always `reasoning_text`."""
Content
python
ray-project__ray
python/ray/_private/metrics_agent.py
{ "start": 1684, "end": 5083 }
class ____(View): """Gauge representation of opencensus view. This class is used to collect process metrics from the reporter agent. Cpp metrics should be collected in a different way. """ def __init__(self, name, description, unit, tags: List[str]): if _is_invalid_metric_name(name): ...
Gauge
python
numba__numba
numba/tests/test_random.py
{ "start": 65375, "end": 67866 }
class ____(ConcurrencyBaseTest): """ Check the PRNG behaves well in child processes. """ # Avoid nested multiprocessing AssertionError # ("daemonic processes are not allowed to have children") _numba_parallel_test_ = False def extract_in_processes(self, nprocs, extract_randomness): ...
TestProcesses
python
apache__airflow
dev/breeze/tests/test_ui_commands.py
{ "start": 3161, "end": 6378 }
class ____: def test_compare_keys_identical(self, tmp_path): # Create temporary locale files en_dir = tmp_path / "en" en_dir.mkdir() de_dir = tmp_path / "de" de_dir.mkdir() test_data = {"greeting": "Hello", "farewell": "Goodbye"} (en_dir / "test.json").write...
TestCompareKeys
python
tensorflow__tensorflow
tensorflow/python/keras/constraints.py
{ "start": 5583, "end": 7620 }
class ____(Constraint): """MinMaxNorm weight constraint. Constrains the weights incident to each hidden unit to have the norm between a lower bound and an upper bound. Also available via the shortcut function `tf.keras.constraints.min_max_norm`. Args: min_value: the minimum norm for the incoming weight...
MinMaxNorm
python
modin-project__modin
modin/tests/pandas/native_df_interoperability/test_compiler_caster.py
{ "start": 7264, "end": 7877 }
class ____(CalculatorTestQc): "Represents a query compiler which knows a lot, and wants to avoid work" def get_backend(self): return "Lazy" # encorage other engines to take my workload def move_to_cost(self, other_qc_cls, api_cls_name, op, arguments): return QCCoercionCost.COST_ZERO ...
OmniscientLazyQC
python
pytorch__pytorch
torch/nn/modules/fold.py
{ "start": 164, "end": 6671 }
class ____(Module): ( r"""Combines an array of sliding local blocks into a large containing tensor. Consider a batched :attr:`input` tensor containing sliding local blocks, e.g., patches of images, of shape :math:`(N, C \times \prod(\text{kernel\_size}), L)`, where :math:`N` is batch dimension...
Fold
python
psf__black
tests/data/cases/docstring_no_string_normalization.py
{ "start": 37, "end": 1814 }
class ____: ''' A multiline class docstring. ''' def AnEquallyLonelyMethod(self): ''' A multiline method docstring''' pass def one_function(): '''This is a docstring with a single line of text.''' pass def shockingly_the_quotes_are_normalized(): '''This is a multi...
ALonelyClass
python
google__jax
tests/pallas/tpu_pallas_test.py
{ "start": 2547, "end": 2895 }
class ____(jtu.JaxTestCase): INTERPRET: bool = False def setUp(self): if not jtu.test_device_matches(['tpu']) and not self.INTERPRET: self.skipTest('Test requires TPUs, or interpret mode') super().setUp() def pallas_call(self, *args, **kwargs): return pl.pallas_call(*args, **kwargs, interpret=...
PallasBaseTest
python
streamlit__streamlit
lib/tests/streamlit/runtime/state/test_presentation.py
{ "start": 1163, "end": 12636 }
class ____: def __init__(self) -> None: self._new_widget_state = _FakeWStates() def _get_widget_metadata(self, widget_id: str) -> WidgetMetadata[Any] | None: return self._new_widget_state.widget_metadata.get(widget_id) def test_apply_presenter_returns_base_when_no_meta() -> None: """Retur...
_FakeSession
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 77572, "end": 80783 }
class ____(ThreadedCANSocketTest): def __init__(self, methodName='runTest'): ThreadedCANSocketTest.__init__(self, methodName=methodName) @classmethod def build_can_frame(cls, can_id, data): """Build a CAN frame.""" can_dlc = len(data) data = data.ljust(8, b'\x00') r...
CANTest
python
pypa__pipenv
pipenv/vendor/click/exceptions.py
{ "start": 2523, "end": 4137 }
class ____(UsageError): """An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is). .. versionadded:: 2.0 :param param: the parame...
BadParameter
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 127891, "end": 129463 }
class ____(TypedDict, total=False): name: Required[str] schema: Required[CoreSchema] mode: Literal[ 'positional_only', 'positional_or_keyword', 'keyword_only', 'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict', ] # default positional_or_k...
ArgumentsV3Parameter
python
django__django
django/contrib/auth/forms.py
{ "start": 1944, "end": 2701 }
class ____(forms.CharField): def to_python(self, value): value = super().to_python(value) if self.max_length is not None and len(value) > self.max_length: # Normalization can increase the string length (e.g. # "ff" -> "ff", "½" -> "1⁄2") but cannot reduce it, so there is no ...
UsernameField
python
great-expectations__great_expectations
great_expectations/datasource/fluent/alloy_datasource.py
{ "start": 358, "end": 984 }
class ____(SQLDatasource): """Adds an alloy datasource to the data context. Args: name: The name of this alloy datasource. connection_string: The connection string used to connect to the postgres database. For example: "postgresql+psycopg2://<username>:<password>@<hostname>:<port>/<...
AlloyDatasource
python
pandas-dev__pandas
asv_bench/benchmarks/rolling.py
{ "start": 10461, "end": 10777 }
class ____: params = ["var", "std", "cov", "corr"] param_names = ["method"] def setup(self, method): df = pd.DataFrame({"A": range(50), "B": range(50)}) self.gb_ewm = df.groupby("A").ewm(com=1.0) def time_groupby_method(self, method): getattr(self.gb_ewm, method)()
GroupbyEWM
python
ipython__ipython
IPython/lib/demo.py
{ "start": 21775, "end": 22608 }
class ____: """Use this mixin to make Demo classes with less visual clutter. Demos using this mixin will clear the screen before every block and use blank marquees. Note that in order for the methods defined here to actually override those of the classes it's mixed with, it must go /first/ in the ...
ClearMixin
python
google__jax
jax/experimental/jax2tf/tests/call_tf_test.py
{ "start": 30868, "end": 40538 }
class ____(tf_test_util.JaxToTfTestCase): """Reloading output of jax2tf into JAX with call_tf.""" def setUp(self): if tf is None: raise unittest.SkipTest("Test requires tensorflow") # TODO(b/171320191): this line works around a missing context initialization # bug in TensorFlow. _ = tf.add(1,...
RoundTripToJaxTest
python
walkccc__LeetCode
solutions/1027. Longest Arithmetic Subsequence/1027.py
{ "start": 0, "end": 426 }
class ____: def longestArithSeqLength(self, nums: list[int]) -> int: n = len(nums) ans = 0 # dp[i][k] := the length of the longest arithmetic subsequence of nums[0..i] # with k = diff + 500 dp = [[0] * 1001 for _ in range(n)] for i in range(n): for j in range(i): k = nums[i] - n...
Solution
python
agronholm__apscheduler
src/apscheduler/triggers/cron/expressions.py
{ "start": 903, "end": 2109 }
class ____: value_re: ClassVar[Pattern] = re.compile(r"\*(?:/(?P<step>\d+))?$") step: int | None = attrs.field( converter=as_int, validator=optional([instance_of(int), positive_number]), default=None, ) def validate_range(self, field_name: str, min_value: int, max_value: int) -...
AllExpression
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 3058, "end": 3464 }
class ____: code: str msg_template: str def __init__(self, **ctx: Any) -> None: self.__dict__ = ctx def __str__(self) -> str: return self.msg_template.format(**self.__dict__) def __reduce__(self) -> Tuple[Callable[..., 'PydanticErrorMixin'], Tuple[Type['PydanticErrorMixin'], 'Dict...
PydanticErrorMixin
python
numba__numba
numba/cuda/simulator/cudadrv/devicearray.py
{ "start": 3378, "end": 13789 }
class ____(object): ''' Implements the interface of a DeviceArray/DeviceRecord, but mostly just wraps a NumPy array. ''' __cuda_ndarray__ = True # There must be gpu_data attribute def __init__(self, ary, stream=0): self._ary = ary self.stream = stream @property def al...
FakeCUDAArray
python
scrapy__scrapy
tests/spiders.py
{ "start": 10338, "end": 11150 }
class ____(MetaSpider): seed = None callback_func = None errback_func = None async def start(self): if isinstance(self.seed, Request): yield self.seed.replace(callback=self.parse, errback=self.on_error) else: yield Request(self.seed, callback=self.parse, errback=...
SingleRequestSpider
python
doocs__leetcode
solution/1500-1599/1582.Special Positions in a Binary Matrix/Solution.py
{ "start": 0, "end": 447 }
class ____: def numSpecial(self, mat: List[List[int]]) -> int: rows = [0] * len(mat) cols = [0] * len(mat[0]) for i, row in enumerate(mat): for j, x in enumerate(row): rows[i] += x cols[j] += x ans = 0 for i, row in enumerate(mat): ...
Solution
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 16786, "end": 17275 }
class ____(_HTTPMove): """ subclass of :class:`~_HTTPMove` This indicates that the requested resource corresponds to any one of a set of representations, each with its own specific location, and agent-driven negotiation information is being provided so that the user can select a preferred repre...
HTTPMultipleChoices
python
getsentry__sentry
tests/sentry/receivers/outbox/test_control.py
{ "start": 594, "end": 3246 }
class ____(TestCase): identifier = 1 @patch("sentry.receivers.outbox.control.maybe_process_tombstone") def test_process_integration_updates(self, mock_maybe_process: MagicMock) -> None: process_integration_updates( object_identifier=self.identifier, region_name=_TEST_REGION.name ...
ProcessControlOutboxTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/test/utils.py
{ "start": 1244, "end": 1300 }
class ____(TypedDict): path: Sequence[str]
GqlAssetKey
python
aio-libs__aiohttp
aiohttp/payload.py
{ "start": 1001, "end": 1108 }
class ____(Exception): """Raised when no payload factory is found for the given data type."""
LookupError
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_vision.py
{ "start": 29980, "end": 31345 }
class ____(PreTrainedModel): config: Data2VecVisionConfig base_model_prefix = "data2vec_vision" input_modalities = ("image",) main_input_name = "pixel_values" supports_gradient_checkpointing = True _no_split_modules = ["Data2VecVisionLayer"] _keys_to_ignore_on_load_unexpected = [r".*relative...
Data2VecVisionPreTrainedModel
python
ray-project__ray
python/ray/serve/tests/common/test_modules.py
{ "start": 867, "end": 1588 }
class ____: def __init__( self, m1: DeploymentHandle, m2: Union[DeploymentHandle, Dict[str, DeploymentHandle]], m2_nested: bool = False, ): self.m1 = m1 self.m2 = m2.get(NESTED_HANDLE_KEY) if m2_nested else m2 async def __call__(self, req): if isinsta...
Combine
python
getsentry__sentry
src/sentry/issues/endpoints/project_performance_issue_settings.py
{ "start": 11573, "end": 16844 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUE_DETECTION_BACKEND publish_status = { "DELETE": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } permission_classes = (ProjectSettingPermission,) def has_feature(self, project, re...
ProjectPerformanceIssueSettingsEndpoint
python
spack__spack
lib/spack/spack/build_environment.py
{ "start": 36774, "end": 49276 }
class ____: """This class encapsulates the logic to determine environment modifications, and is used as well to set globals in modules of package.py.""" def __init__(self, *specs: spack.spec.Spec, context: Context) -> None: """Construct a ModificationsFromDag object. Args: specs...
SetupContext
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
{ "start": 2061, "end": 2116 }
class ____: Options = 'options_menu'
ArrayEditorMenus
python
huggingface__transformers
src/transformers/models/musicgen_melody/modeling_musicgen_melody.py
{ "start": 33630, "end": 57973 }
class ____(MusicgenMelodyPreTrainedModel, GenerationMixin): output_modalities = ("audio",) def __init__(self, config: MusicgenMelodyDecoderConfig): super().__init__(config) self.model = MusicgenMelodyModel(config) self.num_codebooks = config.num_codebooks self.lm_heads = nn.Mo...
MusicgenMelodyForCausalLM
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 64090, "end": 64721 }
class ____(base_classes.Names): def __init__(self, xl): self.xl = xl @property def api(self): return self.xl def __call__(self, name_or_index): return Name(xl=self.xl(name_or_index)) def contains(self, name_or_index): try: self.xl(name_or_index) ...
Names
python
huggingface__transformers
src/transformers/models/aria/modeling_aria.py
{ "start": 21562, "end": 23737 }
class ____(GradientCheckpointingLayer): """ Aria Text Decoder Layer. This class defines a single decoder layer in the language model, incorporating self-attention and Mixture of Experts (MoE) feed-forward network. Args: config (`AriaTextConfig`): Configuration object for the text c...
AriaTextDecoderLayer
python
huggingface__transformers
src/transformers/models/imagegpt/modeling_imagegpt.py
{ "start": 32832, "end": 37156 }
class ____(ImageGPTPreTrainedModel): def __init__(self, config: ImageGPTConfig): super().__init__(config) self.num_labels = config.num_labels self.transformer = ImageGPTModel(config) self.score = nn.Linear(config.n_embd, self.num_labels, bias=False) # Initialize weights and ...
ImageGPTForImageClassification
python
ray-project__ray
python/ray/data/tests/mock_http_server.py
{ "start": 423, "end": 2463 }
class ____(BaseHTTPRequestHandler): files = { "/index/data_file": data, "/index": index, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _respond(self, code=200, headers=None, data=b""): headers = headers or {} headers.update({"User-...
HTTPTestHandler
python
lepture__authlib
authlib/oauth2/rfc8628/errors.py
{ "start": 600, "end": 922 }
class ____(OAuth2Error): """The "device_code" has expired, and the device authorization session has concluded. The client MAY commence a new device authorization request but SHOULD wait for user interaction before restarting to avoid unnecessary polling. """ error = "expired_token"
ExpiredTokenError
python
psf__black
tests/data/cases/nested_stub.py
{ "start": 1070, "end": 1243 }
class ____: class Nested1: foo: int def bar(self): ... field = 1 class Nested2: def bar(self): ... foo: int field = 1
TopLevel
python
realpython__materials
django-vue-graphql/source_code_final/back_end/blog/admin.py
{ "start": 184, "end": 258 }
class ____(admin.ModelAdmin): model = Tag @admin.register(Post)
TagAdmin
python
run-llama__llama_index
llama-index-instrumentation/tests/test_dispatcher.py
{ "start": 1355, "end": 1593 }
class ____(BaseEventHandler): events: List[BaseEvent] = [] @classmethod def class_name(cls): return "_TestEventHandler" def handle(self, e: BaseEvent): # type:ignore self.events.append(e)
_TestEventHandler
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_neptune.py
{ "start": 2459, "end": 3662 }
class ____: def test_serialization(self): """ Asserts that the TaskStateTrigger correctly serializes its arguments and classpath. """ trigger = NeptuneClusterStoppedTrigger(db_cluster_id=CLUSTER_ID) classpath, kwargs = trigger.serialize() assert classpath == "...
TestNeptuneClusterStoppedTrigger
python
google__flatbuffers
tests/namespace_test/NamespaceC/TableInC.py
{ "start": 1987, "end": 3184 }
class ____(object): # TableInCT def __init__(self): self.referToA1 = None # type: Optional[TableInFirstNST] self.referToA2 = None # type: Optional[SecondTableInAT] @classmethod def InitFromBuf(cls, buf, pos): tableInC = TableInC() tableInC.Init(buf, pos) return cls.InitFromObj(tableInC) ...
TableInCT
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/with2.py
{ "start": 254, "end": 944 }
class ____(object): def __enter__(self: _T1) -> _T1: return self def __exit__( self, t: type | None = None, exc: BaseException | None = None, tb: Any | None = None, ) -> bool: return True def requires_int(val: int): pass def requires_class3(val: Class...
Class3
python
ray-project__ray
python/ray/tune/tests/_test_trial_runner_pg.py
{ "start": 482, "end": 9392 }
class ____(unittest.TestCase): def setUp(self): os.environ["TUNE_GLOBAL_CHECKPOINT_S"] = "10000" os.environ["TUNE_MAX_PENDING_TRIALS_PG"] = "auto" # Reset default self.head_cpus = 8 self.head_gpus = 4 self.head_custom = 16 self.cluster = Cluster( initial...
TrialRunnerPlacementGroupTest
python
huggingface__transformers
src/transformers/models/janus/modular_janus.py
{ "start": 31885, "end": 33740 }
class ____(ChameleonVQVAE): _no_split_modules = [ "JanusVQVAEAttnBlock", "JanusVQVAEResnetBlock", "JanusVQVAEVectorQuantizer", ] main_input_name = "pixel_values" def __init__(self, config: JanusVQVAEConfig): super().__init__(config) self.decoder = JanusVQVAEDecod...
JanusVQVAE
python
huggingface__transformers
src/transformers/models/janus/modeling_janus.py
{ "start": 32599, "end": 35694 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.num_resolutions = len(config.channel_multiplier) self.num_res_blocks = config.num_res_blocks base_channels = config.base_channels in_channels = config.in_channels double_latent = config.double...
JanusVQVAEEncoder
python
sqlalchemy__sqlalchemy
test/orm/dml/test_bulk_statements.py
{ "start": 38790, "end": 72141 }
class ____: use_sentinel = False randomize_returning = False def assert_for_downgrade(self, *, sort_by_parameter_order): if ( not sort_by_parameter_order or not self.randomize_returning or not testing.against(["postgresql", "mssql", "mariadb"]) ): ...
BulkDMLReturningInhTest
python
ray-project__ray
python/ray/train/v2/tests/test_metrics.py
{ "start": 628, "end": 9002 }
class ____: """Mock class for ray.util.metrics.Gauge.""" def __init__(self, name: str, description: str, tag_keys: tuple = ()): self._values: dict[set[str], float] = {} def set(self, value: float, tags: dict): self._values[frozenset(tags.items())] = value @pytest.fixture def mock_gauge(m...
MockGauge
python
huggingface__transformers
examples/modular-transformers/modeling_dummy_bert.py
{ "start": 22448, "end": 24453 }
class ____(PreTrainedModel): config_class = DummyBertConfig base_model_prefix = "dummy_bert" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _supports_attention_backend = True _can_record_outputs = { "hidden_stat...
DummyBertPreTrainedModel
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_stochastic_weight_avg.py
{ "start": 1879, "end": 3179 }
class ____(BoringModel): def __init__( self, batchnorm: bool = True, interval: str = "epoch", iterable_dataset: bool = False, crash_on_epoch=None ): super().__init__() layers = [nn.Linear(32, 32)] if batchnorm: layers.append(nn.BatchNorm1d(32)) layers += [nn.R...
SwaTestModel
python
pypa__pipenv
pipenv/utils/dependencies.py
{ "start": 3103, "end": 39601 }
class ____: """A hack, which allows us to tell resolver which version of Python we're using.""" def __init__(self, python_path): self.python_path = python_path def __enter__(self): if self.python_path: os.environ["PIP_PYTHON_PATH"] = str(self.python_path) def __exit__(self...
HackedPythonVersion
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 121840, "end": 126232 }
class ____(Warning): """ Base class for warning about deprecations in ``pkg_resources`` This class is not derived from ``DeprecationWarning``, and as such is visible by default. """ # Ported from ``setuptools`` to avoid introducing an import inter-dependency: _LOCALE_ENCODING = "locale" if sys.ve...
PkgResourcesDeprecationWarning
python
kamyu104__LeetCode-Solutions
Python/furthest-point-from-origin.py
{ "start": 36, "end": 401 }
class ____(object): def furthestDistanceFromOrigin(self, moves): """ :type moves: str :rtype: int """ curr = cnt = 0 for x in moves: if x == 'L': curr -= 1 elif x == 'R': curr += 1 else: ...
Solution
python
graphql-python__graphene
graphene/types/structures.py
{ "start": 1734, "end": 3121 }
class ____(Structure): """ Non-Null Modifier A non-null is a kind of type marker, a wrapping type which points to another type. Non-null types enforce that their values are never null and can ensure an error is raised if this ever occurs during a request. It is useful for fields which you can m...
NonNull
python
numba__numba
numba/core/typeinfer.py
{ "start": 29650, "end": 30752 }
class ____(SetItemRefinement): def __init__(self, target, index, value, loc): self.target = target self.index = index self.value = value self.loc = loc def __call__(self, typeinfer): with new_error_context("typing of setitem at {loc}", loc=self.loc): typevars...
SetItemConstraint
python
ray-project__ray
python/ray/dashboard/modules/reporter/gpu_providers.py
{ "start": 13522, "end": 16900 }
class ____(GpuProvider): """AMD GPU provider using pyamdsmi.""" def __init__(self): super().__init__() self._pyamdsmi = None def get_provider_name(self) -> GpuProviderType: return GpuProviderType.AMD def is_available(self) -> bool: """Check if AMD GPUs are available.""...
AmdGpuProvider
python
allegroai__clearml
clearml/storage/helper.py
{ "start": 42280, "end": 58574 }
class ____(_Driver): scheme = "azure" _containers = {} _max_connections = deferred_config("azure.storage.max_connections", 0) class _Container(object): def __init__( self, name: str, config: AzureContainerConfigurations, account_url: str, ...
_AzureBlobServiceStorageDriver
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/bedrock.py
{ "start": 3964, "end": 5423 }
class ____(AwsBaseWaiterTrigger): """ Trigger when a provisioned throughput job is complete. :param provisioned_model_id: The ARN or name of the provisioned throughput. :param waiter_delay: The amount of time in seconds to wait between attempts. (default: 120) :param waiter_max_attempts: The maxim...
BedrockProvisionModelThroughputCompletedTrigger
python
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 5834, "end": 6003 }
class ____: concurrency: int _BatchMode: TypeAlias = Union[ _DynamicBatching, _FixedSizeBatching, _RateLimitedBatching, _ServerSideBatching ]
_ServerSideBatching
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 1278, "end": 1731 }
class ____: params = ["int", "datetime"] param_names = ["dtype"] def setup(self, dtype): N = 10**6 data = { "int": np.random.randint(1, 10, N), "datetime": date_range("2000-01-01", freq="s", periods=N), } self.s = Series(data[dtype]) if dtype ...
Dropna
python
walkccc__LeetCode
solutions/1672. Richest Customer Wealth/1672.py
{ "start": 0, "end": 112 }
class ____: def maximumWealth(self, accounts: list[list[int]]) -> int: return max(map(sum, accounts))
Solution
python
getsentry__sentry
src/sentry/api/endpoints/project_rule_enable.py
{ "start": 708, "end": 2705 }
class ____(ProjectEndpoint): publish_status = { "PUT": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ISSUES permission_classes = (ProjectAlertRulePermission,) def put(self, request: Request, project, rule_id) -> Response: try: rule = Rule.objects.get(id=rule_id, proj...
ProjectRuleEnableEndpoint
python
openai__openai-python
tests/api_resources/fine_tuning/test_jobs.py
{ "start": 482, "end": 13404 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.create( model="gpt-4o-mini", training_file="file-abc123", ...
TestJobs
python
docker__docker-py
docker/api/swarm.py
{ "start": 198, "end": 18089 }
class ____: def create_swarm_spec(self, *args, **kwargs): """ Create a :py:class:`docker.types.SwarmSpec` instance that can be used as the ``swarm_spec`` argument in :py:meth:`~docker.api.swarm.SwarmApiMixin.init_swarm`. Args: task_history_retention_limit (int):...
SwarmApiMixin
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/bytes.py
{ "start": 3218, "end": 3992 }
class ____(DTypeConfig_V2[Literal["|O"], Literal["vlen-bytes"]]): """ A wrapper around the JSON representation of the ``VariableLengthBytes`` data type in Zarr V2. The ``name`` field of this class contains the value that would appear under the ``dtype`` field in Zarr V2 array metadata. The ``object_cod...
VariableLengthBytesJSON_V2
python
huggingface__transformers
src/transformers/models/align/modeling_align.py
{ "start": 22832, "end": 25311 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention...
AlignTextSelfAttention
python
google__jax
docs/autodidax.py
{ "start": 16910, "end": 22473 }
class ____(Trace): pure = lift = lambda self, val: JVPTracer(self, val, zeros_like(val)) def process_primitive(self, primitive, tracers, params): primals_in, tangents_in = unzip2((t.primal, t.tangent) for t in tracers) jvp_rule = jvp_rules[primitive] primal_outs, tangent_outs = jvp_rule(primals_in, tan...
JVPTrace
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/win32_types.py
{ "start": 5151, "end": 5551 }
class ____(Structure): """ http://msdn.microsoft.com/en-us/library/windows/desktop/aa379560(v=vs.85).aspx """ if TYPE_CHECKING: nLength: int lpSecurityDescriptor: int bInheritHandle: int # BOOL comes back as 'int'. _fields_ = [ ("nLength", DWORD), ("lpSecur...
SECURITY_ATTRIBUTES
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 3662, "end": 3927 }
class ____(Event): name: str = "create_registered_model" @classmethod def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None: tags = arguments.get("tags") or {} return {"is_prompt": _is_prompt(tags)}
CreateRegisteredModelEvent
python
walkccc__LeetCode
solutions/828. Count Unique Characters of All Substrings of a Given String/828-2.py
{ "start": 0, "end": 628 }
class ____: def uniqueLetterString(self, s: str) -> int: ans = 0 # lastSeen[c] := the index of the last time ('a' + i) appeared lastSeen = collections.defaultdict(lambda: -1) # prevSeen[c] := the previous index of the last time ('a' + i) appeared prevLastSeen = collections.defaultdict(lambda: -1) ...
Solution
python
ray-project__ray
python/ray/autoscaler/_private/gcp/node_provider.py
{ "start": 1818, "end": 12623 }
class ____(NodeProvider): def __init__(self, provider_config: dict, cluster_name: str): NodeProvider.__init__(self, provider_config, cluster_name) self.lock = RLock() self._construct_clients() self.cache_stopped_nodes = provider_config.get("cache_stopped_nodes", False) # Cac...
GCPNodeProvider
python
lxml__lxml
src/lxml/tests/test_external_document.py
{ "start": 230, "end": 4748 }
class ____(HelperTestCase): def setUp(self): try: import ctypes from ctypes import pythonapi from ctypes.util import find_library except ImportError: raise unittest.SkipTest("ctypes support missing") def wrap(func, restype, *argtypes): ...
ExternalDocumentTestCase
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 1305, "end": 2055 }
class ____(Operation): def call(self, x): return backend.nn.relu6(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.relu6", "keras.ops.nn.relu6"]) def relu6(x): """Rectified linear unit activation function with upper bound of 6. ...
Relu6
python
django-haystack__django-haystack
test_haystack/test_utils.py
{ "start": 746, "end": 2238 }
class ____(TestCase): fixtures = ["base_data"] def test_get_identifier(self): self.assertEqual(get_identifier("core.mockmodel.1"), "core.mockmodel.1") # Valid object. mock = MockModel.objects.get(pk=1) self.assertEqual(get_identifier(mock), "core.mockmodel.1") @override_se...
GetFacetFieldNameTestCase
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 7981, "end": 10210 }
class ____(BaseModel): name: str subaccounts: list[Account] = [] """ ) Account = module.Account assert Account.model_json_schema() == { '$ref': '#/$defs/Account', '$defs': { 'Account': { 'title': 'Account', 'type': 'object', ...
Account
python
kamyu104__LeetCode-Solutions
Python/detect-cycles-in-2d-grid.py
{ "start": 521, "end": 1549 }
class ____(object): def containsCycle(self, grid): """ :type grid: List[List[str]] :rtype: bool """ def index(n, i, j): return i*n + j union_find = UnionFind(len(grid)*len(grid[0])) for i in xrange(len(grid)): for j in xrange(len(g...
Solution
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/settings.py
{ "start": 7955, "end": 8626 }
class ____(Enum): UNIFORM: str = "uniform" GAUSSIAN: str = "gaussian" MULTIRANGEUNIFORM: str = "multirangeuniform" CONSTANT: str = "constant" def to_settings(self) -> type: _mapping = { ParameterRandomizationType.UNIFORM: UniformSettings, ParameterRandomizationType.G...
ParameterRandomizationType
python
dask__dask
dask/array/_array_expr/random.py
{ "start": 37059, "end": 39911 }
class ____(RandomChoice): _defaults = {} @cached_property def state_data(self): return _spawn_bitgens(self._state, len(self.sizes)) def _layer(self) -> dict: return { k: ( _choice_rng, bitgen, self.array, size,...
RandomChoiceGenerator
python
walkccc__LeetCode
solutions/2182. Construct String With Repeat Limit/2182.py
{ "start": 0, "end": 792 }
class ____: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: ans = '' count = collections.Counter(s) while True: addOne = ans and self._shouldAddOne(ans, count) c = self._getLargestChar(ans, count) if c == ' ': break repeats = 1 if addOne else min(count[c], ...
Solution
python
django__django
tests/select_related_onetoone/models.py
{ "start": 880, "end": 1023 }
class ____(models.Model): name = models.CharField(max_length=100) image = models.OneToOneField(Image, models.SET_NULL, null=True)
Product
python
PyCQA__pylint
tests/functional/u/used/used_before_assignment_typing.py
{ "start": 4844, "end": 5044 }
class ____: # pylint: disable=too-few-public-methods """Conditional imports also guarded by TYPE_CHECKING when used.""" if TYPE_CHECKING: print(urlopen)
ConditionalImportGuardedWhenUsed
python
pytorch__pytorch
test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py
{ "start": 48248, "end": 50718 }
class ____(TestCase): def setUp(self) -> None: self._run_id = "dummy_run_id" self._store = DummyStore() self._backend = DummyRendezvousBackend() self._min_nodes = 3 self._max_nodes = 6 self._timeout: Optional[RendezvousTimeout] = RendezvousTimeout() def _create_h...
DynamicRendezvousHandlerFromBackendTest
python
pydata__xarray
xarray/backends/file_manager.py
{ "start": 16239, "end": 16950 }
class ____(FileManager[T_File]): """FileManager that simply wraps an open file in the FileManager interface.""" def __init__(self, value: T_File, *, close: Callable[[], None] | None = None): if close is None: close = value.close self._value = value self._close = close d...
DummyFileManager
python
doocs__leetcode
solution/2600-2699/2671.Frequency Tracker/Solution.py
{ "start": 0, "end": 750 }
class ____: def __init__(self): self.cnt = defaultdict(int) self.freq = defaultdict(int) def add(self, number: int) -> None: self.freq[self.cnt[number]] -= 1 self.cnt[number] += 1 self.freq[self.cnt[number]] += 1 def deleteOne(self, number: int) -> None: if ...
FrequencyTracker
python
getsentry__sentry
src/sentry/remote_subscriptions/apps.py
{ "start": 36, "end": 145 }
class ____(AppConfig): name = "sentry.remote_subscriptions" def ready(self) -> None: pass
Config