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
sympy__sympy
sympy/stats/rv.py
{ "start": 8632, "end": 9616 }
class ____(RandomSymbol): def __new__(cls, idx_obj, pspace=None): if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() if not isinstance(idx_obj, (Indexed, Function)): raise TypeError("An Function or Indexed object is expected ...
RandomIndexedSymbol
python
mlflow__mlflow
mlflow/pytorch/__init__.py
{ "start": 26519, "end": 45803 }
class ____: """ Wrapper class that creates a predict function such that predict(data: pd.DataFrame) -> model's output as pd.DataFrame (pandas DataFrame) """ def __init__(self, pytorch_model, device): self.pytorch_model = pytorch_model self.device = device self._is_forecastin...
_PyTorchWrapper
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 113437, "end": 114289 }
class ____(Operation): def call(self, x1, x2): return backend.numpy.greater_equal(x1, x2) def compute_output_spec(self, x1, x2): x1_shape = getattr(x1, "shape", []) x2_shape = getattr(x2, "shape", []) output_shape = broadcast_shapes(x1_shape, x2_shape) return KerasTensor...
GreaterEqual
python
ray-project__ray
rllib/utils/replay_buffers/base.py
{ "start": 158, "end": 2271 }
class ____(metaclass=ABCMeta): """Abstract base class for all of RLlib's replay buffers. Mainly defines the `add()` and `sample()` methods that every buffer class must implement to be usable by an Algorithm. Buffers may determine on all the implementation details themselves, e.g. whether to store s...
ReplayBufferInterface
python
openai__openai-python
src/openai/_base_client.py
{ "start": 10410, "end": 27818 }
class ____(Generic[_HttpxClientT, _DefaultStreamT]): _client: _HttpxClientT _version: str _base_url: URL max_retries: int timeout: Union[float, Timeout, None] _strict_response_validation: bool _idempotency_header: str | None _default_stream_cls: type[_DefaultStreamT] | None = None d...
BaseClient
python
coleifer__peewee
tests/transactions.py
{ "start": 11295, "end": 13711 }
class ____(BaseTransactionTestCase): @skip_unless(IS_POSTGRESQL, 'requires postgresql') def test_isolation_level_pg(self): db2 = new_connection() db2.connect() with db2.atomic(isolation_level='SERIALIZABLE'): with db.atomic(isolation_level='SERIALIZABLE'): se...
TestTransactionIsolationLevel
python
pytorch__pytorch
test/inductor/test_fx_fusion.py
{ "start": 1335, "end": 5982 }
class ____(TestCase): def test_sink_cat_after_pointwise(self): def test_kwarg(x, y): return torch.cat([x, y], dim=-1).view(-1).view(128).tanh() def test_arg(x, y): return torch.cat([x, y], -1).view(-1).view(128).tanh() def test_arg2(x, y): return torch.c...
TestFxFusion
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py
{ "start": 16678, "end": 17760 }
class ____(Benchmark): r""" Price 1 objective function. This class defines the Price 1 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Price01}}(x) = (\lvert x_1 \rvert - 5)^2 + (\lvert x_2 \rvert - 5)^2 wit...
Price01
python
openai__openai-python
src/openai/types/shared_params/response_format_json_schema.py
{ "start": 1239, "end": 1529 }
class ____(TypedDict, total=False): json_schema: Required[JSONSchema] """Structured Outputs configuration options, including a JSON Schema.""" type: Required[Literal["json_schema"]] """The type of response format being defined. Always `json_schema`."""
ResponseFormatJSONSchema
python
pytorch__pytorch
test/functorch/test_parsing.py
{ "start": 2169, "end": 7527 }
class ____(TestCase): def test_elementary_axis_name(self) -> None: for name in [ "a", "b", "h", "dx", "h1", "zz", "i9123", "somelongname", "Alex", "camelCase", "u_n_d_e_r_score...
TestParsedExpression
python
pytest-dev__pytest
testing/test_subtests.py
{ "start": 23237, "end": 26826 }
class ____: def create_file(self, pytester: pytest.Pytester) -> None: pytester.makepyfile( """ import logging def test_foo(subtests): logging.info("before") with subtests.test("sub1"): print("sub1 stdout") ...
TestLogging
python
PyCQA__pylint
tests/functional/r/regression/regression_property_no_member_2641.py
{ "start": 690, "end": 919 }
class ____(Person): def __init__(self, name, age, tel): super().__init__(name, age) self.tel = tel MS = Myself("Matheus Saraiva", 36, "988070350") WI = Wife("Joice Saraiva", 34, "999923554") print(WI.name)
Wife
python
facebookresearch__faiss
faiss/gpu/test/test_contrib_gpu.py
{ "start": 3160, "end": 4431 }
class ____(unittest.TestCase): def do_test(self, factory_string): ds = datasets.SyntheticDataset(32, 2000, 4000, 1000) k = 10 index = faiss.index_factory(ds.d, factory_string) index.train(ds.get_train()) index.add(ds.get_database()) index.nprobe = 5 Dref, Ire...
TestBigBatchSearch
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py
{ "start": 514, "end": 6844 }
class ____(OrderedDict): def __init__(self, types): super(GraphQLTypeMap, self).__init__() self.update(reduce(self.reducer, types, OrderedDict())) self._possible_type_map = defaultdict(set) # Keep track of all implementations by interface name. self._implementations = {} ...
GraphQLTypeMap
python
docker__docker-py
tests/unit/utils_proxy_test.py
{ "start": 465, "end": 2784 }
class ____(unittest.TestCase): def test_from_dict(self): config = ProxyConfig.from_dict({ 'httpProxy': HTTP, 'httpsProxy': HTTPS, 'ftpProxy': FTP, 'noProxy': NO_PROXY }) self.assertEqual(CONFIG.http, config.http) self.assertEqual(CONFI...
ProxyConfigTest
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/literal.py
{ "start": 599, "end": 2208 }
class ____(Expr): __slots__ = ("value",) _non_child = ("dtype", "value") value: Any # Python scalar def __init__(self, dtype: DataType, value: Any) -> None: if value is None and dtype.id() == plc.TypeId.EMPTY: # TypeId.EMPTY not supported by libcudf # cuDF Python also m...
Literal
python
openai__openai-python
src/openai/types/chat/chat_completion_assistant_message_param.py
{ "start": 1334, "end": 2441 }
class ____(TypedDict, total=False): role: Required[Literal["assistant"]] """The role of the messages author, in this case `assistant`.""" audio: Optional[Audio] """ Data about a previous audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio). """ con...
ChatCompletionAssistantMessageParam
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_sqs.py
{ "start": 3717, "end": 4724 }
class ____: @pytest.mark.usefixtures("collect_queue_param_deprecation_warning") def test_provider_integrations_with_queue_param(self, cleanup_providers_manager): queue = "https://sqs.us-east-1.amazonaws.com/0123456789/Test" from airflow.providers.amazon.aws.triggers.sqs import SqsSensorTrigger ...
TestMessageQueueTrigger
python
RaRe-Technologies__gensim
gensim/corpora/hashdictionary.py
{ "start": 1212, "end": 13212 }
class ____(utils.SaveLoad, dict): """Mapping between words and their integer ids, using a hashing function. Unlike :class:`~gensim.corpora.dictionary.Dictionary`, building a :class:`~gensim.corpora.hashdictionary.HashDictionary` before using it **isn't a necessary step**. You can start converting word...
HashDictionary
python
TheAlgorithms__Python
data_structures/binary_tree/binary_tree_traversals.py
{ "start": 198, "end": 5536 }
class ____: data: int left: Node | None = None right: Node | None = None def make_tree() -> Node | None: r""" The below tree 1 / \ 2 3 / \ 4 5 """ tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.ri...
Node
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_cloud_storage_transfer_service.py
{ "start": 3061, "end": 11575 }
class ____: def test_serialize(self, trigger): class_path, serialized = trigger.serialize() assert class_path == CLASS_PATH assert serialized == { "project_id": PROJECT_ID, "job_names": JOB_NAMES, "poll_interval": POLL_INTERVAL, "gcp_conn_id":...
TestCloudStorageTransferServiceCreateJobsTrigger
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 107398, "end": 107876 }
class ____(ModelOutput): """ Base class for time series model's predictions outputs that contains the sampled values from the chosen distribution. Args: sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length)` or `(batch_size, num_samples, prediction_length, input_...
SampleTSPredictionOutput
python
numba__numba
numba/tests/test_caching.py
{ "start": 5880, "end": 7758 }
class ____(TestCase): # The source file that will be copied usecases_file = None # Make sure this doesn't conflict with another module modname = None def setUp(self): self.tempdir = temp_directory('test_cache') sys.path.insert(0, self.tempdir) self.modfile = os.path.join(sel...
BaseCacheTest
python
django__django
django/views/generic/edit.py
{ "start": 5714, "end": 5843 }
class ____(TemplateResponseMixin, BaseFormView): """A view for displaying a form and rendering a template response."""
FormView
python
RaRe-Technologies__gensim
gensim/similarities/termsim.py
{ "start": 754, "end": 1912 }
class ____(SaveLoad): """ Base class = common interface for retrieving the most similar terms for a given term. See Also -------- :class:`~gensim.similarities.termsim.SparseTermSimilarityMatrix` A sparse term similarity matrix built using a term similarity index. """ def most_simil...
TermSimilarityIndex
python
ansible__ansible
lib/ansible/module_utils/_internal/_json/_profiles/_module_modern_c2m.py
{ "start": 212, "end": 1048 }
class ____(_profiles._JSONSerializationProfile["Encoder", "Decoder"]): encode_strings_as_utf8 = True @classmethod def post_init(cls) -> None: cls.serialize_map = {} cls.serialize_map.update(cls._common_discard_tags) cls.serialize_map.update( { # The bytes...
_Profile
python
huggingface__transformers
src/transformers/models/seamless_m4t/processing_seamless_m4t.py
{ "start": 955, "end": 1054 }
class ____(TextKwargs): src_lang: Optional[str] tgt_lang: Optional[str]
SeamlessM4TTextKwargs
python
astropy__astropy
astropy/coordinates/builtin_frames/hcrs.py
{ "start": 608, "end": 1610 }
class ____(BaseRADecFrame): """ A coordinate or frame in a Heliocentric system, with axes aligned to ICRS. The ICRS has an origin at the Barycenter and axes which are fixed with respect to space. This coordinate system is distinct from ICRS mainly in that it is relative to the Sun's center-of-...
HCRS
python
langchain-ai__langchain
libs/core/tests/unit_tests/runnables/test_configurable.py
{ "start": 1444, "end": 9148 }
class ____(RunnableSerializable[str, str]): my_other_property: str @override def invoke( self, input: str, config: RunnableConfig | None = None, **kwargs: Any ) -> Any: return input + self.my_other_property def my_other_custom_function(self) -> str: return self.my_other_pro...
MyOtherRunnable
python
cython__cython
Cython/Compiler/FlowControl.py
{ "start": 12648, "end": 12731 }
class ____: """Coming from outer closure, might be initialised or not."""
Unknown
python
getsentry__sentry
tests/sentry/issues/auto_source_code_config/test_process_event.py
{ "start": 27862, "end": 48353 }
class ____(LanguageSpecificDeriveCodeMappings): platform = "java" def test_extension_in_the_wrong_configuration(self) -> None: # We do not include the extension in the configuration to demostrate # that the correct platform -> extension mapping is needed with patch( "sentry....
TestJavaDeriveCodeMappings
python
doocs__leetcode
solution/1800-1899/1863.Sum of All Subset XOR Totals/Solution2.py
{ "start": 0, "end": 321 }
class ____: def subsetXORSum(self, nums: List[int]) -> int: def dfs(i: int, s: int): nonlocal ans if i >= len(nums): ans += s return dfs(i + 1, s) dfs(i + 1, s ^ nums[i]) ans = 0 dfs(0, 0) return ans
Solution
python
pytorch__pytorch
torch/testing/_internal/common_dist_composable.py
{ "start": 886, "end": 1335 }
class ____(nn.Module): def __init__(self, device: torch.device): super().__init__() self.l = nn.Linear(100, 100, device=device) self.seq = nn.Sequential( nn.ReLU(), nn.Linear(100, 100, device=device), nn.ReLU(), ) self.p = nn.Parameter(torc...
UnitParamModule
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py
{ "start": 1854, "end": 2802 }
class ____: """Represents an Airbyte connection, based on data as returned from the API.""" id: str name: str stream_prefix: Optional[str] streams: Mapping[str, "AirbyteStream"] destination_id: str @classmethod def from_connection_details( cls, connection_details: Mappi...
AirbyteConnection
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 3258, "end": 3525 }
class ____(str, _Action, Enum): CREATE = "create_tenants" READ = "read_tenants" UPDATE = "update_tenants" DELETE = "delete_tenants" @staticmethod def values() -> List[str]: return [action.value for action in TenantsAction]
TenantsAction
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-make-elements-in-array-distinct.py
{ "start": 46, "end": 463 }
class ____(object): def minimumOperations(self, nums): """ :type nums: List[int] :rtype: int """ def ceil_divide(a, b): return (a+b-1)//b mx = max(nums) cnt = [0]*mx for i in reversed(xrange(len(nums))): cnt[nums[i]-1] += 1 ...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchMapping1.py
{ "start": 1511, "end": 1600 }
class ____(TypedDict): title: str release_year: int gross_earnings: float
Movie
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 107339, "end": 111736 }
class ____(Metric): """Computes the element-wise (weighted) mean of the given tensors. `MeanTensor` returns a tensor with the same shape of the input tensors. The mean value is updated by keeping local variables `total` and `count`. The `total` tracks the sum of the weighted values, and `count` stores the sum ...
MeanTensor
python
great-expectations__great_expectations
tests/data_context/fixtures/plugins/extended_checkpoint.py
{ "start": 161, "end": 579 }
class ____(Checkpoint): def __init__( self, name: str, data_context, expectation_suite_name: Optional[str] = None, action_list: Optional[List[dict]] = None, ): super().__init__( name=name, data_context=data_context, expectation_...
ExtendedCheckpoint
python
pypa__warehouse
tests/unit/test_views.py
{ "start": 7568, "end": 11341 }
class ____: def test_logged_in_returns_exception(self, pyramid_config): renderer = pyramid_config.testing_add_renderer("403.html") exc = pretend.stub( status_code=403, status="403 Forbidden", headers={}, result=pretend.stub() ) request = pretend.stub(user=pretend.stub(),...
TestForbiddenView
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_sort.py
{ "start": 12603, "end": 16814 }
class ____(__TestCase): def test_safe_object_compare(self): heterogeneous_lists = [[0, 'foo'], [0.0, 'foo'], [('foo',), 'foo']] for L in heterogeneous_lists: self.assertRaises(TypeError, L.sort) self.assertRaises(T...
TestOptimizedCompares
python
psf__black
src/blib2to3/pgen2/grammar.py
{ "start": 839, "end": 6846 }
class ____: """Pgen parsing tables conversion class. Once initialized, this class supplies the grammar tables for the parsing engine implemented by parse.py. The parsing engine accesses the instance variables directly. The class here does not provide initialization of the tables; several subclass...
Grammar
python
pytorch__pytorch
test/export/test_db.py
{ "start": 627, "end": 3636 }
class ____(TestCase): # TODO Maybe we should make this tests actually show up in a file? @parametrize( "name,case", filter_examples_by_support_level(SupportLevel.SUPPORTED).items(), name_fn=lambda name, case: f"case_{name}", ) def test_exportdb_supported(self, name: str, case: Ex...
ExampleTests
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 623, "end": 728 }
class ____( # Comment on A. A, object, ): ... def f(): class A(object): ...
B
python
doocs__leetcode
solution/2000-2099/2049.Count Nodes With the Highest Score/Solution.py
{ "start": 0, "end": 720 }
class ____: def countHighestScoreNodes(self, parents: List[int]) -> int: def dfs(i: int, fa: int): cnt = score = 1 for j in g[i]: if j != fa: t = dfs(j, i) score *= t cnt += t if n - cnt: ...
Solution
python
facebook__pyre-check
tools/upgrade/errors.py
{ "start": 7790, "end": 13929 }
class ____: @classmethod def empty(cls) -> "Errors": return cls([]) @staticmethod def from_json( json_string: str, only_fix_error_code: Optional[int] = None, from_stdin: bool = False, ) -> "Errors": try: errors = json.loads(json_string) ...
Errors
python
tensorflow__tensorflow
tensorflow/python/training/saving/saveable_object_util_test.py
{ "start": 1252, "end": 1846 }
class ____(saveable_object.SaveableObject): def __init__(self, var, slice_spec, name): specs = [saveable_object.SaveSpec(var.read_value(), slice_spec, name)] super().__init__(var, specs, name) def restore(self, restored_tensors, restored_shapes): return self.op.assign(restored_tensors[0]) def _creat...
_VarSaveable
python
tensorflow__tensorflow
tensorflow/python/autograph/core/converter.py
{ "start": 8517, "end": 10711 }
class ____(transformer.Base): """All converters should inherit from this class. Attributes: ctx: EntityContext """ def __init__(self, ctx): super(Base, self).__init__(ctx) self._used = False self._ast_depth = 0 def get_definition_directive(self, node, directive, arg, default): """Retur...
Base
python
ray-project__ray
python/ray/data/_internal/execution/operators/actor_pool_map_operator.py
{ "start": 31426, "end": 48843 }
class ____(AutoscalingActorPool): """A pool of actors for map task execution. This class is in charge of tracking the number of in-flight tasks per actor, providing the least heavily loaded actor to the operator, and killing idle actors when the operator is done submitting work to the pool. """ ...
_ActorPool
python
google__jax
tests/mosaic/gpu_test.py
{ "start": 167081, "end": 192973 }
class ____(TestCase, jtu.JaxTestCase): """Device tests with lowering from the MLIR dialect and layout inference.""" def setUp(self): if mgpu_dialect is None: raise self.skipTest("Test requires Mosaic GPU dialect") super().setUp() @parameterized.product( layout=tuple(mtu.RegisterLayout), ...
MosaicGpuDialectTest
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 202133, "end": 204791 }
class ____(SocketTCPTest, ThreadableTest): def __init__(self, methodName='runTest'): SocketTCPTest.__init__(self, methodName=methodName) ThreadableTest.__init__(self) def clientSetUp(self): self.source_port = socket_helper.find_unused_port() def clientTearDown(self): self....
NetworkConnectionAttributesTest
python
etianen__django-reversion
tests/test_app/tests/test_commands.py
{ "start": 6055, "end": 6417 }
class ____(TestModelMixin, TestBase): databases = {"default", "postgres"} def testDeleteRevisionsModelDb(self): with reversion.create_revision(): TestModel.objects.db_manager("postgres").create() self.callCommand("deleterevisions", model_db="postgres") self.assertNoRevision(...
DeleteRevisionsModelDbTest
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 871, "end": 3752 }
class ____: def test_method(self): class Foo: @classmethod def classmethod(cls): pass def valid(self): pass def valid_kwargs(self, param='value'): pass def valid_vargs_kwargs(self, *args, **kwargs...
TestIsSimpleCallable
python
arrow-py__arrow
arrow/locales.py
{ "start": 15330, "end": 15643 }
class ____(FrenchBaseLocale, Locale): names = ["fr-ca"] month_abbreviations = [ "", "janv", "févr", "mars", "avr", "mai", "juin", "juill", "août", "sept", "oct", "nov", "déc", ]
FrenchCanadianLocale
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_day_count_to_be_close_to_equivalent_week_day_mean.py
{ "start": 1431, "end": 3025 }
class ____(ColumnAggregateMetricProvider): """ This metric expects daily counts of the given column, to be close to the average counts calculated 4 weeks back, respective to the specific day of the week. The expectation fails if the difference in percentage ((current - average) / average) is more than t...
ColumnCountsPerDaysCustom
python
scipy__scipy
benchmarks/benchmarks/stats.py
{ "start": 2151, "end": 2861 }
class ____(Benchmark): param_names = ['alternative', 'mode'] params = [ ['two-sided', 'less', 'greater'], ['auto', 'exact', 'asymp'], ] def setup(self, alternative, mode): rng = np.random.default_rng(0x2e7c964ff9a5cd6be22014c09f1dbba9) self.a = stats.norm.rvs(loc=5, scal...
KS
python
apache__airflow
airflow-core/tests/unit/always/test_secrets.py
{ "start": 1275, "end": 4950 }
class ____: def setup_method(self) -> None: SecretCache.reset() @mock.patch("airflow.secrets.metastore.MetastoreBackend.get_connection") @mock.patch("airflow.secrets.environment_variables.EnvironmentVariablesBackend.get_connection") def test_get_connection_second_try(self, mock_env_get, mock_me...
TestConnectionsFromSecrets
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_shape_base_.py
{ "start": 25930, "end": 27321 }
class ____(TestCase): def test_basic(self): a = np.array([0, 1, 2]) b = [[1, 2], [3, 4]] assert_equal(tile(a, 2), [0, 1, 2, 0, 1, 2]) assert_equal(tile(a, (2, 2)), [[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) assert_equal(tile(a, (1, 2)), [[0, 1, 2, 0, 1, 2]]) assert_equ...
TestTile
python
ray-project__ray
python/ray/serve/tests/unit/test_user_callable_wrapper.py
{ "start": 18229, "end": 18434 }
class ____: async def __call__(self, request: Request) -> str: msg = await request.body() return PlainTextResponse(f"Hello {msg}!") app = FastAPI() @serve.ingress(app)
RawRequestHandler
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 20402, "end": 22210 }
class ____(ClassFilter): """ This class basically filters all the use cases where `self.*` was assigned. """ def __init__(self, instance, instance_class, node_context, origin_scope): super().__init__( class_value=instance_class, node_context=node_context, orig...
SelfAttributeFilter
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 12935, "end": 13363 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_TRANSFORMERS, frozen=True, exclude=True ) poolingStrategy: Literal["masked_mean", "cls"] vectorizeClassName: bool inferenceUrl: Optional[str] passageInferenceUrl: Optio...
_Text2VecTransformersConfig
python
huggingface__transformers
src/transformers/models/layoutlmv3/modeling_layoutlmv3.py
{ "start": 41582, "end": 46692 }
class ____(LayoutLMv3PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.layoutlmv3 = LayoutLMv3Model(config) self.qa_outputs = LayoutLMv3ClassificationHead(config, pool_feature=False) self.post_init() @auto_d...
LayoutLMv3ForQuestionAnswering
python
huggingface__transformers
src/transformers/models/omdet_turbo/modeling_omdet_turbo.py
{ "start": 10275, "end": 11385 }
class ____: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity self.current_load = 0 def has(self, key) -> bool: return key in self.cache def get(self, key): """ Get the value of the key if the key exists in the cache, oth...
OmDetTurboLRUCache
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 6068, "end": 6325 }
class ____: params = [10**3, 10**4, 10**5] param_names = ["N"] def setup(self, N): self.s = Series(np.random.randint(0, N, size=10 * N)).astype("object") def time_mode(self, N): self.s.mode(dropna=False)
ModeObjectDropNAFalse
python
realpython__materials
queue/src/multiprocess_queue.py
{ "start": 1106, "end": 3244 }
class ____(multiprocessing.Process): def __init__(self, queue_in, queue_out, hash_value): super().__init__(daemon=True) self.queue_in = queue_in self.queue_out = queue_out self.hash_value = hash_value def run(self): while True: job = self.queue_in.get() ...
Worker
python
django__django
tests/utils_tests/models.py
{ "start": 107, "end": 203 }
class ____(models.Model): category = models.OneToOneField(Category, models.CASCADE)
CategoryInfo
python
django__django
tests/expressions/models.py
{ "start": 2444, "end": 2565 }
class ____(models.Model): time = models.TimeField(null=True) def __str__(self): return str(self.time)
Time
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qlinear_test.py
{ "start": 217, "end": 1075 }
class ____(op_bench.TorchBenchmarkBase): def init(self, N, IN, OUT, linear_under_test): scale = torch.tensor(1.0 / 255) zero_point = torch.tensor(0) self.X = torch.randn(N, IN, dtype=torch.float32) self.qX = torch.quantize_per_tensor( self.X, scale=scale, zero_point=zero_...
_QLinearBenchmarkBase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-s3/unit_tests/v4/test_source.py
{ "start": 367, "end": 2361 }
class ____(unittest.TestCase): def setUp(self) -> None: self._stream_reader = Mock(spec=SourceS3StreamReader) self._source = SourceS3( self._stream_reader, Config, SourceS3.read_catalog(str(TEST_FILES_FOLDER.joinpath("catalog.json"))), SourceS3.read_co...
SourceTest
python
scikit-learn__scikit-learn
sklearn/neighbors/_graph.py
{ "start": 8917, "end": 16942 }
class ____( ClassNamePrefixFeaturesOutMixin, KNeighborsMixin, TransformerMixin, NeighborsBase ): """Transform X into a (weighted) graph of k nearest neighbors. The transformed data is a sparse graph as returned by kneighbors_graph. Read more in the :ref:`User Guide <neighbors_transformer>`. .. ve...
KNeighborsTransformer
python
pytorch__pytorch
torch/_inductor/compile_fx_ext.py
{ "start": 11053, "end": 12656 }
class ____: """ Helper for _LoggerState - this class actually attaches to the logger in the child process and grabs the log messages themselves. """ state: _LoggerState queue: queue.Queue[logging.LogRecord] handlers: Optional[dict[str, logging.Handler]] def __init__(self, state: _Logge...
_CapturedLogs
python
langchain-ai__langchain
libs/langchain/langchain_classic/output_parsers/structured.py
{ "start": 473, "end": 930 }
class ____(BaseModel): """Schema for a response from a structured output parser.""" name: str """The name of the schema.""" description: str """The description of the schema.""" type: str = "string" """The type of the response.""" def _get_sub_string(schema: ResponseSchema) -> str: re...
ResponseSchema
python
scrapy__scrapy
tests/CrawlerProcess/default_name_resolver.py
{ "start": 58, "end": 424 }
class ____(scrapy.Spider): """ Raises a twisted.internet.error.DNSLookupError: the default name resolver does not handle IPv6 addresses. """ name = "ipv6_spider" start_urls = ["http://[::1]"] if __name__ == "__main__": process = CrawlerProcess(settings={"RETRY_ENABLED": False}) proces...
IPv6Spider
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/device_test.py
{ "start": 16711, "end": 21288 }
class ____(test_util.DTensorBaseTest): def setUp(self): super(DTensorPackUnpackOnOneDMeshTest, self).setUp() global_ids = test_util.create_device_ids_array((2,)) local_device_ids = np.ravel(global_ids).tolist() mesh_dict = { # pylint: disable=g-complex-comprehension device: Mesh( ...
DTensorPackUnpackOnOneDMeshTest
python
eventlet__eventlet
eventlet/green/threading.py
{ "start": 811, "end": 3903 }
class ____: """Wrapper for GreenThread objects to provide Thread-like attributes and methods""" def __init__(self, g): global _count self._g = g self._name = 'GreenThread-%d' % _count _count += 1 def __repr__(self): return '<_GreenThread(%s, %r)>' % (self._name,...
_GreenThread
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py
{ "start": 4171, "end": 4434 }
class ____(BaseModel): connector_technical_name: str connector_repository: str connector_version: str connector_definition_id: str dependencies: List[Dict[str, str]] generation_time: datetime = datetime.utcnow()
ConnectorDependenciesMetadata
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 2454, "end": 3527 }
class ____(LeafResource): def render(self, request): total = getarg(request, b"total", 100, type_=int) show = getarg(request, b"show", 1, type_=int) order = getarg(request, b"order", b"desc") maxlatency = getarg(request, b"maxlatency", 0, type_=float) n = getarg(request, b"n"...
Follow
python
readthedocs__readthedocs.org
readthedocs/core/history.py
{ "start": 2245, "end": 3188 }
class ____(models.Model): """ Abstract model to allow history models track extra data. Extra data includes: - User information to retain after they have been deleted - IP & browser """ extra_history_user_id = models.IntegerField( _("ID"), blank=True, null=True, ...
ExtraFieldsHistoricalModel
python
doocs__leetcode
solution/0700-0799/0719.Find K-th Smallest Pair Distance/Solution.py
{ "start": 0, "end": 387 }
class ____: def smallestDistancePair(self, nums: List[int], k: int) -> int: def count(dist): cnt = 0 for i, b in enumerate(nums): a = b - dist j = bisect_left(nums, a, 0, i) cnt += i - j return cnt nums.sort() ...
Solution
python
prakhar1989__Algorithms
tests/modular_multiplicative_inverse_test.py
{ "start": 146, "end": 623 }
class ____(unittest.TestCase): def test_modular_multiplicative_inverse(self): self.assertEqual(mmi.modular_multiplicative_inv(10, 7), 5) self.assertEqual(mmi.modular_multiplicative_inv(45, 13), 11) self.assertEqual(mmi.modular_multiplicative_inv(52, 1), 0) self.assertRaises(ValueError, mmi.mod...
TestLCS
python
mlflow__mlflow
mlflow/exceptions.py
{ "start": 5818, "end": 5947 }
class ____(MlflowException): """Exception thrown when a http request fails to send due to an invalid URL"""
InvalidUrlException
python
sympy__sympy
sympy/physics/quantum/spin.py
{ "start": 2317, "end": 5597 }
class ____: """Base class for spin operators.""" @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def name(self): return self.args[0] def _print_contents(self, printer, *arg...
SpinOpBase
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 7872, "end": 8140 }
class ____(BaseModel): """ Schema for updating downstream tasks to a skipped state. """ model_config = ConfigDict( extra="forbid", ) tasks: Annotated[list[str | tuple[str, int]], Field(title="Tasks")]
TISkippedDownstreamTasksStatePayload
python
doocs__leetcode
solution/1800-1899/1854.Maximum Population Year/Solution.py
{ "start": 0, "end": 389 }
class ____: def maximumPopulation(self, logs: List[List[int]]) -> int: d = [0] * 101 offset = 1950 for a, b in logs: a, b = a - offset, b - offset d[a] += 1 d[b] -= 1 s = mx = j = 0 for i, x in enumerate(d): s += x i...
Solution
python
falconry__falcon
falcon/media/msgpack.py
{ "start": 2654, "end": 3857 }
class ____(BinaryBaseHandlerWS): """WebSocket media handler for de(serializing) MessagePack to/from BINARY payloads. This handler uses ``msgpack.unpackb()`` and ``msgpack.packb()``. The MessagePack ``bin`` type is used to distinguish between Unicode strings (of type ``str``) and byte strings (of type `...
MessagePackHandlerWS
python
spack__spack
lib/spack/spack/util/web.py
{ "start": 6726, "end": 30594 }
class ____(HTMLParser): """This parser takes an HTML page and selects the include-fragments, used on GitHub, https://github.github.io/include-fragment-element, as well as a possible base url.""" def __init__(self): super().__init__() self.fragments = [] self.base_url = None ...
ExtractMetadataParser
python
pytorch__pytorch
test/distributed/launcher/api_test.py
{ "start": 3137, "end": 13797 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): # start a standalone, single process etcd server to use for all tests. cls._etcd_server = EtcdServer() cls._etcd_server.start() cls._etcd_endpoint = cls._etcd_server.get_endpoint() @classmethod def tearDown...
ElasticLaunchTest
python
pytorch__pytorch
test/distributed/tensor/test_op_strategy.py
{ "start": 1509, "end": 4005 }
class ____(TestCase): def test_batch_dims(self): equation = "abc,abc->abc" input_dims, output_dim = EinsumDims.parse_equation(equation) edims = EinsumDims.parse_dims(input_dims, output_dim) self.assertEqual(edims.batch_dims, ["a", "b", "c"]) self.assertEqual(edims.contractin...
TestEinsumDims
python
django__django
tests/serializers/models/data.py
{ "start": 3693, "end": 3818 }
class ____(models.Model): data = models.ForeignKey(UniqueAnchor, models.SET_NULL, null=True, to_field="data")
FKDataToField
python
pyca__cryptography
src/cryptography/hazmat/asn1/asn1.py
{ "start": 8112, "end": 8420 }
class ____(typing.Generic[U]): value: U Explicit = declarative_asn1.Encoding.Explicit Implicit = declarative_asn1.Encoding.Implicit Size = declarative_asn1.Size PrintableString = declarative_asn1.PrintableString UtcTime = declarative_asn1.UtcTime GeneralizedTime = declarative_asn1.GeneralizedTime
Default
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 255333, "end": 255984 }
class ____(sgqlc.types.Input): """Autogenerated input type of MinimizeComment""" __schema__ = github_schema __field_names__ = ("subject_id", "classifier", "client_mutation_id") subject_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subjectId") """The Node ID of the subject to modify...
MinimizeCommentInput
python
pytorch__pytorch
torch/_dynamo/variables/functions.py
{ "start": 11984, "end": 13431 }
class ____(VariableTracker): def get_filename(self) -> str: return self.get_code().co_filename # type: ignore[attr-defined] def get_name(self) -> str: return self.get_code().co_name # type: ignore[attr-defined] def get_globals(self): raise NotImplementedError def call_functi...
BaseUserFunctionVariable
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/bigtable.py
{ "start": 8036, "end": 12167 }
class ____(GoogleCloudBaseOperator, BigtableValidationMixin): """ Updates an existing Cloud Bigtable instance. For more details about instance creation have a look at the reference: https://googleapis.dev/python/bigtable/latest/instance.html#google.cloud.bigtable.instance.Instance.update .. seeals...
BigtableUpdateInstanceOperator
python
huggingface__transformers
tests/models/code_llama/test_tokenization_code_llama.py
{ "start": 1106, "end": 9299 }
class ____(TokenizerTesterMixin, unittest.TestCase): # TokenizerTesterMixin configuration from_pretrained_id = ["hf-internal-testing/llama-code-tokenizer"] tokenizer_class = CodeLlamaTokenizer integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '<0xF0>', '<0x9F>', '<0x98>', '<0x8A>', '<0...
CodeLlamaTokenizationTest
python
mlflow__mlflow
mlflow/utils/search_utils.py
{ "start": 4627, "end": 40943 }
class ____: LIKE_OPERATOR = "LIKE" ILIKE_OPERATOR = "ILIKE" ASC_OPERATOR = "asc" DESC_OPERATOR = "desc" VALID_ORDER_BY_TAGS = [ASC_OPERATOR, DESC_OPERATOR] VALID_METRIC_COMPARATORS = {">", ">=", "!=", "=", "<", "<="} VALID_PARAM_COMPARATORS = {"!=", "=", LIKE_OPERATOR, ILIKE_OPERATOR} VA...
SearchUtils
python
pyqtgraph__pyqtgraph
pyqtgraph/dockarea/DockDrop.py
{ "start": 2807, "end": 4468 }
class ____(QtWidgets.QWidget): """Overlay widget that draws drop areas during a drag-drop operation""" def __init__(self, parent): QtWidgets.QWidget.__init__(self, parent) self.dropArea = None self.hide() self.setAttribute(QtCore.Qt.WidgetAttribute.WA_TransparentForMouseEven...
DropAreaOverlay
python
catalyst-team__catalyst
catalyst/callbacks/mixup.py
{ "start": 179, "end": 5899 }
class ____(Callback): """ Callback to do mixup augmentation. More details about mixin can be found in the paper `mixup: Beyond Empirical Risk Minimization`: https://arxiv.org/abs/1710.09412 . Args: keys: batch keys to which you want to apply augmentation alpha: beta distribution a=b par...
MixupCallback
python
agronholm__apscheduler
src/apscheduler/_events.py
{ "start": 4265, "end": 4669 }
class ____(DataStoreEvent): """ Signals that the deserialization of a job has failed. :ivar job_id: ID of the job that failed to deserialize :ivar exception: the exception that was raised during deserialization """ job_id: UUID = attrs.field(converter=as_uuid) exception: BaseException # ...
JobDeserializationFailed
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-graphql/llama_index/readers/graphql/base.py
{ "start": 176, "end": 2135 }
class ____(BaseReader): """ GraphQL reader. Combines all GraphQL results into the Document used by LlamaIndex. Args: uri (str): GraphQL uri. headers (Optional[Dict]): Optional http headers. """ def __init__( self, uri: Optional[str] = None, headers: Op...
GraphQLReader
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_comment04.py
{ "start": 315, "end": 1147 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("comment04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with comments.""" workbook = Workboo...
TestCompareXLSXFiles