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
getsentry__sentry
tests/sentry/users/api/bases/test_user.py
{ "start": 5093, "end": 5189 }
class ____(BaseUserEndpointTest): endpoint = RegionSiloUserEndpoint()
RegionSiloUserEndpointTest
python
walkccc__LeetCode
solutions/2116. Check if a Parentheses String Can Be Valid/2116.py
{ "start": 0, "end": 632 }
class ____: def canBeValid(self, s: str, locked: str) -> bool: if len(s) % 2 == 1: return False def check(s: str, locked: str, isForward: bool) -> bool: changeable = 0 l = 0 r = 0 for c, lock in zip(s, locked): if lock == '0': changeable += 1 elif c ==...
Solution
python
pytest-dev__pytest
src/_pytest/_code/code.py
{ "start": 46978, "end": 47755 }
class ____(TerminalRepr): reprentries: Sequence[ReprEntry | ReprEntryNative] extraline: str | None style: TracebackStyle entrysep: ClassVar = "_ " def toterminal(self, tw: TerminalWriter) -> None: # The entries might have different styles. for i, entry in enumerate(self.reprentries...
ReprTraceback
python
kubernetes-client__python
kubernetes/client/models/v1_token_request_status.py
{ "start": 383, "end": 4914 }
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...
V1TokenRequestStatus
python
dask__dask
dask/array/_array_expr/_io.py
{ "start": 402, "end": 434 }
class ____(ArrayExpr): pass
IO
python
simonw__datasette
datasette/views/base.py
{ "start": 5579, "end": 21395 }
class ____(BaseView): name = "" def redirect(self, request, path, forward_querystring=True, remove_args=None): if request.query_string and "?" not in path and forward_querystring: path = f"{path}?{request.query_string}" if remove_args: path = path_with_removed_args(reque...
DataView
python
getsentry__sentry
src/sentry/search/events/datasets/profile_functions.py
{ "start": 1445, "end": 2820 }
class ____: # the internal name in snuba column: str # data type associated with this column kind: Kind # the external name to expose alias: str | None = None # some kinds will have an unit associated with it unit: Unit | None = None COLUMNS = [ Column(alias="project.id", column="...
Column
python
doocs__leetcode
lcof2/剑指 Offer II 065. 最短的单词编码/Solution.py
{ "start": 0, "end": 82 }
class ____: def __init__(self) -> None: self.children = [None] * 26
Trie
python
pytorch__pytorch
test/distributed/checkpoint/test_async_process_executor.py
{ "start": 1033, "end": 3062 }
class ____(StorageWriter): """Unified test storage writer with configurable behaviors.""" def __init__( self, behavior="success", ): """ Create a test storage writer with specified behavior. Args: behavior: "success", "fail_once" """ self...
TestStorageWriter
python
facelessuser__pymdown-extensions
tests/test_targeted.py
{ "start": 81, "end": 5502 }
class ____(unittest.TestCase): """Test UrlParse.""" def test_url(self): """Test URL.""" url = 'http://www.google.com' scheme, netloc, _, _, _, _, is_url, is_absolute = util.parse_url(url) self.assertEqual(scheme, 'http') self.assertEqual(netloc, 'www.google.com') ...
TestUrlParse
python
pypa__pip
src/pip/_internal/req/req_set.py
{ "start": 212, "end": 2828 }
class ____: def __init__(self, check_supported_wheels: bool = True) -> None: """Create a RequirementSet.""" self.requirements: dict[str, InstallRequirement] = OrderedDict() self.check_supported_wheels = check_supported_wheels self.unnamed_requirements: list[InstallRequirement] = []...
RequirementSet
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_role_and_permission_endpoint.py
{ "start": 5801, "end": 7094 }
class ____(TestRoleEndpoint): @pytest.mark.parametrize( ("url", "expected_roles"), [ ("/fab/v1/roles?limit=1", ["Admin"]), ("/fab/v1/roles?limit=2", ["Admin", "Op"]), ( "/fab/v1/roles?offset=1", ["Op", "Public", "Test", "TestNoPermi...
TestGetRolesEndpointPaginationandFilter
python
huggingface__transformers
src/transformers/models/mamba/modeling_mamba.py
{ "start": 26854, "end": 27508 }
class ____(ModelOutput): r""" cache_params (`MambaCache`): The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to avoid providing the old `input_ids`. Includes both the State space model state matrices after the selective scan, and the...
MambaOutput
python
openai__openai-python
src/openai/_types.py
{ "start": 5115, "end": 5931 }
class ____(Protocol): def get(self, __key: str) -> str | None: ... HeadersLike = Union[Headers, HeadersLikeProtocol] ResponseT = TypeVar( "ResponseT", bound=Union[ object, str, None, "BaseModel", List[Any], Dict[str, Any], Response, ModelBui...
HeadersLikeProtocol
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 14303, "end": 15535 }
class ____(Benchmark): r""" Crowned Cross objective function. This class defines the Crowned Cross [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{CrownedCross}}(x) = 0.0001 \left(\left|{e^{\left|{100 - \frac{\sqrt...
CrownedCross
python
django__django
django/contrib/auth/forms.py
{ "start": 17816, "end": 18894 }
class ____(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, "password_incorrect": _( "Your old password was entered incorrectly. Please enter it again." ),...
PasswordChangeForm
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 23158, "end": 24151 }
class ____(object): # ReferrableT def __init__( self, id = 0, ): self.id = id # type: int @classmethod def InitFromBuf(cls, buf, pos): referrable = Referrable() referrable.Init(buf, pos) return cls.InitFromObj(referrable) @classmethod def I...
ReferrableT
python
streamlit__streamlit
lib/tests/streamlit/form_utils_test.py
{ "start": 916, "end": 2797 }
class ____(unittest.TestCase): def tearDown(self) -> None: super().tearDown() # reset context_dg_stack to clean state for other tests # that are executed in the same thread context_dg_stack.set(get_default_dg_stack_value()) @classmethod def setUpClass(cls): super()....
FormUtilsTest
python
huggingface__transformers
src/transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py
{ "start": 842, "end": 4700 }
class ____(PreTrainedConfig): r""" [`VisionEncoderDecoderConfig`] is the configuration class to store the configuration of a [`VisionEncoderDecoderModel`]. It is used to instantiate a Vision-Encoder-Text-Decoder model according to the specified arguments, defining the encoder and decoder configs. C...
VisionEncoderDecoderConfig
python
huggingface__transformers
tests/models/markuplm/test_processing_markuplm.py
{ "start": 6179, "end": 31047 }
class ____(unittest.TestCase): @cached_property def get_html_strings(self): html_string_1 = """ <!DOCTYPE html> <html> <head> <title>Hello world</title> </head> <body> <h1>Welcome</h1> <p>Here is my website.</p> </body> </...
MarkupLMProcessorIntegrationTests
python
numba__numba
numba/tests/npyufunc/test_parallel_env_variable.py
{ "start": 131, "end": 1264 }
class ____(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ ...
TestParallelEnvVariable
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_getlimits.py
{ "start": 903, "end": 1140 }
class ____(TestCase): def test_singleton(self): ftype = finfo(float) ftype2 = finfo(float) assert_equal(id(ftype), id(ftype2)) @skip(reason="torch.finfo is not a singleton. Why demanding it is?")
TestPythonFloat
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py
{ "start": 2172, "end": 2246 }
class ____(TypedDict): a: ReadOnly[float | str] b: ReadOnly[int]
TD5
python
huggingface__transformers
tests/models/clip/test_modeling_clip.py
{ "start": 7672, "end": 11313 }
class ____(CLIPModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as CLIP does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (CLIPVisionModel, CLIPVisionModelWithProjection) if is_torch_available(...
CLIPVisionModelTest
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 1458, "end": 2772 }
class ____: """ Validation if field contains a null byte. Use after `InputRequired()` but before other validators to prevent sending null bytes to the database, which would result in `psycopg.DataError` """ def __init__(self, message=None): if message is None: message = _("N...
PreventNullBytesValidator
python
pandas-dev__pandas
pandas/tests/arrays/interval/test_overlaps.py
{ "start": 875, "end": 3280 }
class ____: def test_overlaps_interval(self, constructor, start_shift, closed, other_closed): start, shift = start_shift interval = Interval(start, start + 3 * shift, other_closed) # intervals: identical, nested, spanning, partial, adjacent, disjoint tuples = [ (start, s...
TestOverlaps
python
django__django
tests/backends/postgresql/test_introspection.py
{ "start": 198, "end": 1577 }
class ____(TestCase): def test_get_sequences(self): with connection.cursor() as cursor: seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table) self.assertEqual( seqs, [ { "table": Person...
DatabaseSequenceTests
python
getsentry__sentry
fixtures/gitlab.py
{ "start": 683, "end": 15856 }
class ____(APITestCase): provider = IntegrationProviderSlug.GITLAB.value def setUp(self): self.login_as(self.user) with assume_test_silo_mode(SiloMode.CONTROL): self.integration = Integration.objects.create( provider=self.provider, name="Example Gitla...
GitLabTestCase
python
kamyu104__LeetCode-Solutions
Python/number-of-flowers-in-full-bloom.py
{ "start": 674, "end": 1123 }
class ____(object): def fullBloomFlowers(self, flowers, persons): """ :type flowers: List[List[int]] :type persons: List[int] :rtype: List[int] """ starts, ends = [], [] for s, e in flowers: starts.append(s) ends.append(e+1) sta...
Solution
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 23031, "end": 27518 }
class ____(Layer): """A layer that applies an activation operation to the input. Parameters: ----------- name: string The name of the activation function that will be used. """ def __init__(self, name): self.activation_name = name self.activation_func = activation_funct...
Activation
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 13690, "end": 14152 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__( event_id=120, name="MONITOR_ADD", api_name="monitor.add", ) def render(self, audit_log_entry: AuditLogEntry) -> str: entry_data = audit_log_entry.data name = entry_data.g...
MonitorAddAuditLogEvent
python
numba__numba
numba/core/typing/listdecl.py
{ "start": 899, "end": 2808 }
class ____(AttributeTemplate): key = types.List # NOTE: some of these should be Sequence / MutableSequence methods @bound_function("list.append") def resolve_append(self, list, args, kws): item, = args assert not kws unified = self.context.unify_pairs(list.dtype, item) ...
ListAttribute
python
celery__celery
t/smoke/tests/stamping/test_hybrid_cluster.py
{ "start": 1415, "end": 5915 }
class ____: def test_sanity(self, celery_setup: CeleryTestSetup): stamp = {"stamp": 42} class CustomStampingVisitor(StampingVisitor): def on_signature(self, sig, **headers) -> dict: return stamp.copy() worker: CeleryTestWorker for worker in celery_setup....
test_stamping_hybrid_worker_cluster
python
kamyu104__LeetCode-Solutions
Python/detonate-the-maximum-bombs.py
{ "start": 1104, "end": 2003 }
class ____(object): def maximumDetonation(self, bombs): """ :type bombs: List[List[int]] :rtype: int """ adj = [[] for _ in xrange(len(bombs))] for i, (xi, yi, ri) in enumerate(bombs): for j, (xj, yj, _) in enumerate(bombs): if j ==...
Solution2
python
google__pytype
pytype/rewrite/abstract/classes.py
{ "start": 8373, "end": 9116 }
class ____(BaseInstance, types.Module): """A module.""" def __init__(self, ctx: base.ContextType, name: str): cls = ctx.abstract_loader.load_builtin('module') super().__init__(ctx, cls, members={}) self.name = name def __repr__(self): return f'Module({self.name})' @property def _attrs(self)...
Module
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 3382, "end": 18938 }
class ____(greentest.TestCase): maxDiff = None __timeout__ = 30 switch_expected = None TRACE = not util.QUIET and os.getenv('GEVENT_DEBUG', '') == 'trace' verbose_dns = TRACE def trace(self, message, *args, **kwargs): if self.TRACE: util.debug(message, *args, **kwargs) ...
TestCase
python
huggingface__transformers
tests/models/hunyuan_v1_dense/test_modeling_hunyuan_v1_dense.py
{ "start": 1596, "end": 1896 }
class ____(unittest.TestCase): def setUp(self): cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @slow def test_model_generation(self): # TODO Need new Dense Model return True
HunYuanDenseV1IntegrationTest
python
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 17877, "end": 21055 }
class ____: scenarii: list[tuple[str, str, bytes | None]] = [ # TLS to TLS: send referrer ( "https://example.com/sekrit.html", "http://not.example.com/", b"https://example.com/sekrit.html", ), ( "https://example1.com/page.html", ...
MixinUnsafeUrl
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 73132, "end": 77686 }
class ____(object): def __init__(self, context, handle, finalizer, external=False): self.context = context self.handle = handle self.external = external if finalizer is not None: weakref.finalize(self, finalizer) def __int__(self): if USE_NV_BINDING: ...
Stream
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run.py
{ "start": 124, "end": 366 }
class ____(str, Enum): """Run execution status.""" QUEUED = "QUEUED" STARTING = "STARTING" STARTED = "STARTED" SUCCESS = "SUCCESS" FAILURE = "FAILURE" CANCELING = "CANCELING" CANCELED = "CANCELED"
DgApiRunStatus
python
readthedocs__readthedocs.org
readthedocs/core/migrations/0004_ad-opt-out.py
{ "start": 238, "end": 1083 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("core", "0003_add_banned_status"), ] operations = [ migrations.AddField( model_name="userprofile", name="allow_ads", field=models.BooleanField( default=True...
Migration
python
huggingface__transformers
src/transformers/models/maskformer/modeling_maskformer_swin.py
{ "start": 31056, "end": 33743 }
class ____(MaskFormerSwinPreTrainedModel): def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.num_layers = len(config.depths) self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1)) self.embeddings = MaskForm...
MaskFormerSwinModel
python
apache__airflow
devel-common/src/tests_common/pytest_plugin.py
{ "start": 32509, "end": 55625 }
class ____(Generic[Dag], Protocol): """ Interface definition for dag_maker return value. This class exists so tests can import the class for type hints. The actual implementation is done in the dag_maker fixture. """ session: Session dag: DAG def __enter__(self) -> Dag: ... def _...
DagMaker
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 1159, "end": 6241 }
class ____: # def test_masked_all(self): # Tests masked_all # Standard dtype test = masked_all((2,), dtype=float) control = array([1, 1], mask=[1, 1], dtype=float) assert_equal(test, control) # Flexible dtype dt = np.dtype({'names': ['a', 'b'], 'formats': ...
TestGeneric
python
gwtw__py-sorting
test/cocktail_sort_test.py
{ "start": 408, "end": 751 }
class ____(unittest.TestCase, BaseCustomComparisonSortTest, BasePositiveIntegerSortTest, BaseNegativeIntegerSortTest, BaseStringSortTest): def setUp(self): self.sort = cocktail_sort.sort if __name__ == '__main__': unitt...
CocktailSortTest
python
doocs__leetcode
solution/2200-2299/2297.Jump Game VIII/Solution.py
{ "start": 0, "end": 735 }
class ____: def minCost(self, nums: List[int], costs: List[int]) -> int: n = len(nums) g = defaultdict(list) stk = [] for i in range(n - 1, -1, -1): while stk and nums[stk[-1]] < nums[i]: stk.pop() if stk: g[i].append(stk[-1]) ...
Solution
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 64923, "end": 65972 }
class ____(BaseDataset): """ Features of datasets with (0,)-shape axes """ def test_array_conversion(self): """ Empty datasets can be converted to NumPy arrays """ ds = self.f.create_dataset(make_name("x"), 0, maxshape=None) self.assertEqual(ds.shape, np.array(ds).shape) ...
TestZeroShape
python
mlflow__mlflow
dev/xtest_viz.py
{ "start": 1372, "end": 1435 }
class ____: name: str date: str status: str
JobResult
python
pdm-project__pdm
src/pdm/cli/commands/self_cmd.py
{ "start": 1951, "end": 2912 }
class ____(BaseCommand): """Manage the PDM program itself (previously known as plugin)""" arguments = (verbose_option,) name = "self" @classmethod def register_to( cls, subparsers: argparse._SubParsersAction, name: str | None = None, **kwargs: Any, ) -> None: ...
Command
python
dask__distributed
distributed/tests/test_worker.py
{ "start": 91580, "end": 110689 }
class ____(Worker): async def get_data(self, comm, *args, **kwargs): comm.abort() @gen_cluster(client=True, nthreads=[("", 1)]) async def test_missing_released_zombie_tasks_2(c, s, b): # If get_data_from_worker raises this will suggest a dead worker to B and it # will transition the task to missin...
BrokenWorker
python
scipy__scipy
scipy/optimize/tests/test_differentiable_functions.py
{ "start": 16653, "end": 17282 }
class ____: def __init__(self): self.nfev = 0 self.njev = 0 self.nhev = 0 def fun(self, x): self.nfev += 1 return np.array([2*(x[0]**2 + x[1]**2 - 1) - x[0], 4*(x[0]**3 + x[1]**2 - 4) - 3*x[0]], dtype=x.dtype) def jac(self, x): self...
ExVectorialFunction
python
pytorch__pytorch
torch/_functorch/_aot_autograd/runtime_wrappers.py
{ "start": 31634, "end": 41930 }
class ____(CompilerWrapper): keep_arg_mask: list[bool] = field(default_factory=list) add_dupe_map: list[int] = field(default_factory=list) old_input_metadata: list[InputAliasInfo] = field(default_factory=list) needs_post_compile: bool = True # NB: Hot path, avoid set lookups here # TODO: Can av...
AOTDedupeWrapper
python
gevent__gevent
src/greentest/3.10/test_signal.py
{ "start": 8914, "end": 14719 }
class ____(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def check_wakeup(self, test_body, *signals, ordered=True): # use a subprocess to have only one thread code = """if 1: import _testcapi import os import signal import struct ...
WakeupSignalTests
python
joke2k__faker
tests/providers/test_phone_number.py
{ "start": 20940, "end": 22041 }
class ____: """Test uz_UZ phone number provider methods""" def test_phone_number(self, faker, num_samples): pattern: Pattern = re.compile( r"(?:" # Non-capturing group r"\+998 \(\d{2}\) \d{3}-\d{2}-\d{2}|" # Example: +998 (93) 123-45-67 r"\+998 \(\d{2}\) \d{3} \d{2...
TestUzUz
python
nedbat__coveragepy
tests/test_arcs.py
{ "start": 58229, "end": 63300 }
class ____(CoverageTest): """Tests of the new async and await keywords in Python 3.5""" def test_async(self) -> None: self.check_coverage( """\ import asyncio async def compute(x, y): # 3 print(f"Compute {x} + {y} ...") ...
AsyncTest
python
cython__cython
tests/run/pep3135_class_cell.py
{ "start": 3518, "end": 3784 }
class ____: def method(self): return __class__ __test__ = { "k": """ >>> OldK = K >>> K = None >>> OldK().method().__name__ 'K' """, "ck": """ >>> OldCK = CK >>> CK = None >>> OldCK().method().__name__ 'CK' """ }
CK
python
cherrypy__cherrypy
cherrypy/test/test_params.py
{ "start": 79, "end": 1864 }
class ____(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose @cherrypy.tools.json_out() @cherrypy.tools.params() def resource(self, limit=None, sort=None): return type(limit).__name__ # for testi...
ParamsTest
python
run-llama__llama_index
llama-index-packs/llama-index-packs-recursive-retriever/llama_index/packs/recursive_retriever/embedded_tables_unstructured/base.py
{ "start": 495, "end": 2422 }
class ____(BaseLlamaPack): """ Embedded Tables + Unstructured.io Retriever pack. Use unstructured.io to parse out embedded tables from an HTML document, build a node graph, and then run our recursive retriever against that. **NOTE**: must take in a single HTML file. """ def __init__( ...
EmbeddedTablesUnstructuredRetrieverPack
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 57871, "end": 58150 }
class ____(_ConfigBase): name: str description: Optional[str] def to_dict(self) -> Dict[str, Any]: out = {"name": self.name} if self.description is not None: out["description"] = self.description return out @dataclass
_PropertyBase
python
google__jax
jax/_src/interpreters/ad.py
{ "start": 50460, "end": 65654 }
class ____(Tracer): __slots__ = ['primal', 'tangent'] def __init__(self, trace, primal, tangent): if config.enable_checks.value: _primal_tangent_shapes_match(primal, tangent) self._trace = trace self.primal = primal self.tangent = tangent @property def aval(self): return get_aval(sel...
LinearizeTracer
python
wandb__wandb
wandb/errors/util.py
{ "start": 467, "end": 1711 }
class ____: """Converts protobuf errors to exceptions and vice versa.""" @staticmethod def to_exception(error: pb.ErrorInfo) -> Optional[Error]: """Convert a protobuf error to an exception. Args: error: The protobuf error to convert. Returns: The correspond...
ProtobufErrorHandler
python
pytest-dev__pytest-xdist
testing/test_dsession.py
{ "start": 18113, "end": 22889 }
class ____: @pytest.mark.xfail def test_rsync_printing(self, pytester: pytest.Pytester, linecomp: Any) -> None: config = pytester.parseconfig() from _pytest.terminal import TerminalReporter rep = TerminalReporter(config, file=linecomp.stringio) config.pluginmanager.register(rep,...
TestDistReporter
python
langchain-ai__langchain
libs/partners/ollama/tests/unit_tests/test_auth.py
{ "start": 7870, "end": 9499 }
class ____: """Test edge cases and error conditions for URL authentication.""" def test_parse_url_with_auth_malformed_url(self) -> None: """Test behavior with malformed URLs.""" malformed_url = "not-a-valid-url" result = parse_url_with_auth(malformed_url) # Shouldn't return a UR...
TestUrlAuthEdgeCases
python
pytorch__pytorch
test/dynamo/test_view.py
{ "start": 158, "end": 3708 }
class ____(torch._dynamo.test_case.TestCase): def test_view_to_2d(self): @torch.compile(fullgraph=True, backend="eager") def f(t, _u0): u0 = t[0].item() u1 = t[1].item() n = u0 * u1 a = torch.randn(n) return a.view(-1, _u0) t = tor...
ViewTests
python
huggingface__transformers
src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py
{ "start": 45854, "end": 50620 }
class ____(Wav2Vec2BertPreTrainedModel): def __init__(self, config, target_lang: Optional[str] = None): r""" target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only releva...
Wav2Vec2BertForCTC
python
huggingface__transformers
src/transformers/models/swinv2/modeling_swinv2.py
{ "start": 8634, "end": 9195 }
class ____(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" def __init__(self, drop_prob: Optional[float] = None) -> None: super().__init__() self.drop_prob = drop_prob def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:...
Swinv2DropPath
python
explosion__spaCy
spacy/displacy/render.py
{ "start": 20189, "end": 24698 }
class ____: """Render named entities as HTML.""" style = "ent" def __init__(self, options: Dict[str, Any] = {}) -> None: """Initialise entity renderer. options (dict): Visualiser-specific options (colors, ents) """ colors = dict(DEFAULT_LABEL_COLORS) user_colors = ...
EntityRenderer
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 63938, "end": 64489 }
class ____(QuantizedCache): def __init__( self, config: PreTrainedConfig, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): logger.warning_once( "`HQQQuantizedCache` is deprec...
HQQQuantizedCache
python
arrow-py__arrow
arrow/locales.py
{ "start": 52086, "end": 53580 }
class ____(Locale): names = ["tl", "tl-ph"] past = "nakaraang {0}" future = "{0} mula ngayon" timeframes = { "now": "ngayon lang", "second": "isang segundo", "seconds": "{0} segundo", "minute": "isang minuto", "minutes": "{0} minuto", "hour": "isang oras...
TagalogLocale
python
doocs__leetcode
solution/0400-0499/0412.Fizz Buzz/Solution.py
{ "start": 0, "end": 379 }
class ____: def fizzBuzz(self, n: int) -> List[str]: ans = [] for i in range(1, n + 1): if i % 15 == 0: ans.append('FizzBuzz') elif i % 3 == 0: ans.append('Fizz') elif i % 5 == 0: ans.append('Buzz') else:...
Solution
python
tqdm__tqdm
tests/tests_contrib_logging.py
{ "start": 754, "end": 964 }
class ____(tqdm): exception_class = RuntimeError @classmethod def write(cls, s, **__): # pylint: disable=arguments-differ raise ErrorRaisingTqdm.exception_class('fail fast')
ErrorRaisingTqdm
python
getsentry__sentry
src/sentry/sentry_apps/api/bases/sentryapps.py
{ "start": 3423, "end": 4355 }
class ____(Endpoint): def handle_exception_with_details(self, request, exc, handler_context=None, scope=None): return self._handle_sentry_app_exception( exception=exc ) or super().handle_exception_with_details(request, exc, handler_context, scope) def _handle_sentry_app_exception(se...
IntegrationPlatformEndpoint
python
django-haystack__django-haystack
test_haystack/elasticsearch7_tests/test_backend.py
{ "start": 62602, "end": 63580 }
class ____(TestCase): def setUp(self): self.raw_es = elasticsearch.Elasticsearch( settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] ) def test_recreate_index(self): clear_elasticsearch_index() sb = connections["elasticsearch"].get_backend() sb.setup_comp...
RecreateIndexTestCase
python
huggingface__transformers
src/transformers/hyperparameter_search.py
{ "start": 1682, "end": 2066 }
class ____(HyperParamSearchBackendBase): name = "optuna" @staticmethod def is_available(): return is_optuna_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_optuna(trainer, n_trials, direction, **kwargs) def default_hp_space(self, t...
OptunaBackend
python
Textualize__textual
tests/text_area/test_escape_binding.py
{ "start": 360, "end": 1880 }
class ____(App): def on_mount(self) -> None: self.push_screen(TextAreaDialog()) async def test_escape_key_when_tab_behavior_is_focus(): """Regression test for https://github.com/Textualize/textual/issues/4110 When the `tab_behavior` of TextArea is the default to shift focus, pressing <Escape>...
TextAreaDialogApp
python
huggingface__transformers
src/transformers/models/flex_olmo/modular_flex_olmo.py
{ "start": 15827, "end": 15998 }
class ____(OlmoeForCausalLM): pass __all__ = [ "FlexOlmoConfig", "FlexOlmoForCausalLM", "FlexOlmoModel", "FlexOlmoPreTrainedModel", ]
FlexOlmoForCausalLM
python
plotly__plotly.py
plotly/graph_objs/choroplethmap/colorbar/_title.py
{ "start": 233, "end": 4013 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "choroplethmap.colorbar" _path_str = "choroplethmap.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font ...
Title
python
joke2k__faker
faker/providers/person/de_DE/__init__.py
{ "start": 70, "end": 47533 }
class ____(PersonProvider): formats_male = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}-{{last_name}}", "{{prefix_male}} {{first...
Provider
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 3495, "end": 3645 }
class ____: def __init__(self, expr): self.expr = expr def __clause_element__(self): return self.expr
ColExpressionDuckTypeOnly
python
pytorch__pytorch
test/dynamo/test_activation_checkpointing.py
{ "start": 59427, "end": 62651 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[4, 4]"): l_x_ = L_x_ wrap_body_0 = self.wrap_body_0 tag_activation_checkpoint = torch.ops.higher_order.tag_activation_checkpoint(wrap_body_0, l_x_, use_reentrant = True); wrap_body_0 = l_x_ = None getitem: "f32[4, 4]" = tag_...
GraphModule
python
vyperlang__vyper
vyper/venom/passes/make_ssa.py
{ "start": 270, "end": 6139 }
class ____(IRPass): """ This pass converts the function into Static Single Assignment (SSA) form. """ dom: DominatorTreeAnalysis cfg: CFGAnalysis liveness: LivenessAnalysis defs: dict[IRVariable, OrderedSet[IRBasicBlock]] def run_pass(self): fn = self.function self.cfg...
MakeSSA
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 54662, "end": 57927 }
class ____(GoogleCloudBaseOperator): """ Gets the latest state of a long-running DlpJob. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPGetDLPJobOperator` :param dlp_job_id: The ID of the DLP job resource to be read...
CloudDLPGetDLPJobOperator
python
sanic-org__sanic
sanic/logging/formatter.py
{ "start": 7846, "end": 8583 }
class ____(AutoAccessFormatter): """ The LegacyFormatter is used if you want to use the old style of logging. You can use it as follows, typically in conjunction with the LegacyFormatter: .. code-block:: python from sanic.log import LOGGING_CONFIG_DEFAULTS LOGGING_CONFIG_DEFAULTS...
LegacyAccessFormatter
python
dask__distributed
distributed/tests/test_nanny.py
{ "start": 17508, "end": 18180 }
class ____(worker.Worker): """A Worker that raises KeyboardInterrupt almost immediately""" async def heartbeat(self): def raise_err(): raise KeyboardInterrupt() self.loop.add_callback(raise_err) @gen_test() async def test_nanny_closed_by_keyboard_interrupt(): async with Sched...
KeyboardInterruptWorker
python
getsentry__sentry
src/sentry/notifications/notification_action/issue_alert_registry/handlers/plugin_issue_alert_handler.py
{ "start": 388, "end": 876 }
class ____(BaseIssueAlertHandler): @classmethod def get_integration_id(cls, action: Action, mapping: ActionFieldMapping) -> dict[str, Any]: return {} @classmethod def get_target_identifier( cls, action: Action, mapping: ActionFieldMapping, organization_id: int ) -> dict[str, Any]: ...
PluginIssueAlertHandler
python
astropy__astropy
astropy/coordinates/tests/test_celestial_transformations.py
{ "start": 8758, "end": 15354 }
class ____: """ Check GCRS<->Heliocentric and Barycentric coordinate conversions. Uses the WHT observing site (information grabbed from data/sites.json). """ def setup_method(self): wht = EarthLocation(342.12 * u.deg, 28.758333333333333 * u.deg, 2327 * u.m) self.obstime = Time("201...
TestHelioBaryCentric
python
numba__numba
numba/tests/test_jitmethod.py
{ "start": 1284, "end": 2000 }
class ____(unittest.TestCase): def test_decorated_function(self): with override_config('DISABLE_JIT', True): def method(x): return x jitted = jit(method) self.assertEqual(jitted, method) self.assertEqual(10, method(10)) self.assertEqual(10, ji...
TestDisabledJIT
python
apache__airflow
providers/redis/tests/integration/redis/sensors/test_redis_pub_sub.py
{ "start": 1190, "end": 2845 }
class ____: def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} self.dag = DAG("test_dag_id", default_args=args) self.mock_context = MagicMock() def test_poke_true(self): sensor = RedisPubSubSensor( task_id="test_task", dag=self.dag, cha...
TestRedisPubSubSensor
python
PyCQA__pylint
pylint/extensions/set_membership.py
{ "start": 488, "end": 1806 }
class ____(BaseChecker): name = "set_membership" msgs = { "R6201": ( "Consider using set for membership test", "use-set-for-membership", "Membership tests are more efficient when performed on " "a lookup optimized datatype like ``sets``.", ), }...
SetMembershipChecker
python
pexpect__pexpect
tests/PexpectTestCase.py
{ "start": 4770, "end": 4845 }
class ____(_PexpectTestCaseBase, unittest.TestCase): pass
PexpectTestCase
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 56481, "end": 57854 }
class ____(Request): """ :param queue: Queue id :type queue: str :param task: Task id :type task: str """ _service = "queues" _action = "move_task_to_back" _version = "2.9" _schema = { "definitions": {}, "properties": { "queue": {"description": "Queue...
MoveTaskToBackRequest
python
pennersr__django-allauth
tests/apps/socialaccount/providers/odnoklassniki/tests.py
{ "start": 254, "end": 1067 }
class ____(OAuth2TestsMixin, TestCase): provider_id = OdnoklassnikiProvider.id def get_mocked_response(self, verified_email=True): return MockedResponse( HTTPStatus.OK, """ {"uid":"561999209121","birthday":"1999-09-09","age":33,"first_name":"Ivan", "last_name":"Petrov","name":"I...
OdnoklassnikiTests
python
pytorch__pytorch
torch/ao/nn/qat/modules/conv.py
{ "start": 5753, "end": 7773 }
class ____(_ConvNd, nn.Conv2d): r""" A Conv2d module attached with FakeQuantize modules for weight, used for quantization aware training. We adopt the same interface as `torch.nn.Conv2d`, please see https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d for documentation. ...
Conv2d
python
walkccc__LeetCode
solutions/2524. Maximum Frequency Score of a Subarray/2524.py
{ "start": 0, "end": 1200 }
class ____: def maxFrequencyScore(self, nums: list[int], k: int) -> int: MOD = 1_000_000_007 count = collections.Counter(nums[:k]) summ = self._getInitialSumm(count, MOD) ans = summ for i in range(k, len(nums)): # Remove the leftmost number that's out-of-window. leftNum = nums[i - k] ...
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1575282, "end": 1575482 }
class ____(VegaLiteSchema): """Vector3number schema wrapper.""" _schema = {"$ref": "#/definitions/Vector3<number>"} def __init__(self, *args): super().__init__(*args)
Vector3number
python
google__jax
jax/_src/core.py
{ "start": 93120, "end": 93384 }
class ____(type): def __instancecheck__(self, inst): from jax._src.state.types import AbstractRef # pytype: disable=import-error return (super().__instancecheck__(inst) or isinstance(inst, Tracer) and isinstance(inst.aval, AbstractRef))
RefMeta
python
pallets__jinja
src/jinja2/utils.py
{ "start": 21321, "end": 22949 }
class ____: """Cycle through values by yield them one at a time, then restarting once the end is reached. Available as ``cycler`` in templates. Similar to ``loop.cycle``, but can be used outside loops or across multiple loops. For example, render a list of folders and files in a list, alternating g...
Cycler
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 125613, "end": 133214 }
class ____(QueryTest, AssertsCompiledSQL): __dialect__ = "default" def test_union(self): User = self.classes.User s = fixture_session() fred = s.query(User).filter(User.name == "fred") ed = s.query(User).filter(User.name == "ed") jack = s.query(User).filter(User.name =...
SetOpsTest
python
apache__thrift
lib/py/src/transport/TTwisted.py
{ "start": 8244, "end": 8447 }
class ____(Interface): processor = Attribute("Thrift processor") iprot_factory = Attribute("Input protocol factory") oprot_factory = Attribute("Output protocol factory")
IThriftServerFactory
python
encode__django-rest-framework
tests/test_response.py
{ "start": 762, "end": 1065 }
class ____(BaseRenderer): media_type = 'text/html' DUMMYSTATUS = status.HTTP_200_OK DUMMYCONTENT = 'dummycontent' def RENDERER_A_SERIALIZER(x): return ('Renderer A: %s' % x).encode('ascii') def RENDERER_B_SERIALIZER(x): return ('Renderer B: %s' % x).encode('ascii')
MockTextMediaRenderer