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
pandas-dev__pandas
pandas/core/methods/selectn.py
{ "start": 1913, "end": 5069 }
class ____(SelectN[Series]): """ Implement n largest/smallest for Series Parameters ---------- obj : Series n : int keep : {'first', 'last'}, default 'first' Returns ------- nordered : Series """ def compute(self, method: str) -> Series: from pandas.core.reshap...
SelectNSeries
python
plotly__plotly.py
plotly/graph_objs/scatter3d/_error_y.py
{ "start": 233, "end": 14881 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatter3d" _path_str = "scatter3d.error_y" _valid_props = { "array", "arrayminus", "arrayminussrc", "arraysrc", "color", "copy_zstyle", "symmetric", "thickness", "traceref", ...
ErrorY
python
doocs__leetcode
solution/2400-2499/2478.Number of Beautiful Partitions/Solution.py
{ "start": 0, "end": 687 }
class ____: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: primes = '2357' if s[0] not in primes or s[-1] in primes: return 0 mod = 10**9 + 7 n = len(s) f = [[0] * (k + 1) for _ in range(n + 1)] g = [[0] * (k + 1) for _ in range(n + ...
Solution
python
openai__openai-python
tests/api_resources/beta/threads/runs/test_steps.py
{ "start": 6465, "end": 12850 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): ...
TestAsyncSteps
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 133306, "end": 136172 }
class ____: def test_removed_as_collaborator_email( self, db_request, pyramid_config, monkeypatch ): removed_user = UserFactory.create() EmailFactory.create(primary=True, verified=True, public=True, user=removed_user) submitter_user = UserFactory.create() EmailFactory.cre...
TestRemovedAsCollaboratorEmail
python
python-pillow__Pillow
Tests/test_image_access.py
{ "start": 3199, "end": 6667 }
class ____: @staticmethod def color(mode: str) -> int | tuple[int, ...]: bands = Image.getmodebands(mode) if bands == 1: return 1 return tuple(range(1, bands + 1)) def check(self, mode: str, expected_color_int: int | None = None) -> None: expected_color = ( ...
TestImageGetPixel
python
Farama-Foundation__Gymnasium
gymnasium/envs/toy_text/taxi.py
{ "start": 445, "end": 25178 }
class ____(Env): """ The Taxi Problem involves navigating to passengers in a grid world, picking them up and dropping them off at one of four locations. ## Description There are four designated pick-up and drop-off locations (Red, Green, Yellow and Blue) in the 5x5 grid world. The taxi starts o...
TaxiEnv
python
spack__spack
lib/spack/spack/test/cmd/repo.py
{ "start": 4167, "end": 4367 }
class ____(Package): pass """ NEW_7ZIP = b"""\ # some comment from spack_repo.builtin.build_systems.generic import Package from spack.package import * from ..blt.package import linker_helpers
_7zip
python
falconry__falcon
falcon/util/mediatypes.py
{ "start": 3873, "end": 4306 }
class ____: main_type: str subtype: str params: dict # NOTE(vytas): Using __slots__ with dataclasses is tricky, but it seems to # work here since we are not using any default values in the definition. __slots__ = ('main_type', 'subtype', 'params') @classmethod def parse(cls, media_ty...
_MediaType
python
langchain-ai__langchain
libs/core/langchain_core/prompts/chat.py
{ "start": 11259, "end": 11338 }
class ____(TypedDict, total=False): image_url: str | dict
_ImageTemplateParam
python
dagster-io__dagster
python_modules/automation/automation/dagster_docs/watcher.py
{ "start": 10158, "end": 11492 }
class ____: """Watches a file for changes and triggers docstring validation.""" def __init__( self, target_file: Path, validation_callback: Callable[[], None], verbose: bool = False ) -> None: """Initialize the file watcher. Args: target_file: The file to watch for chan...
DocstringFileWatcher
python
huggingface__transformers
src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py
{ "start": 14352, "end": 15006 }
class ____(torch.autograd.Function): """Computes a square root with a gradient clipped at `_MAX_SQRT_GRADIENT`.""" @staticmethod def forward(ctx, x: torch.Tensor) -> torch.Tensor: """The forward pass, which is a normal `sqrt`.""" ctx.save_for_backward(x) return torch.sqrt(x) @s...
SqrtBoundDerivative
python
realpython__materials
python-property/circle_v5.py
{ "start": 25, "end": 479 }
class ____: def __init__(self, radius): self.radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): self._diameter = None self._radius = value @property def diameter(self): if self._diameter is None: ...
Circle
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/list_files_test.py
{ "start": 1414, "end": 9115 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def setUp(self): super(ListFilesTest, self).setUp() self.tmp_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmp_dir, ignore_errors=True) super(ListFilesTest, self).tearDown() def _touchTempFiles(self, filenames): ...
ListFilesTest
python
coleifer__peewee
peewee.py
{ "start": 275561, "end": 282044 }
class ____(collections.namedtuple('_PrefetchQuery', ( 'query', 'fields', 'is_backref', 'rel_models', 'field_to_name', 'model'))): def __new__(cls, query, fields=None, is_backref=None, rel_models=None, field_to_name=None, model=None): if fields: if is_backref: ...
PrefetchQuery
python
huggingface__transformers
tests/pipelines/test_pipelines_video_classification.py
{ "start": 1149, "end": 4550 }
class ____(unittest.TestCase): model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING example_video_filepath = None @classmethod def _load_dataset(cls): # Lazy loading of the dataset. Because it is a class method, it will only be loaded once per pytest process. if cls.example_video_file...
VideoClassificationPipelineTests
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/visitors.py
{ "start": 14288, "end": 14415 }
class ____(Protocol): def __call__(s, self: object, visitor: HasTraversalDispatch) -> Any: ...
_InternalTraversalDispatchType
python
python__mypy
mypyc/irbuild/targets.py
{ "start": 279, "end": 657 }
class ____(AssignmentTarget): """Register as an assignment target. This is used for local variables and some temporaries. """ def __init__(self, register: Register) -> None: self.register = register self.type = register.type def __repr__(self) -> str: return f"AssignmentTa...
AssignmentTargetRegister
python
python-pillow__Pillow
src/PIL/PdfParser.py
{ "start": 1617, "end": 1909 }
class ____(RuntimeError): """An error that probably indicates a syntactic or semantic error in the PDF file structure""" pass def check_format_condition(condition: bool, error_message: str) -> None: if not condition: raise PdfFormatError(error_message)
PdfFormatError
python
huggingface__transformers
src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
{ "start": 13566, "end": 15535 }
class ____(nn.Module): def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None: super().__init__() self.fc1 = nn.Linear(dim, hidden_dim) self.act = ACT2FN[hidden_act] self.fc2 = nn.Linear(hidden_dim, dim) def forward(self, x) -> torch.Tensor: return self.f...
VisionMlp
python
django__django
tests/serializers/models/data.py
{ "start": 1331, "end": 1404 }
class ____(models.Model): data = models.FloatField(null=True)
FloatData
python
ipython__ipython
IPython/extensions/tests/test_deduperreload.py
{ "start": 18252, "end": 19215 }
class ____: def __init__(self): self.ns = {} self.user_ns = self.ns self.user_ns_hidden = {} self.auto_magics = AutoreloadMagics(shell=self) @staticmethod def pre_run_cell(obj): try_with_arg = False try: obj.pre_run_cell() except TypeError...
FakeShell
python
dask__dask
dask/dataframe/dask_expr/_quantiles.py
{ "start": 386, "end": 2546 }
class ____(Expr): _parameters = ["frame", "input_npartitions", "upsample", "random_state"] _defaults = {"upsample": 1.0, "random_state": None} @functools.cached_property def _meta(self): return self.frame._meta @property def npartitions(self): return 1 def _divisions(self)...
RepartitionQuantiles
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 178423, "end": 178742 }
class ____: def test_subclass_op(self): class simple(np.ndarray): def __new__(subtype, shape): self = np.ndarray.__new__(subtype, shape, dtype=object) self.fill(0) return self a = simple((3, 4)) assert_equal(a + a, a)
TestSubclass
python
astropy__astropy
astropy/time/formats.py
{ "start": 35085, "end": 36804 }
class ____(TimeFromEpoch): """ Input for a `~matplotlib.axes.Axes` object with ax.xaxis.axis_date(): 1 + number of days from 0001-01-01 00:00:00 UTC. This can be used as follow:: >>> import matplotlib.pyplot as plt >>> jyear = np.linspace(2000, 2001, 20) >>> t = Time(jyear, format='j...
TimePlotDate
python
pandas-dev__pandas
pandas/tests/arrays/test_datetimelike.py
{ "start": 20354, "end": 31421 }
class ____(SharedTests): index_cls = DatetimeIndex array_cls = DatetimeArray scalar_type = Timestamp example_dtype = "M8[ns]" @pytest.fixture def arr1d(self, tz_naive_fixture, freqstr): """ Fixture returning DatetimeArray with parametrized frequency and timezones ...
TestDatetimeArray
python
donnemartin__system-design-primer
solutions/object_oriented_design/parking_lot/parking_lot.py
{ "start": 141, "end": 654 }
class ____(metaclass=ABCMeta): def __init__(self, vehicle_size, license_plate, spot_size): self.vehicle_size = vehicle_size self.license_plate = license_plate self.spot_size self.spots_taken = [] def clear_spots(self): for spot in self.spots_taken: spot.remo...
Vehicle
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/numpy_to_torch.py
{ "start": 847, "end": 2342 }
class ____(ArrayConversion): """Wraps a NumPy-based environment such that it can be interacted with PyTorch Tensors. Actions must be provided as PyTorch Tensors and observations will be returned as PyTorch Tensors. A vector version of the wrapper exists, :class:`gymnasium.wrappers.vector.NumpyToTorch`. ...
NumpyToTorch
python
walkccc__LeetCode
solutions/3196. Maximize Total Cost of Alternating Subarrays/3196.py
{ "start": 0, "end": 387 }
class ____: def maximumTotalCost(self, nums: list[int]) -> int: keep = nums[0] # the maximum cost if the last number is kept flip = nums[0] # the maximum cost if the last number is flipped for i in range(1, len(nums)): keepCurr = max(keep, flip) + nums[i] flipCurr = keep - nums[i] kee...
Solution
python
python__mypy
mypyc/irbuild/prepare.py
{ "start": 26978, "end": 30611 }
class ____(TraverserVisitor): current_path: str def __init__(self, errors: Errors) -> None: super().__init__() # Map of main singledispatch function to list of registered implementations self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list) ...
SingledispatchVisitor
python
euske__pdfminer
pdfminer/layout.py
{ "start": 21450, "end": 21826 }
class ____(LTLayoutContainer): def __init__(self, pageid, bbox, rotate=0): LTLayoutContainer.__init__(self, bbox) self.pageid = pageid self.rotate = rotate return def __repr__(self): return ('<%s(%r) %s rotate=%r>' % (self.__class__.__name__, self.pageid...
LTPage
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_clear_thinking_20251015_edit_response.py
{ "start": 214, "end": 543 }
class ____(BaseModel): cleared_input_tokens: int """Number of input tokens cleared by this edit.""" cleared_thinking_turns: int """Number of thinking turns that were cleared.""" type: Literal["clear_thinking_20251015"] """The type of context management edit applied."""
BetaClearThinking20251015EditResponse
python
gevent__gevent
src/gevent/threadpool.py
{ "start": 1378, "end": 9189 }
class ____(RawGreenlet): # Exists to produce a more useful repr for worker pool # threads/greenlets, and manage the communication of the worker # thread with the threadpool. # Inform the gevent.util.GreenletTree that this should be # considered the root (for printing purposes) greenlet_tree_is_...
_WorkerGreenlet
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/profiling.py
{ "start": 1171, "end": 10237 }
class ____: """Store per-platform/fn profiling results in a file. There was no json module available when this was written, but now the file format which is very deterministically line oriented is kind of handy in any case for diffs and merges. """ def __init__(self, filename, sort="cumulativ...
ProfileStatsFile
python
plotly__plotly.py
_plotly_utils/png.py
{ "start": 10716, "end": 10758 }
class ____(FormatError): pass
ChunkError
python
getsentry__sentry
src/sentry/api/paginator.py
{ "start": 28535, "end": 28629 }
class ____(Protocol): def __call__(self, limit: int, offset: int) -> list[Any]: ...
Callback
python
readthedocs__readthedocs.org
readthedocs/organizations/views/private.py
{ "start": 7436, "end": 7634 }
class ____( PrivateViewMixin, OrganizationTeamMemberView, DeleteViewWithMessage ): success_message = _("Member removed from team") http_method_names = ["post"]
DeleteOrganizationTeamMember
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py
{ "start": 426, "end": 523 }
class ____(DbtCloudException): """Raised when a triggered job run fails"""
DbtCloudJobRunFailed
python
bokeh__bokeh
tests/unit/bokeh/server/test_auth_provider.py
{ "start": 1592, "end": 2508 }
class ____: def test_endpoints(self, null_auth: bsa.NullAuth) -> None: assert null_auth.endpoints == [] def test_get_user(self, null_auth: bsa.NullAuth) -> None: assert null_auth.get_user is None async def test_get_user_async(self, null_auth: bsa.NullAuth) -> None: assert null_auth...
TestNullAuth
python
mlflow__mlflow
mlflow/models/auth_policy.py
{ "start": 1351, "end": 2305 }
class ____: """ Specifies the authentication policy for the model, which includes two key components. System Auth Policy: A list of resources required to serve this model User Auth Policy: A minimal list of scopes that the user should have access to, in order to inv...
AuthPolicy
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/streams.py
{ "start": 6310, "end": 6855 }
class ____(MixpanelStream, ABC): def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, any]: updated_state = latest_record.get(self.cursor_field) if updated_state: state_value = current_stream_state.get(self.cursor_f...
IncrementalMixpanelStream
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_logging_sink.py
{ "start": 1963, "end": 5903 }
class ____(GoogleCloudBaseOperator): """ Creates a Cloud Logging export sink in a GCP project. This operator creates a sink that exports log entries from Cloud Logging to destinations like Cloud Storage, BigQuery, or Pub/Sub. :param project_id: Required. ID of the Google Cloud project where the si...
CloudLoggingCreateSinkOperator
python
fastapi__sqlmodel
docs_src/tutorial/select/tutorial003.py
{ "start": 100, "end": 1141 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): ...
Hero
python
django__django
tests/urlpatterns/tests.py
{ "start": 10932, "end": 13565 }
class ____(SimpleTestCase): def test_matching_urls(self): def no_converter(x): return x test_data = ( ("int", {"0", "1", "01", 1234567890}, int), ("str", {"abcxyz"}, no_converter), ("path", {"allows.ANY*characters"}, no_converter), ("slug"...
ConverterTests
python
doocs__leetcode
solution/1900-1999/1908.Game of Nim/Solution.py
{ "start": 0, "end": 413 }
class ____: def nimGame(self, piles: List[int]) -> bool: @cache def dfs(st): lst = list(st) for i, x in enumerate(lst): for j in range(1, x + 1): lst[i] -= j if not dfs(tuple(lst)): return True ...
Solution
python
urllib3__urllib3
test/with_dummyserver/test_socketlevel.py
{ "start": 87740, "end": 89810 }
class ____(SocketDummyServerTestCase): def test_multipart_assert_header_parsing_no_defects(self) -> None: quit_event = threading.Event() def socket_handler(listener: socket.socket) -> None: for _ in range(2): listener.settimeout(LONG_TIMEOUT) while True:...
TestMultipartResponse
python
getsentry__sentry
src/sentry/seer/endpoints/seer_rpc.py
{ "start": 4823, "end": 4901 }
class ____(TypedDict): name: str type: str descending: bool
SortDict
python
wntrblm__nox
nox/logger.py
{ "start": 1275, "end": 1700 }
class ____(logging.Formatter): def __init__(self, *, add_timestamp: bool = False) -> None: super().__init__(fmt=_get_format(colorlog=False, add_timestamp=add_timestamp)) self._simple_fmt = logging.Formatter("%(message)s") def format(self, record: Any) -> str: if record.levelname == "OUT...
NoxFormatter
python
neetcode-gh__leetcode
python/0525-contiguous-array.py
{ "start": 0, "end": 549 }
class ____: def findMaxLength(self, nums: List[int]) -> int: zero, one = 0, 0 res = 0 diff_index = {} for i, n in enumerate(nums): if n == 0: zero += 1 else: one += 1 if one - zero not in diff_index: ...
Solution
python
numpy__numpy
numpy/_core/tests/test_arraymethod.py
{ "start": 2565, "end": 3223 }
class ____: def test_class_getitem(self, cls: type[np.ndarray]) -> None: """Test `ndarray.__class_getitem__`.""" alias = cls[Any, Any] assert isinstance(alias, types.GenericAlias) assert alias.__origin__ is cls @pytest.mark.parametrize("arg_len", range(4)) def test_subscript...
TestClassGetItem
python
miyuchina__mistletoe
mistletoe/markdown_renderer.py
{ "start": 223, "end": 633 }
class ____(block_token.BlockToken): """ Blank line token. Represents a single blank line. This is a leaf block token without children. """ pattern = re.compile(r"\s*\n$") def __init__(self, _): self.children = [] @classmethod def start(cls, line): return cls.pattern.ma...
BlankLine
python
kubernetes-client__python
kubernetes/client/models/v2_pods_metric_source.py
{ "start": 383, "end": 4387 }
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...
V2PodsMetricSource
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1462412, "end": 1463473 }
class ____(sgqlc.types.Type, Node): """An invitation for a user to be added to a repository.""" __schema__ = github_schema __field_names__ = ("email", "invitee", "inviter", "permalink", "permission", "repository") email = sgqlc.types.Field(String, graphql_name="email") """The email address that rec...
RepositoryInvitation
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 212694, "end": 215479 }
class ____(Request): """ Move datasets to a project :param ids: Datasets to move :type ids: Sequence[str] :param project: Target project ID. If not provided, `project_name` must be provided. Use null for the root project :type project: str :param project_name: Target project name. I...
MoveRequest
python
celery__celery
celery/apps/beat.py
{ "start": 929, "end": 5724 }
class ____: """Beat as a service.""" Service = beat.Service app: Celery = None def __init__(self, max_interval: int | None = None, app: Celery | None = None, socket_timeout: int = 30, pidfile: str | None = None, no_color: bool | None = None, loglevel: str = 'WARN', lo...
Beat
python
kamyu104__LeetCode-Solutions
Python/kth-ancestor-of-a-tree-node.py
{ "start": 257, "end": 1225 }
class ____(object): def __init__(self, n, parent): """ :type n: int :type parent: List[int] """ par = [[p] if p != -1 else [] for p in parent] q = [par[i] for i, p in enumerate(parent) if p != -1] i = 0 while q: new_q = [] for ...
TreeAncestor
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 47464, "end": 48379 }
class ____(themeable): """ x-axis major-tick length Parameters ---------- theme_element : float | complex Value in points. A negative value creates the ticks inside the plot panel. A complex value (e.g. `3j`) creates ticks that span both in and out of the panel. """ ...
axis_ticks_length_major_x
python
great-expectations__great_expectations
great_expectations/expectations/metrics/util.py
{ "start": 11799, "end": 67444 }
class ____(UserDict): """Normal dict except it returns a case-insensitive string for any `name` key values.""" def __init__(self, data: dict[str, Any]): self.data = data @override def __getitem__(self, key: Any) -> Any: item = self.data[key] if key == "name": logger...
CaseInsensitiveNameDict
python
PrefectHQ__prefect
src/integrations/prefect-docker/prefect_docker/deployments/steps.py
{ "start": 2066, "end": 14631 }
class ____(TypedDict): """ The result of a `push_docker_image` step. Attributes: image_name: The name of the pushed image. tag: The tag of the pushed image. image: The name and tag of the pushed image. additional_tags: The additional tags on the image, in addition to `tag`. ...
PushDockerImageResult
python
explosion__spaCy
spacy/lang/ru/lemmatizer.py
{ "start": 294, "end": 7973 }
class ____(Lemmatizer): def __init__( self, vocab: Vocab, model: Optional[Model], name: str = "lemmatizer", *, mode: str = "pymorphy3", overwrite: bool = False, scorer: Optional[Callable] = lemmatizer_score, ) -> None: if mode in {"pymorphy...
RussianLemmatizer
python
langchain-ai__langchain
libs/core/langchain_core/messages/modifier.py
{ "start": 144, "end": 875 }
class ____(BaseMessage): """Message responsible for deleting other messages.""" type: Literal["remove"] = "remove" """The type of the message (used for serialization).""" def __init__( self, id: str, **kwargs: Any, ) -> None: """Create a RemoveMessage. Args...
RemoveMessage
python
django__django
tests/template_tests/syntax_tests/test_url.py
{ "start": 11932, "end": 12560 }
class ____(SimpleTestCase): def test_repr(self): url_node = URLNode(view_name="named-view", args=[], kwargs={}, asvar=None) self.assertEqual( repr(url_node), "<URLNode view_name='named-view' args=[] kwargs={} as=None>", ) url_node = URLNode( view_n...
URLNodeTest
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 64950, "end": 97485 }
class ____(object): # MonsterT def __init__( self, pos = None, mana = 150, hp = 100, name = None, inventory = None, color = 8, testType = 0, test = None, test4 = None, testarrayofstring = None, testarrayoftables = N...
MonsterT
python
pytorch__pytorch
torch/backends/_nnapi/serializer.py
{ "start": 2987, "end": 3626 }
class ____(enum.Enum): QUINT8 = 13 def approx_equal(lhs, rhs, tolerance=1e-6): return abs(lhs - rhs) <= tolerance * min(lhs, rhs) def tensor_size(op_type, dims): ITEM_SIZES = { NNAPI_OperandCode.TENSOR_FLOAT32: 4, NNAPI_OperandCode.TENSOR_INT32: 4, NNAPI_OperandCode.TENSOR_QUANT8...
TorchScalarTypes
python
bokeh__bokeh
src/bokeh/models/widgets/pickers.py
{ "start": 9868, "end": 10230 }
class ____(BaseDatetimePicker): """ Calendar-based date and time picker widget. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) value = Nullable(Datetime, default=None, help=""" The initial or ...
DatetimePicker
python
huggingface__transformers
tests/models/shieldgemma2/test_processing_shieldgemma2.py
{ "start": 2758, "end": 9769 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = ShieldGemma2Processor @classmethod def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class.from_pretrained("google/siglip-so400m-pa...
ShieldGemma2ProcessorTest
python
pytorch__pytorch
torch/_utils.py
{ "start": 33119, "end": 36805 }
class ____: def __init__(self, fget, fset=None): self.fget = fget def __get__(self, instance, owner=None): if owner is None: owner = type(instance) return self.fget.__get__(instance, owner)() def classproperty(func): if not isinstance(func, (classmethod, staticmethod))...
_ClassPropertyDescriptor
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 55265, "end": 56666 }
class ____(ModelOutput): r""" loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`): Total loss. prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_input_channels)`): Prediction output from the forecast head. last_hidden_st...
PatchTSMixerForPredictionOutput
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 19411, "end": 24182 }
class ____(Structure): _fields_ = ( ("sectname", p_str16), ("segname", p_str16), ("addr", p_uint64), ("size", p_uint64), ("offset", p_uint32), ("align", p_uint32), ("reloff", p_uint32), ("nreloc", p_uint32), ("flags", p_uint32), ("reser...
section_64
python
kamyu104__LeetCode-Solutions
Python/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.py
{ "start": 427, "end": 1122 }
class ____(object): def minInteger(self, num, k): """ :type num: str :type k: int :rtype: str """ lookup = collections.defaultdict(list) bit = BIT(len(num)+1) for i in reversed(xrange(len(num))): bit.add(i+1, 1) lookup[int(num[i...
Solution
python
pallets__click
src/click/_termui_impl.py
{ "start": 18044, "end": 27093 }
class ____: def __init__( self, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", ) -> None: self.editor = editor self.env = env self.require_save = require_save self.e...
Editor
python
kamyu104__LeetCode-Solutions
Python/rotate-array.py
{ "start": 1277, "end": 1874 }
class ____(object): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ def rotate(self, nums, k): count = 0 start = 0 while count < len(nums): curr = start prev = nums[curr] wh...
Solution3
python
doocs__leetcode
lcof/面试题54. 二叉搜索树的第k大节点/Solution.py
{ "start": 164, "end": 532 }
class ____: def kthLargest(self, root: TreeNode, k: int) -> int: def dfs(root): nonlocal k, ans if root is None or k == 0: return dfs(root.right) k -= 1 if k == 0: ans = root.val dfs(root.left) a...
Solution
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py
{ "start": 20068, "end": 25214 }
class ____(GoogleCloudBaseOperator): """ Fetches all the Notification Channels identified by the filter passed as filter parameter. The desired return type can be specified by the format parameter, the supported formats are "dict", "json" and None which returns python dictionary, stringified JSON a...
StackdriverListNotificationChannelsOperator
python
bottlepy__bottle
bottle.py
{ "start": 150183, "end": 151940 }
class ____(threading.Thread): """ Interrupt main-thread as soon as a changed module file is detected, the lockfile gets deleted or gets too old. """ def __init__(self, lockfile, interval): threading.Thread.__init__(self) self.daemon = True self.lockfile, self.interval = lockfile...
FileCheckerThread
python
pytorch__pytorch
torch/_dynamo/resume_execution.py
{ "start": 8459, "end": 9996 }
class ____: code: types.CodeType instructions: list[Instruction] = dataclasses.field(default_factory=list) # Python 3.11+ fields # NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists # of instructions of all exception table entries that have the same target. # map from PU...
ResumeFunctionMetadata
python
doocs__leetcode
solution/0900-0999/0920.Number of Music Playlists/Solution.py
{ "start": 0, "end": 447 }
class ____: def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: mod = 10**9 + 7 f = [[0] * (n + 1) for _ in range(goal + 1)] f[0][0] = 1 for i in range(1, goal + 1): for j in range(1, n + 1): f[i][j] = f[i - 1][j - 1] * (n - j + 1) ...
Solution
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 17429, "end": 17717 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): values = helper_functions.get_value("NumSymbols") if len(values) == 0: return 0 return max(max(values), 0) @metafeatures.define("SymbolsMean", dependency="NumSymbols")
SymbolsMax
python
rq__rq
rq/exceptions.py
{ "start": 337, "end": 491 }
class ____(Exception): def __init__(self, msg, extra_info): self.extra_info = extra_info super().__init__(msg)
ShutDownImminentException
python
run-llama__llama_index
llama-index-core/llama_index/core/tools/function_tool.py
{ "start": 1806, "end": 16048 }
class ____(AsyncBaseTool): """ Function Tool. A tool that takes in a function, optionally handles workflow context, and allows the use of callbacks. The callback can return a new ToolOutput to override the default one or a string that will be used as the final content. """ def __init__( ...
FunctionTool
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 4700, "end": 5007 }
class ____(ContractDataError): """ Raises when sending funds to a non-payable method """ _TRACE_ARG = Optional[Union["TraceAPI", Callable[[], Optional["TraceAPI"]]]] _SOURCE_TRACEBACK_ARG = Optional[ Union["SourceTraceback", Callable[[], Optional["SourceTraceback"]]] ]
MethodNonPayableError
python
cherrypy__cherrypy
cherrypy/__init__.py
{ "start": 6534, "end": 8367 }
class ____(object): __slots__ = ['__attrname__', '__dict__'] def __init__(self, attrname): self.__attrname__ = attrname def __getattr__(self, name): child = getattr(serving, self.__attrname__) return getattr(child, name) def __setattr__(self, name, value): if name in (...
_ThreadLocalProxy
python
pytorch__pytorch
torch/ao/quantization/backend_config/backend_config.py
{ "start": 17346, "end": 31509 }
class ____: """ Config object that specifies quantization behavior for a given operator pattern. For a detailed example usage, see :class:`~torch.ao.quantization.backend_config.BackendConfig`. """ def __init__(self, pattern: Pattern | None = None): self.pattern: Pattern | None = pattern ...
BackendPatternConfig
python
walkccc__LeetCode
solutions/1545. Find Kth Bit in Nth Binary String/1545.py
{ "start": 0, "end": 311 }
class ____: def findKthBit(self, n: int, k: int) -> str: if n == 1: return '0' midIndex = pow(2, n - 1) # 1-indexed if k == midIndex: return '1' if k < midIndex: return self.findKthBit(n - 1, k) return '1' if self.findKthBit(n - 1, midIndex * 2 - k) == '0' else '0'
Solution
python
mwaskom__seaborn
tests/test_distributions.py
{ "start": 72921, "end": 80683 }
class ____: # TODO probably good to move these utility attributes/methods somewhere else @pytest.mark.parametrize( "kwargs", [ dict(), dict(x="x"), dict(x="t"), dict(x="a"), dict(x="z", log_scale=True), dict(x="x", binwidth=4), ...
TestDisPlot
python
getsentry__sentry
tests/sentry/issues/endpoints/test_team_all_unresolved_issues.py
{ "start": 570, "end": 11789 }
class ____(APITestCase): endpoint = "sentry-api-0-team-all-unresolved-issues" def test_status_format(self) -> None: project1 = self.create_project(teams=[self.team]) group1_1 = self.create_group(project=project1, first_seen=before_now(days=40)) group1_2 = self.create_group(project=proje...
TeamIssueBreakdownTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vision.py
{ "start": 8671, "end": 9490 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook") def test_minimal_green_path(self, mock_hook): mock_hook.return_value.update_product.return_value = {} op = CloudVisionUpdateProductOperator(location=LOCATION_TEST, product=PRODUCT_TEST, task_id="id") ...
TestCloudVisionProductUpdate
python
astropy__astropy
astropy/time/formats.py
{ "start": 36804, "end": 37280 }
class ____(TimeFromEpoch): """ Stardate: date units from 2318-07-05 12:00:00 UTC. For example, stardate 41153.7 is 00:52 on April 30, 2363. See https://trekguide.com/Stardates.htm#TNG for calculations and reference points. """ name = "stardate" unit = 0.397766856 # Stardate units per day ...
TimeStardate
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/util.py
{ "start": 18714, "end": 32510 }
class ____(_repr_base): """Provide a string view of bound parameters. Truncates display to a given number of 'multi' parameter sets, as well as long values to a given number of characters. """ __slots__ = "params", "batches", "ismulti", "max_params" def __init__( self, params...
_repr_params
python
walkccc__LeetCode
solutions/2044. Count Number of Maximum Bitwise-OR Subsets/2044.py
{ "start": 0, "end": 360 }
class ____: def countMaxOrSubsets(self, nums: list[int]) -> int: ors = functools.reduce(operator.or_, nums) ans = 0 def dfs(i: int, path: int) -> None: nonlocal ans if i == len(nums): if path == ors: ans += 1 return dfs(i + 1, path) dfs(i + 1, path | num...
Solution
python
kamyu104__LeetCode-Solutions
Python/minesweeper.py
{ "start": 43, "end": 1222 }
class ____(object): def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ if board[click[0]][click[1]] == 'M': board[click[0]][click[1]] = 'X' return board stk = [click]...
Solution
python
getsentry__sentry
src/sentry/models/dynamicsampling.py
{ "start": 2282, "end": 2895 }
class ____(Model): """ Many-to-many relationship between a custom dynamic sampling rule and a project. """ __relocation_scope__ = RelocationScope.Organization custom_dynamic_sampling_rule = FlexibleForeignKey( "sentry.CustomDynamicSamplingRule", on_delete=models.CASCADE ) project =...
CustomDynamicSamplingRuleProject
python
protocolbuffers__protobuf
objectivec/DevTools/pddm.py
{ "start": 4203, "end": 4365 }
class ____(Exception): """Error thrown by pddm.""" def __init__(self, message="Error"): self.message = message super().__init__(self.message)
PDDMError
python
pytorch__pytorch
torch/_inductor/runtime/triton_heuristics.py
{ "start": 140740, "end": 140969 }
class ____(GridExpr): def generate(self, meta: dict[str, int]) -> None: assert meta.get("XBLOCK", 1) == 1 self.x_grid = self.ceildiv("r0_numel", meta.get("R0_BLOCK")) self.y_grid = "xnumel"
SplitScanGrid
python
django__django
tests/multiple_database/tests.py
{ "start": 77644, "end": 77957 }
class ____: # A router that only expresses an opinion on migrate, # passing pets to the 'other' database def allow_migrate(self, db, app_label, model_name=None, **hints): if db == "other": return model_name == "pet" else: return model_name != "pet"
AntiPetRouter
python
encode__django-rest-framework
tests/test_one_to_one_with_inheritance.py
{ "start": 433, "end": 603 }
class ____(serializers.ModelSerializer): class Meta: model = ChildModel fields = ['id', 'name1', 'name2', 'childassociatedmodel']
DerivedModelSerializer
python
coleifer__peewee
tests/sqlcipher_ext.py
{ "start": 739, "end": 803 }
class ____(FTSModel, TestModel): content = TextField()
FTSNote
python
qdrant__qdrant-client
tools/async_client_generator/client_generator.py
{ "start": 465, "end": 3847 }
class ____(BaseGenerator): def __init__( self, keep_sync: Optional[list[str]] = None, class_replace_map: Optional[dict[str, str]] = None, import_replace_map: Optional[dict[str, str]] = None, exclude_methods: Optional[list[str]] = None, ): super().__init__() ...
ClientGenerator
python
protocolbuffers__protobuf
python/google/protobuf/internal/json_format_test.py
{ "start": 1148, "end": 3175 }
class ____(unittest.TestCase): def FillAllFields(self, message): message.int32_value = 20 message.int64_value = -20 message.uint32_value = 3120987654 message.uint64_value = 12345678900 message.float_value = float('-inf') message.double_value = 3.1415 message.bool_value = True message....
JsonFormatBase
python
tiangolo__fastapi
fastapi/security/oauth2.py
{ "start": 17920, "end": 21248 }
class ____(OAuth2): """ OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency. """ def __init__( self, authorizationUrl: str, tokenUrl: Annotated[ str, Doc( ...
OAuth2AuthorizationCodeBearer