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
django__django
django/contrib/auth/middleware.py
{ "start": 10703, "end": 11208 }
class ____(RemoteUserMiddleware): """ Middleware for web-server provided authentication on logon pages. Like RemoteUserMiddleware but keeps the user authenticated even if the ``request.META`` key is not found in the request. Useful for setups when the external authentication is only expected to hap...
PersistentRemoteUserMiddleware
python
doocs__leetcode
solution/2400-2499/2466.Count Ways To Build Good Strings/Solution.py
{ "start": 0, "end": 384 }
class ____: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: @cache def dfs(i): if i > high: return 0 ans = 0 if low <= i <= high: ans += 1 ans += dfs(i + zero) + dfs(i + one) retu...
Solution
python
sympy__sympy
sympy/geometry/ellipse.py
{ "start": 1341, "end": 42460 }
class ____(GeometrySet): """An elliptical GeometryEntity. Parameters ========== center : Point, optional Default value is Point(0, 0) hradius : number or SymPy expression, optional vradius : number or SymPy expression, optional eccentricity : number or SymPy expression, optional ...
Ellipse
python
great-expectations__great_expectations
great_expectations/data_context/types/resource_identifiers.py
{ "start": 1677, "end": 1915 }
class ____(Schema): name = fields.Str() # noinspection PyUnusedLocal @post_load def make_expectation_suite_identifier(self, data, **kwargs): return ExpectationSuiteIdentifier(**data)
ExpectationSuiteIdentifierSchema
python
ethereum__web3.py
web3/providers/persistent/persistent.py
{ "start": 1206, "end": 19399 }
class ____(AsyncJSONBaseProvider, ABC): logger = logging.getLogger("web3.providers.PersistentConnectionProvider") has_persistent_connection = True _send_func_cache: tuple[ int | None, Callable[..., Coroutine[Any, Any, RPCRequest]] | None ] = (None, None) _recv_func_cache: tuple[ int...
PersistentConnectionProvider
python
spack__spack
lib/spack/spack/util/package_hash.py
{ "start": 8084, "end": 14597 }
class ____(ast.NodeTransformer): """Remove multi-methods when we know statically that they won't be used. Say we have multi-methods like this:: class SomePackage: def foo(self): print("implementation 1") @when("@1.0") def foo(self): print("implementation 2") ...
ResolveMultiMethods
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 6959, "end": 7151 }
class ____(SQLRole): """A SELECT statement embedded in DML, typically INSERT from SELECT""" __slots__ = () _role_name = "SELECT statement or equivalent textual object"
DMLSelectRole
python
scipy__scipy
scipy/stats/_hypotests.py
{ "start": 16380, "end": 30025 }
class ____: def __init__(self, statistic, pvalue): self.statistic = statistic self.pvalue = pvalue def __repr__(self): return (f"{self.__class__.__name__}(statistic={self.statistic}, " f"pvalue={self.pvalue})") def _psi1_mod(x, *, xp=None): """ psi1 is defined ...
CramerVonMisesResult
python
matplotlib__matplotlib
lib/matplotlib/tests/test_ticker.py
{ "start": 23736, "end": 25354 }
class ____: def test_set_params(self): """ Create symmetrical log locator with default subs =[1.0] numticks = 15, and change it to something else. See if change was successful. Should not exception. """ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)...
TestSymmetricalLogLocator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 13465, "end": 13523 }
class ____(EventsMixin, GeoReport): pass
GeoEventsReport
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_autofilter08.py
{ "start": 315, "end": 2576 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("autofilter08.xlsx") self.set_text_file("autofilter_data.txt") def test_create_file(self): """ Test the creation of a simple...
TestCompareXLSXFiles
python
google__pytype
pytype/rewrite/abstract/functions.py
{ "start": 10789, "end": 10929 }
class ____(Protocol): def get_return_value(self) -> base.BaseValue: ... _HasReturnT = TypeVar('_HasReturnT', bound=_HasReturn)
_HasReturn
python
ray-project__ray
rllib/examples/envs/classes/parametric_actions_cartpole.py
{ "start": 109, "end": 3328 }
class ____(gym.Env): """Parametric action version of CartPole. In this env there are only ever two valid actions, but we pretend there are actually up to `max_avail_actions` actions that can be taken, and the two valid actions are randomly hidden among this set. At each step, we emit a dict of: ...
ParametricActionsCartPole
python
PrefectHQ__prefect
src/prefect/server/schemas/actions.py
{ "start": 4479, "end": 9774 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to create a deployment.""" name: str = Field( default=..., description="The name of the deployment.", examples=["my-deployment"], ) flow_id: UUID = Field( default=..., description="The ID of the flow assoc...
DeploymentCreate
python
pytorch__pytorch
torch/profiler/profiler.py
{ "start": 2839, "end": 19934 }
class ____: """Low-level profiler wrap the autograd profile Args: activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values: ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``, ``torch.profiler.ProfilerActivit...
_KinetoProfile
python
kamyu104__LeetCode-Solutions
Python/find-the-number-of-subarrays-where-boundary-elements-are-maximum.py
{ "start": 57, "end": 482 }
class ____(object): def numberOfSubarrays(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 stk = [] for x in nums: while stk and stk[-1][0] < x: stk.pop() if not stk or stk[-1][0] != x: s...
Solution
python
Textualize__rich
benchmarks/benchmarks.py
{ "start": 5078, "end": 5574 }
class ____: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False, width=100 ) self.color = Color.parse("#0d1da0") def time_downgrade_to_eight_bit(self): self.color.downgrade(ColorSystem.EIGHT_BIT) def time_down...
ColorSuite
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 7026, "end": 7514 }
class ____(BaseModel, extra="forbid"): """ Operation for performing changes of collection aliases. Alias changes are atomic, meaning that no collection modifications can happen between alias operations. """ actions: List["AliasOperations"] = Field( ..., description="Operation for perfor...
ChangeAliasesOperation
python
django-extensions__django-extensions
tests/test_randomchar_field.py
{ "start": 561, "end": 3623 }
class ____(TestCase): def testRandomCharField(self): m = RandomCharTestModel() m.save() assert len(m.random_char_field) == 8, m.random_char_field def testRandomCharFieldUnique(self): m = RandomCharTestModelUnique() m.save() assert len(m.random_char_field) == 8, m...
RandomCharFieldTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_format14.py
{ "start": 315, "end": 2245 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_format14.xlsx") def test_create_file(self): """Test the creation of a file with user defined default format""" workbook = ...
TestCompareXLSXFiles
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 7788, "end": 8272 }
class ____(str, BaseEnum): """How object deletions in multi node environments should be resolved. Attributes: PERMANENT_DELETION: Once an object has been deleted on one node it will be deleted on all nodes in case of conflicts. NO_AUTOMATED_RESOLUTION: No deletion resolution. """ DELET...
ReplicationDeletionStrategy
python
pallets__quart
src/quart/wrappers/response.py
{ "start": 3607, "end": 5604 }
class ____(ResponseBody): """Provides an async file accessor with range setting. The :attr:`Response.response` attribute must be async-iterable and yield bytes, which this wrapper does for a file. In addition it allows a range to be set on the file, thereby supporting conditional requests. Att...
FileBody
python
run-llama__llama_index
llama-index-packs/llama-index-packs-diff-private-simple-dataset/llama_index/packs/diff_private_simple_dataset/base.py
{ "start": 1535, "end": 2011 }
class ____(BaseModel): instruction: str = Field(description="Instruction associated with underlying task.") text_heading: str = Field(description="Heading used for text.") label_heading: str = Field(description="Label heading used for label.") def _batch(iterable, n=1) -> Iterable[Any]: """Return iter...
PromptBundle
python
apache__airflow
providers/standard/tests/unit/standard/decorators/test_branch_external_python.py
{ "start": 1234, "end": 3919 }
class ____: # when run in "Parallel" test run environment, sometimes this test runs for a long time # because creating virtualenv and starting new Python interpreter creates a lot of IO/contention # possibilities. So we are increasing the timeout for this test to 3x of the default timeout @pytest.mark.e...
TestBranchExternalPythonDecoratedOperator
python
pyca__cryptography
tests/hazmat/primitives/test_hash_vectors.py
{ "start": 4048, "end": 4409 }
class ____: test_sha3_224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), ["SHA3_224LongMsg.rsp", "SHA3_224ShortMsg.rsp"], hashes.SHA3_224(), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA3_256()), skip_messa...
TestSHA3224
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py
{ "start": 19897, "end": 40113 }
class ____(StepModifyingFiles): context: PublishConnectorContext title = "Disable progressive rollout in metadata file" async def _run(self) -> StepResult: raw_metadata = await dagger_read_file(await self.context.get_connector_dir(include=[METADATA_FILE_NAME]), METADATA_FILE_NAME) current_m...
DisableProgressiveRollout
python
numba__numba
numba/tests/npyufunc/test_dufunc.py
{ "start": 29949, "end": 34743 }
class ____(TestDUFuncMethodsBase): def _check_reduce(self, ufunc, dtype=None, initial=None): @njit def foo(a, axis, dtype, initial): return ufunc.reduce(a, axis=axis, dtype=dtype, initial=ini...
TestDUFuncReduce
python
scipy__scipy
scipy/spatial/transform/_rotation_spline.py
{ "start": 6411, "end": 14244 }
class ____: """Interpolate rotations with continuous angular rate and acceleration. The rotation vectors between each consecutive orientation are cubic functions of time and it is guaranteed that angular rate and acceleration are continuous. Such interpolation are analogous to cubic spline interpol...
RotationSpline
python
Pylons__pyramid
tests/test_integration.py
{ "start": 566, "end": 714 }
class ____(Interface): pass @view_config(for_=INothing) @wsgiapp def wsgiapptest(environ, start_response): """ """ return '123'
INothing
python
ansible__ansible
lib/ansible/module_utils/facts/system/cmdline.py
{ "start": 854, "end": 2608 }
class ____(BaseFactCollector): name = 'cmdline' _fact_ids = set() # type: t.Set[str] def _get_proc_cmdline(self): return get_file_content('/proc/cmdline') def _parse_proc_cmdline(self, data): cmdline_dict = {} try: for piece in shlex.split(data, posix=False): ...
CmdLineFactCollector
python
huggingface__transformers
src/transformers/models/resnet/convert_resnet_to_pytorch.py
{ "start": 1964, "end": 6982 }
class ____: src: nn.Module dest: nn.Module verbose: int = 0 src_skip: list = field(default_factory=list) dest_skip: list = field(default_factory=list) def __call__(self, x: Tensor): """ Transfer the weights of `self.src` to `self.dest` by performing a forward pass using `x` as i...
ModuleTransfer
python
pytest-dev__pytest
testing/example_scripts/unittest/test_unittest_asynctest.py
{ "start": 146, "end": 470 }
class ____(asynctest.TestCase): async def tearDown(self): teardowns.append(None) async def test_error(self): await asyncio.sleep(0) self.fail("failing on purpose") async def test_ok(self): await asyncio.sleep(0) def test_teardowns(self): assert len(teardowns) =...
Test
python
ray-project__ray
python/ray/util/spark/cluster_init.py
{ "start": 69944, "end": 76922 }
class ____: """Create a ray on spark autoscaling cluster.""" def __init__( self, head_resources: dict, worker_node_types: dict, extra_provider_config: dict, upscaling_speed: float, idle_timeout_minutes: float, ): """Create the cluster. Args: ...
AutoscalingCluster
python
huggingface__transformers
examples/quantization/custom_quantization_int8_example.py
{ "start": 4137, "end": 5026 }
class ____(QuantizationConfigMixin): """ Configuration for INT8 symmetric quantization. """ def __init__(self, modules_to_not_convert: Optional[list[str]] = None, **kwargs): self.quant_method = "int8_symmetric" self.modules_to_not_convert = modules_to_not_convert def __repr__(self)...
Int8SymmetricConfig
python
openai__openai-python
src/openai/resources/beta/beta.py
{ "start": 2236, "end": 3571 }
class ____(AsyncAPIResource): @cached_property def chat(self) -> AsyncChat: return AsyncChat(self._client) @cached_property def realtime(self) -> AsyncRealtime: return AsyncRealtime(self._client) @cached_property def chatkit(self) -> AsyncChatKit: return AsyncChatKit(se...
AsyncBeta
python
getsentry__sentry
src/sentry/analytics/events/first_transaction_sent.py
{ "start": 79, "end": 293 }
class ____(analytics.Event): organization_id: int project_id: int platform: str | None = None default_user_id: int | None = None analytics.register(FirstTransactionSentEvent)
FirstTransactionSentEvent
python
cython__cython
Cython/Compiler/Code.py
{ "start": 50879, "end": 94850 }
class ____: # filename_table {string : int} for finding filename table indexes # filename_list [string] filenames in filename table order # input_file_contents dict contents (=list of lines) of any file that was used as input # to create this output ...
GlobalState
python
pytorch__pytorch
torch/__init__.py
{ "start": 72311, "end": 72541 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.bfloat16
BFloat16Storage
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/subprocess_env_manager.py
{ "start": 1876, "end": 1981 }
class ____(NamedTuple): cmd: EnvironmentCommand worker_id: int payload: Any
EnvironmentResponse
python
doocs__leetcode
solution/1500-1599/1583.Count Unhappy Friends/Solution.py
{ "start": 0, "end": 556 }
class ____: def unhappyFriends( self, n: int, preferences: List[List[int]], pairs: List[List[int]] ) -> int: d = [{x: j for j, x in enumerate(p)} for p in preferences] p = {} for x, y in pairs: p[x] = y p[y] = x ans = 0 for x in range(n): ...
Solution
python
RaRe-Technologies__gensim
gensim/similarities/nmslib.py
{ "start": 3601, "end": 9603 }
class ____(): """This class allows to use `NMSLIB <https://github.com/nmslib/nmslib>`_ as indexer for `most_similar` method from :class:`~gensim.models.word2vec.Word2Vec`, :class:`~gensim.models.doc2vec.Doc2Vec`, :class:`~gensim.models.fasttext.FastText` and :class:`~gensim.models.keyedvectors.Word2VecKeyed...
NmslibIndexer
python
spulec__freezegun
freezegun/api.py
{ "start": 9731, "end": 10778 }
class ____(real_date, metaclass=FakeDateMeta): def __add__(self, other: Any) -> "FakeDate": result = real_date.__add__(self, other) if result is NotImplemented: return result return date_to_fakedate(result) def __sub__(self, other: Any) -> "FakeDate": # type: ignore ...
FakeDate
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 199281, "end": 201715 }
class ____(VegaLiteSchema): """ BoxPlotConfig schema wrapper. Parameters ---------- box : bool, dict, :class:`BarConfig`, :class:`AreaConfig`, :class:`LineConfig`, :class:`MarkConfig`, :class:`RectConfig`, :class:`TickConfig`, :class:`AnyMarkConfig` extent : float, Literal['min-max'] T...
BoxPlotConfig
python
pytorch__pytorch
torch/multiprocessing/spawn.py
{ "start": 2590, "end": 7645 }
class ____: def __init__(self, processes, error_files): self.error_files = error_files self.processes = processes self.sentinels = { process.sentinel: index for index, process in enumerate(processes) } def pids(self): return [int(process.pid) for process in s...
ProcessContext
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 122971, "end": 123493 }
class ____(Operation): def call(self, x): return backend.numpy.isnan(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype="bool") @keras_export(["keras.ops.isnan", "keras.ops.numpy.isnan"]) def isnan(x): """Test element-wise for NaN and return result as a boolean tensor....
Isnan
python
kamyu104__LeetCode-Solutions
Python/shortest-subarray-with-or-at-least-k-i.py
{ "start": 83, "end": 1136 }
class ____(object): def minimumSubarrayLength(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def update(x, d, curr): for i in xrange(len(cnt)): if x < (1<<i): break if not (x&(1<<i...
Solution
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/fivetran/customize_fivetran_translator_asset_spec.py
{ "start": 473, "end": 1181 }
class ____(DagsterFivetranTranslator): def get_asset_spec(self, props: FivetranConnectorTableProps) -> dg.AssetSpec: # We create the default asset spec using super() default_spec = super().get_asset_spec(props) # We customize the metadata and asset key prefix for all assets return de...
MyCustomFivetranTranslator
python
astropy__astropy
astropy/time/tests/test_pickle.py
{ "start": 132, "end": 1201 }
class ____: """Basic pickle test of time""" def test_pickle(self): times = ["1999-01-01 00:00:00.123456789", "2010-01-01 00:00:00"] t1 = Time(times, scale="utc") for prot in range(pickle.HIGHEST_PROTOCOL): t1d = pickle.dumps(t1, prot) t1l = pickle.loads(t1d) ...
TestPickle
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chartsheet03.py
{ "start": 315, "end": 1425 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chartsheet03.xlsx") def test_create_file(self): """Test the worksheet properties of an XlsxWriter chartsheet file.""" workbook = W...
TestCompareXLSXFiles
python
doocs__leetcode
solution/0000-0099/0077.Combinations/Solution2.py
{ "start": 0, "end": 412 }
class ____: def combine(self, n: int, k: int) -> List[List[int]]: def dfs(i: int): if len(t) == k: ans.append(t[:]) return if i > n: return for j in range(i, n + 1): t.append(j) dfs(j + 1) ...
Solution
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 50683, "end": 53556 }
class ____(LogitsProcessor): r""" N-grams are groups of "n" consecutive words, characters, or tokens taken from a sequence of text. Given the sentence: "She runs fast", the bi-grams (n=2) would be ("she", "runs") and ("runs", "fast"). In text generation, avoiding repetitions of word sequences provides a...
NoRepeatNGramLogitsProcessor
python
getsentry__sentry
tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py
{ "start": 19960, "end": 20508 }
class ____(TestTicketingIssueAlertHandlerBase): def setUp(self) -> None: super().setUp() self.handler = GithubIssueAlertHandler() def test_build_rule_action_blob(self) -> None: for expected in GITHUB_ACTION_DATA_BLOBS: if expected["id"] == ACTION_FIELD_MAPPINGS[Action.Type.G...
TestGithubIssueAlertHandler
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 9095, "end": 16110 }
class ____(nn.Module): def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=[0, 0]): super().__init__() if dim % num_heads != 0: raise ValueError( f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})" ...
Swin2SRSelfAttention
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_title03.py
{ "start": 315, "end": 1330 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_title03.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with default title.""" workbook = Work...
TestCompareXLSXFiles
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
{ "start": 21949, "end": 31737 }
class ____(SearchStrategy[Ex]): """A strategy which samples from a set of elements. This is essentially equivalent to using a OneOfStrategy over Just strategies but may be more efficient and convenient. """ _MAX_FILTER_CALLS: ClassVar[int] = 10_000 def __init__( self, elements:...
SampledFromStrategy
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hparams.py
{ "start": 2805, "end": 9512 }
class ____(BoringDataModule): """Tests that a model can take an object.""" @decorate @decorate def __init__(self, hparams, *my_args, **my_kwargs): super().__init__() self.save_hyperparameters(hparams) # ------------------------- # STANDARD TESTS # ------------------------- def _run_st...
SaveHparamsDecoratedDataModule
python
eventlet__eventlet
tests/websocket_test.py
{ "start": 757, "end": 20374 }
class ____(tests.wsgi_test._TestBase): TEST_TIMEOUT = 5 def set_site(self): self.site = wsapp def test_incorrect_headers(self): http = httplib.HTTPConnection(*self.server_addr) http.request("GET", "/echo") response = http.getresponse() assert response.status == 400 ...
TestWebSocket
python
geekcomputers__Python
inheritance_YahV1729.py
{ "start": 221, "end": 525 }
class ____(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is employee def isEmployee(self): return False # Inherited or Sub class (Note Person in bracket)
Person
python
walkccc__LeetCode
solutions/29. Divide Two Integers/29.py
{ "start": 0, "end": 458 }
class ____: def divide(self, dividend: int, divisor: int) -> int: # -2^{31} / -1 = 2^31 will overflow, so return 2^31 - 1. if dividend == -2**31 and divisor == -1: return 2**31 - 1 sign = -1 if (dividend > 0) ^ (divisor > 0) else 1 ans = 0 dvd = abs(dividend) dvs = abs(divisor) whi...
Solution
python
joke2k__faker
tests/mymodule/en_US/__init__.py
{ "start": 43, "end": 113 }
class ____(BaseProvider): def foo(self): return "bar"
Provider
python
django__django
tests/expressions/models.py
{ "start": 741, "end": 1295 }
class ____(models.Model): name = models.CharField(max_length=100) num_employees = models.PositiveIntegerField() num_chairs = models.PositiveIntegerField() ceo = models.ForeignKey( Employee, models.CASCADE, related_name="company_ceo_set", ) point_of_contact = models.Foreig...
Company
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_quantize.py
{ "start": 2490, "end": 4446 }
class ____: def __init__(self, mod): self.mod = mod @torch.no_grad() def create_quantized_state_dict(self): cur_state_dict = self.mod.state_dict() for fqn, mod in self.mod.named_modules(): if isinstance(mod, torch.nn.Linear) and not fqn.endswith(".gate"): ...
WeightOnlyInt8QuantHandler
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 124317, "end": 125020 }
class ____(str, Enum): """ Methods for transferring a shard from one node to another. - `stream_records` - Stream all shard records in batches until the whole shard is transferred. - `snapshot` - Snapshot the shard, transfer and restore it on the receiver. - `wal_delta` - Attempt to transfer shard difference...
ShardTransferMethod
python
numba__numba
numba/tests/test_sets.py
{ "start": 18248, "end": 20450 }
class ____(BaseTest): """ Test unboxing of Python sets into native Numba sets. """ @contextlib.contextmanager def assert_type_error(self, msg): with self.assertRaises(TypeError) as raises: yield if msg is not None: self.assertRegex(str(raises.exception), msg)...
TestUnboxing
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 38156, "end": 38483 }
class ____(ExprNode): __slots__ = ("value",) def validate(self): if not isinstance(self.value, Call): raise StructureException( "`staticcall` must be followed by a function call", self.value, hint="did you forget parentheses?", ) ...
StaticCall
python
pypa__setuptools
setuptools/command/editable_wheel.py
{ "start": 30377, "end": 31465 }
class ____(namespaces.Installer): def __init__(self, distribution, installation_dir, editable_name, src_root) -> None: self.distribution = distribution self.src_root = src_root self.installation_dir = installation_dir self.editable_name = editable_name self.outputs: list[str]...
_NamespaceInstaller
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 50508, "end": 50756 }
class ____(_TestSubsets, __TestCase): left = set() right = set([1, 2]) name = "one empty, one non-empty" cases = "!=", "<", "<=" #------------------------------------------------------------------------------
TestSubsetEmptyNonEmpty
python
google__jax
jax/experimental/sparse/transform.py
{ "start": 6134, "end": 8829 }
class ____(NamedTuple): shape: tuple[int, ...] data_ref: int | None indices_ref: int | None = None indptr_ref: int | None = None indices_sorted: bool | None = False unique_indices: bool | None = False @property def ndim(self): return len(self.shape) def is_sparse(self): return self.indices_r...
SparsifyValue
python
ray-project__ray
python/ray/data/_internal/actor_autoscaler/default_actor_autoscaler.py
{ "start": 651, "end": 9448 }
class ____(ActorAutoscaler): def __init__( self, topology: "Topology", resource_manager: "ResourceManager", *, config: AutoscalingConfig, ): super().__init__(topology, resource_manager) self._actor_pool_scaling_up_threshold = ( config.actor_po...
DefaultActorAutoscaler
python
pikepdf__pikepdf
tests/test_object.py
{ "start": 10316, "end": 14058 }
class ____: def test_contains(self): d = Dictionary({'/Monty': 'Python', '/Flying': 'Circus'}) assert Name.Flying in d assert Name('/Monty') in d assert Name.Brian not in d def test_none(self): d = pikepdf.Dictionary({'/One': 1, '/Two': 2}) with pytest.raises(Val...
TestDictionary
python
ray-project__ray
python/ray/autoscaler/v2/schema.py
{ "start": 5601, "end": 6960 }
class ____: # Healthy nodes information (non-idle) active_nodes: List[NodeInfo] = field(default_factory=list) # Idle node information idle_nodes: List[NodeInfo] = field(default_factory=list) # Pending launches. pending_launches: List[LaunchRequest] = field(default_factory=list) # Failed laun...
ClusterStatus
python
python-pillow__Pillow
src/PIL/ExifTags.py
{ "start": 9305, "end": 9461 }
class ____(IntEnum): Exif = 0x8769 GPSInfo = 0x8825 MakerNote = 0x927C Makernote = 0x927C # Deprecated Interop = 0xA005 IFD1 = -1
IFD
python
ray-project__ray
python/ray/_common/tests/test_signature.py
{ "start": 14128, "end": 16658 }
class ____: """Integration tests for signature utilities working together.""" def test_complete_workflow(self): """Test complete workflow from function to flatten/recover.""" def test_func(x: int, y: str = "default", z: Optional[Any] = None): return f"{x}_{y}_{z}" # Extrac...
TestIntegration
python
huggingface__transformers
src/transformers/models/sew_d/modeling_sew_d.py
{ "start": 17616, "end": 18363 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size) self.dropout = StableDropout(config.pooler_dropout) self.config = config def forward(self, hidden_states): # We "pool" the m...
ContextPooler
python
walkccc__LeetCode
solutions/174. Dungeon Game/174.py
{ "start": 0, "end": 345 }
class ____: def calculateMinimumHP(self, dungeon: list[list[int]]) -> int: m = len(dungeon) n = len(dungeon[0]) dp = [math.inf] * (n + 1) dp[n - 1] = 1 for i in reversed(range(m)): for j in reversed(range(n)): dp[j] = min(dp[j], dp[j + 1]) - dungeon[i][j] dp[j] = max(dp[j], ...
Solution
python
tiangolo__fastapi
scripts/docs.py
{ "start": 1276, "end": 17690 }
class ____(HTMLParser): """Extract visible text from a string with HTML tags.""" def __init__(self): super().__init__() self.text_parts = [] def handle_data(self, data): self.text_parts.append(data) def extract_visible_text(self, html: str) -> str: self.reset() ...
VisibleTextExtractor
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/neptune.py
{ "start": 894, "end": 4704 }
class ____(AwsBaseHook): """ Interact with Amazon Neptune. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` """ AVAILABLE_STATES = ["a...
NeptuneHook
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/pipes/message_readers.py
{ "start": 988, "end": 2388 }
class ____(PipesChunkedLogReader): def __init__( self, *, bucket: str, key: str, client: Optional[GCSClient] = None, interval: float = 10, target_stream: Optional[IO[str]] = None, # TODO: maybe move this parameter to a different scope decode_fn...
PipesGCSLogReader
python
viewflow__viewflow
tests/json/test_json__basics.py
{ "start": 3131, "end": 3234 }
class ____(forms.ModelForm): class Meta: model = Client exclude = ["data"]
ClientForm
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 43094, "end": 58257 }
class ____(Pop2PianoPreTrainedModel, GenerationMixin): _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: Pop2PianoConfig): super().__init__(config) self.config = config ...
Pop2PianoForConditionalGeneration
python
ApeWorX__ape
src/ape/managers/accounts.py
{ "start": 1018, "end": 7304 }
class ____(list, ManagerAccessMixin): __test__ = False _impersonated_accounts: dict[AddressType, ImpersonatedAccount] = {} _accounts_by_index: dict[int, AccountAPI] = {} @log_instead_of_fail(default="<TestAccountManager>") def __repr__(self) -> str: return f"<apetest-wallet {self.hd_path}>...
TestAccountManager
python
pytorch__pytorch
.ci/lumen_cli/cli/lib/common/cli_helper.py
{ "start": 393, "end": 620 }
class ____(ABC): def __init__(self, args: Any) -> None: self.args = args @abstractmethod def run(self) -> None: """runs main logics, required""" # Pretty help: keep newlines + show defaults
BaseRunner
python
pypa__pip
tests/conftest.py
{ "start": 25071, "end": 33096 }
class ____: """Mock package structure used to generate a PyPI repository. FakePackage name and version should correspond to sdists (.tar.gz files) in our test data.""" name: str version: str filename: str metadata: MetadataKind # This will override any dependencies specified in the act...
FakePackage
python
doocs__leetcode
solution/3600-3699/3652.Best Time to Buy and Sell Stock using Strategy/Solution.py
{ "start": 0, "end": 450 }
class ____: def maxProfit(self, prices: List[int], strategy: List[int], k: int) -> int: n = len(prices) s = [0] * (n + 1) t = [0] * (n + 1) for i, (a, b) in enumerate(zip(prices, strategy), 1): s[i] = s[i - 1] + a * b t[i] = t[i - 1] + a ans = s[n] ...
Solution
python
pytorch__pytorch
torch/ao/nn/quantized/modules/functional_modules.py
{ "start": 2819, "end": 4551 }
class ____(torch.nn.Module): r"""module to replace FloatFunctional module before FX graph mode quantization, since activation_post_process will be inserted in top level module directly Valid operation names: - add - cat - mul - add_relu - add_scalar - mul_sca...
FXFloatFunctional
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict18.py
{ "start": 1858, "end": 1907 }
class ____(TypedDict, Generic[_T1]): x: _T1
TD9
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/methods/test_normalize.py
{ "start": 114, "end": 1009 }
class ____: @pytest.mark.parametrize("arg", ["2013-11-30", "2013-11-30 12:00:00"]) def test_normalize(self, tz_naive_fixture, arg, unit): tz = tz_naive_fixture ts = Timestamp(arg, tz=tz).as_unit(unit) result = ts.normalize() expected = Timestamp("2013-11-30", tz=tz) asser...
TestTimestampNormalize
python
django__django
tests/model_formsets/models.py
{ "start": 3837, "end": 3963 }
class ____(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name
Repository
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 81225, "end": 92335 }
class ____(TFLiteFrozenGraphConverterV2): """Converts a TensorFlow model into TensorFlow Lite model. Attributes: optimizations: Experimental flag, subject to change. Set of optimizations to apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a set of values of type `tf.lite.Optimi...
TFLiteConverterV2
python
getsentry__sentry
src/sentry/search/events/builder/profile_functions.py
{ "start": 3004, "end": 3435 }
class ____(ProfileFunctionsQueryBuilderMixin, BaseQueryBuilder): function_alias_prefix = "sentry_" config_class = ProfileFunctionsDatasetConfig def process_results(self, results: Any) -> EventsResponse: processed: EventsResponse = super().process_results(results) for row in processed["data"...
ProfileFunctionsQueryBuilder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/property_with_parameters.py
{ "start": 1063, "end": 1214 }
class ____: @cached_property def cached_prop(self, value): # [property-with-parameters] ... import abc import enum import types
Cached
python
numba__numba
numba/core/types/scalars.py
{ "start": 4084, "end": 4989 }
class ____(Type): """ Common base class for np.datetime64 and np.timedelta64. """ def __init__(self, unit, *args, **kws): name = '%s[%s]' % (self.type_name, unit) self.unit = unit self.unit_code = npdatetime_helpers.DATETIME_UNITS[self.unit] super(_NPDatetimeBase, self)....
_NPDatetimeBase
python
getsentry__sentry
src/sentry/integrations/github_enterprise/integration.py
{ "start": 14401, "end": 20295 }
class ____(GitHubIntegrationProvider): key = IntegrationProviderSlug.GITHUB_ENTERPRISE.value name = "GitHub Enterprise" metadata = metadata integration_cls = GitHubEnterpriseIntegration features = frozenset( [ IntegrationFeatures.COMMITS, IntegrationFeatures.ISSUE_BAS...
GitHubEnterpriseIntegrationProvider
python
openai__openai-python
src/openai/resources/beta/beta.py
{ "start": 5147, "end": 5725 }
class ____: def __init__(self, beta: AsyncBeta) -> None: self._beta = beta @cached_property def chatkit(self) -> AsyncChatKitWithStreamingResponse: return AsyncChatKitWithStreamingResponse(self._beta.chatkit) @cached_property def assistants(self) -> AsyncAssistantsWithStreamingResp...
AsyncBetaWithStreamingResponse
python
pennersr__django-allauth
allauth/headless/account/views.py
{ "start": 8579, "end": 9195 }
class ____(APIView): handle_json_input = False def post(self, request, *args, **kwargs): process = None stage = LoginStageController.enter(request, PhoneVerificationStage.key) if stage: process = flows.phone_verification.PhoneVerificationStageProcess.resume( ...
ResendPhoneVerificationCodeView
python
astropy__astropy
astropy/samp/hub.py
{ "start": 54486, "end": 56022 }
class ____: """ A base class to make writing Web Profile GUI consent dialogs easier. The concrete class must: 1) Poll ``handle_queue`` periodically, using the timer services of the GUI's event loop. This function will call ``self.show_dialog`` when a request requires aut...
WebProfileDialog
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hparams.py
{ "start": 11474, "end": 17760 }
class ____(CustomBoringModel, metaclass=_MetaType): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.save_hyperparameters() if _OMEGACONF_AVAILABLE: class DictConfSubClassBoringModel(SubClassBoringModel): def __init__(self, *args, dict_conf=OmegaConf.create(...
MetaTypeBoringModel
python
PrefectHQ__prefect
src/integrations/prefect-azure/tests/conftest.py
{ "start": 485, "end": 753 }
class ____: def __init__(self, items): self.items = items async def __aiter__(self): for item in self.items: yield item mock_container = { "prefect.txt": b"prefect_works", "folder/prefect.txt": b"prefect_works", }
AsyncIter
python
airbytehq__airbyte
airbyte-integrations/bases/base-normalization/normalization/transform_catalog/stream_processor.py
{ "start": 2055, "end": 73366 }
class ____(object): """ Takes as input an Airbyte Stream as described in the (configured) Airbyte Catalog's Json Schema. Associated input raw data is expected to be stored in a staging area table. This processor generates SQL models to transform such a stream into a final table in the destination schem...
StreamProcessor
python
huggingface__transformers
tests/utils/test_image_processing_utils.py
{ "start": 2871, "end": 8714 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls._token = TOKEN def test_push_to_hub(self): with TemporaryHubRepo(token=self._token) as tmp_repo: image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) image_process...
ImageProcessorPushToHubTester