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
gevent__gevent
src/gevent/tests/test__monkey_queue.py
{ "start": 8588, "end": 8966 }
class ____(BaseQueueTest): type2test = Queue.PriorityQueue def test__init(self): item1 = (2, 'b') item2 = (1, 'a') q = self.type2test(items=[item1, item2]) self.assertTupleEqual(item2, q.get_nowait()) self.assertTupleEqual(item1, q.get_nowait()) # A Queue subclass that...
PriorityQueueTest
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_ops_test.py
{ "start": 6386, "end": 6713 }
class ____(test_util.TensorFlowTestCase): def testShape(self): tensor = constant_op.constant([1.0, 2.0]) self.assertEqual([2], tensor.get_shape()) self.assertEqual([2], control_flow_ops.with_dependencies( [constant_op.constant(1.0)], tensor).get_shape())
ShapeTestCase
python
pytest-dev__pytest-asyncio
docs/reference/fixtures/event_loop_policy_example.py
{ "start": 184, "end": 575 }
class ____(DefaultEventLoopPolicy): pass @pytest.fixture(scope="module") def event_loop_policy(request): return CustomEventLoopPolicy() @pytest.mark.asyncio(loop_scope="module") @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def test_uses_custom_event_loop_policy(): assert isinstance(as...
CustomEventLoopPolicy
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 5757, "end": 5839 }
class ____(BaseModel): my_var: Union[str, None] = Field(default=None)
InnerModel
python
HypothesisWorks__hypothesis
hypothesis-python/tests/conjecture/test_test_data.py
{ "start": 2207, "end": 2557 }
class ____(SearchStrategy): def do_draw(self, data): data.draw_boolean() raise ValueError def test_closes_interval_on_error_in_strategy(): d = ConjectureData.for_choices((True,)) with pytest.raises(ValueError): d.draw(BoomStrategy()) d.freeze() assert not any(eg.end is None...
BoomStrategy
python
django__django
tests/admin_changelist/models.py
{ "start": 2086, "end": 2289 }
class ____(models.Model): player = models.ForeignKey(ChordsMusician, models.CASCADE) band = models.ForeignKey(ChordsBand, models.CASCADE) instrument = models.CharField(max_length=15)
Invitation
python
numba__numba
numba/core/typing/builtins.py
{ "start": 1164, "end": 1622 }
class ____(ConcreteTemplate): int_cases = [signature(ty, ty) for ty in sorted(types.signed_domain)] uint_cases = [signature(ty, ty) for ty in sorted(types.unsigned_domain)] real_cases = [signature(ty, ty) for ty in sorted(types.real_domain)] complex_cases = [signature(ty.underlying_float, ty) ...
Abs
python
jazzband__django-oauth-toolkit
tests/test_rest_framework.py
{ "start": 2768, "end": 2878 }
class ____(BrokenOAuth2View): permission_classes = [TokenMatchesOASRequirements]
MethodScopeAltViewWrongAuth
python
huggingface__transformers
src/transformers/models/diffllama/modular_diffllama.py
{ "start": 1666, "end": 1792 }
class ____(MistralMLP): pass def lambda_init_fn(layer_idx): return 0.8 - 0.6 * math.exp(-0.3 * layer_idx)
DiffLlamaMLP
python
google__jax
jax/_src/core.py
{ "start": 117742, "end": 119644 }
class ____(TypeError): pass custom_typechecks: dict[Primitive, Callable] = {} def _check_closed_call(_, *in_atoms, call_jaxpr): in_avals = [x.aval for x in in_atoms] if not all(map(typecompat, call_jaxpr.in_avals, in_avals)): raise JaxprTypeError("Closed call in_avals mismatch") return call_jaxpr.out_avals,...
JaxprTypeError
python
pydata__xarray
xarray/computation/arithmetic.py
{ "start": 3377, "end": 3630 }
class ____( ImplementsArrayReduce, IncludeNumpySameMethods, SupportsArithmetic, VariableOpsMixin, ): __slots__ = () # prioritize our operations over those of numpy.ndarray (priority=0) __array_priority__ = 50
VariableArithmetic
python
doocs__leetcode
solution/2000-2099/2014.Longest Subsequence Repeated k Times/Solution.py
{ "start": 0, "end": 764 }
class ____: def longestSubsequenceRepeatedK(self, s: str, k: int) -> str: def check(t: str, k: int) -> bool: i = 0 for c in s: if c == t[i]: i += 1 if i == len(t): k -= 1 if k == 0...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 23035, "end": 23218 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("ARCHIVED", "NOT_ARCHIVED")
ProjectCardArchivedState
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/testing/codegen.py
{ "start": 1296, "end": 1455 }
class ____(NodeSampler): sample_map = dict(( (gast.UnaryOp, 1), (gast.BinOp, 8), (gast.Name, 1), (gast.Call, 0), ))
ExpressionSampler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/tryExcept4.py
{ "start": 169, "end": 444 }
class ____(BaseException): def __init__(self, code: int): pass # This should generate an error because CustomException1 # requires an argument to instantiate. if a or 2 > 1: raise CustomException1 if a or 2 > 1: raise CustomException1(3)
CustomException1
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/lambda_function.py
{ "start": 1298, "end": 3287 }
class ____(AwsBaseSensor[LambdaHook]): """ Poll the deployment state of the AWS Lambda function until it reaches a target state. Fails if the query fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:LambdaFunctionStateSensor...
LambdaFunctionStateSensor
python
ray-project__ray
rllib/env/wrappers/multi_agent_env_compatibility.py
{ "start": 144, "end": 2574 }
class ____(MultiAgentEnv): """A wrapper converting MultiAgentEnv from old gym API to the new one. "Old API" refers to step() method returning (observation, reward, done, info), and reset() only retuning the observation. "New API" refers to step() method returning (observation, reward, terminated, t...
MultiAgentEnvCompatibility
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/empty/base.py
{ "start": 569, "end": 2932 }
class ____(BaseIndex[EmptyIndexStruct]): """ Empty Index. An index that doesn't contain any documents. Used for pure LLM calls. NOTE: this exists because an empty index it allows certain properties, such as the ability to be composed with other indices + token counting + others. """ ...
EmptyIndex
python
facebook__pyre-check
tools/generate_taint_models/model.py
{ "start": 12771, "end": 13501 }
class ____(Model): def __init__(self, class_name: str, attribute_name: str, annotation: str) -> None: self.class_name = class_name self.attribute_name = attribute_name self.annotation = annotation def __str__(self) -> str: return f"@property\ndef {self.class_name}.{self.attribut...
PropertyModel
python
apache__airflow
providers/opsgenie/tests/unit/opsgenie/operators/test_opsgenie.py
{ "start": 4559, "end": 5761 }
class ____: _config = {"user": "example_user", "note": "my_closing_note", "source": "some_source"} expected_payload_dict = { "user": _config["user"], "note": _config["note"], "source": _config["source"], } def setup_method(self): args = {"owner": "airflow", "start_date":...
TestOpsgenieCloseAlertOperator
python
getsentry__sentry
src/sentry/notifications/platform/types.py
{ "start": 7060, "end": 7189 }
class ____(NotificationBodyTextBlock): type: Literal[NotificationBodyTextBlockType.CODE] text: str @dataclass
CodeTextBlock
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-seller-partner/unit_tests/test_migrations.py
{ "start": 7749, "end": 8364 }
class ____: @pytest.mark.parametrize("config", [INVALID_STREAM_NAMES_CONFIG, INVALID_OPTION_NAMES_CONFIG]) def test_given_invalid_config_then_it_should_raise_error(self, config): source = get_source(config) with pytest.raises(ValueError) as e: source.streams(config) assert "s...
TestValidations
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock-v.py
{ "start": 1261, "end": 1825 }
class ____(object): def maximumProfit(self, prices, k): """ :type prices: List[int] :type k: int :rtype: int """ bought = [float("-inf")]*k sold = [float("-inf")]*k result = [float("-inf")]*(k+1) result[0] = 0 for x in prices: ...
Solution3
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 38806, "end": 39351 }
class ____(typing.Protocol): pass def test_issue_4194_regression(): # this was an edge case where we were calling issubclass on something # that was not a type, which errored. I don't have a more principled test # case or name for this. inner = typing.Union[typing.Sequence["A"], MyProtocol] A ...
MyProtocol
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 700053, "end": 700541 }
class ____(sgqlc.types.Type): """Autogenerated return type of MinimizeComment""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "minimized_comment") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing ...
MinimizeCommentPayload
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 4547, "end": 4810 }
class ____(unittest.TestCase): def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.port = socket_helper.bind_port(self.serv) def tearDown(self): self.serv.close() self.serv = None
SocketUDPTest
python
realpython__materials
python-in-operator/permissions.py
{ "start": 0, "end": 325 }
class ____: def __init__(self, username, permissions): self.username = username self.permissions = permissions admin = User("admin", "wrx") john = User("john", "rx") def has_permission(user, permission): return permission in user.permissions has_permission(admin, "w") has_permission(john, ...
User
python
davidhalter__jedi
test/completion/import_tree/recurse_class1.py
{ "start": 30, "end": 87 }
class ____(recurse_class2.C): def a(self): pass
C
python
kamyu104__LeetCode-Solutions
Python/construct-binary-tree-from-preorder-and-postorder-traversal.py
{ "start": 766, "end": 2034 }
class ____(object): def constructFromPrePost(self, pre, post): """ :type pre: List[int] :type post: List[int] :rtype: TreeNode """ def constructFromPrePostHelper(pre, pre_s, pre_e, post, post_s, post_e, post_entry_idx_map): if pre_s >= pre_e or post_s >= p...
Solution2
python
PyCQA__pylint
tests/functional/u/undefined/undefined_variable_py30.py
{ "start": 2096, "end": 2172 }
class ____(ThirdGood): """ This should not trigger anything. """
FourthGood
python
django__django
tests/select_related_regress/models.py
{ "start": 106, "end": 240 }
class ____(models.Model): building = models.ForeignKey("Building", models.CASCADE) name = models.CharField(max_length=10)
Device
python
joke2k__faker
faker/providers/address/it_IT/__init__.py
{ "start": 174, "end": 667128 }
class ____(AddressProvider): # Converted from: https://download.geonames.org/export/zip/IT.zip cap_city_province = { "67010": [["Barete", "AQ"]], "67012": [["San Giovanni", "AQ"], ["Cagnano Amiterno", "AQ"]], "67013": [["Mascioni", "AQ"], ["Campotosto", "AQ"], ["Ortolano", "AQ"], ["Poggi...
Provider
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/noreturn2.py
{ "start": 316, "end": 445 }
class ____: def always_noreturn(self) -> NoReturn: func1() def sometimes_noreturn(self) -> int: return 0
C
python
allegroai__clearml
clearml/utilities/locks/utils.py
{ "start": 7388, "end": 10664 }
class ____(Lock): """ A reentrant lock, functions in a similar way to threading.RLock in that it can be acquired multiple times. When the corresponding number of release() calls are made the lock will finally release the underlying file lock. """ def __init__( self, filename: s...
RLock
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/utils/websocket_client.py
{ "start": 16956, "end": 35251 }
class ____(Configurable): """Pure-async client for remote WS Jupyter kernels.""" shell_channel_class = _WebSocketChannel # type: ignore[assignment] iopub_channel_class = _WebSocketChannel # type: ignore[assignment] hb_channel_class = _WebSocketHBChannel # type: ignore[assignment] stdin_channel_c...
_WebSocketKernelClient
python
anthropics__anthropic-sdk-python
src/anthropic/lib/streaming/_beta_types.py
{ "start": 1956, "end": 2747 }
class ____(BetaRawContentBlockStopEvent, GenericModel, Generic[ResponseFormatT]): type: Literal["content_block_stop"] if TYPE_CHECKING: content_block: ParsedBetaContentBlock[ResponseFormatT] else: content_block: ParsedBetaContentBlock ParsedBetaMessageStreamEvent = Annotated[ Union[ ...
ParsedBetaContentBlockStopEvent
python
pypa__pip
tests/unit/metadata/test_metadata_pkg_resources.py
{ "start": 1022, "end": 3944 }
class ____(list[mock.Mock]): def require(self, name: str) -> None: pass workingset = _MockWorkingSet( ( mock.Mock(test_name="global", project_name="global"), mock.Mock(test_name="editable", project_name="editable"), mock.Mock(test_name="normal", project_name="normal"), ...
_MockWorkingSet
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/graph/base_asset_graph.py
{ "start": 2711, "end": 3402 }
class ____(ABC, Generic[T_EntityKey]): key: T_EntityKey @property @abstractmethod def partitions_def(self) -> Optional[PartitionsDefinition]: ... @property @abstractmethod def partition_mappings(self) -> Mapping[EntityKey, PartitionMapping]: ... @property @abstractmethod def a...
BaseEntityNode
python
mlflow__mlflow
mlflow/gateway/providers/bedrock.py
{ "start": 5537, "end": 10535 }
class ____(BaseProvider): NAME = "Amazon Bedrock" CONFIG_TYPE = AmazonBedrockConfig def __init__(self, config: EndpointConfig): super().__init__(config) if config.model.config is None or not isinstance(config.model.config, AmazonBedrockConfig): raise TypeError(f"Invalid config ...
AmazonBedrockProvider
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 35847, "end": 36006 }
class ____(Projection): r"""Base class for pseudoconic projections. Pseudoconics are a subclass of conics with concentric parallels. """
PseudoConic
python
h5py__h5py
h5py/tests/test_file2.py
{ "start": 652, "end": 1789 }
class ____(TestCase): """ Behavior on object deallocation. Note most of this behavior is delegated to FileID. """ @pytest.mark.thread_unsafe(reason="global object counters") def test_autoclose(self): """ File objects close automatically when out of scope, but other obje...
TestDealloc
python
kamyu104__LeetCode-Solutions
Python/count-common-words-with-one-occurrence.py
{ "start": 58, "end": 407 }
class ____(object): def countWords(self, words1, words2): """ :type words1: List[str] :type words2: List[str] :rtype: int """ cnt = collections.Counter(words1) for c in words2: if cnt[c] < 2: cnt[c] -= 1 return sum(v == 0 fo...
Solution
python
pytorch__pytorch
torch/testing/_internal/common_optimizers.py
{ "start": 1615, "end": 1766 }
class ____(Enum): """Enumerates when an error is raised when testing optimizers.""" CONSTRUCTION_ERROR = 0 STEP_ERROR = 1
OptimizerErrorEnum
python
viewflow__viewflow
viewflow/workflow/nodes/view.py
{ "start": 4072, "end": 8235 }
class ____( mixins.NextNodeMixin, mixins.NodePermissionMixin, Node, ): """User task.""" activation_class = ViewActivation task_type = "HUMAN" shape = { "width": 150, "height": 100, "text-align": "middle", "svg": """ <rect class="task" width="150...
View
python
kamyu104__LeetCode-Solutions
Python/find-the-sequence-of-strings-appeared-on-the-screen.py
{ "start": 40, "end": 286 }
class ____(object): def stringSequence(self, target): """ :type target: str :rtype: List[str] """ return [target[:i]+chr(x) for i in xrange(len(target)) for x in xrange(ord('a'), ord(target[i])+1)]
Solution
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 24932, "end": 29228 }
class ____: input_gen_types1 = [ "dense", "transposed", "strided", "broadcast1", "broadcast2", "broadcast3", "double", "int", ] input_gen_types2 = input_gen_types1 gen = None @staticmethod def kernel(a, b): return (a + b,) ...
SweepInputs2
python
google__pytype
pytype/overlays/special_builtins.py
{ "start": 25635, "end": 26165 }
class ____(abstract.Function, mixin.HasSlots): """StaticMethod instance (constructed by StaticMethod.call()).""" def __init__(self, ctx, cls, func): super().__init__("staticmethod", ctx) mixin.HasSlots.init_mixin(self) self.func = func self.cls = cls self.set_native_slot("__get__", self.func_sl...
StaticMethodInstance
python
doocs__leetcode
solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/Solution.py
{ "start": 0, "end": 208 }
class ____: def minSwaps(self, s: str) -> int: x = 0 for c in s: if c == "[": x += 1 elif x: x -= 1 return (x + 1) >> 1
Solution
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 23671, "end": 25300 }
class ____(Module): r"""Applies the LeakyReLU function element-wise. .. math:: \text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x) or .. math:: \text{LeakyReLU}(x) = \begin{cases} x, & \text{ if } x \geq 0 \\ \text{negative\_slope} \times x,...
LeakyReLU
python
mamba-org__mamba
releaser.py
{ "start": 2790, "end": 2912 }
class ____: def __init__(self): self.items = [] self.applies_to = ["all"] self.text = ""
Section
python
fsspec__filesystem_spec
fsspec/implementations/reference.py
{ "start": 2379, "end": 20376 }
class ____(collections.abc.MutableMapping): """This interface can be used to read/write references from Parquet stores. It is not intended for other types of references. It can be used with Kerchunk's MultiZarrToZarr method to combine references into a parquet store. Examples of this use-case can be...
LazyReferenceMapper
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_combined02.py
{ "start": 315, "end": 1339 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_combined02.xlsx") self.ignore_elements = {"xl/charts/chart1.xml": ["<c:dispBlanksAs"]} def test_create_file(self): """Test t...
TestCompareXLSXFiles
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-gitbook/tests/test_simple_gitbook_reader.py
{ "start": 2428, "end": 4470 }
class ____(unittest.TestCase): """Test cases for SimpleGitbookReader class.""" def setUp(self): """Sets up test environment before each test case.""" self.mock_client = MockGitbookClient("fake_token") self.reader = SimpleGitbookReader(api_token="fake_token") self.reader.client =...
TestSimpleGitbookReader
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/gen_ai.py
{ "start": 11168, "end": 14071 }
class ____(GoogleCloudBaseOperator): """ Use Count Tokens API to calculate the number of input tokens before sending a request to Gemini API. :param project_id: Required. The ID of the Google Cloud project that the service belongs to (templated). :param location: Required. The ID of the Google ...
GenAICountTokensOperator
python
kamyu104__LeetCode-Solutions
Python/partition-array-for-maximum-xor-and-and.py
{ "start": 1532, "end": 2788 }
class ____(object): def maximizeXorAndXor(self, nums): """ :type nums: List[int] :rtype: int """ def max_xor_subset(nums): # Time: O(nlogr) base = [0]*l for x in nums: # gaussian elimination over GF(2) for i in reversed(xrange(len(ba...
Solution2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 180845, "end": 181813 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateDiscussion""" __schema__ = github_schema __field_names__ = ("repository_id", "title", "body", "category_id", "client_mutation_id") repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId") """The id o...
CreateDiscussionInput
python
bokeh__bokeh
tests/unit/bokeh/util/test_dataclasses.py
{ "start": 1218, "end": 2181 }
class ____: f0: int f1: list[int] f2: X | None = None f3: dc.NotRequired[bool | None] = dc.Unspecified def test_entries() -> None: x0 = X(0, [1, 2, 3]) assert dict(dc.entries(x0)) == dict(f0=0, f1=[1, 2, 3], f2=None) x1 = X(0, [1, 2, 3], f3=None) assert dict(dc.entries(x1)) == dict(f0=...
X
python
PyCQA__isort
isort/exceptions.py
{ "start": 1603, "end": 1856 }
class ____(ISortError): """Should be raised when a file is skipped for any reason""" def __init__(self, message: str, file_path: str): super().__init__(message) self.message = message self.file_path = file_path
FileSkipped
python
viewflow__viewflow
tests/workflow/test_managers__sql.py
{ "start": 8299, "end": 8416 }
class ____(flow.Flow): process_class = GrandChildProcess start = flow.Start(lambda request: None)
GrandChildFlow
python
lazyprogrammer__machine_learning_examples
cnn_class2/tf_resnet_first_layers.py
{ "start": 2223, "end": 4631 }
class ____: def __init__(self): self.layers = [ # before conv block ConvLayer(d=7, mi=3, mo=64, stride=2, padding='SAME'), BatchNormLayer(64), ReLULayer(), MaxPoolLayer(dim=3), # conv block ConvBlock(mi=64, fm_sizes=[64, 64, 256], stride=1), ] self.input_ = tf.pla...
PartialResNet
python
pydantic__pydantic
pydantic/networks.py
{ "start": 18194, "end": 19167 }
class ____(_BaseUrl): """Base type for all URLs. * Any scheme allowed * Top-level domain (TLD) not required * Host not required Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`, the types export the following properties: - `scheme`: ...
AnyUrl
python
aio-libs__aiohttp
aiohttp/web_log.py
{ "start": 367, "end": 7627 }
class ____(AbstractAccessLogger): """Helper object to log access. Usage: log = logging.getLogger("spam") log_format = "%a %{User-Agent}i" access_logger = AccessLogger(log, log_format) access_logger.log(request, response, time) Format: %% The percent sign %a...
AccessLogger
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/cfg_test.py
{ "start": 2761, "end": 40394 }
class ____(test.TestCase): def _build_cfg(self, fn): node, _ = parser.parse_entity(fn, future_features=()) cfgs = cfg.build(node) return cfgs def _repr_set(self, node_set): return frozenset(repr(n) for n in node_set) def _as_set(self, elements): if elements is None: return frozenset()...
AstToCfgTest
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 3132, "end": 3652 }
class ____(BaseModel): class Config: extra = Extra.allow type: Literal["CustomBackoffStrategy"] class_name: str = Field( ..., description="Fully-qualified name of the class that will be implementing the custom backoff strategy. The format is `source_<name>.<package>.<class_name>`.",...
CustomBackoffStrategy
python
jackfrued__Python-100-Days
公开课/年薪50W+的Python程序员如何写代码/code/Python/opencourse/part03/example.py
{ "start": 52, "end": 138 }
class ____(enum.Enum): """花色(枚举)""" SPADE, HEART, CLUB, DIAMOND = range(4)
Suite
python
ethereum__web3.py
web3/exceptions.py
{ "start": 9022, "end": 9135 }
class ____(Web3RPCError): """ Raised when the method is not available on the node """
MethodUnavailable
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py
{ "start": 28746, "end": 32308 }
class ____(GoogleCloudBaseOperator): """ Disables one or more enabled notification channels identified by filter parameter. Inoperative in case the policy is already disabled. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:...
StackdriverDisableNotificationChannelsOperator
python
gevent__gevent
src/gevent/_interfaces.py
{ "start": 8231, "end": 9396 }
class ____(Interface): """ An event loop watcher. These objects call their *callback* function when the event loop detects the event has happened. .. important:: You *must* call :meth:`close` when you are done with this object to avoid leaking native resources. """ def start(callba...
IWatcher
python
tensorflow__tensorflow
tensorflow/python/data/ops/sparse_batch_op.py
{ "start": 1228, "end": 2702 }
class ____(dataset_ops.UnaryDataset): """A `Dataset` that batches ragged dense elements into `tf.sparse.SparseTensor`s.""" def __init__(self, input_dataset, batch_size, row_shape, name=None): """See `Dataset.dense_to_sparse_batch()` for more details.""" if not isinstance( dataset_ops.get_legacy_out...
_DenseToSparseBatchDataset
python
huggingface__transformers
src/transformers/models/gemma3n/modular_gemma3n.py
{ "start": 77344, "end": 84204 }
class ____(nn.Module): """Alternating Updates (AltUp) The AltUp module wraps transformer layers. The `predict` step modifies the input to the transformer layer, and the `correct` step propagates the output of the transformer layer to the sparsely updated dimensions. See more in the research paper:...
Gemma3nTextAltUp
python
huggingface__transformers
tests/models/reformer/test_modeling_reformer.py
{ "start": 25382, "end": 31452 }
class ____(ReformerTesterMixin, GenerationTesterMixin, ModelTesterMixin, unittest.TestCase): all_model_classes = ( (ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering) if is_torch_available() else () ) test_sequence_classification...
ReformerLocalAttnModelTest
python
getsentry__sentry
src/sentry/integrations/gitlab/utils.py
{ "start": 198, "end": 684 }
class ____: def __init__(self, info: Mapping[str, int]) -> None: self.limit = info["limit"] self.remaining = info["remaining"] self.reset = info["reset"] self.used = info["used"] def next_window(self) -> str: return datetime.fromtimestamp(self.reset).strftime("%H:%M:%S")...
GitLabRateLimitInfo
python
ApeWorX__ape
src/ape_cache/base.py
{ "start": 139, "end": 348 }
class ____: """ Base class to generate ``__tablename__`` automatically """ id: Any __name__: str @declared_attr def __tablename__(cls) -> str: return cls.__name__.lower()
Base
python
django-debug-toolbar__django-debug-toolbar
tests/test_integration.py
{ "start": 1918, "end": 11567 }
class ____(BaseTestCase): def test_show_toolbar(self): self.assertTrue(show_toolbar(self.request)) def test_show_toolbar_DEBUG(self): with self.settings(DEBUG=False): self.assertFalse(show_toolbar(self.request)) def test_show_toolbar_INTERNAL_IPS(self): with self.settin...
DebugToolbarTestCase
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-clean-the-classroom.py
{ "start": 65, "end": 1773 }
class ____(object): def minMoves(self, classroom, energy): """ :type classroom: List[str] :type energy: int :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) m, n = len(classroom), len(classroom[0]) lookup = {} r = c = -1 ...
Solution
python
run-llama__llama_index
llama-index-core/tests/indices/query/test_query_bundle.py
{ "start": 565, "end": 2895 }
class ____(BaseEmbedding): @classmethod def class_name(cls) -> str: return "MockEmbedding" async def _aget_query_embedding(self, query: str) -> List[float]: text_embed_map: Dict[str, List[float]] = { "It is what it is.": [1.0, 0.0, 0.0, 0.0, 0.0], "The meaning of lif...
MockEmbedding
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/looker.py
{ "start": 8900, "end": 9117 }
class ____(Enum): """The job status string.""" QUEUED = "added" PENDING = "pending" RUNNING = "running" CANCELLED = "killed" DONE = "complete" ERROR = "error" UNKNOWN = "unknown"
JobStatus
python
tensorflow__tensorflow
tensorflow/python/distribute/mirrored_strategy_test.py
{ "start": 58569, "end": 61271 }
class ____(test.TestCase, parameterized.TestCase): def testBackwardFunctionDevicePlacement(self, distribution): with distribution.scope(): w = variable_v1.VariableV1([1.5], name="w") b = variable_v1.VariableV1([0.5], name="b") @def_function.function def forward(x, w, b): return x * w +...
FunctionTest
python
huggingface__transformers
src/transformers/models/gemma3/modeling_gemma3.py
{ "start": 2553, "end": 3098 }
class ____(BaseModelOutputWithPast): r""" image_hidden_states (`torch.FloatTensor`, *optional*): A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. ...
Gemma3ModelOutputWithPast
python
ray-project__ray
release/train_tests/benchmark/runner.py
{ "start": 362, "end": 14534 }
class ____: """Generic runner that sets up the training loop scaffolding. Collects perf metrics and handles periodic checkpointing and validation. """ def __init__(self, factory: BenchmarkFactory): self.factory = factory self.benchmark_config = factory.benchmark_config self._s...
TrainLoopRunner
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_dialect.py
{ "start": 17966, "end": 21151 }
class ____(fixtures.TestBase): __only_on__ = "oracle" __backend__ = True def test_table_round_trip(self, metadata, connection): oracle.RESERVED_WORDS.discard("UNION") table = Table( "t1", metadata, Column("option", Integer), Column("plain", I...
QuotedBindRoundTripTest
python
simplejson__simplejson
simplejson/tests/__init__.py
{ "start": 78, "end": 343 }
class ____(unittest.TestSuite): def run(self, result): import simplejson simplejson._toggle_speedups(False) result = unittest.TestSuite.run(self, result) simplejson._toggle_speedups(True) return result
NoExtensionTestSuite
python
laurentluce__python-algorithms
algorithms/tests/test_binary_tree.py
{ "start": 76, "end": 6024 }
class ____(unittest.TestCase): def setUp(self): self.root_single_node = binary_tree.Node(None) self.root = binary_tree.Node(10) self.root.left = binary_tree.Node(5) self.root.left.left = binary_tree.Node(3) self.root.left.right = binary_tree.Node(7) self.root.right =...
BinaryTreeTest
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/tf_record_test_base.py
{ "start": 8444, "end": 11740 }
class ____(test_base.DatasetTestBase): """Base class for TFRecord-based tests.""" def setUp(self): super(TFRecordTestBase, self).setUp() self._num_files = 2 self._num_records = 7 self._filenames = self._createFiles() def _interleave(self, iterators, cycle_length): pending_iterators = iterato...
TFRecordTestBase
python
kamyu104__LeetCode-Solutions
Python/sort-features-by-popularity.py
{ "start": 54, "end": 618 }
class ____(object): def sortFeatures(self, features, responses): """ :type features: List[str] :type responses: List[str] :rtype: List[str] """ features_set = set(features) order = {word: i for i, word in enumerate(features)} freq = collections.default...
Solution
python
pytorch__pytorch
test/ao/sparsity/test_composability.py
{ "start": 13713, "end": 25947 }
class ____(TestCase): r"""This series of tests checks that various steps of the quantization and sparsity flow compose cleanly despite variation in sequencing. """ @xfailIfS390X def test_q_prep_fx_before_s_prep(self): r""" This test checks that the ordering of prepare_fx -> sparse p...
TestFxComposability
python
ansible__ansible
test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py
{ "start": 1097, "end": 1344 }
class ____(BaseVarsPlugin): def get_vars(self, loader, path, entities, cache=True): super(VarsModule, self).get_vars(loader, path, entities) return {'collection': False, 'name': 'v1_vars_plugin', 'v1_vars_plugin': True}
VarsModule
python
python__mypy
mypy/traverser.py
{ "start": 29414, "end": 30070 }
class ____(FuncCollectorBase): def __init__(self) -> None: super().__init__() self.in_assignment = False self.yield_expressions: list[tuple[YieldExpr, bool]] = [] def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None: self.in_assignment = True super().visit_assig...
YieldCollector
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/12_Proximal_Policy_Optimization/DPPO.py
{ "start": 4577, "end": 8270 }
class ____(object): def __init__(self, wid): self.wid = wid self.env = gym.make(GAME).unwrapped self.ppo = GLOBAL_PPO def work(self): global GLOBAL_EP, GLOBAL_RUNNING_R, GLOBAL_UPDATE_COUNTER while not COORD.should_stop(): s = self.env.reset() ep_...
Worker
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py
{ "start": 9124, "end": 9558 }
class ____(SearchParams): l_value_is: Annotated[PositiveInt | None, Field(ge=10, le=10_000)] = None iterative_search: DiskANNIterativeScanMode | None = None @override def search_settings(self, exclude_none=True): return { f"diskann.{key}": value for key, value in self.mo...
DiskANNSearchParams
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 34835, "end": 35113 }
class ____(Structure): _fields_ = ( ("thunk", p_long), # Actually a pointer to a function ("key", p_ulong), ("offset", p_ulong), ) def describe(self): return {"thunk": self.thunk, "key": self.key, "offset": self.offset}
tlv_descriptor
python
huggingface__transformers
tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py
{ "start": 24858, "end": 32308 }
class ____(unittest.TestCase): def test_compute_mask_indices(self): batch_size = 4 sequence_length = 60 mask_prob = 0.5 mask_length = 1 mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) mask = torch.from_numpy(mask).to(torch_device) ...
Wav2Vec2ConformerUtilsTest
python
kennethreitz__tablib
src/tablib/exceptions.py
{ "start": 0, "end": 86 }
class ____(Exception): "Only Datasets can be added to a DataBook"
InvalidDatasetType
python
coleifer__peewee
tests/shortcuts.py
{ "start": 1119, "end": 1214 }
class ____(TestModel): name = TextField() StudentCourseProxy = DeferredThroughModel()
Student
python
jazzband__django-polymorphic
example/pexp/models.py
{ "start": 722, "end": 799 }
class ____(UUIDModelB): field3 = models.CharField(max_length=10)
UUIDModelC
python
google__jax
tests/gpu_memory_flags_test.py
{ "start": 754, "end": 1757 }
class ____(absltest.TestCase): # This test must be run in its own subprocess. @jtu.skip_under_pytest("Test must run in an isolated process") @unittest.skipIf( "XLA_PYTHON_CLIENT_ALLOCATOR" in os.environ, "Test does not work if the python client allocator has been overridden", ) def test_gpu_memor...
GpuMemoryAllocationTest
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/test_basic_configuration.py
{ "start": 1314, "end": 1649 }
class ____(SomeStuff, TestCase): pass if not (PYPY or GRAALPY): # xfail # This is excessively slow in general, but particularly on pypy. We just # disable it altogether there as it's a niche case. class TestConstraintsWithoutTransactions(SomeStuff, TransactionTestCase): pass
TestConstraintsWithTransactions
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 15221, "end": 16362 }
class ____(ExtensionType): oid = ExtensionOID.CRL_DISTRIBUTION_POINTS def __init__( self, distribution_points: Iterable[DistributionPoint] ) -> None: distribution_points = list(distribution_points) if not all( isinstance(x, DistributionPoint) for x in distribution_points...
CRLDistributionPoints
python
kamyu104__LeetCode-Solutions
Python/check-if-the-number-is-fascinating.py
{ "start": 518, "end": 743 }
class ____(object): def isFascinating(self, n): """ :type n: int :rtype: bool """ s = str(n)+str(2*n)+str(3*n) return '0' not in s and len(s) == 9 and len(set(s)) == 9
Solution2
python
Pylons__pyramid
tests/test_view.py
{ "start": 40579, "end": 40917 }
class ____: def __init__(self, info=None): if info is None: info = DummyVenusianInfo() self.info = info self.attachments = [] def attach(self, wrapped, callback, category=None, depth=1): self.attachments.append((wrapped, callback, category, depth)) return sel...
DummyVenusian