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
wandb__wandb
wandb/sdk/artifacts/exceptions.py
{ "start": 2015, "end": 2170 }
class ____(ValueError): """Raised when there are fewer items than expected in a collection. Intended for internal use only. """
TooFewItemsError
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 10735, "end": 10969 }
class ____(models.Model): random_char_field = RandomCharField(length=8, lowercase=True) class Meta: app_label = "django_extensions" verbose_name = "lowercase alpha digits"
RandomCharTestModelLowercaseAlphaDigits
python
miyuchina__mistletoe
test/test_block_token.py
{ "start": 28561, "end": 29447 }
class ____(unittest.TestCase): def test_get_set_pos(self): lines = [ "# heading\n", "somewhat interesting\n", "content\n", ] wrapper = block_tokenizer.FileWrapper(lines) assert next(wrapper) == "# heading\n" anchor = wrapper.get_pos() ...
TestFileWrapper
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/api.py
{ "start": 3457, "end": 4400 }
class ____: """Holds the information about the rendezvous.""" def __init__( self, store: Store, rank: int, world_size: int, bootstrap_store_info: RendezvousStoreInfo, ): self._store = store self._rank = rank self._world_size = world_size ...
RendezvousInfo
python
numba__numba
numba/tests/test_listobject.py
{ "start": 3883, "end": 7349 }
class ____(MemoryLeakMixin, TestCase): """Test list getitem. """ def test_list_getitem_singleton(self): @njit def foo(n): l = listobject.new_list(int32) l.append(n) return l[0] self.assertEqual(foo(0), 0) def test_list_getitem_singleton_negtive_...
TestGetitem
python
plotly__plotly.py
plotly/graph_objs/choroplethmapbox/_selected.py
{ "start": 233, "end": 2497 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "choroplethmapbox" _path_str = "choroplethmapbox.selected" _valid_props = {"marker"} @property def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :c...
Selected
python
pytorch__pytorch
test/inductor/test_snode_runtime.py
{ "start": 2480, "end": 2856 }
class ____(TestCase): device = DEVICE def test_no_op(self): def f(a): return a inp = (T(10, 10),) self.assertZero(calculate_runtime(f, *inp)) def test_no_cuda(self): def f(a): return a inp = (torch.randn((10, 10), device="cpu"),) se...
UnsupportedTests
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/common_transformers/anf_test.py
{ "start": 13204, "end": 15474 }
class ____(AnfTestBase): def test_constants_in_function_calls(self): # An example specific configuration that differs from the default: Moving # literals out of being directly passed to functions, but nothing else. try: # TODO(b/140808434): Fix this. # gast pre-0.3 literals = (gast.Num,...
AnfConfiguredTest
python
pyca__cryptography
src/cryptography/fernet.py
{ "start": 5225, "end": 6963 }
class ____: def __init__(self, fernets: Iterable[Fernet]): fernets = list(fernets) if not fernets: raise ValueError( "MultiFernet requires at least one Fernet instance" ) self._fernets = fernets def encrypt(self, msg: bytes) -> bytes: retu...
MultiFernet
python
google__pytype
pytype/pytd/visitors.py
{ "start": 1457, "end": 4144 }
class ____(Visitor): """Fill in ClassType pointers using symbol tables. This is an in-place visitor! It modifies the original tree. This is necessary because we introduce loops. """ def __init__(self, lookup_map, fallback=None): """Create this visitor. You're expected to then pass this instance to ...
FillInLocalPointers
python
getsentry__sentry
tests/sentry/issues/test_attributes.py
{ "start": 7519, "end": 9697 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.group_2 = self.create_group() def test(self) -> None: self.run_attr_test([self.group, self.group_2], {"status": GroupStatus.RESOLVED}, "status") self.run_attr_test( [self.group, self.group_2], ...
PostUpdateLogGroupAttributesChangedTest
python
walkccc__LeetCode
solutions/3218. Minimum Cost for Cutting Cake I/3218.py
{ "start": 0, "end": 546 }
class ____: def minimumCost( self, m: int, n: int, horizontalCut: list[int], verticalCut: list[int], ) -> int: ans = 0 sumH = sum(horizontalCut) sumV = sum(verticalCut) horizontalCut.sort() verticalCut.sort() while horizontalCut and verticalCut: if horiz...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes1.py
{ "start": 996, "end": 1158 }
class ____(type[T]): pass def func2(cls: type[T]): class M(cls): pass def func3(cls: T2) -> T2: class M(cls): pass return M
L
python
walkccc__LeetCode
solutions/111. Minimum Depth of Binary Tree/111-2.py
{ "start": 0, "end": 408 }
class ____: def minDepth(self, root: TreeNode | None) -> int: if not root: return 0 q = collections.deque([root]) step = 1 while q: for _ in range(len(q)): node = q.popleft() if not node.left and not node.right: return step if node.left: q.appe...
Solution
python
pydata__xarray
xarray/tests/test_plot.py
{ "start": 71658, "end": 73496 }
class ____(PlotTestCase): """ Test pcolormesh axes when x and y are in logscale """ plotfunc = staticmethod(xplt.pcolormesh) @pytest.fixture(autouse=True) def setUp(self) -> None: self.boundaries = (-1, 9, -4, 3) shape = (8, 11) x = np.logspace(self.boundaries[0], self....
TestPcolormeshLogscale
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 80846, "end": 81248 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear1 = FunctionalLinear() self.linear2 = FunctionalLinear() def forward(self, x): x = self.linear1(x) x = self.linear2(x) return x def get_example_inputs(self) -> tuple[Any, ...
TwoLayerFunctionalLinearModel
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 21851, "end": 22680 }
class ____(unittest.TestCase): # A RuntimeError should be raised if Thread.start() is called # multiple times. # pylint:disable=bad-thread-instantiation def test_start_thread_again(self): thread_ = threading.Thread() thread_.start() self.assertRaises(RuntimeError, thread_.start) ...
ThreadingExceptionTests
python
python-markdown__markdown
markdown/blockprocessors.py
{ "start": 10571, "end": 12055 }
class ____(BlockProcessor): """ Process code blocks. """ def test(self, parent: etree.Element, block: str) -> bool: return block.startswith(' '*self.tab_length) def run(self, parent: etree.Element, blocks: list[str]) -> None: sibling = self.lastChild(parent) block = blocks.pop(0) ...
CodeBlockProcessor
python
ApeWorX__ape
src/ape/managers/query.py
{ "start": 649, "end": 3763 }
class ____(QueryAPI): """ Default implementation of the :class:`~ape.api.query.QueryAPI`. Allows for the query of blockchain data using connected provider. """ def __init__(self): self.supports_contract_creation = None @singledispatchmethod def estimate_query(self, query: QueryType...
DefaultQueryProvider
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess1.py
{ "start": 396, "end": 619 }
class ____(Generic[_T]): @overload def __get__(self, instance: None, owner: Any) -> "DescriptorA[_T]": # type: ignore ... @overload def __get__(self, instance: Any, owner: Any) -> _T: ...
DescriptorA
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 25671, "end": 27548 }
class ____(Token): """Represents a 'for-loop' in the code. Expressions are of the form: "for target in iter: body..." Parameters ========== target : symbol iter : iterable body : CodeBlock or iterable ! When passed an iterable it is used to instantiate a CodeBlo...
For
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py
{ "start": 15779, "end": 17168 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.hidden_size = config.hidden_size self.num_experts = config.num_experts self.top_k = config.num_experts_per_tok self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False) self.exp...
Qwen3VLMoeTextSparseMoeBlock
python
openai__openai-python
src/openai/resources/vector_stores/files.py
{ "start": 39018, "end": 39703 }
class ____: def __init__(self, files: AsyncFiles) -> None: self._files = files self.create = async_to_streamed_response_wrapper( files.create, ) self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) self.update = async_to_strea...
AsyncFilesWithStreamingResponse
python
ApeWorX__ape
src/ape/contracts/base.py
{ "start": 1705, "end": 3710 }
class ____(ManagerAccessMixin): def __init__( self, deployment_bytecode: HexBytes, abi: "ConstructorABI", ) -> None: self.deployment_bytecode = deployment_bytecode self.abi = abi if not self.deployment_bytecode: logger.warning("Deploying an empty cont...
ContractConstructor
python
crytic__slither
slither/core/declarations/modifier.py
{ "start": 78, "end": 121 }
class ____(FunctionContract): pass
Modifier
python
pytorch__pytorch
test/quantization/pt2e/test_xnnpack_quantizer.py
{ "start": 43232, "end": 45933 }
class ____(PT2EQuantizationTestCase): @skip_if_no_torchvision @skipIfNoQNNPACK def test_resnet18(self): import torchvision with override_quantized_engine("qnnpack"): example_inputs = (torch.randn(1, 3, 224, 224),) m = torchvision.models.resnet18().eval() ...
TestXNNPACKQuantizerModels
python
django__django
django/contrib/gis/db/backends/oracle/models.py
{ "start": 488, "end": 1421 }
class ____(models.Model): "Maps to the Oracle USER_SDO_GEOM_METADATA table." table_name = models.CharField(max_length=32) column_name = models.CharField(max_length=1024) srid = models.IntegerField(primary_key=True) # TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY). class Meta...
OracleGeometryColumns
python
run-llama__llama_index
llama-index-packs/llama-index-packs-fuzzy-citation/llama_index/packs/fuzzy_citation/base.py
{ "start": 421, "end": 4388 }
class ____(CustomQueryEngine): """ Runs any query engine and then analyzes the response to find relevant sentences. Using fuzzy matching, response.metadata is assigned to a dictionary containing a mapping of response+node sentence pairs and the node text start and end character indices in the origi...
FuzzyCitationQueryEngine
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 12662, "end": 13117 }
class ____(HTTPException): """*406* `Not Acceptable` Raise if the server can't return any content conforming to the `Accept` headers of the client. """ code = 406 description = ( "The resource identified by the request is only capable of" " generating response entities which ha...
NotAcceptable
python
FactoryBoy__factory_boy
tests/test_mongoengine.py
{ "start": 394, "end": 526 }
class ____(mongoengine.Document): name = mongoengine.StringField() address = mongoengine.EmbeddedDocumentField(Address)
Person
python
PyCQA__pylint
tests/functional/t/too/too_few_public_methods_37.py
{ "start": 398, "end": 481 }
class ____: date_from = None date_to = None @dataclass
ScheduledTxSearchModel
python
kamyu104__LeetCode-Solutions
Python/delete-nodes-from-linked-list-present-in-array.py
{ "start": 55, "end": 504 }
class ____(object): def modifiedList(self, nums, head): """ :type nums: List[int] :type head: Optional[ListNode] :rtype: Optional[ListNode] """ lookup = set(nums) curr = dummy = ListNode(0, head) while curr.next: if curr.next.val not in loo...
Solution
python
coleifer__peewee
playhouse/sqlite_changelog.py
{ "start": 66, "end": 282 }
class ____(Model): timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')]) action = TextField() table = TextField() primary_key = IntegerField() changes = JSONField()
BaseChangeLog
python
django__django
tests/i18n/tests.py
{ "start": 76147, "end": 76584 }
class ____(SimpleTestCase): def setUp(self): super().setUp() activate("de") self.addCleanup(deactivate) def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the transl...
ResolutionOrderI18NTests
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-stackoverflow/llama_index/readers/stackoverflow/base.py
{ "start": 358, "end": 2629 }
class ____: link: str score: int last_activity_date: int creation_date: int post_id: Optional[int] = None post_type: Optional[str] = None body_markdown: Optional[str] = None owner_account_id: Optional[int] = None owner_reputation: Optional[int] = None owner_user_id: Optional[int]...
StackOverflowPost
python
PrefectHQ__prefect
tests/server/utilities/test_database.py
{ "start": 15863, "end": 16708 }
class ____: def test_sqlite_now_compilation(self) -> None: dialect = sa.dialects.sqlite.dialect() expression = sa.func.now() compiled = expression.compile( dialect=dialect, compile_kwargs={"render_postcompile": True} ) assert str(compiled) == "strftime('%Y-%m-%d %...
TestCustomFunctions
python
pypa__pip
src/pip/_vendor/rich/layout.py
{ "start": 3009, "end": 3626 }
class ____(Splitter): """Split a layout region in to columns.""" name = "column" def get_tree_icon(self) -> str: return "[layout.tree.column]⬍" def divide( self, children: Sequence["Layout"], region: Region ) -> Iterable[Tuple["Layout", Region]]: x, y, width, height = regi...
ColumnSplitter
python
astropy__astropy
astropy/modeling/bounding_box.py
{ "start": 30844, "end": 34759 }
class ____(_BaseSelectorArgument): """ Contains a single CompoundBoundingBox slicing input. Parameters ---------- index : int The index of the input in the input list ignore : bool Whether or not this input will be ignored by the bounding box. Methods ------- valid...
_SelectorArgument
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 1791, "end": 1892 }
class ____(MilvusException): """Raise when collections doesn't exist"""
CollectionNotExistException
python
spack__spack
lib/spack/spack/llnl/util/tty/log.py
{ "start": 12659, "end": 15225 }
class ____: """Represents a file. Can be an open stream, a path to a file (not opened yet), or neither. When unwrapped, it returns an open file (or file-like) object. """ def __init__(self, file_like, append=False): # This records whether the file-like object returned by "unwrap" is ...
FileWrapper
python
cython__cython
Cython/Build/Inline.py
{ "start": 15933, "end": 16267 }
class ____: def __init__(self, f): self._f = f self._body = get_body(inspect.getsource(f)) def __call__(self, *args, **kwds): all = inspect.getcallargs(self._f, *args, **kwds) return cython_inline(self._body, locals=self._f.__globals__, globals=self._f.__globals__, **all)
RuntimeCompiledFunction
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dtbuild3/package.py
{ "start": 217, "end": 456 }
class ____(Package): """Simple package which acts as a build dependency""" homepage = "http://www.example.com" url = "http://www.example.com/dtbuild3-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef")
Dtbuild3
python
pytoolz__cytoolz
cytoolz/tests/test_none_safe.py
{ "start": 1211, "end": 12214 }
class ____: def __init__(self, exc): self.exc = exc def __iter__(self): return self def __next__(self): raise self.exc def next(self): raise self.exc def test_dicttoolz(): tested = [] assert raises((TypeError, AttributeError), lambda: assoc(None, 1, 2)) t...
GenException
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 913147, "end": 915952 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "comments", "diff_side", "is_collapsed", "is_outdated", "is_resolved", "line", "original_line", "original_start_...
PullRequestReviewThread
python
altair-viz__altair
altair/vegalite/v6/schema/mixins.py
{ "start": 50021, "end": 54970 }
class ____(SchemaBase): """ ErrorBarDef schema wrapper. Parameters ---------- clip : bool Whether a composite mark be clipped to the enclosing group's width and height. color : str, dict, :class:`Color`, :class:`ExprRef`, :class:`Gradient`, :class:`HexColor`, :class:`ColorName`, :class:...
_ErrorBarDef
python
TheAlgorithms__Python
other/lfu_cache.py
{ "start": 137, "end": 839 }
class ____[T, U]: """ Double Linked List Node built specifically for LFU Cache >>> node = DoubleLinkedListNode(1,1) >>> node Node: key: 1, val: 1, freq: 0, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val ...
DoubleLinkedListNode
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-clickhouse/llama_index/vector_stores/clickhouse/base.py
{ "start": 3344, "end": 19480 }
class ____(BasePydanticVectorStore): """ ClickHouse Vector Store. In this vector store, embeddings and docs are stored within an existing ClickHouse cluster. During query time, the index uses ClickHouse to query for the top k most similar nodes. Args: clickhouse_client (httpclient):...
ClickHouseVectorStore
python
miyuchina__mistletoe
mistletoe/contrib/scheme.py
{ "start": 1151, "end": 1398 }
class ____(span_token.SpanToken): pattern = re.compile(r"([^\s()]+)") parse_inner = False def __init__(self, match): self.name = match.group(0) def __repr__(self): return '<Variable {!r}>'.format(self.name)
Variable
python
ray-project__ray
python/ray/data/_internal/progress_bar.py
{ "start": 971, "end": 3236 }
class ____(ABC): """Abstract class to define a progress bar.""" def block_until_complete(self, remaining: List[ObjectRef]) -> None: t = threading.current_thread() while remaining: done, remaining = ray.wait( remaining, num_returns=len(remaining), fetch_local=False, t...
AbstractProgressBar
python
altair-viz__altair
tools/vega_expr.py
{ "start": 8242, "end": 12115 }
class ____: """ Perform many ``1:1`` replacements on a given text. Structured wrapper around a `dict`_ and `re.sub`_. Parameters ---------- mapping Optional initial mapping. fmt_match **Combined** format string/regex pattern. Receives the keys of the final ``self._m...
ReplaceMany
python
getsentry__sentry
src/sentry/issues/endpoints/project_user_issue.py
{ "start": 5870, "end": 6071 }
class ____(ProjectPermission): scope_map = { "GET": [], "POST": ["event:read", "event:write", "event:admin"], "PUT": [], "DELETE": [], }
ProjectUserIssuePermission
python
walkccc__LeetCode
solutions/32. Longest Valid Parentheses/32.py
{ "start": 0, "end": 362 }
class ____: def longestValidParentheses(self, s: str) -> int: s2 = ')' + s # dp[i] := the length of the longest valid parentheses in the substring # s2[1..i] dp = [0] * len(s2) for i in range(1, len(s2)): if s2[i] == ')' and s2[i - dp[i - 1] - 1] == '(': dp[i] = dp[i - 1] + dp[i - d...
Solution
python
huggingface__transformers
tests/models/parakeet/test_modeling_parakeet.py
{ "start": 6759, "end": 8880 }
class ____: def __init__(self, parent, encoder_kwargs=None, is_training=True, vocab_size=128, pad_token_id=0): if encoder_kwargs is None: encoder_kwargs = {} self.parent = parent self.encoder_model_tester = ParakeetEncoderModelTester(parent, **encoder_kwargs) self.is_tra...
ParakeetForCTCModelTester
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1053135, "end": 1053621 }
class ____(sgqlc.types.Type): """Autogenerated return type of VerifyVerifiableDomain""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "domain") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the ...
VerifyVerifiableDomainPayload
python
apache__airflow
airflow-core/src/airflow/executors/base_executor.py
{ "start": 4514, "end": 23410 }
class ____(LoggingMixin): """ Base class to inherit for concrete executors such as Celery, Kubernetes, Local, etc. :param parallelism: how many jobs should run at one time. """ active_spans = ThreadSafeDict() supports_ad_hoc_ti_run: bool = False sentry_integration: str = "" is_local:...
BaseExecutor
python
pypa__pip
src/pip/_vendor/urllib3/exceptions.py
{ "start": 3233, "end": 3386 }
class ____(ConnectTimeoutError, PoolError): """Raised when we fail to establish a new connection. Usually ECONNREFUSED.""" pass
NewConnectionError
python
psf__black
tests/data/miscellaneous/force_pyi.py
{ "start": 81, "end": 192 }
class ____: def BMethod(self) -> None: ... @overload def BMethod(self, arg : List[str]) -> None: ...
B
python
apache__airflow
providers/snowflake/tests/unit/snowflake/operators/test_snowflake.py
{ "start": 6002, "end": 7079 }
class ____: @mock.patch("airflow.providers.common.sql.operators.sql.SQLIntervalCheckOperator.__init__") def test_get_db_hook( self, mock_snowflake_interval_check_operator, ): SnowflakeIntervalCheckOperator( task_id="snowflake_check", table="test-table-id", metrics_thresho...
TestSnowflakeIntervalCheckOperator
python
bokeh__bokeh
src/bokeh/models/axes.py
{ "start": 12262, "end": 12739 }
class ____(LinearAxis): ''' A ``LinearAxis`` that picks nice numbers for tick locations on a datetime scale. Configured with a ``DatetimeTickFormatter`` by default. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init_...
DatetimeAxis
python
ethereum__web3.py
tests/integration/test_ethereum_tester.py
{ "start": 6498, "end": 7701 }
class ____(Web3ModuleTest): def _check_web3_client_version(self, client_version): assert client_version.startswith("EthereumTester/") test_batch_requests = not_implemented( Web3ModuleTest.test_batch_requests, Web3TypeError ) test_batch_requests_raises_for_common_unsupported_methods = no...
TestEthereumTesterWeb3Module
python
wandb__wandb
wandb/filesync/step_checksum.py
{ "start": 1183, "end": 4672 }
class ____: def __init__( self, api: "internal_api.Api", tempdir: "tempfile.TemporaryDirectory", request_queue: "queue.Queue[Event]", output_queue: "queue.Queue[step_upload.Event]", stats: "stats.Stats", ) -> None: self._api = api self._tempdir = t...
StepChecksum
python
ray-project__ray
python/ray/data/tests/test_hash_shuffle.py
{ "start": 774, "end": 8824 }
class ____: # Expected outputs expected_ray_remote_args: Dict[str, Any] expected_num_partitions: int expected_num_aggregators: int # Input dataset configurations left_size_bytes: Optional[int] right_size_bytes: Optional[int] left_num_blocks: Optional[int] right_num_blocks: Optional[...
JoinTestCase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py
{ "start": 7369, "end": 8158 }
class ____(FBMarketingReversedIncrementalStream): """See: https://developers.facebook.com/docs/marketing-api/reference/video""" entity_prefix = "video" def fields(self, **kwargs) -> List[str]: """Remove account_id from fields as cannot be requested, but it is part of schema as foreign key, will be...
Videos
python
coleifer__peewee
tests/base_models.py
{ "start": 1606, "end": 1798 }
class ____(TestModel): first = CharField() last = CharField() empno = CharField(unique=True) class Meta: indexes = ( (('first', 'last'), True), )
Emp
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/_execution.py
{ "start": 1251, "end": 2411 }
class ____(abc.ABC): """Configuration contract for persistent shell sessions. Concrete subclasses encapsulate how a shell process is launched and constrained. Each policy documents its security guarantees and the operating environments in which it is appropriate. Use `HostExecutionPolicy` for trusted,...
BaseExecutionPolicy
python
doocs__leetcode
lcof/面试题42. 连续子数组的最大和/Solution.py
{ "start": 0, "end": 194 }
class ____: def maxSubArray(self, nums: List[int]) -> int: ans, f = -inf, 0 for x in nums: f = max(f, 0) + x ans = max(ans, f) return ans
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 136312, "end": 136707 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(SavedReplyOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc.t...
SavedReplyOrder
python
ipython__ipython
IPython/core/alias.py
{ "start": 4907, "end": 7570 }
class ____: """Callable object storing the details of one alias. Instances are registered as magic functions to allow use of aliases. """ # Prepare blacklist blacklist = {'cd','popd','pushd','dhist','alias','unalias'} def __init__(self, shell, name, cmd): self.shell = shell se...
Alias
python
openai__openai-python
src/openai/types/beta/realtime/session_update_event.py
{ "start": 4982, "end": 10937 }
class ____(BaseModel): client_secret: Optional[SessionClientSecret] = None """Configuration options for the generated client secret.""" input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. Fo...
Session
python
python-poetry__poetry
src/poetry/console/commands/build.py
{ "start": 832, "end": 1171 }
class ____: clean: bool formats: list[DistributionType] output: str config_settings: dict[str, Any] = dataclasses.field(default_factory=dict) def __post_init__(self) -> None: for fmt in self.formats: if fmt not in BUILD_FORMATS: raise ValueError(f"Invalid format:...
BuildOptions
python
walkccc__LeetCode
solutions/163. Missing Ranges/163.py
{ "start": 0, "end": 601 }
class ____: def findMissingRanges( self, nums: list[int], lower: int, upper: int, ) -> list[list[int]]: def getRange(lo: int, hi: int) -> list[int]: if lo == hi: return [lo, lo] return [lo, hi] if not nums: return [getRange(lower, upper)] ans = [] ...
Solution
python
walkccc__LeetCode
solutions/1374. Generate a String With Characters That Have Odd Counts/1374.py
{ "start": 0, "end": 133 }
class ____: def generateTheString(self, n: int) -> str: s = 'a' * n if n % 2 == 0: s = s[:-1] + 'b' return s
Solution
python
fluentpython__example-code-2e
15-more-types/protocol/random/generic_randompick_test.py
{ "start": 162, "end": 889 }
class ____(Generic[T_co]): def __init__(self, items: Iterable[T_co]) -> None: self._items = list(items) random.shuffle(self._items) def pick(self) -> T_co: return self._items.pop() def test_issubclass() -> None: assert issubclass(LottoPicker, RandomPicker) def test_isinstance() ...
LottoPicker
python
kubernetes-client__python
kubernetes/client/models/v1beta1_resource_claim_template.py
{ "start": 383, "end": 7056 }
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...
V1beta1ResourceClaimTemplate
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/floating_axes.py
{ "start": 8341, "end": 9993 }
class ____: def __init__(self, *args, grid_helper, **kwargs): _api.check_isinstance(GridHelperCurveLinear, grid_helper=grid_helper) super().__init__(*args, grid_helper=grid_helper, **kwargs) self.set_aspect(1.) def _gen_axes_patch(self): # docstring inherited x0, x1, y0...
FloatingAxesBase
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 61441, "end": 61557 }
class ____(_ConfigBase): cache: Optional[bool] rescore_limit: int training_limit: int @dataclass
_SQConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol2.py
{ "start": 372, "end": 644 }
class ____: def write(self, data: bytes) -> None: pass def f(writer: Writer[bytes]): pass def g(writer: Writer[T], v: T | None = None): pass def h(writer: Writer[StrLike], v: StrLike | None = None): pass w = WriteFile() f(w) g(w) h(w)
WriteFile
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink37.py
{ "start": 315, "end": 953 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink37.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workb...
TestCompareXLSXFiles
python
google__pytype
pytype/errors/errors.py
{ "start": 5246, "end": 14480 }
class ____: """Representation of an error in the error log. Attributes: name: The error name. bad_call: Optionally, a `pytype.function.BadCall` of details of a bad function call. details: Optionally, a string of message details. filename: The file in which the error occurred. line: The li...
Error
python
django__django
tests/multiple_database/tests.py
{ "start": 86614, "end": 87352 }
class ____(TestCase): databases = {"default", "other"} def test_m2m_collection(self): b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) p = Person.objects.create(name="Marty Alchin") # test add b.authors.add(p) # te...
RouterModelArgumentTestCase
python
huggingface__transformers
src/transformers/models/smolvlm/modular_smolvlm.py
{ "start": 4697, "end": 6763 }
class ____(Idefics3Config): r""" This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configu...
SmolVLMConfig
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 11249, "end": 12295 }
class ____(graphene.Mutation): """Launches multiple job runs.""" Output = graphene.NonNull(GrapheneLaunchMultipleRunsResultOrError) class Arguments: executionParamsList = non_null_list(GrapheneExecutionParams) class Meta: name = "LaunchMultipleRunsMutation" @capture_error asy...
GrapheneLaunchMultipleRunsMutation
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-nvidia/llama_index/llms/nvidia/utils.py
{ "start": 257, "end": 29440 }
class ____(BaseModel): """ Model information. id: unique identifier for the model, passed as model parameter for requests model_type: API type (chat, vlm, embedding, ranking, completions) client: client name, e.g. NvidiaGenerator, NVIDIAEmbeddings, NVIDIARerank, NvidiaTextEmbedder, Nvidi...
Model
python
huggingface__transformers
src/transformers/models/edgetam_video/modeling_edgetam_video.py
{ "start": 28491, "end": 29177 }
class ____(nn.Module): def __init__(self, config: EdgeTamVideoConfig, in_channels: int, out_channels: int): super().__init__() self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=config.mask_downsampler_kernel_size, stride=config.mask_downsam...
EdgeTamVideoMaskDownSamplerLayer
python
bokeh__bokeh
tests/unit/bokeh/command/subcommands/test_serve.py
{ "start": 21172, "end": 23807 }
class ____: def test_default(self) -> None: requests = pytest.importorskip("requests") with run_bokeh_serve(["--port", "0", "--glob", APPS]) as (_, nbsr): port = check_port(nbsr) assert port > 0 r = requests.get(f"http://localhost:{port}/favicon.ico") ...
TestIco
python
fastai__fastai
fastai/layers.py
{ "start": 11918, "end": 12164 }
class ____(nn.Embedding): "Embedding layer with truncated normal initialization" def __init__(self, ni, nf, std=0.01): super().__init__(ni, nf) trunc_normal_(self.weight.data, std=std) # %% ../nbs/01_layers.ipynb 86
Embedding
python
walkccc__LeetCode
solutions/3539. Find Sum of Array Product of Magical Sequences/3539.py
{ "start": 0, "end": 858 }
class ____: def magicalSum(self, m: int, k: int, nums: list[int]) -> int: MOD = 1_000_000_007 @functools.lru_cache(None) def dp(m: int, k: int, i: int, carry: int) -> int: """ Returns the number of magical sequences of length `k` that can be formed from the first `i` numbers in `nums` w...
Solution
python
scikit-learn__scikit-learn
sklearn/externals/array_api_compat/common/_typing.py
{ "start": 1576, "end": 1731 }
class ____(Protocol[_T_co]): def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ... def __len__(self, /) -> int: ...
NestedSequence
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/gradients_test.py
{ "start": 13419, "end": 22706 }
class ____(test.TestCase): def run_and_assert_equal(self, targets1, targets2, atol=1e-4, rtol=1e-4): targets1 = nest.flatten(targets1) targets2 = nest.flatten(targets2) assert len(targets1) == len(targets2) init = variables.global_variables_initializer() self.evaluate(init) outputs = self.eva...
GradientsTest
python
euske__pdfminer
pdfminer/cmapdb.py
{ "start": 1173, "end": 2580 }
class ____(CMapBase): def __init__(self, **kwargs): CMapBase.__init__(self, **kwargs) self.code2cid = {} return def __repr__(self): return '<CMap: %s>' % self.attrs.get('CMapName') def use_cmap(self, cmap): assert isinstance(cmap, CMap) def copy(dst, src):...
CMap
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/networks.py
{ "start": 29185, "end": 29359 }
class ____(nn.Module): def __init__(self, lr): # Todo: add learning rate decay super().__init__() self.learning_rate = torch.Tensor([lr])
LearningRate
python
tensorflow__tensorflow
tensorflow/python/ops/matmul_benchmark.py
{ "start": 2359, "end": 5551 }
class ____(test.Benchmark): """Benchmark matmul!""" def run_graph(self, device, n, m, k, transpose_a, transpose_b, num_iters, dtype): """Run the graph and print its execution time. Args: device: String, the device to run on. n: tensor A's first dimension size. m: tensor A...
MatmulBenchmark
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass7.py
{ "start": 570, "end": 763 }
class ____(metaclass=MetaClass2): def __new__(cls, *args, **kwargs): raise RuntimeError("Cannot instantiate directly") v2 = Class2() reveal_type(v2, expected_text="NoReturn")
Class2
python
Netflix__metaflow
test/core/metaflow_extensions/test_org/plugins/cards/simplecard/__init__.py
{ "start": 470, "end": 653 }
class ____(TestEditableCard): type = "editable_import_test_card" ALLOW_USER_COMPONENTS = True CARDS = [TestEditableImportCard, TestNonEditableImportCard]
TestEditableImportCard
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/gcs_upload.py
{ "start": 1330, "end": 1453 }
class ____: id: str deleted: bool description: str blob_id: Optional[str] @dataclass(frozen=True)
DeletedFile
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 115963, "end": 116397 }
class ____(sgqlc.types.Enum): """The possible commit status states. Enumeration Choices: * `ERROR`: Status is errored. * `EXPECTED`: Status is expected. * `FAILURE`: Status is failing. * `PENDING`: Status is pending. * `SUCCESS`: Status is successful. """ __schema__ = github_schem...
StatusState
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py
{ "start": 3622, "end": 5119 }
class ____: @mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook")) def test_execute(self, mock_hook_class): # Create the mock hook and set up expected response mock_hook = mock.MagicMock() mock_hook_class.return_value = mock_hook expected_response = { "n...
TestGetFeatureViewSyncOperator
python
crytic__slither
slither/detectors/functions/gelato_unprotected_randomness.py
{ "start": 254, "end": 2729 }
class ____(AbstractDetector): """ Unprotected Gelato VRF requests """ ARGUMENT = "gelato-unprotected-randomness" HELP = "Call to _requestRandomness within an unprotected function" IMPACT = DetectorClassification.MEDIUM CONFIDENCE = DetectorClassification.MEDIUM WIKI = "https://github.c...
GelatoUnprotectedRandomness
python
pypa__hatch
src/hatch/env/context.py
{ "start": 267, "end": 2798 }
class ____(EnvironmentContextFormatterBase): def __init__(self, environment): self.environment = environment self.CONTEXT_NAME = f"environment_{environment.PLUGIN_NAME}" def formatters(self): # noqa: PLR6301 """ This returns a mapping of supported field names to their respectiv...
EnvironmentContextFormatter
python
doocs__leetcode
solution/1800-1899/1839.Longest Substring Of All Vowels in Order/Solution.py
{ "start": 0, "end": 538 }
class ____: def longestBeautifulSubstring(self, word: str) -> int: arr = [] n = len(word) i = 0 while i < n: j = i while j < n and word[j] == word[i]: j += 1 arr.append((word[i], j - i)) i = j ans = 0 for...
Solution