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
ray-project__ray
python/ray/llm/tests/batch/cpu/processor/test_processor_base.py
{ "start": 12342, "end": 16860 }
class ____: """Tests for preprocess_map_kwargs and postprocess_map_kwargs.""" def test_map_kwargs_stored_in_processor(self): """Test that map kwargs are correctly stored in Processor.""" preprocess_kwargs = {"num_cpus": 0.5} postprocess_kwargs = {"num_cpus": 0.25, "memory": 1024} ...
TestMapKwargs
python
sqlalchemy__sqlalchemy
test/orm/test_deprecations.py
{ "start": 19826, "end": 26195 }
class ____( fixtures.RemovesEvents, _fixtures.FixtureTest, AssertsCompiledSQL ): __dialect__ = "default" def test_listen_on_mapper_mapper_event_fn(self, registry): from sqlalchemy.orm import mapper m1 = Mock() with expect_deprecated( r"The `sqlalchemy.orm.mapper\(\)` s...
DeprecatedMapperTest
python
apache__airflow
providers/apache/hive/src/airflow/providers/apache/hive/transfers/vertica_to_hive.py
{ "start": 1296, "end": 5590 }
class ____(BaseOperator): """ Moves data from Vertica to Hive. The operator runs your query against Vertica, stores the file locally before loading it into a Hive table. If the ``create`` or ``recreate`` arguments are set to ``True``, a ``CREATE TABLE`` and ``DROP TABLE`` statements are generat...
VerticaToHiveOperator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-intercom/components.py
{ "start": 9548, "end": 10334 }
class ____(DefaultErrorHandler): """ Custom error handler that triggers a reset on HTTP 500 errors. """ def interpret_response(self, response_or_exception: Optional[Union[requests.Response, Exception]]) -> ErrorResolution: if isinstance(response_or_exception, requests.Response) and response_or_...
IntercomErrorHandler
python
huggingface__transformers
src/transformers/models/flaubert/modeling_flaubert.py
{ "start": 29624, "end": 31776 }
class ____(PreTrainedModel): config: FlaubertConfig base_model_prefix = "transformer" def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) @property def dummy_inputs(self): inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]) ...
FlaubertPreTrainedModel
python
readthedocs__readthedocs.org
readthedocs/audit/serializers.py
{ "start": 631, "end": 769 }
class ____(serializers.ModelSerializer): class Meta: model = Organization fields = ["id", "slug"]
OrganizationSerializer
python
getsentry__sentry-python
sentry_sdk/profiler/continuous_profiler.py
{ "start": 5344, "end": 5471 }
class ____: active: bool = True def stop(self): # type: () -> None self.active = False
ContinuousProfile
python
huggingface__transformers
src/transformers/models/edgetam_video/modeling_edgetam_video.py
{ "start": 2221, "end": 3530 }
class ____(nn.LayerNorm): r"""LayerNorm that supports two data formats: channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_s...
EdgeTamVideoLayerNorm
python
gevent__gevent
src/gevent/_util.py
{ "start": 5100, "end": 5691 }
class ____(object): """ A non-data descriptor used just like @property. The difference is the function value is assigned to the instance dict the first time it is accessed and then the function is never called again. Contrast with `readproperty`. """ def __init__(self, func): se...
Lazy
python
doocs__leetcode
solution/0300-0399/0316.Remove Duplicate Letters/Solution.py
{ "start": 0, "end": 413 }
class ____: def removeDuplicateLetters(self, s: str) -> str: last = {c: i for i, c in enumerate(s)} stk = [] vis = set() for i, c in enumerate(s): if c in vis: continue while stk and stk[-1] > c and last[stk[-1]] > i: vis.remove...
Solution
python
wandb__wandb
wandb/vendor/pygments/lexers/dotnet.py
{ "start": 20409, "end": 21059 }
class ____(DelegatingLexer): """ Lexer for highlighting C# within ASP.NET pages. """ name = 'aspx-cs' aliases = ['aspx-cs'] filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'] mimetypes = [] def __init__(self, **options): super(CSharpAspxLexer, self).__init_...
CSharpAspxLexer
python
urllib3__urllib3
src/urllib3/util/retry.py
{ "start": 651, "end": 822 }
class ____(typing.NamedTuple): method: str | None url: str | None error: Exception | None status: int | None redirect_location: str | None
RequestHistory
python
celery__celery
t/smoke/tests/stamping/workers/legacy.py
{ "start": 198, "end": 1491 }
class ____(CeleryWorkerContainer): @property def client(self) -> Any: return self @classmethod def version(cls) -> str: return "4.4.7" # Last version of 4.x @classmethod def log_level(cls) -> str: return "INFO" @classmethod def worker_name(cls) -> str: ...
LegacyWorkerContainer
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-memgraph/llama_index/graph_stores/memgraph/kg_base.py
{ "start": 1030, "end": 5662 }
class ____(GraphStore): def __init__( self, username: str, password: str, url: str, database: str = "memgraph", node_label: str = "Entity", **kwargs: Any, ) -> None: try: import neo4j except ImportError: raise Import...
MemgraphGraphStore
python
huggingface__transformers
src/transformers/models/informer/modeling_informer.py
{ "start": 31781, "end": 37264 }
class ____(GradientCheckpointingLayer): def __init__(self, config: InformerConfig, layer_idx: Optional[int] = None): super().__init__() self.embed_dim = config.d_model self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropou...
InformerDecoderLayer
python
great-expectations__great_expectations
great_expectations/core/config_substitutor.py
{ "start": 545, "end": 19604 }
class ____: """ Responsible for encapsulating all logic around $VARIABLE (or ${VARIABLE}) substitution. While the config variables utilized for substitution are provided at runtime, all the behavior necessary to actually update config objects with their appropriate runtime values should be defined ...
_ConfigurationSubstitutor
python
apache__airflow
providers/google/src/airflow/providers/google/common/hooks/base_google.py
{ "start": 32008, "end": 33491 }
class ____(BaseHook): """GoogleBaseAsyncHook inherits from BaseHook class, run on the trigger worker.""" sync_hook_class: Any = None def __init__(self, **kwargs: Any) -> None: # add default value to gcp_conn_id if "gcp_conn_id" not in kwargs: kwargs["gcp_conn_id"] = "google_clo...
GoogleBaseAsyncHook
python
pallets__jinja
tests/test_filters.py
{ "start": 604, "end": 32741 }
class ____: def test_filter_calling(self, env): rv = env.call_filter("sum", [1, 2, 3]) assert rv == 6 def test_capitalize(self, env): tmpl = env.from_string('{{ "foo bar"|capitalize }}') assert tmpl.render() == "Foo bar" def test_center(self, env): tmpl = env.from_s...
TestFilter
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultFunction2.py
{ "start": 1270, "end": 1383 }
class ____(Generic[T6, T7, T8]): def __new__(cls, x: T7, /) -> Self: ... def method1(self) -> T7: ...
ClassC
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 97535, "end": 101899 }
class ____(SingleODESolver): r""" Gives solution of the Bessel differential equation .. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x) if `n` is integer then the solution is of the form ``Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x))`` as both the solutions are linearly indepe...
SecondLinearBessel
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_clip_grad_norm_.py
{ "start": 769, "end": 3888 }
class ____(FSDPTest): def _test_clip_grad_norm( self, max_norm: Union[float, int], norm_type: Union[float, int], ref_model: nn.Module, ref_optim: torch.optim.Optimizer, model: nn.Module, optim: torch.optim.Optimizer, inp: torch.Tensor, dp_mesh:...
_TestClipGradNormBase
python
python-markdown__markdown
tests/test_syntax/extensions/test_toc.py
{ "start": 58296, "end": 59971 }
class ____(TestCase): def testStripElement(self): self.assertEqual( strip_tags('foo <em>bar</em>'), 'foo bar' ) def testStripOpenElement(self): self.assertEqual( strip_tags('foo <em>bar'), 'foo bar' ) def testStripEmptyElemen...
testStripTags
python
scipy__scipy
scipy/optimize/tests/test_zeros.py
{ "start": 5555, "end": 8775 }
class ____(TestScalarRootFinders): @pytest.mark.parametrize('method', bracket_methods) @pytest.mark.parametrize('function', tstutils_functions) def test_basic_root_scalar(self, method, function): # Tests bracketing root finders called via `root_scalar` on a small # set of simple problems, ea...
TestBracketMethods
python
encode__django-rest-framework
tests/test_relations_pk.py
{ "start": 7924, "end": 15826 }
class ____(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') target.save() new_target = ForeignKeyTarget(name='target-2') new_target.save() for idx in range(1, 4): source = ForeignKeySource(name='source-%d' % idx, target=target) so...
PKForeignKeyTests
python
keras-team__keras
keras/src/layers/preprocessing/data_layer_test.py
{ "start": 255, "end": 1223 }
class ____(DataLayer): def __init__(self, data_format=None, seed=None, **kwargs): super().__init__(**kwargs) self.data_format = backend.standardize_data_format(data_format) self.seed = seed self.generator = SeedGenerator(seed) def call(self, inputs): images_shape = self....
RandomRGBToHSVLayer
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/telemetry/__init__.py
{ "start": 4881, "end": 11335 }
class ____( NamedTuple( "_TelemetryEntry", [ ("action", str), ("client_time", str), ("event_id", str), ("elapsed_time", str), ("instance_id", str), ("metadata", Mapping[str, str]), ("python_version", str), ...
TelemetryEntry
python
apache__airflow
airflow-core/src/airflow/triggers/base.py
{ "start": 1550, "end": 4566 }
class ____(abc.ABC, LoggingMixin): """ Base class for all triggers. A trigger has two contexts it can exist in: - Inside an Operator, when it's passed to TaskDeferred - Actively running in a trigger worker We use the same class for both situations, and rely on all Trigger classes to be ...
BaseTrigger
python
huggingface__transformers
src/transformers/models/granite/modeling_granite.py
{ "start": 14380, "end": 17399 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: GraniteConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self...
GraniteRotaryEmbedding
python
kubernetes-client__python
kubernetes/client/models/v1_replication_controller_spec.py
{ "start": 383, "end": 7744 }
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...
V1ReplicationControllerSpec
python
has2k1__plotnine
plotnine/scales/scale_color.py
{ "start": 14298, "end": 14362 }
class ____(scale_fill_cmap): pass @alias
scale_fill_continuous
python
rapidsai__cudf
python/cudf/cudf/core/join/join.py
{ "start": 812, "end": 25504 }
class ____: @staticmethod @acquire_spill_lock() def _joiner( lhs: list[ColumnBase], rhs: list[ColumnBase], how: str, ) -> tuple[ColumnBase, ColumnBase]: if how == "outer": how = "full" if (join_func := getattr(plc.join, f"{how}_join", None)) is None: ...
Merge
python
dask__dask
dask/_expr.py
{ "start": 989, "end": 26020 }
class ____: _parameters: list[str] = [] _defaults: dict[str, Any] = {} _pickle_functools_cache: bool = True operands: list _determ_token: str | None def __new__(cls, *args, _determ_token=None, **kwargs): operands = list(args) for parameter in cls._parameters[len(operands) :]:...
Expr
python
getsentry__sentry
src/sentry/models/apikey.py
{ "start": 1156, "end": 4099 }
class ____(ReplicatedControlModel, HasApiScopes): __relocation_scope__ = RelocationScope.Global category = OutboxCategory.API_KEY_UPDATE replication_version = 3 organization_id = HybridCloudForeignKey("sentry.Organization", on_delete="CASCADE") label = models.CharField(max_length=64, blank=True, de...
ApiKey
python
PyCQA__pylint
pylint/exceptions.py
{ "start": 527, "end": 872 }
class ____(UnknownMessageError): """Raised when a message id or symbol that was deleted from pylint is encountered. """ def __init__(self, msgid_or_symbol: str, removal_explanation: str): super().__init__( f"'{msgid_or_symbol}' was removed from pylint, see {removal_explanation}." ...
DeletedMessageError
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 13207, "end": 13562 }
class ____(AnsibleAction): """ An action runtime failure. This exception provides a result dictionary via the ContributesToTaskResult mixin. """ @property def result_contribution(self) -> _c.Mapping[str, object]: return self._result | dict( failed=True, msg=self...
AnsibleActionFail
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 95486, "end": 96174 }
class ____(ScaledMMConfigMixin, MTIAConfigHeuristic): """Scaled MM template heuristic for MTIA (non-TMA)""" def __init__(self) -> None: super().__init__() # Override mm_configs to use scaled_mm_configs self.mm_configs = self.scaled_mm_configs # NOTE: overriding exhaustive config...
MTIAScaledMMTemplateConfigHeuristic
python
getsentry__sentry
src/sentry/tasks/statistical_detectors.py
{ "start": 8610, "end": 37018 }
class ____(RegressionDetector): source = "profile" kind = "function" regression_type = RegressionType.FUNCTION min_change = 100_000_000 # 100ms in ns buffer_period = timedelta(days=1) resolution_rel_threshold = 0.1 escalation_rel_threshold = 0.75 @classmethod def min_throughput_thr...
FunctionRegressionDetector
python
doocs__leetcode
solution/1300-1399/1307.Verbal Arithmetic Puzzle/Solution.py
{ "start": 0, "end": 3272 }
class ____: def isAnyMapping( self, words, row, col, bal, letToDig, digToLet, totalRows, totalCols ): # If traversed all columns. if col == totalCols: return bal == 0 # At the end of a particular column. if row == totalRows: return bal % 10 == 0 a...
Solution
python
walkccc__LeetCode
solutions/179. Largest Number/179.py
{ "start": 0, "end": 90 }
class ____(str): def __lt__(x: str, y: str) -> bool: return x + y > y + x
LargerStrKey
python
google__pytype
pytype/datatypes_test.py
{ "start": 1086, "end": 1661 }
class ____(unittest.TestCase): def test_merge(self): uf = datatypes.UnionFind() uf.merge("k1", "k2") self.assertEqual(uf.find_by_name("k1"), uf.find_by_name("k2")) self.assertNotEqual(uf.find_by_name("k1"), uf.find_by_name("k3")) def test_merge_from(self): uf1 = datatypes.UnionFind() uf1.m...
UnionFindTest
python
getsentry__sentry
src/sentry/testutils/helpers/alert_rule.py
{ "start": 225, "end": 869 }
class ____: _suspended_values: _FactoryRegistry @classmethod def suspend(cls) -> "TemporaryAlertRuleTriggerActionRegistry": obj = cls(AlertRuleTriggerAction._factory_registrations) AlertRuleTriggerAction._factory_registrations = _FactoryRegistry() return obj def restore(self) -...
TemporaryAlertRuleTriggerActionRegistry
python
modin-project__modin
modin/config/envvars.py
{ "start": 33875, "end": 35312 }
class ____(EnvironmentVariable, type=int): """ Minimum number of rows/columns in a single pandas partition split. Once a partition for a pandas dataframe has more than this many elements, Modin adds another partition. """ varname = "MODIN_MIN_PARTITION_SIZE" default = 32 @classmethod ...
MinPartitionSize
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/_redaction.py
{ "start": 455, "end": 602 }
class ____(TypedDict): """Represents an individual match of sensitive data.""" type: str value: str start: int end: int
PIIMatch
python
pypa__pip
src/pip/_vendor/urllib3/contrib/pyopenssl.py
{ "start": 9154, "end": 13846 }
class ____(object): """API-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. """ def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self....
WrappedSocket
python
sphinx-doc__sphinx
sphinx/search/nl.py
{ "start": 189, "end": 582 }
class ____(SearchLanguage): lang = 'nl' language_name = 'Dutch' js_stemmer_rawcode = 'dutch-stemmer.js' stopwords = DUTCH_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('dutch') def stem(self, word...
SearchDutch
python
ansible__ansible
lib/ansible/plugins/test/uri.py
{ "start": 746, "end": 965 }
class ____(object): """ Ansible URI jinja2 test """ def tests(self): return { # file testing 'uri': is_uri, 'url': is_url, 'urn': is_urn, }
TestModule
python
scipy__scipy
scipy/sparse/tests/test_extract.py
{ "start": 200, "end": 1685 }
class ____: def setup_method(self): self.cases = [ csr_array([[1,2]]), csr_array([[1,0]]), csr_array([[0,0]]), csr_array([[1],[2]]), csr_array([[1],[0]]), csr_array([[0],[0]]), csr_array([[1,2],[3,4]]), csr_array...
TestExtract
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1403305, "end": 1406351 }
class ____(VegaLiteSchema): """ TimeUnitParams schema wrapper. Time Unit Params for encoding predicate, which can specified if the data is already "binned". Parameters ---------- binned : bool Whether the data has already been binned to this time unit. If true, Vega-Lite will ...
TimeUnitParams
python
getsentry__sentry
tests/sentry/snuba/test_entity_subscriptions.py
{ "start": 23825, "end": 28339 }
class ____(TestCase): def test(self) -> None: cases = [ (EntityKey.Events, SnubaQuery.Type.ERROR, Dataset.Events, "count()", "", True, True), ( EntityKey.Transactions, SnubaQuery.Type.PERFORMANCE, Dataset.Transactions, "...
GetEntityKeyFromSnubaQueryTest
python
apache__airflow
providers/common/compat/src/airflow/providers/common/compat/lineage/entities.py
{ "start": 967, "end": 1181 }
class ____: """File entity. Refers to a file.""" template_fields: ClassVar[tuple[str, ...]] = ("url",) url: str = attr.ib() type_hint: str | None = None @attr.s(auto_attribs=True, kw_only=True)
File
python
gevent__gevent
src/gevent/thread.py
{ "start": 3954, "end": 7612 }
class ____: # The constructor must accept and ignore all arguments # to match the stdlib. def __init__(self, *_args, **_kwargs): """Does nothing; ignores args""" # Must keep a weak reference to the greenlet # to avoid problems managing the _active list of # threads, which can sometimes ...
_ThreadHandle
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/rpc_communicator.py
{ "start": 706, "end": 1098 }
class ____(UnityToExternalProtoServicer): def __init__(self): self.parent_conn, self.child_conn = Pipe() def Initialize(self, request, context): self.child_conn.send(request) return self.child_conn.recv() def Exchange(self, request, context): self.child_conn.send(request) ...
UnityToExternalServicerImplementation
python
dagster-io__dagster
python_modules/dagster/dagster/_core/workspace/load_target.py
{ "start": 598, "end": 803 }
class ____(ABC): @abstractmethod def create_origins(self) -> Sequence[CodeLocationOrigin]: """Reloads the CodeLocationOrigins for this workspace.""" @record(kw_only=False)
WorkspaceLoadTarget
python
scrapy__scrapy
tests/test_command_runspider.py
{ "start": 8541, "end": 8994 }
class ____(scrapy.Spider): name = 'myspider' async def start(self): return yield """ args = ["-o", "example1.json", "-O", "example2.json"] log = self.get_log(tmp_path, spider_code, args=args) assert ( "error: Please use only one of -o/--output and -O/--overwr...
MySpider
python
faif__python-patterns
patterns/creational/builder.py
{ "start": 2343, "end": 3054 }
class ____(ComplexBuilding): def build_floor(self) -> None: self.floor = "One" def build_size(self) -> None: self.size = "Big and fancy" def construct_building(cls) -> Building: building = cls() building.build_floor() building.build_size() return building def main(): """...
ComplexHouse
python
sympy__sympy
sympy/tensor/functions.py
{ "start": 3749, "end": 4166 }
class ____(Exception): """ Raised when ``shape()`` is called on non-array object. This error can be imported from ``sympy.tensor.functions``. Examples ======== >>> from sympy import shape >>> from sympy.abc import x >>> shape(x) Traceback (most recent call last): ... sym...
NoShapeError
python
tensorflow__tensorflow
tensorflow/python/ops/variables.py
{ "start": 54868, "end": 76281 }
class ____: """A container for partitioned `Variable` objects. @compatibility(eager) `tf.PartitionedVariable` is not compatible with eager execution. Use `tf.Variable` instead which is compatible with both eager execution and graph construction. See [the TensorFlow Eager Execution guide](https://www.tens...
PartitionedVariable
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 4224, "end": 10183 }
class ____(nn.Module): def __init__(self, config, is_cross_attention=False, layer_idx=None): super().__init__() self.config = config self.mask_value = None self.multi_query = config.multi_query self.embed_dim = config.hidden_size self.num_heads = config.num_attention...
GPTBigCodeAttention
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 68797, "end": 71866 }
class ____: """ State that helps to provide a reentrant gdb.execute() function. """ def __init__(self): f = tempfile.NamedTemporaryFile('r+') self.file = f self.filename = f.name self.fd = f.fileno() _execute("set logging file %s" % self.filename) self.fi...
_LoggingState
python
astropy__astropy
astropy/coordinates/builtin_frames/galactocentric.py
{ "start": 17997, "end": 25250 }
class ____(BaseCoordinateFrame): r""" A coordinate or frame in the Galactocentric system. This frame allows specifying the Sun-Galactic center distance, the height of the Sun above the Galactic midplane, and the solar motion relative to the Galactic center. However, as there is no modern standard d...
Galactocentric
python
ray-project__ray
rllib/models/torch/recurrent_net.py
{ "start": 980, "end": 5223 }
class ____(TorchModelV2): """Helper class to simplify implementing RNN models with TorchModelV2. Instead of implementing forward(), you can implement forward_rnn() which takes batches with the time dimension added already. Here is an example implementation for a subclass ``MyRNNClass(RecurrentNetw...
RecurrentNetwork
python
pytorch__pytorch
tools/linter/adapters/test_has_main_linter.py
{ "start": 1953, "end": 3811 }
class ____(NamedTuple): path: str | None line: int | None char: int | None code: str severity: LintSeverity name: str original: str | None replacement: str | None description: str | None def check_file(filename: str) -> list[LintMessage]: lint_messages = [] with open(filen...
LintMessage
python
readthedocs__readthedocs.org
readthedocs/storage/s3_storage.py
{ "start": 2380, "end": 2911 }
class ____: bucket_name = getattr(settings, "S3_STATIC_STORAGE_BUCKET", None) override_hostname = getattr(settings, "S3_STATIC_STORAGE_OVERRIDE_HOSTNAME", None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.bucket_name: raise ImproperlyConfi...
S3StaticStorageMixin
python
kamyu104__LeetCode-Solutions
Python/minimum-sum-of-values-by-dividing-array.py
{ "start": 114, "end": 2219 }
class ____(object): def minimumValueSum(self, nums, andValues): """ :type nums: List[int] :type andValues: List[int] :rtype: int """ INF = float("inf") L = max(nums).bit_length() def update(cnt, x, d): for i in xrange(L): if...
Solution
python
tensorflow__tensorflow
tensorflow/python/distribute/one_device_strategy.py
{ "start": 9887, "end": 18367 }
class ____(distribute_lib.StrategyExtendedV1): """Implementation of OneDeviceStrategy.""" def __init__(self, container_strategy, device): super(OneDeviceExtended, self).__init__(container_strategy) self._device = device_util.resolve(device) self._input_device = device_util.get_host_for_device(self._dev...
OneDeviceExtended
python
pandas-dev__pandas
pandas/tests/frame/methods/test_dot.py
{ "start": 3193, "end": 5116 }
class ____(DotSharedTests): @pytest.fixture def obj(self): return DataFrame( np.random.default_rng(2).standard_normal((3, 4)), index=["a", "b", "c"], columns=["p", "q", "r", "s"], ) @pytest.fixture def other(self): return DataFrame( ...
TestDataFrameDot
python
tensorflow__tensorflow
tensorflow/compiler/tests/add_n_test.py
{ "start": 1029, "end": 3321 }
class ____(xla_test.XLATestCase): def testAddTensorLists(self): with self.session(), self.test_scope(): l1 = list_ops.tensor_list_reserve( element_shape=[], element_dtype=dtypes.float32, num_elements=3) l2 = list_ops.tensor_list_reserve( element_shape=[], element_dtype=dtypes.floa...
XlaAddNTest
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/parser_test.py
{ "start": 1036, "end": 11696 }
class ____(test.TestCase): def assertAstMatches(self, actual_node, expected_node_src, expr=True): if expr: # Ensure multi-line expressions parse. expected_node = gast.parse('({})'.format(expected_node_src)).body[0] expected_node = expected_node.value else: expected_node = gast.parse(e...
ParserTest
python
tensorflow__tensorflow
tensorflow/python/ops/gradients_test.py
{ "start": 41324, "end": 55688 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testCustomGradientTrivial(self): @custom_gradient.custom_gradient def MyIdentity(x): def Grad(dy): return [3 * dy] return x, Grad with ops.Graph().as_default(): x = constant(3.) y = MyIdentity(MyIden...
CustomGradientTest
python
rapidsai__cudf
python/cudf/cudf/pandas/fast_slow_proxy.py
{ "start": 2273, "end": 2400 }
class ____(IntEnum): """Simple enum to track the type of wrapped object of a final proxy""" SLOW = 0 FAST = 1
_State
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 36932, "end": 55589 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testInvolutionLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_o...
FlipTransposeRotateTest
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py
{ "start": 69, "end": 1489 }
class ____(ValidationRule): __slots__ = 'fragment_definitions', 'operation_definitions', 'fragment_adjacencies', 'spread_names' def __init__(self, context): super(NoUnusedFragments, self).__init__(context) self.operation_definitions = [] self.fragment_definitions = [] def enter_Ope...
NoUnusedFragments
python
h5py__h5py
h5py/tests/test_vds/test_highlevel_vds.py
{ "start": 13337, "end": 15398 }
class ____(ut.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.f1 = osp.join(self.tmpdir, 'testfile1.h5') self.f2 = osp.join(self.tmpdir, 'testfile2.h5') self.data1 = np.arange(10) self.data2 = np.arange(10) * -1 with h5.File(self.f1, 'w') as f: ...
RelativeLinkTestCase
python
huggingface__transformers
src/transformers/models/albert/modeling_albert.py
{ "start": 16772, "end": 20747 }
class ____(AlbertPreTrainedModel): _tied_weights_keys = { "predictions.decoder.weight": "albert.embeddings.word_embeddings.weight", "predictions.decoder.bias": "predictions.bias", } def __init__(self, config: AlbertConfig): super().__init__(config) self.albert = AlbertModel...
AlbertForPreTraining
python
faif__python-patterns
patterns/behavioral/chain_of_responsibility.py
{ "start": 760, "end": 1381 }
class ____(ABC): def __init__(self, successor: Optional["Handler"] = None): self.successor = successor def handle(self, request: int) -> None: """ Handle request and stop. If can't - call next handler in chain. As an alternative you might even in case of success ...
Handler
python
getsentry__sentry
tests/sentry/integrations/msteams/test_integration.py
{ "start": 4740, "end": 7291 }
class ____(TestCase): def setUp(self) -> None: self.integration = self.create_provider_integration( provider="msteams", name="MS Teams", external_id=team_id, metadata={ "access_token": "test-access-token", "service_url": "https:...
MsTeamsIntegrationSendNotificationTest
python
charliermarsh__ruff
crates/ruff_benchmark/resources/numpy/ctypeslib.py
{ "start": 5452, "end": 6332 }
class ____(_ndptr_base): @classmethod def from_param(cls, obj): if not isinstance(obj, ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError("array must have data type %s" % cls._...
_ndptr
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 2929, "end": 6350 }
class ____(Generic[T], EventWithMetadata): """Event corresponding to one of an op's outputs. Op compute functions must explicitly yield events of this type when they have more than one output, or when they also yield events of other types, or when defining a op using the :py:class:`OpDefinition` API di...
Output
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 51507, "end": 62726 }
class ____(InspectTool): ''' *toolbar icon*: |hover_icon| The hover tool is a passive inspector tool. It is generally on at all times, but can be configured in the inspector's menu associated with the *toolbar icon* shown above. By default, the hover tool displays informational tooltips whenever t...
HoverTool
python
wandb__wandb
wandb/vendor/pygments/util.py
{ "start": 9123, "end": 11900 }
class ____(object): """Generic class to defer some work. Handled specially in RegexLexerMeta, to support regex string construction at first use. """ def get(self): raise NotImplementedError def guess_decode(text): """Decode *text* with guessed encoding. First try UTF-8; this shou...
Future
python
doocs__leetcode
solution/3400-3499/3431.Minimum Unlocked Indices to Sort Nums/Solution.py
{ "start": 0, "end": 591 }
class ____: def minUnlockedIndices(self, nums: List[int], locked: List[int]) -> int: n = len(nums) first2 = first3 = n last1 = last2 = -1 for i, x in enumerate(nums): if x == 1: last1 = i elif x == 2: first2 = min(first2, i) ...
Solution
python
astropy__astropy
astropy/io/ascii/latex.py
{ "start": 2339, "end": 3614 }
class ____(core.BaseSplitter): """Split LaTeX table data. Default delimiter is `&`.""" delimiter = "&" def __call__(self, lines: list[str]) -> Generator[list[str], None, None]: last_line = RE_COMMENT.split(lines[-1])[0].strip() if not last_line.endswith(r"\\"): lines[-1] = last...
LatexSplitter
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 507518, "end": 513591 }
class ____(BinopNode): # Binary operation taking numeric arguments. infix = True overflow_check = False overflow_bit_node = None def analyse_c_operation(self, env): type1 = self.operand1.type type2 = self.operand2.type self.type = self.compute_c_result_type(type1, type2) ...
NumBinopNode
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/colliding_class_names.py
{ "start": 272, "end": 361 }
class ____: def also_tainted_but_missing_from_analysis(): return _test_source()
C
python
getsentry__sentry
src/sentry/preprod/pull_request/comment_types.py
{ "start": 1507, "end": 2002 }
class ____(BaseModel): """ Represents a GitHub issue comment (general PR comment). These are comments in the main PR conversation thread. """ id: int node_id: str url: str html_url: str body: str user: CommentUser | None created_at: datetime updated_at: datetime issu...
IssueComment
python
pypa__setuptools
setuptools/_vendor/wheel/vendored/packaging/_musllinux.py
{ "start": 301, "end": 2674 }
class ____(NamedTuple): major: int minor: int def _parse_musl_version(output: str) -> Optional[_MuslVersion]: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if n...
_MuslVersion
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 72560, "end": 74347 }
class ____: """ Check that verbosity also controls the string length threshold to shorten it using ellipsis. """ @pytest.mark.parametrize( "verbose, expected_size", [ (0, DEFAULT_REPR_MAX_SIZE), (1, DEFAULT_REPR_MAX_SIZE * 10), (2, None), ...
TestReprSizeVerbosity
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/multitenancy/memcache.py
{ "start": 861, "end": 1928 }
class ____(webapp2.RequestHandler): """Increments counters in the global namespace as well as in whichever namespace is specified by the request, which is arbitrarily named 'default' if not specified.""" def get(self, namespace="default"): global_count = memcache.incr("counter", initial_value=0...
MemcacheCounterHandler
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 193562, "end": 195457 }
class ____(Binding): """ BindInput schema wrapper. Parameters ---------- autocomplete : str A hint for form autofill. See the `HTML autocomplete attribute <https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete>`__ for additional information. debounce ...
BindInput
python
simplejson__simplejson
simplejson/tests/test_pass1.py
{ "start": 1539, "end": 1746 }
class ____(TestCase): def test_parse(self): # test in/out equivalence and parsing res = json.loads(JSON) out = json.dumps(res) self.assertEqual(res, json.loads(out))
TestPass1
python
django__django
tests/forms_tests/widget_tests/test_choicewidget.py
{ "start": 91, "end": 3150 }
class ____(WidgetTest): widget = ChoiceWidget @property def nested_widgets(self): nested_widget = self.widget( choices=( ("outer1", "Outer 1"), ('Group "1"', (("inner1", "Inner 1"), ("inner2", "Inner 2"))), ), ) nested_widget_d...
ChoiceWidgetTest
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 24118, "end": 24202 }
class ____(VariableTracker): """ It could be anything! """
UnknownVariable
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 2041, "end": 2232 }
class ____(CallableTemplate): key = cuda.const.array_like def generic(self): def typer(ndarray): return ndarray return typer @register
Cuda_const_array_like
python
getsentry__sentry
src/sentry/issues/endpoints/organization_issue_metrics.py
{ "start": 7323, "end": 7392 }
class ____(TypedDict): timestamp: float value: float
TimeSeries
python
tornadoweb__tornado
tornado/test/concurrent_test.py
{ "start": 2984, "end": 3364 }
class ____: def __init__(self, port): self.port = port def process_response(self, data): m = re.match("(.*)\t(.*)\n", to_unicode(data)) if m is None: raise Exception("did not match") status, message = m.groups() if status == "ok": return message ...
BaseCapClient
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_origin.py
{ "start": 14745, "end": 16372 }
class ____(LegacyNamedTupleMixin): """Serializable representation of an ExternalRepository that can be used to uniquely it or reload it in across process boundaries. """ code_location_origin: CodeLocationOrigin repository_name: str def get_id(self) -> str: return create_snapshot_id(sel...
RemoteRepositoryOrigin
python
facebook__pyre-check
tools/upgrade/repository.py
{ "start": 329, "end": 1437 }
class ____: MIGRATION_SUMMARY: str = ( "Migrating buck integration to use configurations.\n " "For more information about this migration, please see: " "https://fb.workplace.com/groups/295311271085134/permalink/552700215346237/" ) def commit_message( self, title: str...
Repository
python
plotly__plotly.py
plotly/graph_objs/layout/ternary/aaxis/_title.py
{ "start": 235, "end": 2875 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.ternary.aaxis" _path_str = "layout.ternary.aaxis.title" _valid_props = {"font", "text"} @property def font(self): """ Sets this axis' title font. The 'font' property is an instance of Font that may be ...
Title
python
getsentry__sentry
src/sentry/integrations/utils/codecov.py
{ "start": 4703, "end": 4872 }
class ____(TypedDict): repository: Repository # Config is a serialized RepositoryProjectPathConfig config: Any outcome: RepositoryLinkOutcome
CodecovConfig
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_dialect.py
{ "start": 5280, "end": 8633 }
class ____(fixtures.TestBase): __backend__ = True __only_on__ = "oracle" @testing.combinations( ( "db is not connected", None, True, ), ( "ORA-1234 fake error", 1234, False, ), ( "ORA...
DialectWBackendTest