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
google__pytype
pytype/tests/test_functools.py
{ "start": 68, "end": 1781 }
class ____(test_base.BaseTest): """Tests for @cached.property.""" def test_basic(self): self.Check(""" import functools class A: @functools.cached_property def f(self): return 42 a = A() x = a.f assert_type(x, int) a.f = 43 x = a.f a...
TestCachedProperty
python
sqlalchemy__sqlalchemy
test/sql/test_query.py
{ "start": 28255, "end": 32738 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column("user_id", INT, primary_key=True), Column("user_name", VARCHAR(20)), ) Table( ...
LimitTest
python
sympy__sympy
sympy/functions/special/beta_functions.py
{ "start": 786, "end": 5651 }
class ____(DefinedFunction): r""" The beta integral is called the Eulerian integral of the first kind by Legendre: .. math:: \mathrm{B}(x,y) \int^{1}_{0} t^{x-1} (1-t)^{y-1} \mathrm{d}t. Explanation =========== The Beta function or Euler's first integral is closely associated ...
beta
python
django__django
django/db/models/aggregates.py
{ "start": 9851, "end": 10232 }
class ____(NumericOutputFieldMixin, Aggregate): name = "StdDev" arity = 1 def __init__(self, expression, sample=False, **extra): self.function = "STDDEV_SAMP" if sample else "STDDEV_POP" super().__init__(expression, **extra) def _get_repr_options(self): return {**super()._get_r...
StdDev
python
scrapy__scrapy
tests/test_downloader_handlers_http_base.py
{ "start": 24656, "end": 26281 }
class ____(ABC): """Base class for special cases tested with just one simple request""" keyfile = "keys/localhost.key" certfile = "keys/localhost.crt" host = "localhost" cipher_string: str | None = None @pytest.fixture(scope="class") def simple_mockserver(self) -> Generator[SimpleMockServe...
TestSimpleHttpsBase
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 26543, "end": 27023 }
class ____(SpmConverter): def unk_id(self, proto): unk_id = 3 return unk_id def post_processor(self): return processors.TemplateProcessing( single="<s> $A </s>", pair="<s> $A </s> </s> $B </s>", special_tokens=[ ("<s>", self.original_t...
BarthezConverter
python
ansible__ansible
test/integration/targets/ansible-test-sanity-yamllint/ansible_collections/ns/col/plugins/inventory/inventory1.py
{ "start": 596, "end": 665 }
class ____(BaseInventoryPlugin): NAME = 'inventory1'
InventoryModule
python
facelessuser__soupsieve
soupsieve/css_parser.py
{ "start": 9547, "end": 10749 }
class ____(SelectorPattern): """Selector pattern.""" def __init__(self, patterns: tuple[tuple[str, tuple[str, ...], str, type[SelectorPattern]], ...]) -> None: """Initialize.""" self.patterns = {} for p in patterns: name = p[0] pattern = p[3](name, p[2]) ...
SpecialPseudoPattern
python
walkccc__LeetCode
solutions/1836. Remove Duplicates From an Unsorted Linked List/1836.py
{ "start": 0, "end": 424 }
class ____: def deleteDuplicatesUnsorted(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) count = collections.Counter() curr = head while curr: count[curr.val] += 1 curr = curr.next curr = dummy while curr: while curr.next and curr.next.val in count and count[c...
Solution
python
pandas-dev__pandas
asv_bench/benchmarks/index_object.py
{ "start": 1959, "end": 2804 }
class ____: def setup(self): self.idx_inc = RangeIndex(start=0, stop=10**6, step=3) self.idx_dec = RangeIndex(start=10**6, stop=-1, step=-3) def time_max(self): self.idx_inc.max() def time_max_trivial(self): self.idx_dec.max() def time_min(self): self.idx_dec.m...
Range
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-for-cutting-cake-ii.py
{ "start": 792, "end": 1496 }
class ____(object): def minimumCost(self, m, n, horizontalCut, verticalCut): """ :type m: int :type n: int :type horizontalCut: List[int] :type verticalCut: List[int] :rtype: int """ horizontalCut.sort(reverse=True) verticalCut.sort(reverse=Tru...
Solution2
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/matrix_solve_op_test.py
{ "start": 1432, "end": 6132 }
class ____(test.TestCase): def _verifySolve(self, x, y, batch_dims=None): for np_type in [np.float32, np.float64, np.complex64, np.complex128]: if np_type == np.float32 or np_type == np.complex64: tol = 1e-5 else: tol = 1e-12 for adjoint in False, True: if np_type in (np...
MatrixSolveOpTest
python
allegroai__clearml
clearml/backend_api/services/v2_9/auth.py
{ "start": 6677, "end": 8286 }
class ____(Request): """ Edit a users' auth data properties :param user: User ID :type user: str :param role: The new user's role within the company :type role: str """ _service = "auth" _action = "edit_user" _version = "2.9" _schema = { "definitions": {}, ...
EditUserRequest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox42.py
{ "start": 315, "end": 904 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox42.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workb...
TestCompareXLSXFiles
python
getsentry__sentry
tests/sentry/grouping/test_builtin_fingerprinting.py
{ "start": 22610, "end": 34354 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.chunkload_error_trace: dict[str, Any] = { "fingerprint": ["my-route", "{{ default }}"], "exception": { "values": [ { ...
BuiltInFingerprintingTest
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 4164, "end": 5242 }
class ____: username = wtforms.StringField( validators=[ wtforms.validators.InputRequired(), PreventNullBytesValidator(message=INVALID_USERNAME_MESSAGE), wtforms.validators.Length( max=50, message=_("Choose a username with 50 characters or less.") ...
NewUsernameMixin
python
realpython__materials
python-protocol/contents.py
{ "start": 648, "end": 1200 }
class ____: def __init__(self): self.videos = [] def create_content(self) -> str: return "Recording a video." def add_video(self, title: str, path: str) -> None: self.videos.append(f"{title}: {path}") print(f"Video added: {title}") def produce_content(creator: ContentCrea...
Vlog
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/plan.py
{ "start": 131, "end": 598 }
class ____: """Abstract class for logical/physical execution plans. This plan should hold an operator representing the plan DAG and any auxiliary data that's useful for plan optimization or execution. """ def __init__(self, context: "DataContext"): self._context = context @property ...
Plan
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 88662, "end": 89569 }
class ____(GeneratedAirbyteDestination): @public def __init__(self, name: str, project_id: str, credentials_json: Optional[str] = None): """Airbyte Destination for Firestore. Documentation can be found at https://docs.airbyte.com/integrations/destinations/firestore Args: na...
FirestoreDestination
python
html5lib__html5lib-python
setup.py
{ "start": 668, "end": 4831 }
class ____(dict): def __setitem__(self, key, value): pass def pop(self, i=-1): return self[i] if _markerlib and sys.version_info[0] == 3: env = _markerlib.markers._VARS for key in list(env.keys()): new_key = key.replace('.', '_') if new_key != key: env[new...
Python3MarkerDict
python
jazzband__django-pipeline
tests/tests/test_utils.py
{ "start": 92, "end": 549 }
class ____(TestCase): def test_guess_type(self): self.assertEqual("text/css", guess_type("stylesheet.css")) self.assertEqual("text/coffeescript", guess_type("application.coffee")) self.assertEqual("text/less", guess_type("stylesheet.less")) def test_mimetypes_are_str(self): for ...
UtilTest
python
scikit-learn__scikit-learn
sklearn/base.py
{ "start": 24177, "end": 25834 }
class ____: """Mixin class for all cluster estimators in scikit-learn. - set estimator type to `"clusterer"` through the `estimator_type` tag; - `fit_predict` method returning the cluster labels associated to each sample. Examples -------- >>> import numpy as np >>> from sklearn.base impor...
ClusterMixin
python
kamyu104__LeetCode-Solutions
Python/insertion-sort-list.py
{ "start": 276, "end": 1129 }
class ____(object): # @param head, a ListNode # @return a ListNode def insertionSortList(self, head): if head is None or self.isSorted(head): return head dummy = ListNode(-2147483648) dummy.next = head cur, sorted_tail = head.next, head while cur: ...
Solution
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 15350, "end": 16095 }
class ____(BiffRecord): """ This record specifies the base date for displaying date values. All dates are stored as count of days past this base date. In BIFF2-BIFF4 this record is part of the Calculation Settings Block. In BIFF5-BIFF8 it is stored in the Workbook Globals Substream. ...
DateModeRecord
python
lazyprogrammer__machine_learning_examples
ann_class2/dropout_theano.py
{ "start": 1517, "end": 5111 }
class ____(object): def __init__(self, hidden_layer_sizes, p_keep): self.hidden_layer_sizes = hidden_layer_sizes self.dropout_rates = p_keep def fit(self, X, Y, Xvalid, Yvalid, learning_rate=1e-2, mu=0.9, decay=0.9, epochs=10, batch_sz=100, show_fig=False): X = X.astype(np.float32) ...
ANN
python
plotly__plotly.py
tests/test_core/test_update_objects/test_update_annotations.py
{ "start": 134, "end": 18089 }
class ____(TestCase): def setUp(self): self.fig = make_subplots( rows=2, cols=2, specs=[[{}, {"secondary_y": True}], [{}, {"type": "polar"}]] ) def assert_selected( self, prop, inds, selector=None, row=None, col=None, secondary_y=None ): # ## Test select_* ...
TestSelectForEachUpdateAnnotations
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-apify/llama_index/readers/apify/dataset/base.py
{ "start": 170, "end": 1596 }
class ____(BaseReader): """ Apify Dataset reader. Reads a dataset on the Apify platform. Args: apify_api_token (str): Apify API token. """ def __init__(self, apify_api_token: str) -> None: """Initialize Apify dataset reader.""" from apify_client import ApifyClient ...
ApifyDataset
python
pikepdf__pikepdf
src/pikepdf/form.py
{ "start": 700, "end": 5828 }
class ____: """Utility class to make it easier to work with interactive forms. This is easier to use than the core {class}`pikepdf.AcroForm` implementation, but is higher-level, and abstracts over details in ways which do impose some limitations, such as failing for PDFs which have multiple fields with...
Form
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/components/test_utils/basic_components.py
{ "start": 1249, "end": 1376 }
class ____(BaseModel): nested: dict[str, MyNestedModel] model_config = ConfigDict(extra="forbid")
MyNestedComponentModel
python
keras-team__keras
keras/src/saving/serialization_lib_test.py
{ "start": 1198, "end": 1294 }
class ____(keras.layers.Wrapper): def call(self, x): return self.layer(x)
WrapperLayer
python
doocs__leetcode
solution/2200-2299/2293.Min Max Game/Solution.py
{ "start": 0, "end": 302 }
class ____: def minMaxGame(self, nums: List[int]) -> int: n = len(nums) while n > 1: n >>= 1 for i in range(n): a, b = nums[i << 1], nums[i << 1 | 1] nums[i] = min(a, b) if i % 2 == 0 else max(a, b) return nums[0]
Solution
python
django__django
tests/test_client/views.py
{ "start": 12711, "end": 12868 }
class ____(Exception): def __init__(self, one, two): pass def two_arg_exception(request): raise TwoArgException("one", "two")
TwoArgException
python
RaRe-Technologies__gensim
gensim/test/test_corpora.py
{ "start": 16093, "end": 17011 }
class ____(CorpusTestCase): def setUp(self): self.corpus_class = bleicorpus.BleiCorpus self.file_extension = '.blei' def test_save_format_for_dtm(self): corpus = [[(1, 1.0)], [], [(0, 5.0), (2, 1.0)], []] test_file = get_tmpfile('gensim_corpus.tst') self.corpus_class.sav...
TestBleiCorpus
python
numba__numba
numba/tests/test_serialize.py
{ "start": 7462, "end": 8053 }
class ____(TestCase): def test_numba_unpickle(self): # Test that _numba_unpickle is memorizing its output from numba.core.serialize import _numba_unpickle random_obj = object() bytebuf = pickle.dumps(random_obj) hashed = hash(random_obj) got1 = _numba_unpickle(id(ra...
TestSerializationMisc
python
eventlet__eventlet
eventlet/hubs/__init__.py
{ "start": 5979, "end": 6013 }
class ____(IOError): pass
IOClosed
python
doocs__leetcode
solution/0300-0399/0362.Design Hit Counter/Solution.py
{ "start": 0, "end": 406 }
class ____: def __init__(self): self.ts = [] def hit(self, timestamp: int) -> None: self.ts.append(timestamp) def getHits(self, timestamp: int) -> int: return len(self.ts) - bisect_left(self.ts, timestamp - 300 + 1) # Your HitCounter object will be instantiated and called as suc...
HitCounter
python
realpython__materials
structural-pattern-matching/repl_enhanced.py
{ "start": 366, "end": 1778 }
class ____: indentation_level: int = 0 def __post_init__(self) -> None: readline.parse_and_bind("tab: complete") readline.set_completer(rlcompleter.Completer().complete) if PYTHON_HISTORY.exists(): readline.read_history_file(PYTHON_HISTORY) atexit.register(readline.w...
Console
python
walkccc__LeetCode
solutions/1877. Minimize Maximum Pair Sum in Array/1877.py
{ "start": 0, "end": 161 }
class ____: def minPairSum(self, nums: list[int]) -> int: nums.sort() return max(nums[i] + nums[len(nums) - 1 - i] for i in range(len(nums) // 2))
Solution
python
huggingface__transformers
src/transformers/models/emu3/image_processing_emu3.py
{ "start": 2734, "end": 27211 }
class ____(BaseImageProcessor): r""" Constructs a Emu3 image processor that dynamically resizes images based on the original images. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. resample (`PILImageResampling`...
Emu3ImageProcessor
python
h5py__h5py
h5py/_hl/dataset.py
{ "start": 12011, "end": 15429 }
class ____: """ Class to iterate through list of chunks of a given dataset """ def __init__(self, dset, source_sel=None): self._shape = dset.shape rank = len(dset.shape) if not dset.chunks: # can only use with chunked datasets raise TypeError("Chunked dat...
ChunkIterator
python
rapidsai__cudf
python/cudf/cudf/core/series.py
{ "start": 14290, "end": 123173 }
class ____(SingleColumnFrame, IndexedFrame): """ One-dimensional GPU array (including time series). Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Sta...
Series
python
boto__boto3
tests/integration/test_dynamodb.py
{ "start": 2088, "end": 2460 }
class ____(BaseDynamoDBTest): def test_put_get_item(self): self.table.put_item(Item=self.item_data) self.addCleanup(self.table.delete_item, Key={'MyHashKey': 'mykey'}) response = self.table.get_item( Key={'MyHashKey': 'mykey'}, ConsistentRead=True ) self.assertEqu...
TestDynamoDBTypes
python
etianen__django-reversion
tests/test_app/tests/test_commands.py
{ "start": 5227, "end": 6055 }
class ____(TestModelMixin, TestBase): databases = {"default", "mysql", "postgres"} def testDeleteRevisionsDb(self): with reversion.create_revision(using="postgres"): TestModel.objects.create() self.callCommand("deleterevisions", using="postgres") self.assertNoRevision(using=...
DeleteRevisionsDbTest
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 36014, "end": 36042 }
class ____(DC1): b: 'A'
DC2
python
pallets__quart
src/quart/routing.py
{ "start": 1089, "end": 2752 }
class ____(Map): def bind_to_request( self, request: BaseRequestWebsocket, subdomain: str | None, server_name: str | None, ) -> MapAdapter: host: str if server_name is None: host = request.host.lower() else: host = server_name.lower...
QuartMap
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external.py
{ "start": 42393, "end": 45098 }
class ____: def __init__(self, partition_set_snap: PartitionSetSnap, handle: RepositoryHandle): self._partition_set_snap = check.inst_param( partition_set_snap, "partition_set_snap", PartitionSetSnap ) self._handle = PartitionSetHandle( partition_set_name=partition_se...
RemotePartitionSet
python
huggingface__transformers
src/transformers/models/glpn/image_processing_glpn.py
{ "start": 1518, "end": 1886 }
class ____(ImagesKwargs, total=False): """ size_divisor (`int`, *optional*, defaults to 32): When `do_resize` is `True`, images are resized so their height and width are rounded down to the closest multiple of `size_divisor`. """ size_divisor: int resample: PILImageResampling @req...
GLPNImageProcessorKwargs
python
facebook__pyre-check
scripts/tests/analyze_leaks_test.py
{ "start": 763, "end": 32088 }
class ____(unittest.TestCase): def test_load_pysa_call_graph_input_format(self) -> None: json_call_graph: JSON = { "my_module.my_function": [ "something_that.my_function_calls", "builtins.print", "my_module.my_function", ], ...
AnalyzeIssueTraceTest
python
docker__docker-py
docker/models/images.py
{ "start": 4183, "end": 6472 }
class ____(Model): """ Image metadata stored on the registry, including available platforms. """ def __init__(self, image_name, *args, **kwargs): super().__init__(*args, **kwargs) self.image_name = image_name @property def id(self): """ The ID of the object. ...
RegistryData
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/subscript4.py
{ "start": 233, "end": 924 }
class ____(NamedTuple): first: int second: str recorder_pair: Recorder[tuple[int, str]] = Recorder() pair = IntStrPair(1, "value") result1 = recorder_pair[*pair] reveal_type(result1, expected_text="tuple[int, str]") recorder_order: Recorder[tuple[int, str]] = Recorder() tail_value: str = "tail" result2 = rec...
IntStrPair
python
Farama-Foundation__Gymnasium
tests/envs/registration/utils_envs.py
{ "start": 374, "end": 808 }
class ____(gym.Env): """Environment that does not have human-rendering.""" observation_space = gym.spaces.Box(low=-1, high=1, shape=(1,)) action_space = gym.spaces.Box(low=-1, high=1, shape=(1,)) metadata = {"render_modes": ["rgb_array"], "render_fps": 4} def __init__(self, render_mode: list[str]...
NoHuman
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/hstore.py
{ "start": 645, "end": 7511 }
class ____(sqltypes.Indexable, sqltypes.Concatenable, sqltypes.TypeEngine): """Represent the PostgreSQL HSTORE type. The :class:`.HSTORE` type stores dictionaries containing strings, e.g.:: data_table = Table( "data_table", metadata, Column("id", Integer, primary_ke...
HSTORE
python
pydantic__pydantic
tests/mypy/outputs/mypy-default_ini/plugin_success_baseConfig.py
{ "start": 757, "end": 1098 }
class ____(BaseModel, from_attributes=True): x: float y: str class NotConfig: frozen = True kwargs_model = KwargsModel(x=1, y='y') KwargsModel(x=1, y='y', z='z') # MYPY: error: Unexpected keyword argument "z" for "KwargsModel" [call-arg] kwargs_model.x = 2 kwargs_model.model_validate(kwargs_mode...
KwargsModel
python
agronholm__apscheduler
src/apscheduler/triggers/cron/__init__.py
{ "start": 574, "end": 10181 }
class ____(Trigger): """ Triggers when current time matches all specified time constraints, similarly to how the UNIX cron scheduler works. :param year: 4-digit year :param month: month (1-12) :param day: day of the (1-31) :param week: ISO week (1-53) :param day_of_week: number or name ...
CronTrigger
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 6342, "end": 7211 }
class ____(util.MdCase): """Test highlight line wraps.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'line_spans': '__my_span', 'linenums_style': 'pymdownx-inline' } } def test_linespans(self): ...
TestHighlightLineWrapsPymdownxInline
python
MongoEngine__mongoengine
mongoengine/queryset/manager.py
{ "start": 135, "end": 2222 }
class ____: """ The default QuerySet Manager. Custom QuerySet Manager functions can extend this class and users can add extra queryset functionality. Any custom manager methods must accept a :class:`~mongoengine.Document` class as its first argument, and a :class:`~mongoengine.queryset.QuerySe...
QuerySetManager
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image08.py
{ "start": 315, "end": 1115 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image08.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_c...
TestCompareXLSXFiles
python
doocs__leetcode
solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/Solution.py
{ "start": 0, "end": 636 }
class ____: def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int: k += 1 n = len(nums) g = [[0] * n for _ in range(n)] for i in range(n): s = mx = 0 for j in range(i, n): s += nums[j] mx = max(mx, nums[j]) ...
Solution
python
tiangolo__fastapi
tests/test_dependency_duplicates.py
{ "start": 212, "end": 8577 }
class ____(BaseModel): data: str def duplicate_dependency(item: Item): return item def dependency(item2: Item): return item2 def sub_duplicate_dependency( item: Item, sub_item: Item = Depends(duplicate_dependency) ): return [item, sub_item] @app.post("/with-duplicates") async def with_duplic...
Item
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 31230, "end": 33393 }
class ____(nn.Module): """ A class to patchify the time series sequence into different patches Returns: `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)` """ def __init__(self, config: PatchTSMixerConfig): super().__init__() self.sequence_leng...
PatchTSMixerPatchify
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/yamllint.py
{ "start": 597, "end": 3424 }
class ____(SanitySingleVersion): """Sanity test using yamllint.""" @property def error_code(self) -> t.Optional[str]: """Error code for ansible-test matching the format used by the underlying test program, or None if the program does not use error codes.""" return 'ansible-test' @prope...
YamllintTest
python
celery__celery
t/unit/worker/test_components.py
{ "start": 520, "end": 1291 }
class ____: def setup_method(self): self.w = Mock(name='w') self.hub = Hub(self.w) self.w.hub = Mock(name='w.hub') @patch('celery.worker.components.set_event_loop') @patch('celery.worker.components.get_event_loop') def test_create(self, get_event_loop, set_event_loop): ...
test_Hub
python
doocs__leetcode
solution/0700-0799/0746.Min Cost Climbing Stairs/Solution2.py
{ "start": 0, "end": 250 }
class ____: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) f = [0] * (n + 1) for i in range(2, n + 1): f[i] = min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]) return f[n]
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 433598, "end": 437378 }
class ____(VegaLiteSchema): """ GenericUnitSpecEncodingAnyMark schema wrapper. Base interface for a unit (single-view) specification. Parameters ---------- mark : dict, :class:`Mark`, :class:`AnyMark`, :class:`BoxPlot`, :class:`MarkDef`, :class:`ErrorBar`, :class:`ErrorBand`, :class:`BoxPlotDe...
GenericUnitSpecEncodingAnyMark
python
pytorch__pytorch
test/distributed/_composable/test_checkpoint.py
{ "start": 1390, "end": 1702 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.l1 = nn.Linear(100, 100) self.seq = nn.Sequential( nn.ReLU(), nn.Linear(100, 100), nn.ReLU(), ) def forward(self, x): return self.seq(self.l1(x))
ToyModel
python
simonw__datasette
datasette/utils/asgi.py
{ "start": 1209, "end": 1301 }
class ____(Base400): status = 400 SAMESITE_VALUES = ("strict", "lax", "none")
BadRequest
python
EpistasisLab__tpot
tpot/search_spaces/pipelines/union.py
{ "start": 1725, "end": 3854 }
class ____(SklearnIndividual): """ Takes in a list of search spaces. each space is a list of SearchSpaces. Will produce a FeatureUnion pipeline. Each step in the pipeline will correspond to the the search space provided in the same index. The resulting pipeline will be a FeatureUnion of the steps in the...
UnionPipelineIndividual
python
apache__airflow
task-sdk/tests/task_sdk/bases/test_sensor.py
{ "start": 25150, "end": 26530 }
class ____: def test_poke_mode_only_allows_poke_mode(self): try: sensor = DummyPokeOnlySensor(task_id="foo", mode="poke", poke_changes_mode=False) except ValueError: self.fail("__init__ failed with mode='poke'.") try: sensor.poke({}) except ValueEr...
TestPokeModeOnly
python
django__django
tests/admin_views/admin.py
{ "start": 37615, "end": 37984 }
class ____(admin.ModelAdmin): list_display = ( "content", "date", callable_year, "model_year", "modeladmin_year", "model_year_reversed", "section", ) sortable_by = ("date", callable_year) @admin.display(ordering="date") def modeladmin_year(sel...
ArticleAdmin6
python
streamlit__streamlit
lib/tests/streamlit/web/server/server_test.py
{ "start": 22969, "end": 24384 }
class ____(tornado.testing.AsyncHTTPTestCase): async def does_script_run_without_error(self): return True, "test_message" def setUp(self): self._old_config = config.get_option("server.scriptHealthCheckEnabled") config._set_option("server.scriptHealthCheckEnabled", True, "test") ...
ScriptCheckEndpointExistsTest
python
pandas-dev__pandas
pandas/tseries/holiday.py
{ "start": 13437, "end": 13659 }
class ____(type): def __new__(cls, clsname: str, bases, attrs): calendar_class = super().__new__(cls, clsname, bases, attrs) register(calendar_class) return calendar_class
HolidayCalendarMetaClass
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 30158, "end": 30464 }
class ____( SuperMixin, OfflineTestCaseMixin, TestCase ): """ Test that templates extending templates using relative paths (e.g. ./base.html) are evaluated correctly """ templates_dir = "test_extends_relative" expected_hash = "817b5defb197"
OfflineCompressExtendsRelativeTestCase
python
pyca__cryptography
tests/hazmat/asn1/test_serialization.py
{ "start": 4601, "end": 6554 }
class ____: def test_fail_generalized_time_precision(self) -> None: with pytest.raises( ValueError, match="decoded GeneralizedTime data has higher precision than " "supported", ): asn1.decode_der( asn1.GeneralizedTime, b"\x18\x171999010...
TestGeneralizedTime
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 101486, "end": 102336 }
class ____(nn.Module): def __init__( self, dense_dim, dense_out, embedding_dim, top_out_in, top_out_out ) -> None: super().__init__() self.dense_mlp = nn.Sequential( nn.Linear(dense_dim, dense_out), ) self.top_mlp = nn.Sequential( nn.Linear(dense_...
DenseTopMLP
python
numba__numba
numba/tests/test_parfors.py
{ "start": 90140, "end": 91868 }
class ____(TestParforsBase): def test_parfor_options(self): def test_impl(a): n = a.shape[0] b = np.ones(n) c = np.array([ i for i in range(n) ]) b[:n] = a + b * c for i in prange(n): c[i] = b[i] * a[i] return reduce(la...
TestParforsOptions
python
Textualize__textual
src/textual/events.py
{ "start": 17158, "end": 19221 }
class ____(MouseEvent, bubble=True): """Sent when a widget is clicked. - [X] Bubbles - [ ] Verbose Args: chain: The number of clicks in the chain. 2 is a double click, 3 is a triple click, etc. """ def __init__( self, widget: Widget | None, x: int, y: i...
Click
python
google__pytype
pytype/ast/visitor_test.py
{ "start": 1840, "end": 3760 }
class ____(unittest.TestCase): """Tests for visitor.BaseVisitor.""" def test_visit_order(self): module = ast.parse(textwrap.dedent(""" def f(): def g(): def h(): pass """)) v = _VisitOrderVisitor(ast) v.visit(module) self.assertEqual(v.funcs, ["h", "g", "f"])...
BaseVisitorTest
python
apache__airflow
providers/google/tests/unit/google/firebase/hooks/test_firestore.py
{ "start": 10184, "end": 11220 }
class ____: hook: CloudFirestoreHook | None = None def setup_method(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_no_default_project_id, ): self.hook = CloudFirestoreHook(gcp_conn_i...
TestCloudFirestoreHookWithoutProjectId
python
huggingface__transformers
src/transformers/models/smolvlm/modeling_smolvlm.py
{ "start": 9762, "end": 10925 }
class ____(GradientCheckpointingLayer): def __init__(self, config: SmolVLMVisionConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = SmolVLMVisionAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp ...
SmolVLMEncoderLayer
python
doocs__leetcode
solution/1000-1099/1004.Max Consecutive Ones III/Solution.py
{ "start": 0, "end": 254 }
class ____: def longestOnes(self, nums: List[int], k: int) -> int: l = cnt = 0 for x in nums: cnt += x ^ 1 if cnt > k: cnt -= nums[l] ^ 1 l += 1 return len(nums) - l
Solution
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 4887, "end": 5353 }
class ____: """Test pl_PL bank provider""" def test_bban(self, faker, num_samples): for _ in range(num_samples): assert re.fullmatch(r"\d{24}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() assert...
TestPlPl
python
sympy__sympy
sympy/physics/quantum/cartesian.py
{ "start": 7710, "end": 9092 }
class ____(Bra): """1D cartesian momentum eigenbra.""" @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxKet @property def momentum(self): """The momentum of the state.""" return self.label[0] #----------------...
PxBra
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-non-overlapping-substrings.py
{ "start": 29, "end": 1207 }
class ____(object): def maxNumOfSubstrings(self, s): """ :type s: str :rtype: List[str] """ def find_right_from_left(s, first, last, left): right, i = last[ord(s[left])-ord('a')], left while i <= right: if first[ord(s[i])-ord('a')] < le...
Solution
python
openai__openai-python
src/openai/types/beta/chatkit/thread_list_items_params.py
{ "start": 211, "end": 697 }
class ____(TypedDict, total=False): after: str """List items created after this thread item ID. Defaults to null for the first page. """ before: str """List items created before this thread item ID. Defaults to null for the newest results. """ limit: int """Maximum number of ...
ThreadListItemsParams
python
astropy__astropy
astropy/modeling/fitting.py
{ "start": 70571, "end": 73385 }
class ____(Fitter): """ Simplex algorithm and least squares statistic. Raises ------ `ModelLinearityError` A linear model is passed to a nonlinear fitter """ supported_constraints = Simplex.supported_constraints def __init__(self): super().__init__(optimizer=Simplex, ...
SimplexLSQFitter
python
pytorch__pytorch
torch/_dynamo/decorators.py
{ "start": 20335, "end": 33381 }
class ____: """ This represents an dimension of a tensor and the corresponding min and max values it can take. Don't create this class directly; instead, use :func:`mark_dynamic`. """ dim: int min: int max: int @forbid_in_graph def mark_unbacked( t: Any, index: Union[int, lis...
_DimRange
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec22.py
{ "start": 599, "end": 848 }
class ____(Generic[P, R]): def __init__(self, func: Callable[Concatenate[int, P], R]): self.func = func def create_partial(self, first: int) -> Callable[P, R]: return MyPartial[P, R](first=first, func=self.func)
MyPartialCreator
python
gevent__gevent
src/gevent/_ffi/watcher.py
{ "start": 6213, "end": 14873 }
class ____(metaclass=AbstractWatcherType): _callback = None _args = None _watcher = None # self._handle has a reference to self, keeping it alive. # We must keep self._handle alive for ffi.from_handle() to be # able to work. We only fill this in when we are started, # and when we are stoppe...
watcher
python
pyca__cryptography
src/cryptography/hazmat/bindings/openssl/binding.py
{ "start": 1763, "end": 4084 }
class ____: """ OpenSSL API wrapper. """ lib: typing.ClassVar[typing.Any] = None ffi = _openssl.ffi _lib_loaded = False _init_lock = threading.Lock() def __init__(self) -> None: self._ensure_ffi_initialized() @classmethod def _ensure_ffi_initialized(cls) -> None: ...
Binding
python
imageio__imageio
imageio/plugins/_tifffile.py
{ "start": 172095, "end": 176347 }
class ____(object): """Series of TIFF pages with compatible shape and data type. Attributes ---------- pages : list of TiffPage Sequence of TiffPages in series. dtype : numpy.dtype Data type (native byte order) of the image array in series. shape : tuple Dimensions of th...
TiffPageSeries
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/reduction_ops_test.py
{ "start": 18107, "end": 22661 }
class ____(BaseReductionTest): def _tf_reduce(self, x, reduction_axes, keepdims): return math_ops.reduce_mean(x, reduction_axes, keepdims) def _np_reduce(self, x, reduction_axes, keepdims): if isinstance(reduction_axes, list) or isinstance(reduction_axes, ...
MeanReductionTest
python
sqlalchemy__sqlalchemy
examples/extending_query/temporal_range.py
{ "start": 539, "end": 3754 }
class ____: """Mixin that identifies a class as having a timestamp column""" timestamp = Column( DateTime, default=partial(datetime.datetime.now, datetime.timezone.utc), nullable=False, ) def temporal_range(range_lower, range_upper): return orm.with_loader_criteria( Ha...
HasTemporal
python
redis__redis-py
tests/test_maint_notifications.py
{ "start": 2713, "end": 9353 }
class ____: """Test the NodeMovingNotification class.""" def test_init(self): """Test NodeMovingNotification initialization.""" with patch("time.monotonic", return_value=1000): notification = NodeMovingNotification( id=1, new_node_host="localhost", new_node_port=6379...
TestNodeMovingNotification
python
spack__spack
lib/spack/spack/test/oci/mock_registry.py
{ "start": 689, "end": 2028 }
class ____: """This class is a small router for requests to the OCI registry. It is used to dispatch requests to a handler, and middleware can be used to transform requests, as well as return responses early (e.g. for authentication).""" def __init__(self) -> None: self.routes: List[Tuple[...
Router
python
numba__numba
numba/tests/test_linalg.py
{ "start": 21365, "end": 25484 }
class ____(TestCase): """ The sample matrix code TestLinalgBase.specific_sample_matrix() is a bit involved, this class tests it works as intended. """ def test_specific_sample_matrix(self): # add a default test to the ctor, it never runs so doesn't matter inst = TestLinalgBase('spe...
TestTestLinalgBase
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 34445, "end": 35122 }
class ____(ModelOutput): r""" loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`): MSE loss. prediction_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction outputs of the time series modeling heads. "...
PatchTSTForPretrainingOutput
python
google__pytype
pytype/pyc/opcodes_test.py
{ "start": 4565, "end": 5929 }
class ____(unittest.TestCase): """Tests for opcodes._get_exception_bitmask.""" def assertBitmask(self, *, offset_to_op, exc_ranges, expected_bitmask): bitmask = bin(opcodes._get_exception_bitmask(offset_to_op, exc_ranges)) self.assertEqual(bitmask, expected_bitmask) def test_one_exception_range(self): ...
ExceptionBitmaskTest
python
django-mptt__django-mptt
tests/myapp/models.py
{ "start": 3562, "end": 3711 }
class ____(MPTTModel): parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", on_delete=models.CASCADE )
Tree
python
sphinx-doc__sphinx
sphinx/transforms/__init__.py
{ "start": 14462, "end": 15164 }
class ____(SphinxTransform): """Sort glossaries that have the ``sorted`` flag.""" # This must be done after i18n, therefore not right # away in the glossary directive. default_priority = 500 def apply(self, **kwargs: Any) -> None: for glossary in self.document.findall(addnodes.glossary): ...
GlossarySorter
python
pypa__pipenv
pipenv/patched/pip/_vendor/rich/spinner.py
{ "start": 309, "end": 4364 }
class ____: """A spinner animation. Args: name (str): Name of spinner (run python -m rich.spinner). text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". style (StyleType, optional): Style for spinner animation. Def...
Spinner