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
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/retries.py
{ "start": 2014, "end": 6363 }
class ____: def __init__(self, previous_attempts: Optional[Mapping[str, int]] = None): self._attempts = defaultdict(int) for key, val in check.opt_mapping_param( previous_attempts, "previous_attempts", key_type=str, value_type=int ).items(): self._attempts[key] = val ...
RetryState
python
numba__numba
numba/tests/test_parfors_passes.py
{ "start": 589, "end": 1011 }
class ____(object): def __init__(self, typingctx, targetctx, args, test_ir): self.state = compiler.StateDict() self.state.typingctx = typingctx self.state.targetctx = targetctx self.state.args = args self.state.func_ir = test_ir self.state.typemap = None self....
MyPipeline
python
apache__airflow
providers/ftp/src/airflow/providers/ftp/hooks/ftp.py
{ "start": 9857, "end": 11066 }
class ____(FTPHook): """Interact with FTPS.""" def get_conn(self) -> ftplib.FTP: """Return an FTPS connection object.""" import ssl if self.conn is None: params = self.get_connection(self.ftp_conn_id) pasv = params.extra_dejson.get("passive", True) e...
FTPSHook
python
getsentry__sentry
src/sentry/snuba/snuba_query_validator.py
{ "start": 2361, "end": 17211 }
class ____(BaseDataSourceValidator[QuerySubscription]): query_type = serializers.IntegerField(required=False) dataset = serializers.CharField(required=True) query = serializers.CharField(required=True, allow_blank=True) aggregate = serializers.CharField(required=True) time_window = serializers.Integ...
SnubaQueryValidator
python
pennersr__django-allauth
allauth/socialaccount/providers/battlenet/views.py
{ "start": 662, "end": 2059 }
class ____: APAC = "apac" CN = "cn" EU = "eu" KR = "kr" SEA = "sea" TW = "tw" US = "us" def _check_errors(response): try: data = response.json() except ValueError: # JSONDecodeError on py3 raise OAuth2Error("Invalid JSON from Battle.net API: %r" % (response.text)) ...
Region
python
networkx__networkx
networkx/algorithms/isomorphism/vf2userfunc.py
{ "start": 4736, "end": 7165 }
class ____(vf2.DiGraphMatcher): """VF2 isomorphism checker for directed graphs.""" def __init__(self, G1, G2, node_match=None, edge_match=None): """Initialize graph matcher. Parameters ---------- G1, G2 : graph The graphs to be tested. node_match : callable...
DiGraphMatcher
python
jackfrued__Python-100-Days
Day31-35/code/example04.py
{ "start": 53, "end": 1021 }
class ____(object): """物品""" def __init__(self, name, price, weight): self.name = name self.price = price self.weight = weight @property def value(self): """价格重量比""" return self.price / self.weight def input_thing(): """输入物品信息""" name_str, price_str, w...
Thing
python
fluentpython__example-code-2e
19-concurrency/primes/threads.py
{ "start": 306, "end": 1931 }
class ____(NamedTuple): n: int prime: bool elapsed: float JobQueue = SimpleQueue[int] # <4> ResultQueue = SimpleQueue[PrimeResult] # <5> def check(n: int) -> PrimeResult: # <6> t0 = perf_counter() res = is_prime(n) return PrimeResult(n, res, perf_counter() - t0) def worker(jobs: JobQueue, ...
PrimeResult
python
joblib__joblib
joblib/externals/loky/backend/synchronize.py
{ "start": 5958, "end": 6808 }
class ____(SemLock): def __init__(self): super().__init__(RECURSIVE_MUTEX, 1, 1) def __repr__(self): try: if self._semlock._is_mine(): name = process.current_process().name if threading.current_thread().name != "MainThread": name =...
RLock
python
scrapy__scrapy
scrapy/exceptions.py
{ "start": 1667, "end": 1880 }
class ____(Exception): """To indicate a command-line usage error""" def __init__(self, *a: Any, **kw: Any): self.print_help = kw.pop("print_help", True) super().__init__(*a, **kw)
UsageError
python
ray-project__ray
release/llm_tests/serve/probes/query_utils.py
{ "start": 3118, "end": 4849 }
class ____: def __init__(self, response=List[BaseModel]): self.response = response def messages(self): """In case of streamed response, what are the individual chunked messages? that contain the content we care about?""" vals = [] for r in self.response: if len(r.cho...
TextGenerationProbeResponse
python
coleifer__peewee
tests/sqlite.py
{ "start": 1333, "end": 2236 }
class ____(object): def __init__(self): self.total = 0. self.count = 0. def step(self, value, weight=None): weight = weight or 1. self.total += weight self.count += (weight * value) def finalize(self): if self.total != 0.: return self.count / sel...
WeightedAverage
python
doocs__leetcode
solution/1100-1199/1109.Corporate Flight Bookings/Solution.py
{ "start": 0, "end": 297 }
class ____: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: ans = [0] * n for first, last, seats in bookings: ans[first - 1] += seats if last < n: ans[last] -= seats return list(accumulate(ans))
Solution
python
great-expectations__great_expectations
great_expectations/datasource/fluent/data_connector/s3_data_connector.py
{ "start": 959, "end": 11523 }
class ____(FilePathDataConnector): """Extension of FilePathDataConnector used to connect to S3. Args: datasource_name: The name of the Datasource associated with this DataConnector instance data_asset_name: The name of the DataAsset using this DataConnector instance s3_client: Referenc...
S3DataConnector
python
ray-project__ray
rllib/models/tf/recurrent_net.py
{ "start": 5139, "end": 11569 }
class ____(RecurrentNetwork): """An LSTM wrapper serving as an interface for ModelV2s that set use_lstm.""" def __init__( self, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, num_outputs: int, model_config: ModelConfigDict, name: str, ): ...
LSTMWrapper
python
pypa__warehouse
tests/common/db/oidc.py
{ "start": 1305, "end": 1671 }
class ____(WarehouseFactory): class Meta: model = GitLabPublisher id = factory.Faker("uuid4", cast_to=None) project = factory.Faker("pystr", max_chars=12) namespace = factory.Faker("pystr", max_chars=12) workflow_filepath = "subfolder/example.yml" environment = "production" issuer_u...
GitLabPublisherFactory
python
pytorch__pytorch
tools/test/test_docstring_linter.py
{ "start": 856, "end": 6139 }
class ____(LinterTestCase): LinterClass = DocstringLinter maxDiff = 10_240 def test_python_code(self): self.lint_test(TEST_FILE, ARGS) @mock.patch("sys.stdout", new_callable=io.StringIO) def test_end_to_end(self, mock_stdout): argv_base = *ARGS, str(TEST_FILE), str(TEST_FILE2) ...
TestDocstringLinter
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 10580, "end": 10886 }
class ____(InvalidRequestError): """A database result was required but none was found. .. versionchanged:: 1.4 This exception is now part of the ``sqlalchemy.exc`` module in Core, moved from the ORM. The symbol remains importable from ``sqlalchemy.orm.exc``. """
NoResultFound
python
tensorflow__tensorflow
tensorflow/lite/python/interpreter.py
{ "start": 12011, "end": 13773 }
class ____(enum.Enum): """Different types of op resolvers for Tensorflow Lite. * `AUTO`: Indicates the op resolver that is chosen by default in TfLite Python, which is the "BUILTIN" as described below. * `BUILTIN`: Indicates the op resolver for built-in ops with optimized kernel implementation. * `BUI...
OpResolverType
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_rank_manager.py
{ "start": 370, "end": 871 }
class ____: """Mock replica for testing without heavy dependencies.""" def __init__( self, replica_id: str, deployment_name: str = "test_deployment", app_name: str = "test_app", ): self.replica_id = ReplicaID( unique_id=replica_id, deployment_...
MockDeploymentReplica
python
doocs__leetcode
solution/0500-0599/0540.Single Element in a Sorted Array/Solution.py
{ "start": 0, "end": 294 }
class ____: def singleNonDuplicate(self, nums: List[int]) -> int: l, r = 0, len(nums) - 1 while l < r: mid = (l + r) >> 1 if nums[mid] != nums[mid ^ 1]: r = mid else: l = mid + 1 return nums[l]
Solution
python
ray-project__ray
python/ray/llm/_internal/common/callbacks/base.py
{ "start": 4620, "end": 5094 }
class ____: """Configuration for the callback to be used in LLMConfig""" callback_class: Union[str, Type[CallbackBase]] = CallbackBase """Class to use for the callback. Can be custom user defined class""" callback_kwargs: Dict[str, Any] = field(default_factory=dict) """Keyword arguments to pass to ...
CallbackConfig
python
getsentry__sentry
src/sentry/hybridcloud/rpc/sig.py
{ "start": 263, "end": 482 }
class ____(Exception): def __init__(self, signature: SerializableFunctionSignature, message: str) -> None: super().__init__(f"{signature.generate_name('.')}: {message}")
_SerializableFunctionSignatureException
python
walkccc__LeetCode
solutions/771. Jewels and Stones/771.py
{ "start": 0, "end": 163 }
class ____: def numJewelsInStones(self, jewels: str, stones: str) -> int: jewelsSet = set(jewels) return sum(stone in jewelsSet for stone in stones)
Solution
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 63035, "end": 65126 }
class ____(BaseModel): """ Task serializer for responses. """ task_id: Annotated[str | None, Field(title="Task Id")] = None task_display_name: Annotated[str | None, Field(title="Task Display Name")] = None owner: Annotated[str | None, Field(title="Owner")] = None start_date: Annotated[datet...
TaskResponse
python
networkx__networkx
networkx/tests/test_relabel.py
{ "start": 143, "end": 14554 }
class ____: def test_convert_node_labels_to_integers(self): # test that empty graph converts fine for all options G = empty_graph() H = nx.convert_node_labels_to_integers(G, 100) assert list(H.nodes()) == [] assert list(H.edges()) == [] for opt in ["default", "sorted...
TestRelabel
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_numeric_columns.py
{ "start": 546, "end": 2357 }
class ____(DataProfilerProfileMetricProvider): metric_name = "data_profiler.profile_numeric_columns" value_keys = ("profile_path",) @metric_value(engine=PandasExecutionEngine) def _pandas( cls, execution_engine, metric_domain_kwargs, metric_value_kwargs, metrics...
DataProfilerProfileNumericColumns
python
getsentry__responses
responses/__init__.py
{ "start": 3202, "end": 6888 }
class ____: """Class to mock up built-in False boolean. Used for backwards compatibility, see https://github.com/getsentry/responses/issues/464 """ def __bool__(self) -> bool: return False def urlencoded_params_matcher(params: Optional[Dict[str, str]]) -> Callable[..., Any]: warn( ...
FalseBool
python
PyCQA__pylint
pylint/checkers/base_checker.py
{ "start": 8594, "end": 8887 }
class ____(BaseChecker): """Base class for checkers that want to have access to the token stream.""" @abc.abstractmethod def process_tokens(self, tokens: list[TokenInfo]) -> None: """Should be overridden by subclasses.""" raise NotImplementedError()
BaseTokenChecker
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/writeonly.py
{ "start": 15912, "end": 16352 }
class ____: """simplified CollectionAdapter for internal API consistency""" data: Collection[Any] def __init__(self, data: Collection[Any]): self.data = data def __iter__(self) -> Iterator[Any]: return iter(self.data) def _reset_empty(self) -> None: pass def __len__(...
_DynamicCollectionAdapter
python
PyCQA__pylint
tests/functional/s/super/super_checks.py
{ "start": 1247, "end": 1292 }
class ____: """Just an empty class."""
Empty
python
langchain-ai__langchain
libs/core/tests/unit_tests/indexing/test_in_memory_indexer.py
{ "start": 653, "end": 1699 }
class ____(AsyncDocumentIndexTestSuite): # Something funky is going on with mypy and async pytest fixture @pytest.fixture @override async def index(self) -> AsyncGenerator[DocumentIndex, None]: yield InMemoryDocumentIndex() # noqa: PT022 def test_sync_retriever() -> None: index = InMemory...
TestAsyncDocumentIndexerTestSuite
python
apache__thrift
test/py.twisted/test_suite.py
{ "start": 1473, "end": 2705 }
class ____: def __init__(self): self.onewaysQueue = defer.DeferredQueue() def testVoid(self): pass def testString(self, s): return s def testByte(self, b): return b def testI16(self, i16): return i16 def testI32(self, i32): return i32 def...
TestHandler
python
apache__airflow
airflow-core/src/airflow/traces/tracer.py
{ "start": 4816, "end": 6456 }
class ____: """If no Tracer is configured, EmptyTracer is used as a fallback.""" @classmethod def get_tracer( cls, component: str, trace_id: int | None = None, span_id: int | None = None, ): """Get a tracer using provided node id and trace id.""" return c...
EmptyTrace
python
astropy__astropy
astropy/io/fits/header.py
{ "start": 1502, "end": 67693 }
class ____: """ FITS header class. This class exposes both a dict-like interface and a list-like interface to FITS headers. The header may be indexed by keyword and, like a dict, the associated value will be returned. When the header contains cards with duplicate keywords, only the value of t...
Header
python
doocs__leetcode
solution/2000-2099/2011.Final Value of Variable After Performing Operations/Solution.py
{ "start": 0, "end": 152 }
class ____: def finalValueAfterOperations(self, operations: List[str]) -> int: return sum(1 if s[1] == '+' else -1 for s in operations)
Solution
python
doocs__leetcode
solution/2300-2399/2393.Count Strictly Increasing Subarrays/Solution.py
{ "start": 0, "end": 259 }
class ____: def countSubarrays(self, nums: List[int]) -> int: ans = cnt = 1 for x, y in pairwise(nums): if x < y: cnt += 1 else: cnt = 1 ans += cnt return ans
Solution
python
getsentry__sentry
tests/sentry/integrations/jira/test_utils.py
{ "start": 237, "end": 723 }
class ____(TestCase): def test_jira_cloud(self) -> None: user_response = StubService.get_stub_data("jira", "user.json") assert build_user_choice(user_response, "accountId") == ( "012345:00000000-1111-2222-3333-444444444444", "Saif Hakim", ) def test_unexpected_id...
BuildUserChoiceTest
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py
{ "start": 1682, "end": 6812 }
class ____: root_path: Path workspace_root_path: Optional[Path] = None root_file_path: Optional[Path] = None root_validation_result: Optional["DgConfigValidationResult"] = None container_workspace_file_path: Optional[Path] = None container_workspace_validation_result: Optional["DgConfigValidatio...
DgConfigFileDiscoveryResult
python
fluentpython__example-code-2e
21-async/domains/curio/domainlib.py
{ "start": 143, "end": 646 }
class ____(NamedTuple): domain: str found: bool async def probe(domain: str) -> Result: try: await socket.getaddrinfo(domain, None) except socket.gaierror: return Result(domain, False) return Result(domain, True) async def multi_probe(domains: Iterable[str]) -> AsyncIterator[Resu...
Result
python
automl__auto-sklearn
autosklearn/pipeline/components/regression/liblinear_svr.py
{ "start": 564, "end": 3916 }
class ____(AutoSklearnRegressionAlgorithm): # Liblinear is not deterministic as it uses a RNG inside def __init__( self, loss, epsilon, dual, tol, C, fit_intercept, intercept_scaling, random_state=None, ): self.epsilon = epsilon...
LibLinear_SVR
python
tensorflow__tensorflow
tensorflow/python/ops/distributions/gamma.py
{ "start": 10078, "end": 12218 }
class ____(Gamma): """`Gamma` with softplus of `concentration` and `rate`.""" @deprecation.deprecated( "2019-01-01", "Use `tfd.Gamma(tf.nn.softplus(concentration), " "tf.nn.softplus(rate))` instead.", warn_once=True) def __init__(self, concentration, rate, ...
GammaWithSoftplusConcentrationRate
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 14199, "end": 16814 }
class ____: @pytest.fixture def crawler(self) -> Crawler: return get_crawler(Spider) @pytest.fixture def mwman(self, crawler: Crawler) -> SpiderMiddlewareManager: return SpiderMiddlewareManager.from_crawler(crawler) def test_simple_mw(self, mwman: SpiderMiddlewareManager) -> None: ...
TestUniversalMiddlewareManager
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 80166, "end": 80511 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.weight = torch.rand((5, 5)) self.bias = torch.zeros(5) def forward(self, x): return F.linear(x, self.weight, self.bias) def get_example_inputs(self) -> tuple[Any, ...]: return (torch.ra...
FunctionalLinear
python
prompt-toolkit__python-prompt-toolkit
tests/test_print_formatted_text.py
{ "start": 359, "end": 3039 }
class ____: "Emulate an stdout object." def __init__(self): self._data = [] def write(self, data): self._data.append(data) @property def data(self): return "".join(self._data) def flush(self): pass def isatty(self): return True def fileno(sel...
_Capture
python
google__jax
tests/api_test.py
{ "start": 257174, "end": 257710 }
class ____(jtu.JaxTestCase): @unittest.skipIf(not sys.executable, "test requires sys.executable") @jtu.run_on_devices("cpu") def test_no_backend_warning_on_cpu_if_platform_specified(self): warning_not_expected = ( "import jax; " "jax.config.update('jax_platform_name', 'cpu'); " "jax.numpy.a...
BackendsTest
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 2370, "end": 2780 }
class ____: """Regression test for 4644""" __seventyseven = 77 __ninetyone = 91 def __init__(self): self.twentyone = 21 * (1 / (self.__seventyseven + 33)) % 100 self.ninetyfive = Klass.__ninetyone + 4 k = Klass() print(k.twentyone) print(k.ninetyfive) # https://github.com/pylint-dev...
Klass
python
pypa__warehouse
warehouse/oidc/views.py
{ "start": 1342, "end": 1403 }
class ____(TypedDict): code: str description: str
Error
python
docker__docker-py
docker/types/services.py
{ "start": 29780, "end": 30493 }
class ____(dict): """ Specification for DNS related configurations in resolver configuration file (``resolv.conf``). Part of a :py:class:`ContainerSpec` definition. Args: nameservers (:py:class:`list`): The IP addresses of the name servers. search (:p...
DNSConfig
python
walkccc__LeetCode
solutions/2379. Minimum Recolors to Get K Consecutive Black Blocks/2379.py
{ "start": 0, "end": 318 }
class ____: def minimumRecolors(self, blocks: str, k: int) -> int: countB = 0 maxCountB = 0 for i, block in enumerate(blocks): if block == 'B': countB += 1 if i >= k and blocks[i - k] == 'B': countB -= 1 maxCountB = max(maxCountB, countB) return k - maxCountB
Solution
python
spack__spack
lib/spack/spack/test/repo.py
{ "start": 18269, "end": 19136 }
class ____(PackageBase): pass """ ) with spack.repo.use_repositories(str(repo_dir)) as repo: assert len(repo.all_package_names()) == 0 stderr = capsys.readouterr().err assert "cannot be used because `zlib-ng` is not a valid Spack package module name" in stderr assert "cannot be used be...
Uppercase
python
pallets__werkzeug
src/werkzeug/sansio/request.py
{ "start": 1268, "end": 19832 }
class ____: """Represents the non-IO parts of a HTTP request, including the method, URL info, and headers. This class is not meant for general use. It should only be used when implementing WSGI, ASGI, or another HTTP application spec. Werkzeug provides a WSGI implementation at :cls:`werkzeug.wrappe...
Request
python
numba__numba
numba/core/utils.py
{ "start": 6822, "end": 9629 }
class ____(object): OPTIONS = {} def __init__(self): self._values = self.OPTIONS.copy() def set(self, name, value=True): if name not in self.OPTIONS: raise NameError("Invalid flag: %s" % name) self._values[name] = value def unset(self, name): self.set(name,...
ConfigOptions
python
has2k1__plotnine
plotnine/scales/scale_color.py
{ "start": 8290, "end": 9064 }
class ____(_scale_color_continuous): """ Create a n color gradient See Also -------- plotnine.scale_color_gradient plotnine.scale_color_gradientn mizani.palettes.gradient_n_pal : The palette class that generates the colour gradient. """ colors: InitVar[Sequence[str]] ""...
scale_color_gradientn
python
django-import-export__django-import-export
tests/core/tests/test_tmp_storages.py
{ "start": 376, "end": 810 }
class ____(TestCase): def setUp(self): self.storage = BaseStorage() def test_save(self): with self.assertRaises(NotImplementedError): self.storage.save(None) def test_read(self): with self.assertRaises(NotImplementedError): self.storage.read() def test_...
TestBaseStorage
python
wandb__wandb
wandb/vendor/pygments/lexers/hexdump.py
{ "start": 394, "end": 3507 }
class ____(RegexLexer): """ For typical hex dump output formats by the UNIX and GNU/Linux tools ``hexdump``, ``hd``, ``hexcat``, ``od`` and ``xxd``, and the DOS tool ``DEBUG``. For example: .. sourcecode:: hexdump 00000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| ...
HexdumpLexer
python
numba__llvmlite
llvmlite/binding/value.py
{ "start": 997, "end": 1685 }
class ____(enum.IntEnum): # The LLVMValueKind enum from llvm-c/Core.h argument = 0 basic_block = 1 memory_use = 2 memory_def = 3 memory_phi = 4 function = 5 global_alias = 6 global_ifunc = 7 global_variable = 8 block_address = 9 constant_expr = 10 constant_array = 1...
ValueKind
python
pypa__pipenv
pipenv/vendor/colorama/winterm.py
{ "start": 621, "end": 7134 }
class ____(object): def __init__(self): self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back self._default_style = self._style # In order to emulate LI...
WinTerm
python
ray-project__ray
python/ray/tune/tests/test_tune_restore_warm_start.py
{ "start": 822, "end": 4931 }
class ____: def setUp(self): ray.init(num_cpus=1) self.tmpdir = tempfile.mkdtemp() self.experiment_name = "results" def tearDown(self): shutil.rmtree(self.tmpdir) ray.shutdown() _register_all() def set_basic_conf(self): raise NotImplementedError() ...
AbstractWarmStartTest
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/10_A3C/A3C_RNN.py
{ "start": 5384, "end": 9429 }
class ____(object): def __init__(self, name, globalAC): self.env = gym.make(GAME).unwrapped self.name = name self.AC = ACNet(name, globalAC) def work(self): global GLOBAL_RUNNING_R, GLOBAL_EP total_step = 1 buffer_s, buffer_a, buffer_r = [], [], [] while ...
Worker
python
pydata__xarray
asv_bench/benchmarks/combine.py
{ "start": 1681, "end": 2833 }
class ____: """Benchmark concatenating and merging large datasets""" def setup(self): """Create 4 datasets with two different variables""" t_size, x_size, y_size = 50, 450, 400 t = np.arange(t_size) data = np.random.randn(t_size, x_size, y_size) self.dsA0 = xr.Dataset(...
Combine3d
python
django__django
tests/generic_relations_regress/models.py
{ "start": 4078, "end": 4192 }
class ____(models.Model): b = models.ForeignKey(B, models.CASCADE) class Meta: ordering = ("id",)
C
python
huggingface__transformers
src/transformers/models/owlvit/modeling_owlvit.py
{ "start": 12491, "end": 16074 }
class ____(nn.Module): def __init__(self, config: OwlViTVisionConfig): super().__init__() self.patch_size = config.patch_size self.config = config self.embed_dim = config.hidden_size self.class_embedding = nn.Parameter(torch.randn(config.hidden_size)) self.patch_embe...
OwlViTVisionEmbeddings
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 328625, "end": 335799 }
class ____(CompositeMarkDef): """ ErrorBandDef schema wrapper. Parameters ---------- type : :class:`ErrorBand`, Literal['errorband'] The mark type. This could a primitive mark type (one of ``"bar"``, ``"circle"``, ``"square"``, ``"tick"``, ``"line"``, ``"area"``, ``"point"``, ``"geo...
ErrorBandDef
python
viewflow__viewflow
viewflow/workflow/flow/nodes.py
{ "start": 8054, "end": 8445 }
class ____( mixins.NodeDetailMixin, mixins.NodeExecuteMixin, mixins.NodeCancelMixin, mixins.NodeUndoMixin, mixins.NodeReviveMixin, nodes.Join, ): index_view_class = views.IndexTaskView detail_view_class = views.DetailTaskView cancel_view_class = views.CancelTaskView undo_view_cla...
Join
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classVar2.py
{ "start": 174, "end": 282 }
class ____(t.Protocol): var1: t.ClassVar[str] var2: t.ClassVar[str] var3: _ClassVar = ["hi"]
Proto
python
mozilla__bleach
bleach/_vendor/html5lib/_utils.py
{ "start": 1333, "end": 2358 }
class ____(dict): """Dict with 2 special properties: On initiation, keys that are lists, sets or tuples are converted to multiple keys so accessing any one of the items in the original list-like object returns the matching value md = MethodDispatcher({("foo", "bar"):"baz"}) md["foo"] == "baz" ...
MethodDispatcher
python
getsentry__sentry
src/social_auth/exceptions.py
{ "start": 47, "end": 138 }
class ____(ValueError): """Base class for pipeline exceptions."""
SocialAuthBaseException
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 3860, "end": 4204 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.String) partitionName = graphene.NonNull(graphene.String) runId = graphene.Field(graphene.String) runStatus = graphene.Field(GrapheneRunStatus) runDuration = graphene.Field(graphene.Float) class Meta: name = "PartitionStatu...
GraphenePartitionStatus
python
MongoEngine__mongoengine
mongoengine/base/document.py
{ "start": 832, "end": 46593 }
class ____: # TODO simplify how `_changed_fields` is used. # Currently, handling of `_changed_fields` seems unnecessarily convoluted: # 1. `BaseDocument` defines `_changed_fields` in its `__slots__`, yet it's # not setting it to `[]` (or any other value) in `__init__`. # 2. `EmbeddedDocument` set...
BaseDocument
python
google__pytype
pytype/pytd/optimize.py
{ "start": 17405, "end": 21153 }
class ____(visitors.Visitor): """Simplifies classes with only a __call__ function to just a method. This transforms class Foo: m: Bar class Bar: def __call__(self: Foo, ...) to class Foo: def m(self, ...) . """ def __init__(self): super().__init__() self._module = Non...
PullInMethodClasses
python
huggingface__transformers
tests/models/data2vec/test_modeling_data2vec_audio.py
{ "start": 24282, "end": 26914 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( lambda x: x["id"] in [f"1272-141231-00...
Data2VecAudioModelIntegrationTest
python
Netflix__metaflow
test/parallel/pytorch_parallel_test_flow.py
{ "start": 83, "end": 2332 }
class ____(FlowSpec): """ Test flow to test @pytorch_parallel. """ num_parallel = Parameter( "num_parallel", help="Number of nodes in cluster", default=3 ) @step def start(self): self.next(self.parallel_step, num_parallel=self.num_parallel) @pytorch_parallel @step ...
PytorchParallelTest
python
coleifer__peewee
playhouse/sqlite_ext.py
{ "start": 1077, "end": 1439 }
class ____(AutoField): auto_increment = True column_name = name = required_name = 'rowid' def bind(self, model, name, *args): if name != self.required_name: raise ValueError('%s must be named "%s".' % (type(self), self.required_name)) super(RowIDFiel...
RowIDField
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 85625, "end": 86127 }
class ____: def test_simple(self): a = [1, 2, 3] b = [1, 2, np.inf] c = [1, 2, np.nan] np.asarray_chkfinite(a) assert_raises(ValueError, np.asarray_chkfinite, b) assert_raises(ValueError, np.asarray_chkfinite, c) def test_dtype_order(self): # Regression ...
TestCheckFinite
python
apache__airflow
providers/standard/src/airflow/providers/standard/triggers/external_task.py
{ "start": 1377, "end": 7588 }
class ____(BaseTrigger): """ A trigger to monitor tasks, task group and dag execution in Apache Airflow. :param external_dag_id: The ID of the external dag. :param run_ids: A list of run ids for the external dag. :param external_task_ids: A collection of external task IDs to wait for. :param ex...
WorkflowTrigger
python
bokeh__bokeh
tests/unit/bokeh/models/test_mappers.py
{ "start": 3822, "end": 4145 }
class ____: def test_basic(self) -> None: mapper = bmm.LinearColorMapper() check_properties_existence(mapper, [ "palette", "domain", "low", "high", "low_color", "high_color", "nan_color"], )
Test_LinearColorMapper
python
PyCQA__pylint
tests/functional/u/used/used_before_assignment.py
{ "start": 3677, "end": 4306 }
class ____: # pylint: disable=invalid-name, too-few-public-methods, undefined-variable '''Issue #8754, no crash from unexpected assignment between attribute and variable''' T.attr = attr if outer(): NOT_ALWAYS_DEFINED = True print(NOT_ALWAYS_DEFINED) # [used-before-assignment] def inner_if_continues_o...
T
python
modin-project__modin
modin/core/dataframe/pandas/interchange/dataframe_protocol/exception.py
{ "start": 894, "end": 1035 }
class ____(Exception): """Exception to be raised if there is no validity buffer for ``PandasProtocolColumn``.""" pass
NoValidityBuffer
python
pytorch__pytorch
test/test_file_check.py
{ "start": 140, "end": 1369 }
class ____(TestCase): def test_not_run(self): stdout, _ = self.run_process_no_exception( """\ from torch.testing import FileCheck file_check = FileCheck().check("not run") del file_check """, ) FileCheck().check("You have not run this instance of FileCheck!").check_next( ...
TestFileCheck
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 18745, "end": 18840 }
class ____(IterableExportEventsStreamAdjustableRange): data_field = "customEvent"
CustomEvent
python
huggingface__transformers
src/transformers/models/xlm_roberta/modular_xlm_roberta.py
{ "start": 9393, "end": 12977 }
class ____(RobertaForSequenceClassification): def __init__(self, config): super().__init__(config) del self.xlm_roberta self.roberta = XLMRobertaModel(config, add_pooling_layer=False) @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch...
XLMRobertaForSequenceClassification
python
Farama-Foundation__Gymnasium
gymnasium/envs/tabular/cliffwalking.py
{ "start": 12591, "end": 13648 }
class ____(FunctionalJaxEnv, EzPickle): """A Gymnasium Env wrapper for the functional cliffwalking env.""" metadata = {"render_modes": ["rgb_array"], "render_fps": 50, "jax": True} def __init__(self, render_mode: str | None = None, **kwargs): """Initializes Gym wrapper for cliffwalking functional ...
CliffWalkingJaxEnv
python
PyCQA__pylint
tests/functional/t/too/too_few_public_methods.py
{ "start": 592, "end": 852 }
class ____: """A class can define only special methods.""" def __init__(self, iterable): self._list = list(iterable) def __len__(self): return len(self._list) def __getitem__(self, index): return self._list[index]
DumbList
python
pypa__warehouse
tests/unit/admin/views/test_projects.py
{ "start": 2286, "end": 4965 }
class ____: def test_gets_project(self, db_request): project = ProjectFactory.create() journals = sorted( JournalEntryFactory.create_batch(75, name=project.name), key=lambda x: (x.submitted_date, x.id), reverse=True, ) roles = sorted( R...
TestProjectDetail
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 47872, "end": 48620 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 4]"): l_x_ = L_x_ wrap_body_0 = self.wrap_body_0 wrap = torch.ops.higher_order.wrap(wrap_body_0, l_x_); wrap_body_0 = l_x_ = None getitem: "f32[3, 4]" = wrap[0]; wrap = None return (getitem,) class wrap_body...
GraphModule
python
huggingface__transformers
src/transformers/models/encodec/modeling_encodec.py
{ "start": 2586, "end": 2867 }
class ____(ModelOutput): r""" audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*): Decoded audio values, obtained using the decoder part of Encodec. """ audio_values: Optional[torch.FloatTensor] = None
EncodecDecoderOutput
python
matplotlib__matplotlib
lib/matplotlib/testing/jpl_units/UnitDbl.py
{ "start": 87, "end": 5882 }
class ____: """Class UnitDbl in development.""" # Unit conversion table. Small subset of the full one but enough # to test the required functions. First field is a scale factor to # convert the input units to the units of the second field. Only # units in this table are allowed. allowed = { ...
UnitDbl
python
google__jax
jax/_src/pallas/pipelining/schedulers.py
{ "start": 11589, "end": 20563 }
class ____(Protocol): def __call__( self, ctx: PipelineContext, stage: internal.PipelineStage, args: Sequence[Any], ) -> PipelineState: ... def eval_stage(ctx: PipelineContext, stage: internal.PipelineStage, args ) -> PipelineState: """Evaluates a single stage.""" fl...
EvalStageFunc
python
milvus-io__pymilvus
pymilvus/bulk_writer/bulk_writer.py
{ "start": 1086, "end": 14325 }
class ____: def __init__( self, schema: CollectionSchema, chunk_size: int, file_type: BulkFileType, config: Optional[dict] = None, **kwargs, ): self._schema = schema self._buffer_size = 0 self._buffer_row_count = 0 self._total_row_c...
BulkWriter
python
allegroai__clearml
clearml/backend_interface/metrics/events.py
{ "start": 18730, "end": 19633 }
class ____(UploadEvent): def __init__( self, metric: str, variant: str, stream: Union[io.StringIO, io.BytesIO], local_image_path: Optional[str] = None, iter: int = 0, upload_uri: Optional[str] = None, file_history_size: Optional[int] = None, de...
MediaEvent
python
pypa__setuptools
setuptools/warnings.py
{ "start": 3420, "end": 3796 }
class ____(SetuptoolsWarning): """ Base class for warning deprecations in ``setuptools`` This class is not derived from ``DeprecationWarning``, and as such is visible by default. """ def _should_enforce(): enforce = os.getenv("SETUPTOOLS_ENFORCE_DEPRECATION", "false").lower() return enfor...
SetuptoolsDeprecationWarning
python
pypa__warehouse
tests/unit/test_forms.py
{ "start": 1074, "end": 2495 }
class ____: def test_invalid_fields(self): validator = PasswordStrengthValidator(user_input_fields=["foo"]) with pytest.raises(ValidationError) as exc: validator({}, pretend.stub()) assert str(exc.value) == "Invalid field name: 'foo'" @pytest.mark.parametrize("password", ["t...
TestPasswordStrengthValidator
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/document_summary/retrievers.py
{ "start": 4685, "end": 7206 }
class ____(BaseRetriever): """ Document Summary Index Embedding Retriever. Args: index (DocumentSummaryIndex): The index to retrieve from. similarity_top_k (int): The number of summary nodes to retrieve. """ def __init__( self, index: DocumentSummaryIndex, ...
DocumentSummaryIndexEmbeddingRetriever
python
kamyu104__LeetCode-Solutions
Python/count-beautiful-substrings-i.py
{ "start": 79, "end": 976 }
class ____(object): def beautifulSubstrings(self, s, k): """ :type s: str :type k: int :rtype: int """ VOWELS = set("aeiou") prefix = [0]*(len(s)+1) for i in xrange(len(s)): prefix[i+1] = prefix[i]+(+1 if s[i] in VOWELS else -1) new...
Solution
python
langchain-ai__langchain
libs/core/langchain_core/prompt_values.py
{ "start": 3057, "end": 3532 }
class ____(PromptValue): """Image prompt value.""" image_url: ImageURL """Image URL.""" type: Literal["ImagePromptValue"] = "ImagePromptValue" def to_string(self) -> str: """Return prompt (image URL) as string.""" return self.image_url.get("url", "") def to_messages(self) -> l...
ImagePromptValue
python
mahmoud__boltons
boltons/cacheutils.py
{ "start": 11340, "end": 13180 }
class ____(LRI): """The ``LRU`` is :class:`dict` subtype implementation of the *Least-Recently Used* caching strategy. Args: max_size (int): Max number of items to cache. Defaults to ``128``. values (iterable): Initial values for the cache. Defaults to ``None``. on_miss (callable): ...
LRU
python
jazzband__django-oauth-toolkit
tests/test_auth_backends.py
{ "start": 1464, "end": 3483 }
class ____(BaseTest): def test_authenticate(self): auth_headers = { "HTTP_AUTHORIZATION": "Bearer " + "tokstr", } request = self.factory.get("/a-resource", **auth_headers) backend = OAuth2Backend() credentials = {"request": request} u = backend.authentica...
TestOAuth2Backend
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 24960, "end": 28252 }
class ____(Response): """ Response of models.archive_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "models" _action = "archive_many" _version = "2.23" _schema = { "definitions": {}, ...
ArchiveManyResponse
python
pytorch__pytorch
torch/fx/passes/pass_manager.py
{ "start": 4692, "end": 7085 }
class ____: """ Construct a PassManager. Collects passes and constraints. This defines the pass schedule, manages pass constraints and pass execution. Args: passes (Optional[List[Callable]]): list of passes. A pass is a callable which modifies an object and returns modified obj...
PassManager