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
kamyu104__LeetCode-Solutions
Python/number-of-islands.py
{ "start": 2546, "end": 3519 }
class ____(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def bfs(grid, i, j): if grid[i][j] == '0': return False grid[i][j] ='0' ...
Solution3
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/auth_generated.py
{ "start": 233, "end": 408 }
class ____(BaseModel): """ HTTPException Model used for error response. """ detail: Annotated[str | dict[str, Any], Field(title="Detail")]
HTTPExceptionResponse
python
pydantic__pydantic
pydantic/v1/utils.py
{ "start": 12961, "end": 14720 }
class ____(Representation): """ Hack to make object's smell just enough like dicts for validate_model. We can't inherit from Mapping[str, Any] because it upsets cython so we have to implement all methods ourselves. """ __slots__ = ('_obj',) def __init__(self, obj: Any): self._obj = ob...
GetterDict
python
wandb__wandb
wandb/vendor/pygments/style.py
{ "start": 883, "end": 4554 }
class ____(type): def __new__(mcs, name, bases, dct): obj = type.__new__(mcs, name, bases, dct) for token in STANDARD_TYPES: if token not in obj.styles: obj.styles[token] = '' def colorformat(text): if text in ansicolors: return text ...
StyleMeta
python
joke2k__faker
faker/providers/isbn/en_US/__init__.py
{ "start": 42, "end": 1166 }
class ____(ISBNProvider): rules = { # EAN prefix "978": { # Registration group "0": [ # Registrant rule (min, max, registrant length) ("0000000", "1999999", 2), ("2000000", "2279999", 3), ("2280000", "2289999", 4...
Provider
python
django__django
django/utils/feedgenerator.py
{ "start": 11341, "end": 13663 }
class ____(RssFeed): # Spec: https://cyber.harvard.edu/rss/rss.html _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQ...
Rss201rev2Feed
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-events-that-can-be-attended-ii.py
{ "start": 688, "end": 1233 }
class ____(object): def maxValue(self, events, k): """ :type events: List[List[int]] :type k: int :rtype: int """ events.sort() sorted_starts = [x[0] for x in events] dp = [[0]*(k+1) for _ in xrange(len(events)+1)] for i in reversed(xrange(len(...
Solution2
python
kamyu104__LeetCode-Solutions
Python/type-of-triangle-ii.py
{ "start": 36, "end": 400 }
class ____(object): def triangleType(self, nums): """ :type nums: List[int] :rtype: str """ nums.sort() a, b, c = nums if a+b <= c: return "none" if a == b == c: return "equilateral" if a == b or b == c: retu...
Solution
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/inspect_utils_test.py
{ "start": 1943, "end": 16582 }
class ____(test.TestCase): def test_islambda(self): def test_fn(): pass self.assertTrue(inspect_utils.islambda(lambda x: x)) self.assertFalse(inspect_utils.islambda(test_fn)) def test_islambda_renamed_lambda(self): l = lambda x: 1 l.__name__ = 'f' self.assertTrue(inspect_utils.islam...
InspectUtilsTest
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 174622, "end": 176457 }
class ____( fixtures.TestBase, testing.AssertsCompiledSQL ): __dialect__ = "default" def _combinations(fn): return testing.combinations( desc, asc, nulls_first, nulls_last, any_, all_, distinct, bitwise_...
StandaloneOperatorTranslateTest
python
pytorch__pytorch
torch/distributions/dirichlet.py
{ "start": 634, "end": 1100 }
class ____(Function): @staticmethod # pyrefly: ignore [bad-override] def forward(ctx, concentration): x = torch._sample_dirichlet(concentration) ctx.save_for_backward(x, concentration) return x @staticmethod @once_differentiable # pyrefly: ignore [bad-override] def b...
_Dirichlet
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/image/base.py
{ "start": 376, "end": 5312 }
class ____(BaseReader): """ Image parser. Extract text from images using DONUT or pytesseract. """ def __init__( self, parser_config: Optional[Dict] = None, keep_image: bool = False, parse_text: bool = False, text_type: str = "text", pytesseract_mod...
ImageReader
python
gevent__gevent
src/gevent/monkey/_patch_thread_gte313.py
{ "start": 222, "end": 4082 }
class ____(BasePatcher): def patch_active_threads(self): from gevent.threading import main_native_thread for thread in self.threading_mod._active.values(): if thread == main_native_thread(): from gevent.thread import _ThreadHandle from greenlet import g...
Patcher
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-path-with-alternating-directions-i.py
{ "start": 36, "end": 303 }
class ____(object): def minCost(self, m, n): """ :type m: int :type n: int :rtype: int """ if (m, n) == (1, 1): return 1 if (m, n) in ((1, 2), (2, 1)): return 3 return -1
Solution
python
encode__httpx
httpx/_urls.py
{ "start": 14147, "end": 21515 }
class ____(typing.Mapping[str, str]): """ URL query parameters, as a multi-dict. """ def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: assert len(args) < 2, "Too many arguments." assert not (args and kwargs), "Cannot mix named and unnamed arguments." ...
QueryParams
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/config_schema.py
{ "start": 1644, "end": 4468 }
class ____(DagsterTypeLoader): def __init__(self, config_type, func, required_resource_keys): self._config_type = check.inst_param(config_type, "config_type", ConfigType) self._func = check.callable_param(func, "func") self._required_resource_keys = check.opt_set_param( required_...
DagsterTypeLoaderFromDecorator
python
Textualize__textual
docs/examples/how-to/layout02.py
{ "start": 491, "end": 650 }
class ____(App): def on_ready(self) -> None: self.push_screen(TweetScreen()) if __name__ == "__main__": app = LayoutApp() app.run()
LayoutApp
python
doocs__leetcode
solution/1800-1899/1895.Largest Magic Square/Solution.py
{ "start": 0, "end": 1578 }
class ____: def largestMagicSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) rowsum = [[0] * (n + 1) for _ in range(m + 1)] colsum = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): rowsum[...
Solution
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 5358, "end": 5699 }
class ____(InvalidConfigError): def __init__(self, message, missing_config_variable=None) -> None: if not missing_config_variable: missing_config_variable = [] self.message = message self.missing_config_variable = missing_config_variable super().__init__(self.message)
MissingConfigVariableError
python
numba__numba
numba/core/errors.py
{ "start": 18087, "end": 18451 }
class ____(IRError): """ An undefined variable is encountered during interpretation of IR. """ def __init__(self, name, loc=None): self.name = name msg = ("The compiler failed to analyze the bytecode. " "Variable '%s' is not defined." % name) super(NotDefinedError...
NotDefinedError
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/GradientEditorItem.py
{ "start": 14399, "end": 32717 }
class ____(TickSliderItem): """ **Bases:** :class:`TickSliderItem <pyqtgraph.TickSliderItem>` An item that can be used to define a color gradient. Implements common pre-defined gradients that are customizable by the user. :class: `GradientWidget <pyqtgraph.GradientWidget>` provides a widget wi...
GradientEditorItem
python
huggingface__transformers
src/transformers/models/fuyu/processing_fuyu.py
{ "start": 14009, "end": 36433 }
class ____(ProcessorMixin): r""" Constructs a Fuyu processor which wraps a Fuyu image processor and a Llama tokenizer into a single processor. [`FuyuProcessor`] offers all the functionalities of [`FuyuImageProcessor`] and [`LlamaTokenizerFast`]. See the [`~FuyuProcessor.__call__`] and [`~FuyuProcessor....
FuyuProcessor
python
spack__spack
lib/spack/spack/test/jobserver.py
{ "start": 4340, "end": 8767 }
class ____: """Test JobServer class functionality.""" def test_creates_new_jobserver(self): """Should create a new FIFO-based jobserver when none exists.""" js = JobServer(4) try: assert js.created is True assert js.fifo_path is not None assert os.pa...
TestJobServer
python
sanic-org__sanic
sanic/touchup/schemes/ode.py
{ "start": 1564, "end": 2857 }
class ____(NodeTransformer): def __init__(self, registered_events) -> None: self._registered_events = registered_events def visit_Expr(self, node: Expr) -> Any: call = node.value if isinstance(call, Await): call = call.value func = getattr(call, "func", None) ...
RemoveDispatch
python
pennersr__django-allauth
allauth/socialaccount/providers/draugiem/views.py
{ "start": 549, "end": 2915 }
class ____(Exception): pass ACCESS_TOKEN_URL = "https://api.draugiem.lv/json" # nosec AUTHORIZE_URL = "https://api.draugiem.lv/authorize" def login(request): app = get_adapter().get_app(request, DraugiemProvider.id) redirect_url = request.build_absolute_uri(reverse(callback)) # Draugiem mandates a ...
DraugiemApiError
python
django__django
tests/admin_views/models.py
{ "start": 2014, "end": 2281 }
class ____(models.Model): """ A simple book that has chapters. """ name = models.CharField(max_length=100, verbose_name="¿Name?") def __str__(self): return self.name def get_absolute_url(self): return f"/books/{self.id}/"
Book
python
arrow-py__arrow
tests/test_parser.py
{ "start": 5704, "end": 30955 }
class ____: def test_parse_list(self, mocker): mocker.patch( "arrow.parser.DateTimeParser._parse_multiformat", string="str", formats=["fmt_a", "fmt_b"], return_value="result", ) result = self.parser.parse("str", ["fmt_a", "fmt_b"]) ass...
TestDateTimeParserParse
python
kamyu104__LeetCode-Solutions
Python/sum-of-number-and-its-reverse.py
{ "start": 1496, "end": 1709 }
class ____(object): def sumOfNumberAndReverse(self, num): """ :type num: int :rtype: bool """ return any(x+int(str(x)[::-1]) == num for x in xrange(num//2, num+1))
Solution3
python
django__django
tests/m2m_through_regress/models.py
{ "start": 2480, "end": 2574 }
class ____(IndividualCompetitor): class Meta: proxy = True
ProxiedIndividualCompetitor
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/components/reward_providers/curiosity_reward_provider.py
{ "start": 988, "end": 2543 }
class ____(BaseRewardProvider): beta = 0.2 # Forward vs Inverse loss weight loss_multiplier = 10.0 # Loss multiplier def __init__(self, specs: BehaviorSpec, settings: CuriositySettings) -> None: super().__init__(specs, settings) self._ignore_done = True self._network = CuriosityNe...
CuriosityRewardProvider
python
fluentpython__example-code-2e
15-more-types/protocol/mymax/mymax.py
{ "start": 128, "end": 1705 }
class ____(Protocol): def __lt__(self, other: Any) -> bool: ... T = TypeVar('T') LT = TypeVar('LT', bound=SupportsLessThan) DT = TypeVar('DT') MISSING = object() EMPTY_MSG = 'max() arg is an empty sequence' @overload def max(__arg1: LT, __arg2: LT, *args: LT, key: None = ...) -> LT: ... @overload def max(__a...
SupportsLessThan
python
django__django
tests/migrations/test_migrations_plan/0004_fourth.py
{ "start": 35, "end": 225 }
class ____(migrations.Migration): dependencies = [ ("migrations", "0003_third"), ] operations = [migrations.RunSQL("SELECT * FROM migrations_author WHERE id = 1")]
Migration
python
fluentpython__example-code-2e
15-more-types/cafeteria/cafeteria.py
{ "start": 38, "end": 80 }
class ____: """Any beverage."""
Beverage
python
lepture__authlib
authlib/oauth2/rfc6749/grants/refresh_token.py
{ "start": 603, "end": 6569 }
class ____(BaseGrant, TokenEndpointMixin): """A special grant endpoint for refresh_token grant_type. Refreshing an Access Token per `Section 6`_. .. _`Section 6`: https://tools.ietf.org/html/rfc6749#section-6 """ GRANT_TYPE = "refresh_token" #: The authorization server MAY issue a new refresh...
RefreshTokenGrant
python
django__django
django/contrib/admin/exceptions.py
{ "start": 335, "end": 426 }
class ____(Exception): """The model is already registered.""" pass
AlreadyRegistered
python
zarr-developers__zarr-python
src/zarr/codecs/sharding.py
{ "start": 2024, "end": 2594 }
class ____(ByteGetter): shard_dict: ShardMapping chunk_coords: tuple[int, ...] async def get( self, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> Buffer | None: assert byte_range is None, "byte_range is not supported within shards" assert prototype == de...
_ShardingByteGetter
python
ray-project__ray
python/ray/_private/state_api_test_utils.py
{ "start": 874, "end": 953 }
class ____: latency_sec: float result_size: int @dataclass
StateAPIMetric
python
doocs__leetcode
solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py
{ "start": 394, "end": 780 }
class ____: def maxBalancedSubsequenceSum(self, nums: List[int]) -> int: arr = [x - i for i, x in enumerate(nums)] s = sorted(set(arr)) tree = BinaryIndexedTree(len(s)) for i, x in enumerate(nums): j = bisect_left(s, x - i) + 1 v = max(tree.query(j), 0) + x ...
Solution
python
pallets__click
src/click/parser.py
{ "start": 4007, "end": 5800 }
class ____: def __init__( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ): self._short_opts = [] self._long_opts = [] self.prefixes: set[str...
_Option
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_member_invite_index.py
{ "start": 8379, "end": 14055 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-member-invite-index" method = "post" def setUp(self) -> None: self.login_as(self.user) def test_forbid_qq(self) -> None: data = {"email": "1234@qq.com", "orgRole": "member", "teams": [self.team.slug]} response = sel...
OrganizationMemberInvitePostTest
python
apache__avro
lang/py/avro/test/sample_http_server.py
{ "start": 1570, "end": 2054 }
class ____(avro.ipc.Responder): def __init__(self) -> None: super().__init__(MAIL_PROTOCOL) def invoke(self, message: avro.protocol.Message, request: Mapping[str, Mapping[str, str]]) -> str: if message.name == "send": return f"Sent message to {request['message']['to']} from {request...
MailResponder
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 64251, "end": 64744 }
class ____(PlotActionTool): ''' *toolbar icon*: |redo_icon| Redo tool reverses the last action performed by undo tool. .. |redo_icon| image:: /_images/icons/redo.svg :height: 24px :alt: Icon of an arrow on a circular arc pointing to the right representing the redo tool in the toolbar. ...
RedoTool
python
doocs__leetcode
lcof/面试题13. 机器人的运动范围/Solution.py
{ "start": 0, "end": 385 }
class ____: def movingCount(self, m: int, n: int, k: int) -> int: def f(x: int) -> int: return x // 10 + x % 10 def dfs(i, j): if i >= m or j >= n or f(i) + f(j) > k or (i, j) in vis: return 0 vis.add((i, j)) return 1 + dfs(i + 1, j) +...
Solution
python
PyCQA__pydocstyle
src/tests/test_cases/canonical_google_examples.py
{ "start": 3371, "end": 4176 }
class ____: """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """ @expect("D401: First line should be in imperative mood " ...
SampleClass
python
squidfunk__mkdocs-material
material/plugins/privacy/parser.py
{ "start": 1682, "end": 1955 }
class ____(HTMLParser): # Initialize parser def __init__(self): super().__init__(convert_charrefs = True) self.result = None # Create element def handle_starttag(self, tag, attrs): self.result = Element(tag, dict(attrs))
FragmentParser
python
getsentry__sentry
tests/sentry/middleware/test_access_log_middleware.py
{ "start": 3399, "end": 3533 }
class ____(OrganizationEndpoint): def get(self, request, organization): return Response({"ok": True})
MyOrganizationEndpoint
python
catalyst-team__catalyst
examples/self_supervised/src/runner.py
{ "start": 8956, "end": 15615 }
class ____(ISelfSupervisedRunner, Runner): """Runner for experiments with contrastive model. Args: input_key: key in ``runner.batch`` dict mapping for model input target_key: key in ``runner.batch`` dict mapping for target loss_key: key for ``runner.batch_metrics`` to store criterion lo...
SelfSupervisedRunner
python
psf__black
tests/data/cases/class_blank_parentheses.py
{ "start": 50, "end": 184 }
class ____ ( ): first_test_data = 90 second_test_data = 100 def test_func(self): return None
ClassWithSpaceParentheses
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 11449, "end": 11750 }
class ____(MarkdownHeader): """An H1 Markdown header.""" LEVEL = 1 DEFAULT_CSS = """ MarkdownH1 { content-align: center middle; color: $markdown-h1-color; background: $markdown-h1-background; text-style: $markdown-h1-text-style; } """
MarkdownH1
python
scipy__scipy
scipy/optimize/_dual_annealing.py
{ "start": 5336, "end": 8776 }
class ____: """ Class used to record the energy state. At any time, it knows what is the currently used coordinates and the most recent best location. Parameters ---------- lower : array_like A 1-D NumPy ndarray containing lower bounds for generating an initial random components...
EnergyState
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_modelresource/test_resource_fields.py
{ "start": 8459, "end": 10460 }
class ____(TestCase): class BookResource(resources.ModelResource): author_name = fields.Field( attribute="author_json__name", column_name="author_name", readonly=True ) class Meta: model = Book fields = ("id", "author_name") def get_queryset(sel...
ModelResourceDeclarationFieldWithDictKey
python
pypa__virtualenv
src/virtualenv/create/via_global_ref/_virtualenv.py
{ "start": 1629, "end": 5347 }
class ____: """A meta path finder that allows patching the imported distutils modules.""" fullname = None # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup, # because there are gevent-based applications that need to be first to import threading by...
_Finder
python
scikit-learn__scikit-learn
sklearn/svm/_classes.py
{ "start": 35408, "end": 45314 }
class ____(BaseSVC): """Nu-Support Vector Classification. Similar to SVC but uses a parameter to control the number of support vectors. The implementation is based on libsvm. Read more in the :ref:`User Guide <svm_classification>`. Parameters ---------- nu : float, default=0.5 ...
NuSVC
python
realpython__materials
django-todo-list/source_code_final/todo_app/views.py
{ "start": 675, "end": 896 }
class ____(CreateView): model = ToDoList fields = ["title"] def get_context_data(self): context = super().get_context_data() context["title"] = "Add a new list" return context
ListCreate
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/gcs/gcs_fake_resource.py
{ "start": 1570, "end": 2927 }
class ____: def __init__(self): from unittest import mock self.buckets: dict[str, FakeGCSBucket] = {} self.mock_extras = mock.MagicMock() def bucket(self, bucket_name: str, *args, **kwargs): self.mock_extras.bucket(*args, **kwargs) if bucket_name not in self.buckets.ke...
FakeGCSClient
python
getsentry__sentry
src/sentry/interfaces/user.py
{ "start": 467, "end": 3132 }
class ____(Interface): """ An interface which describes the authenticated User for a request. You should provide **at least** either an `id` (a unique identifier for an authenticated user) or `ip_address` (their IP address). All other attributes are optional. >>> { >>> "id": "unique_i...
User
python
doocs__leetcode
solution/0800-0899/0847.Shortest Path Visiting All Nodes/Solution.py
{ "start": 0, "end": 636 }
class ____: def shortestPathLength(self, graph: List[List[int]]) -> int: n = len(graph) q = deque() vis = set() for i in range(n): q.append((i, 1 << i)) vis.add((i, 1 << i)) ans = 0 while 1: for _ in range(len(q)): i...
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0032_increase_webhook_maxsize.py
{ "start": 150, "end": 567 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0031_add_modified_date_importedfile"), ] operations = [ migrations.AlterField( model_name="webhook", name="url", field=models.URLField( blank=T...
Migration
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py
{ "start": 4657, "end": 5111 }
class ____: """ Represents a Sentry App notification action. """ settings: list[SentryAppFormConfigDataBlob] = dataclasses.field(default_factory=list) @classmethod def from_list(cls, data: list[dict[str, Any]] | None) -> "SentryAppDataBlob": if data is None: return cls() ...
SentryAppDataBlob
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/run_operands.py
{ "start": 891, "end": 3079 }
class ____(SubsetAutomationCondition): @property def name(self) -> str: return "executed_with_root_target" async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride] def _filter_fn(run_record: "RunRecord") -> bool: ...
LatestRunExecutedWithRootTargetCondition
python
ray-project__ray
python/ray/autoscaler/_private/local/node_provider.py
{ "start": 638, "end": 4481 }
class ____: def __init__(self, lock_path, save_path, provider_config): self.lock = RLock() os.makedirs(os.path.dirname(lock_path), exist_ok=True) self.file_lock = FileLock(lock_path) self.save_path = save_path with self.lock: with self.file_lock: ...
ClusterState
python
pypa__warehouse
warehouse/subscriptions/models.py
{ "start": 1114, "end": 1243 }
class ____(str, enum.Enum): Month = "month" Year = "year" Week = "week" Day = "day"
StripeSubscriptionPriceInterval
python
fluentpython__example-code
12-inheritance/diamond.py
{ "start": 186, "end": 411 }
class ____(B, C): def ping(self): super().ping() print('post-ping:', self) def pingpong(self): self.ping() super().ping() self.pong() super().pong() C.pong(self)
D
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 85856, "end": 86377 }
class ____: def test_required_passed_to_both_django_file_path_field_and_base(self): field = serializers.FilePathField( path=os.path.abspath(os.path.dirname(__file__)), required=False, ) assert "" in field.choices # Django adds empty choice if not required ass...
TestFilePathFieldRequired
python
facelessuser__pymdown-extensions
pymdownx/caret.py
{ "start": 5329, "end": 5529 }
class ____(util.PatternSequenceProcessor): """Just insert processor.""" PATTERNS = [ util.PatSeqItem(re.compile(INS, re.DOTALL | re.UNICODE), 'single', 'ins') ]
CaretInsertProcessor
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol10.py
{ "start": 737, "end": 854 }
class ____(Protocol): def __call__(self, a: int, /, *args: Any, k: str, **kwargs: Any) -> None: pass
Proto6
python
jazzband__django-simple-history
simple_history/tests/tests/test_deprecation.py
{ "start": 18, "end": 356 }
class ____(unittest.TestCase): """Tests that check whether ``DeprecationWarning`` is raised for certain features, and that compare ``simple_history.__version__`` against the version the features will be removed in. If this class is empty, it normally means that nothing is currently deprecated. """
DeprecationWarningTest
python
doocs__leetcode
solution/3200-3299/3237.Alt and Tab Simulation/Solution.py
{ "start": 0, "end": 352 }
class ____: def simulationResult(self, windows: List[int], queries: List[int]) -> List[int]: s = set() ans = [] for q in queries[::-1]: if q not in s: ans.append(q) s.add(q) for w in windows: if w not in s: ans.a...
Solution
python
walkccc__LeetCode
solutions/1823. Find the Winner of the Circular Game/1823-2.py
{ "start": 0, "end": 633 }
class ____: def findTheWinner(self, n: int, k: int) -> int: # e.g. n = 4, k = 2. # By using 0-indexed notation, we have the following circle: # # 0 -> 1 -> 2 -> 3 -> 0 # x # 0 -> 1 -> 2 -> 0 # # After the first round, 1 is removed. # So, 2 becomes 0, 3 becomes 1, and...
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_cloud_sql.py
{ "start": 25931, "end": 39266 }
class ____: 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.cloudsql_hook_no_default_project_id = CloudSQLHook(api_version="v1", gcp_conn_id...
TestGcpSqlHookNoDefaultProjectID
python
pydata__xarray
xarray/core/indexing.py
{ "start": 31066, "end": 32868 }
class ____(ExplicitlyIndexedNDArrayMixin): __slots__ = ("_copied", "array") def __init__(self, array: duckarray[Any, Any]): self.array = as_indexable(array) self._copied = False def _ensure_copied(self): if not self._copied: self.array = as_indexable(np.array(self.array...
CopyOnWriteArray
python
ray-project__ray
rllib/algorithms/dreamerv3/utils/debugging.py
{ "start": 229, "end": 5970 }
class ____(CartPoleEnv): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) low = np.concatenate([np.array([0.0]), self.observation_space.low]) high = np.concatenate([np.array([1000.0]), self.observation_space.high]) self.observation_space = gym.spaces.Box(low, ...
CartPoleDebug
python
huggingface__transformers
src/transformers/models/video_llava/modeling_video_llava.py
{ "start": 19257, "end": 32641 }
class ____(VideoLlavaPreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = { "^language_model.model": "model.language_model", "^image_tower": "model.image_tower", "^video_tower": "model.video_tower", "^multi_modal_projector": "model.multi_modal_projector", "^lan...
VideoLlavaForConditionalGeneration
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/vendor/pretty.py
{ "start": 3878, "end": 4164 }
class ____: def __init__(self, value: object): self.value = value def __hash__(self) -> int: return hash((type(self), id(self.value))) def __eq__(self, __o: object) -> bool: return isinstance(__o, type(self)) and id(self.value) == id(__o.value)
IDKey
python
RaRe-Technologies__gensim
gensim/models/logentropy_model.py
{ "start": 776, "end": 5329 }
class ____(interfaces.TransformationABC): r"""Objects of this class realize the transformation between word-document co-occurrence matrix (int) into a locally/globally weighted matrix (positive floats). This is done by a log entropy normalization, optionally normalizing the resulting documents to unit leng...
LogEntropyModel
python
jmcnamara__XlsxWriter
xlsxwriter/test/vml/test_write_div.py
{ "start": 289, "end": 738 }
class ____(unittest.TestCase): """ Test the Vml _write_div() method. """ def setUp(self): self.fh = StringIO() self.vml = Vml() self.vml._set_filehandle(self.fh) def test_write_div(self): """Test the _write_div() method""" self.vml._write_div("left") ...
TestWriteDiv
python
huggingface__transformers
tests/models/gpt_neox_japanese/test_modeling_gpt_neox_japanese.py
{ "start": 1316, "end": 7966 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_head...
GPTNeoXJapaneseModelTester
python
numba__numba
numba/core/compiler_machinery.py
{ "start": 2828, "end": 2920 }
class ____(CompilerPass): """ Base class for lowering passes """ pass
LoweringPass
python
doocs__leetcode
solution/1800-1899/1856.Maximum Subarray Min-Product/Solution.py
{ "start": 0, "end": 721 }
class ____: def maxSumMinProduct(self, nums: List[int]) -> int: n = len(nums) left = [-1] * n right = [n] * n stk = [] for i, x in enumerate(nums): while stk and nums[stk[-1]] >= x: stk.pop() if stk: left[i] = stk[-1] ...
Solution
python
eth-brownie__brownie
brownie/network/gas/strategies.py
{ "start": 1328, "end": 2434 }
class ____(TimeGasStrategy): """ Gas strategy for linear gas price increase. Arguments --------- initial_gas_price : int The initial gas price to use in the first transaction max_gas_price : int The maximum gas price to use increment : float Multiplier applied to the...
LinearScalingStrategy
python
pyca__cryptography
tests/hazmat/primitives/test_ssh.py
{ "start": 43312, "end": 44932 }
class ____: def test_load_ssh_public_key(self, backend): ssh_key = ( b"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2fgpmpYO61qeAxGd0wgRaN/E4" b"GR+xWvBmvxjxrB1vG user@chiron.local" ) key = load_ssh_public_key(ssh_key, backend) assert isinstance(key, ed25519.Ed25519P...
TestEd25519SSHSerialization
python
pytorch__pytorch
test/functorch/test_eager_transforms.py
{ "start": 57339, "end": 79794 }
class ____(VmapTearDownMixin, TestCase): @jacrev_and_jacfwd def test_simple(self, device, jacapi): x = torch.randn(3, device=device) y = jacapi(torch.sin)(x) expected = torch.diagflat(x.cos()) assert torch.allclose(y, expected) @jacrev_and_jacfwd def test_simple_not_flat...
TestJac
python
getsentry__sentry
src/sentry/relocation/api/endpoints/details.py
{ "start": 574, "end": 1417 }
class ____(Endpoint): owner = ApiOwner.HYBRID_CLOUD publish_status = { # TODO(getsentry/team-ospo#214): Stabilize before GA. "GET": ApiPublishStatus.EXPERIMENTAL, } permission_classes = (SuperuserOrStaffFeatureFlaggedPermission,) def get(self, request: Request, relocation_uuid: str)...
RelocationDetailsEndpoint
python
huggingface__transformers
src/transformers/models/glm4_moe/modeling_glm4_moe.py
{ "start": 25633, "end": 28757 }
class ____(Glm4MoePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = Glm4M...
Glm4MoeForCausalLM
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 68769, "end": 71852 }
class ____: def test_basic(self, xp): actual = signal.order_filter(xp.asarray([1, 2, 3]), xp.asarray([1, 0, 1]), 1) expect = xp.asarray([2, 3, 2]) xp_assert_equal(actual, expect) def test_doc_example(self, xp): x = xp.reshape(xp.arange(25, dtype=xp_default_dtype(xp)), (5, 5)) ...
TestOrderFilt
python
google__jax
tests/array_test.py
{ "start": 62829, "end": 66138 }
class ____(jtu.JaxTestCase): # tests that the PRNGs are automatically sharded as expected @parameterized.named_parameters(("3", 3), ("4", 4), ("5", 5)) @jtu.skip_on_devices("gpu") def test_random_bits_is_pure_map_1d(self, num_devices): @jax.jit def f(x): bits = prng.threefry_random_bits(jnp.array...
RngShardingTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/looker.py
{ "start": 1200, "end": 4077 }
class ____(GoogleCloudBaseOperator): """ Submits a PDT materialization job to Looker. :param looker_conn_id: Required. The connection ID to use connecting to Looker. :param model: Required. The model of the PDT to start building. :param view: Required. The view of the PDT to start building. :pa...
LookerStartPdtBuildOperator
python
facelessuser__pymdown-extensions
tests/test_extensions/test_inlinehilite.py
{ "start": 8155, "end": 9527 }
class ____(util.MdCase): """Test inline highlight with CodeHilite.""" extension = [ 'markdown.extensions.codehilite', 'pymdownx.inlinehilite', ] extension_configs = { 'markdown.extensions.codehilite': { 'guess_lang': False }, 'pymdownx.inlinehilite': ...
TestInlineHiliteCodeHilite
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 60807, "end": 62776 }
class ____(TestCase): """Tests for ``padded()``""" def test_no_n(self): seq = [1, 2, 3] # No fillvalue self.assertEqual(mi.take(5, mi.padded(seq)), [1, 2, 3, None, None]) # With fillvalue self.assertEqual( mi.take(5, mi.padded(seq, fillvalue='')), [1, 2, 3,...
PaddedTest
python
viewflow__viewflow
viewflow/contrib/admin/apps.py
{ "start": 302, "end": 444 }
class ____(AppConfig): """Default application config.""" name = "viewflow.contrib.admin" label = "viewflow_admin"
ViewflowAdminConfig
python
PyCQA__pylint
tests/functional/r/regression/regression_9865_calling_bound_lambda.py
{ "start": 160, "end": 266 }
class ____: eq = lambda self, y: self == y def test_lambda_method(): ret = C().eq(1) return ret
C
python
bokeh__bokeh
src/bokeh/models/mappers.py
{ "start": 3348, "end": 4905 }
class ____(Mapper): ''' Base class for mappers that map categorical factors to other values. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) factors = FactorSeq(help=""" A sequence of factors /...
CategoricalMapper
python
ray-project__ray
python/ray/serve/tests/test_util.py
{ "start": 2543, "end": 8207 }
class ____: def test_merge_empty(self): assert {"env_vars": {}} == override_runtime_envs_except_env_vars({}, {}) def test_merge_empty_parent(self): child = {"env_vars": {"test1": "test_val"}, "working_dir": "."} assert child == override_runtime_envs_except_env_vars({}, child) def t...
TestOverrideRuntimeEnvsExceptEnvVars
python
pennersr__django-allauth
allauth/headless/mfa/response.py
{ "start": 2315, "end": 2524 }
class ____(APIResponse): def __init__(self, request, authenticator, meta=None): data = _authenticator_data(authenticator) super().__init__(request, data=data, meta=meta)
AuthenticatorResponse
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/time.py
{ "start": 8733, "end": 18503 }
class ____(TimeDTypeBase[np.dtypes.TimeDelta64DType, np.timedelta64], HasEndianness): """ A Zarr data type for arrays containing NumPy TimeDelta64 data. Wraps the ``np.dtypesTimeDelta64DType`` data type. Scalars for this data type are instances of `np.timedelta64`. Attributes ---------- dt...
TimeDelta64
python
redis__redis-py
redis/client.py
{ "start": 50767, "end": 52369 }
class ____(threading.Thread): def __init__( self, pubsub, sleep_time: float, daemon: bool = False, exception_handler: Union[ Callable[[Exception, "PubSub", "PubSubWorkerThread"], None], None ] = None, sharded_pubsub: bool = False, ): su...
PubSubWorkerThread
python
getsentry__sentry
src/sentry/integrations/example/integration.py
{ "start": 8546, "end": 8699 }
class ____(ExampleIntegrationProvider): key = "aliased" integration_key = "example" name = "Integration Key Example"
AliasedIntegrationProvider
python
django__django
django/views/generic/dates.py
{ "start": 18384, "end": 18564 }
class ____(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView): """List of objects published in a given week.""" template_name_suffix = "_archive_week"
WeekArchiveView
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 120421, "end": 122446 }
class ____: def test_minmax_blocked(self): # simd tests on max/min, test all alignments, slow but important # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once) for dt, sz in [(np.float32, 15), (np.float64, 7)]: for out, inp, msg in _gen_alignment_data(dtype=dt, type='unary', ...
TestMinMax
python
openai__openai-python
src/openai/types/eval_create_params.py
{ "start": 5307, "end": 6087 }
class ____(TypedDict, total=False): input: Required[Iterable[TestingCriterionLabelModelInput]] """A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. """ labels: Required[SequenceNotStr[str]] """The labels to classif...
TestingCriterionLabelModel