language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
getsentry__sentry
src/sentry/utils/snuba_rpc.py
{ "start": 2496, "end": 12165 }
class ____(Protocol): def SerializeToString(self, deterministic: bool = ...) -> bytes: ... @property def meta( self, ) -> ( sentry_protos.snuba.v1alpha.request_common_pb2.RequestMeta | sentry_protos.snuba.v1.request_common_pb2.RequestMeta ): ... def table_rpc(requests: lis...
SnubaRPCRequest
python
django-import-export__django-import-export
tests/core/tests/test_widgets.py
{ "start": 3760, "end": 5943 }
class ____(TestCase, RowDeprecationTestMixin): def setUp(self): self.date = date(2012, 8, 13) self.widget = widgets.DateWidget("%d.%m.%Y") def test_render(self): self.assertEqual(self.widget.render(self.date), "13.08.2012") def test_render_derived_date(self): derived_date =...
DateWidgetTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format19.py
{ "start": 315, "end": 1563 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format19.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.go...
TestCompareXLSXFiles
python
doocs__leetcode
solution/1300-1399/1385.Find the Distance Value Between Two Arrays/Solution.py
{ "start": 0, "end": 273 }
class ____: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: arr2.sort() ans = 0 for x in arr1: i = bisect_left(arr2, x - d) ans += i == len(arr2) or arr2[i] > x + d return ans
Solution
python
pytorch__pytorch
torch/distributed/_functional_collectives.py
{ "start": 32116, "end": 46275 }
class ____(torch.autograd.Function): """ _FromTorchTensor allows autograd to propagate from a normal Tensor to an AsyncCollectiveTensor. """ @staticmethod def forward( # type: ignore[override] ctx, # pyre-ignore[2]: Parameter must be annotated. input: torch.Tensor, ) -> to...
_FromTorchTensor
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 17878, "end": 18413 }
class ____(TestCurrencyProvider): """Test uk_UA currency provider.""" @classmethod def setup_class(cls): from faker.providers.currency.uk_UA import Provider as UkUaCurrencyProvider cls.provider = UkUaCurrencyProvider cls.currencies = cls.provider.currencies cls.cryptocurren...
TestUkUa
python
ray-project__ray
python/ray/train/v2/_internal/state/schema.py
{ "start": 4508, "end": 4735 }
class ____(BaseModel): """GPU usage statistics for a process.""" pid: int = Field(description="The process ID.") gpuMemoryUsage: int = Field(description="The GPU memory usage in bytes.") @DeveloperAPI
ProcessGPUUsage
python
kubernetes-client__python
kubernetes/client/models/v1beta1_volume_attributes_class.py
{ "start": 383, "end": 9693 }
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...
V1beta1VolumeAttributesClass
python
scipy__scipy
scipy/stats/tests/test_generation/reference_distributions.py
{ "start": 14851, "end": 15120 }
class ____(ReferenceDistribution): def __init(self, *, df): super().__init__(df=df) def _pdf(self, x, df): return (mp.gamma((df + mp.one)/2)/(mp.sqrt(df * mp.pi) * mp.gamma(df/2)) * (mp.one + x*x/df)**(-(df + mp.one)/2))
StudentT
python
django-crispy-forms__django-crispy-forms
crispy_forms/layout.py
{ "start": 28923, "end": 29428 }
class ____: """ Layout object. It can contain pure HTML and it has access to the whole context of the page where the form is being rendered. Examples:: HTML("{% if saved %}Data saved{% endif %}") HTML('<input type="hidden" name="{{ step_field }}" value="{{ step0 }}" />') """ d...
HTML
python
spyder-ide__spyder
spyder/api/widgets/mixins.py
{ "start": 13929, "end": 23367 }
class ____: """ Provide methods to create, add and get actions in a unified way. This mixin uses a custom action object. """ def _update_action_state(self, action_name, value): """ This allows to update the state of a togglable action without emitting signals. This...
SpyderActionMixin
python
walkccc__LeetCode
solutions/2204. Distance to a Cycle in Undirected Graph/2204.py
{ "start": 0, "end": 1432 }
class ____: def distanceToCycle(self, n: int, edges: list[list[int]]) -> list[int]: ans = [0] * n graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) NO_RANK = -2 # The minRank that u can reach with forward edges def getRank(u: int, currRank: ...
Solution
python
wandb__wandb
wandb/vendor/pygments/lexers/dylan.py
{ "start": 8300, "end": 8915 }
class ____(RegexLexer): """ For Dylan LID (Library Interchange Definition) files. .. versionadded:: 1.6 """ name = 'DylanLID' aliases = ['dylan-lid', 'lid'] filenames = ['*.lid', '*.hdp'] mimetypes = ['text/x-dylan-lid'] flags = re.IGNORECASE tokens = { 'root': [ ...
DylanLidLexer
python
marshmallow-code__apispec
src/apispec/ext/marshmallow/__init__.py
{ "start": 3578, "end": 8997 }
class ____(BasePlugin): """APISpec plugin for translating marshmallow schemas to OpenAPI/JSONSchema format. :param callable schema_name_resolver: Callable to generate the schema definition name. Receives the `Schema` class and returns the name to be used in refs within the generated spec. When ...
MarshmallowPlugin
python
python__mypy
mypy/types.py
{ "start": 16361, "end": 16962 }
class ____(Type): """Only used by find_isinstance_check() etc.""" __slots__ = ("type_guard",) def __init__(self, type_guard: Type) -> None: super().__init__(line=type_guard.line, column=type_guard.column) self.type_guard = type_guard def __repr__(self) -> str: return f"TypeGua...
TypeGuardedType
python
huggingface__transformers
src/transformers/models/dpr/tokenization_dpr.py
{ "start": 15041, "end": 15767 }
class ____(CustomDPRReaderTokenizerMixin, BertTokenizer): r""" Construct a DPRReader tokenizer. [`DPRReaderTokenizer`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and wordpiece. The difference is that is has three inputs strings: question, titles and...
DPRReaderTokenizer
python
walkccc__LeetCode
solutions/1240. Tiling a Rectangle with the Fewest Squares/1240.py
{ "start": 0, "end": 827 }
class ____: def tilingRectangle(self, n: int, m: int) -> int: @functools.lru_cache(None) def dp(heights: int) -> int: minHeight = min(heights) if minHeight == n: # All filled. return 0 ans = m * n heightsList = list(heights) start = heightsList.index(minHeight) #...
Solution
python
weaviate__weaviate-python-client
weaviate/collections/filters.py
{ "start": 526, "end": 6019 }
class ____: @overload @staticmethod def convert(weav_filter: Literal[None]) -> None: ... @overload @staticmethod def convert(weav_filter: _Filters) -> base_pb2.Filters: ... @staticmethod def convert(weav_filter: Optional[_Filters]) -> Optional[base_pb2.Filters]: if weav_filter ...
_FilterToGRPC
python
redis__redis-py
redis/asyncio/multidb/healthcheck.py
{ "start": 1988, "end": 2859 }
class ____(AbstractHealthCheckPolicy): """ Policy that returns True if all health check probes are successful. """ def __init__(self, health_check_probes: int, health_check_delay: float): super().__init__(health_check_probes, health_check_delay) async def execute(self, health_checks: List[...
HealthyAllPolicy
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_impls.py
{ "start": 8875, "end": 13316 }
class ____( NamedTuple( "_AutoMaterializeAssetPartitionsFilter", [("latest_run_required_tags", Optional[Mapping[str, str]])], ) ): """A filter that can be applied to an asset partition, during auto-materialize evaluation, and returns a boolean for whether it passes. Args: la...
AutoMaterializeAssetPartitionsFilter
python
pypa__hatch
src/hatch/cli/terminal.py
{ "start": 3982, "end": 13075 }
class ____: def __init__(self, *, verbosity: int, enable_color: bool | None, interactive: bool | None): # Force consistent output for test assertions self.testing = "HATCH_SELF_TESTING" in os.environ self.verbosity = verbosity self.console = Console( force_terminal=enabl...
Terminal
python
astropy__astropy
astropy/visualization/wcsaxes/ticks.py
{ "start": 240, "end": 6582 }
class ____(Line2D): """ Ticks are derived from Line2D, and note that ticks themselves are markers. Thus, you should use set_mec, set_mew, etc. To change the tick size (length), you need to use set_ticksize. To change the direction of the ticks (ticks are in opposite direction of ticklabels by d...
Ticks
python
run-llama__llama_index
llama-index-packs/llama-index-packs-gmail-openai-agent/llama_index/packs/gmail_openai_agent/base.py
{ "start": 296, "end": 1234 }
class ____(BaseLlamaPack): def __init__(self, gmail_tool_kwargs: Dict[str, Any]) -> None: """Init params.""" try: from llama_index.tools.google import GmailToolSpec except ImportError: raise ImportError("llama_hub not installed.") self.tool_spec = GmailToolSp...
GmailOpenAIAgentPack
python
walkccc__LeetCode
solutions/2065. Maximum Path Quality of a Graph/2065-2.py
{ "start": 0, "end": 723 }
class ____: def maximalPathQuality( self, values: list[int], edges: list[list[int]], maxTime: int, ) -> int: ans = 0 graph = [[] for _ in range(len(values))] # (node, quality, remainingTime, seen) q = collections.deque([(0, values[0], maxTime, {0})]) for u, v, time in ed...
Solution
python
django__django
tests/custom_lookups/tests.py
{ "start": 1143, "end": 1518 }
class ____(models.Transform): lookup_name = "div3" def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) return "(%s) %%%% 3" % lhs, lhs_params def as_oracle(self, compiler, connection, **extra_context): lhs, lhs_params = compiler.compile(self.lhs) ...
Div3Transform
python
getsentry__sentry
tests/sentry/issues/auto_source_code_config/test_process_event.py
{ "start": 17650, "end": 17899 }
class ____(BaseDeriveCodeMappings): @property def platform(self) -> str: raise NotImplementedError @property def frames(self) -> list[dict[str, str | bool]]: raise NotImplementedError
LanguageSpecificDeriveCodeMappings
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 60529, "end": 66453 }
class ____(ExtensionType): oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT def __init__( self, full_name: Iterable[GeneralName] | None, relative_name: RelativeDistinguishedName | None, only_contains_user_certs: bool, only_contains_ca_certs: bool, only_some_reasons:...
IssuingDistributionPoint
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP037_3.py
{ "start": 311, "end": 478 }
class ____: _singleton: ClassVar[Optional["EmptyCell"]] = None # the behavior of _singleton above should match a non-ClassVar _doubleton: "EmptyCell"
EmptyCell
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_changed_validator.py
{ "start": 3022, "end": 3256 }
class ____: def test_extract_class_with_docstring(self): with tempfile.TemporaryDirectory() as temp_dir: test_file = Path(temp_dir) / "test_module.py" test_file.write_text('''
TestExtractSymbolsFromFile
python
scipy__scipy
scipy/odr/_odrpack.py
{ "start": 5422, "end": 10676 }
class ____: """ The data to fit. Parameters ---------- x : array_like Observed data for the independent variable of the regression y : array_like, optional If array-like, observed data for the dependent variable of the regression. A scalar input implies that the model to...
Data
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py
{ "start": 800, "end": 846 }
class ____(Generic[AnyStr]): s: AnyStr
MyStr
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 44824, "end": 46463 }
class ____(_CompositeTestBase, fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("x", Integer), ...
MutableInheritedCompositesTest
python
walkccc__LeetCode
solutions/1121. Divide Array Into Increasing Sequences/1121.py
{ "start": 0, "end": 435 }
class ____: def canDivideIntoSubsequences(self, nums: list[int], k: int) -> bool: # Find the number with the maxFreq, we need at least maxFreq * k elements # e.g. nums = [1, 2, 2, 3, 4], we have maxFreq = 2 (two 2s), so we have to # Split nums into two subsequences say k = 3, the minimum length of nums is...
Solution
python
ipython__ipython
tests/test_interactiveshell.py
{ "start": 24395, "end": 24832 }
class ____(ExitCodeChecks): def setUp(self): super().setUp() self.system = ip.system_piped @skip_win32 def test_exit_code_ok(self): ExitCodeChecks.test_exit_code_ok(self) @skip_win32 def test_exit_code_error(self): ExitCodeChecks.test_exit_code_error(self) @ski...
TestSystemPipedExitCode
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/utils.py
{ "start": 5709, "end": 6336 }
class ____(QtCore.QObject): sigFpsUpdate = QtCore.Signal(object) def __init__(self, interval=1000): super().__init__() self.count = 0 self.last_update = 0 self.interval = interval def update(self): self.count += 1 if self.last_update == 0: self....
FrameCounter
python
python__mypy
mypyc/test-data/fixtures/ir.py
{ "start": 673, "end": 821 }
class ____(Protocol[T_contra, T_co]): def __rdivmod__(self, other: T_contra) -> T_co: ... _M = TypeVar("_M", contravariant=True)
__SupportsRDivMod
python
keras-team__keras
keras/src/layers/preprocessing/feature_space.py
{ "start": 30303, "end": 30373 }
class ____(DataLayer): def call(self, x): return x
TFDIdentity
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 89487, "end": 90171 }
class ____(ScaledMMConfigMixin, CPUConfigHeuristic): """Scaled MM template heuristic for CPU (non-TMA)""" def __init__(self) -> None: super().__init__() # Override mm_configs to use scaled_mm_configs self.mm_configs = self.scaled_mm_configs # NOTE: overriding exhaustive configs ...
CPUScaledMMTemplateConfigHeuristic
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 80914, "end": 92105 }
class ____(compiler.DDLCompiler): def get_column_specification(self, column, **kwargs): colspec = self.preparer.format_column(column) # type is not accepted in a computed column if column.computed is not None: colspec += " " + self.process(column.computed) else: ...
MSDDLCompiler
python
doocs__leetcode
solution/2600-2699/2660.Determine the Winner of a Bowling Game/Solution.py
{ "start": 0, "end": 410 }
class ____: def isWinner(self, player1: List[int], player2: List[int]) -> int: def f(arr: List[int]) -> int: s = 0 for i, x in enumerate(arr): k = 2 if (i and arr[i - 1] == 10) or (i > 1 and arr[i - 2] == 10) else 1 s += k * x return s ...
Solution
python
pytorch__pytorch
torch/distributed/fsdp/_common_utils.py
{ "start": 6720, "end": 22547 }
class ____(Enum): """ An enum that indicates the state of a ``FlatParamHandle`. """ IDLE = auto() FORWARD = auto() BACKWARD_PRE = auto() BACKWARD_POST = auto() SUMMON_FULL_PARAMS = auto() def _is_composable(state: _FSDPState): # TODO: This is a temporary hack for differentiate bet...
HandleTrainingState
python
pola-rs__polars
py-polars/src/polars/expr/whenthen.py
{ "start": 3412, "end": 4305 }
class ____: """ Utility class for the `when-then-otherwise` expression. Represents the state of the expression after an additional `when` is called. In this state, `then` must be called to continue to finish the expression. """ def __init__(self, chained_when: Any) -> None: self._chai...
ChainedWhen
python
doocs__leetcode
solution/1600-1699/1630.Arithmetic Subarrays/Solution.py
{ "start": 0, "end": 485 }
class ____: def checkArithmeticSubarrays( self, nums: List[int], l: List[int], r: List[int] ) -> List[bool]: def check(nums, l, r): n = r - l + 1 s = set(nums[l : l + n]) a1, an = min(nums[l : l + n]), max(nums[l : l + n]) d, mod = divmod(an - a1, ...
Solution
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 41360, "end": 43265 }
class ____(TestCase): """Tests for ``side_effect()``""" def test_individual(self): # The function increments the counter for each call counter = [0] def func(arg): counter[0] += 1 result = list(mi.side_effect(func, range(10))) self.assertEqual(result, list(...
SideEffectTests
python
modin-project__modin
modin/core/dataframe/pandas/metadata/index.py
{ "start": 981, "end": 12390 }
class ____: """ A class that hides the various implementations of the index needed for optimization. Parameters ---------- value : sequence, PandasDataframe or callable() -> (pandas.Index, list of ints), optional If a sequence passed this will be considered as the index values. If a...
ModinIndex
python
pytorch__pytorch
test/fx/quantization.py
{ "start": 1778, "end": 2193 }
class ____(MinMaxObserver): def quantize(self, quantizer, node, load_arg): if not self.all_tensors: return NotImplemented scale, zeropoint = self.scale_zeropoint() return quantizer.quantized_graph.create_node( "call_function", torch.ops.quantized.add, ...
Add
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 15322, "end": 15950 }
class ____: """ TensorMetadata plus the elements as a list of raw values. Used for hashing inlined constants. """ tensor_metadata: TensorMetadata values: list[Any] def _ident(x: T) -> T: return x def extract_tensor_metadata_for_cache_key(t: Tensor) -> TensorMetadata: """ Extract...
TensorMetadataAndValues
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared_tests/test_check.py
{ "start": 29324, "end": 33930 }
class ____(collections.abc.Mapping): def __init__(self, **kwargs): self._dict = dict() for key, value in kwargs.items(): self._dict[key] = value def __getitem__(self, key): return self._dict[key] def __iter__(self): return iter(self._dict) def __len__(self)...
SimpleMapping
python
getsentry__sentry
tests/sentry/utils/test_circuit_breaker2.py
{ "start": 893, "end": 4293 }
class ____(CircuitBreaker): """ A circuit breaker with extra methods useful for mocking state. To understand the methods below, it helps to understand the `RedisSlidingWindowRateLimiter` which powers the circuit breaker. Details can be found in https://github.com/getsentry/sentry-redis-tools/blob/d...
MockCircuitBreaker
python
openai__openai-python
src/openai/resources/fine_tuning/jobs/checkpoints.py
{ "start": 3612, "end": 6476 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCheckpointsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://ww...
AsyncCheckpoints
python
pydantic__pydantic
tests/mypy/modules/generics.py
{ "start": 405, "end": 764 }
class ____(Response[HtmlBody]): def custom_method(self) -> None: doctype = self.body.doctype print(f'self: {doctype}') example = {'url': 'foo.com', 'body': {'raw': '..<html>..', 'doctype': 'html'}} resp = HtmlResponse.model_validate(example) resp.custom_method() assert_type(resp.body, HtmlBody) ...
HtmlResponse
python
django__django
tests/delete_regress/tests.py
{ "start": 14357, "end": 14614 }
class ____(SimpleTestCase): def test_disallowed_delete_distinct_on(self): msg = "Cannot call delete() after .distinct(*fields)." with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct("id").delete()
DeleteDistinct
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassConverter2.py
{ "start": 1530, "end": 1670 }
class ____(ModelBase): b: tuple[int, ...] = model_field(converter=tuple) DC3([1, 2, 3]) # This should generate an error. DC3(["", 1])
DC3
python
getsentry__sentry
tests/sentry/receivers/test_sentry_apps.py
{ "start": 8176, "end": 10663 }
class ____(APITestCase): def setUp(self) -> None: self.issue = self.create_group(project=self.project) self.sentry_app = self.create_sentry_app(events=["issue.assigned"]) self.install = self.create_sentry_app_installation( organization=self.organization, slug=self.sentry_app.sl...
TestIssueAssigned
python
getsentry__sentry
src/sentry/auth_v2/endpoints/feature_flag_view.py
{ "start": 417, "end": 1042 }
class ____(AuthV2Endpoint): owner = ApiOwner.ENTERPRISE publish_status = {"GET": ApiPublishStatus.EXPERIMENTAL} enforce_rate_limit = True rate_limits = RateLimitConfig( limit_overrides={ "GET": {RateLimitCategory.IP: RateLimit(limit=30, window=60)} # 30 per minute per IP } ...
FeatureFlagView
python
tensorflow__tensorflow
tensorflow/python/trackable/base.py
{ "start": 2474, "end": 3105 }
class ____(TrackableReference): """TrackableReference that stores weak references.""" __slots__ = () def __init__(self, name, ref): if not isinstance(ref, weakref.ref): ref = weakref.ref(ref) super(WeakTrackableReference, self).__init__(name=name, ref=ref) @property def ref(self): return s...
WeakTrackableReference
python
fsspec__filesystem_spec
fsspec/implementations/tests/conftest.py
{ "start": 257, "end": 941 }
class ____(LocalFileSystem): protocol = ["file", "other"] FILESYSTEMS = { "local": LocalFileSystem, "multi": MultiProtocolFileSystem, "memory": MemoryFileSystem, } READ_ONLY_FILESYSTEMS = [] @pytest.fixture(scope="function") def fs(request): pyarrow_fs = pytest.importorskip("pyarrow.fs") Fi...
MultiProtocolFileSystem
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 32388, "end": 36316 }
class ____(SingleContinuousDistribution): _argnames = ('mean', 'std', 'rate') set = Interval(-oo, oo) @staticmethod def check(mean, std, rate): _value_check( std > 0, "Standard deviation of ExGaussian must be positive.") _value_check(rate > 0, "Rate of ExGaussian must be po...
ExGaussianDistribution
python
imageio__imageio
imageio/plugins/tifffile.py
{ "start": 7905, "end": 20664 }
class ____(Format): """Provides support for a wide range of Tiff images using the tifffile backend. Images that contain multiple pages can be read using ``imageio.mimread()`` to read the individual pages, or ``imageio.volread()`` to obtain a single (higher dimensional) array. Note that global ...
TiffFormat
python
ray-project__ray
python/ray/dashboard/modules/job/tests/test_utils.py
{ "start": 2383, "end": 2918 }
class ____: async def test_basic(self): request = MockRequest(entrypoint="echo hi") expected = JobSubmitRequest(entrypoint="echo hi") assert await parse_and_validate_request(request, JobSubmitRequest) == expected async def test_forward_compatibility(self): request = MockRequest(...
TestParseAndValidateRequest
python
Netflix__metaflow
metaflow/plugins/cards/card_modules/card.py
{ "start": 3385, "end": 4627 }
class ____(object): # Setting REALTIME_UPDATABLE as True will allow metaflow to update the card # during Task runtime. REALTIME_UPDATABLE = False _component_id = None _logger = None @property def component_id(self): return self._component_id @component_id.setter def comp...
MetaflowCardComponent
python
doocs__leetcode
solution/2900-2999/2974.Minimum Number Game/Solution.py
{ "start": 0, "end": 250 }
class ____: def numberGame(self, nums: List[int]) -> List[int]: heapify(nums) ans = [] while nums: a, b = heappop(nums), heappop(nums) ans.append(b) ans.append(a) return ans
Solution
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 38516, "end": 69530 }
class ____(PatternEntry): """ The replacement pattern for the graph """ normalize_args: Callable[..., list[Any]] @staticmethod def replace_with_graph( match: Match, graph: torch.fx.Graph, replacement_graph: Union[torch.fx.Graph, torch.fx.GraphModule], args: Sequ...
ReplacementPatternEntry
python
getsentry__sentry
tests/sentry/data_secrecy/test_types.py
{ "start": 7277, "end": 7903 }
class ____(TestCase): def test_grant_cache_status_values(self) -> None: """Test that GrantCacheStatus enum has expected values""" assert GrantCacheStatus.CACHE_MISS == "cache_miss" assert GrantCacheStatus.NEGATIVE_CACHE == "negative_cache" assert GrantCacheStatus.VALID_WINDOW == "val...
GrantCacheStatusTest
python
ray-project__ray
python/ray/data/_internal/execution/operators/join.py
{ "start": 1631, "end": 14812 }
class ____(StatefulShuffleAggregation): """Aggregation performing distributed joining of the 2 sequences, by utilising hash-based shuffling. Hash-based shuffling applied to 2 input sequences and employing the same partitioning scheme allows to - Accumulate identical keys from both sequences in...
JoiningShuffleAggregation
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/components.py
{ "start": 959, "end": 2641 }
class ____(RecordFilter): """ Filter duplicated records based on the "Id" field. This can happen when we use predicates that could match the same record multiple times. e.g. With one record like: {"type":"RECORD","record":{"stream":"accounts","data":{"Id":151049662, "Name":"Airbyte Plum...
DuplicatedRecordsFilter
python
wandb__wandb
wandb/sdk/lib/timer.py
{ "start": 37, "end": 440 }
class ____: def __init__(self) -> None: self.start_time: float = time.time() self.start: float = time.perf_counter() self.stop: float = self.start def __enter__(self) -> "Timer": return self def __exit__(self, *args: Any) -> None: self.stop = time.perf_counter() ...
Timer
python
huggingface__transformers
tests/models/luke/test_modeling_luke.py
{ "start": 33771, "end": 37018 }
class ____(unittest.TestCase): @slow def test_inference_base_model(self): model = LukeModel.from_pretrained("studio-ousia/luke-base").eval() model.to(torch_device) tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", task="entity_classification") text = ( ...
LukeModelIntegrationTests
python
neetcode-gh__leetcode
python/1254-number-of-closed-islands.py
{ "start": 0, "end": 781 }
class ____: def closedIsland(self, grid: List[List[int]]) -> int: r = len(grid) c = len(grid[0]) seen = set() def dfs(x, y): if x < 0 or x >= r or y < 0 or y >= c or (x, y) in seen or grid[x][y] == 1: return seen.add((x, y)) grid[x...
Solution
python
kamyu104__LeetCode-Solutions
Python/largest-substring-between-two-equal-characters.py
{ "start": 29, "end": 318 }
class ____(object): def maxLengthBetweenEqualCharacters(self, s): """ :type s: str :rtype: int """ result, lookup = -1, {} for i, c in enumerate(s): result = max(result, i-lookup.setdefault(c, i)-1) return result
Solution
python
huggingface__transformers
src/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py
{ "start": 764, "end": 5820 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`XLMRobertaXLModel`]. It is used to instantiate a XLM_ROBERTA_XL model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a s...
XLMRobertaXLConfig
python
facelessuser__soupsieve
tests/test_level1/test_pseudo_class.py
{ "start": 103, "end": 495 }
class ____(util.TestCase): """Test pseudo-classes.""" def test_pseudo_class_not_implemented(self): """Test pseudo-class that is not implemented.""" self.assert_raises(':not-implemented', SelectorSyntaxError) def test_unrecognized_pseudo(self): """Test unrecognized pseudo class."""...
TestPseudoClass
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py
{ "start": 19622, "end": 22282 }
class ____: """Test camelize_dict_keys function.""" def test_camelize_flat_dict(self): """Test camelizing keys in a flat dictionary.""" input_dict = {"test_key": "value", "another_key": "value2"} expected = {"testKey": "value", "anotherKey": "value2"} assert camelize_dict_keys(i...
TestCamelizeDictKeys
python
doocs__leetcode
solution/0300-0399/0372.Super Pow/Solution.py
{ "start": 0, "end": 226 }
class ____: def superPow(self, a: int, b: List[int]) -> int: mod = 1337 ans = 1 for e in b[::-1]: ans = ans * pow(a, e, mod) % mod a = pow(a, 10, mod) return ans
Solution
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source.py
{ "start": 3015, "end": 3241 }
class ____(BaseModel): text: str """The text output from the model.""" type: Literal["output_text"] """The type of the output text. Always `output_text`."""
InputMessagesTemplateTemplateEvalItemContentOutputText
python
Textualize__textual
src/textual/widget.py
{ "start": 6561, "end": 6622 }
class ____(Exception): """Base widget error."""
WidgetError
python
tensorflow__tensorflow
tensorflow/python/framework/tensor.py
{ "start": 28615, "end": 30812 }
class ____(type_spec.TypeSpec): """Describes a dense object with shape, dtype, and name.""" __slots__ = ["_shape", "_dtype", "_name"] _component_specs = property(lambda self: self) def __init__(self, shape, dtype=dtypes.float32, name=None): """Creates a TensorSpec. Args: shape: Value convertib...
DenseSpec
python
django__django
tests/db_functions/text/test_repeat.py
{ "start": 186, "end": 1276 }
class ____(TestCase): def test_basic(self): Author.objects.create(name="John", alias="xyz") none_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) tests = ( (Repeat("name", 0), ""), (Repeat("name", 2), "JohnJohn"), ...
RepeatTests
python
huggingface__transformers
src/transformers/models/grounding_dino/modeling_grounding_dino.py
{ "start": 49054, "end": 54747 }
class ____(nn.Module): def __init__(self, config: GroundingDinoConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = GroundingDinoMultiscaleDeformableAttention( config, num_heads=config.encoder_attention_heads, n_points=config.encoder_n_points ) ...
GroundingDinoDeformableLayer
python
redis__redis-py
redis/asyncio/multidb/command_executor.py
{ "start": 3562, "end": 11856 }
class ____(BaseCommandExecutor, AsyncCommandExecutor): def __init__( self, failure_detectors: List[AsyncFailureDetector], databases: Databases, command_retry: Retry, failover_strategy: AsyncFailoverStrategy, event_dispatcher: EventDispatcherInterface, failover...
DefaultCommandExecutor
python
plotly__plotly.py
plotly/graph_objs/scatterpolar/_line.py
{ "start": 233, "end": 8428 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolar" _path_str = "scatterpolar.line" _valid_props = { "backoff", "backoffsrc", "color", "dash", "shape", "smoothing", "width", } @property def backoff(self): """ ...
Line
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 14513, "end": 15183 }
class ____(MarkdownList): """A Bullet list Markdown block.""" DEFAULT_CSS = """ MarkdownBulletList { margin: 0 0 1 0; padding: 0 0; } MarkdownBulletList Horizontal { height: auto; width: 1fr; } MarkdownBulletList Vertical { height: auto; wid...
MarkdownBulletList
python
haoel__leetcode
algorithms/python/ConvertBSTtoGreaterTree/convertBST.py
{ "start": 151, "end": 468 }
class ____: def convertBST(self, root): self.total = 0 def helper(node): if not node: return helper(node.right) node.val += self.total self.total = node.val helper(node.left) helper(root) return root
Solution
python
Textualize__textual
src/textual/lazy.py
{ "start": 113, "end": 1966 }
class ____(Widget): """Wraps a widget so that it is mounted *lazily*. Lazy widgets are mounted after the first refresh. This can be used to display some parts of the UI very quickly, followed by the lazy widgets. Technically, this won't make anything faster, but it reduces the time the user sees a blan...
Lazy
python
openai__openai-python
src/openai/types/beta/threads/runs/code_interpreter_output_image.py
{ "start": 242, "end": 408 }
class ____(BaseModel): file_id: Optional[str] = None """ The [file](https://platform.openai.com/docs/api-reference/files) ID of the image. """
Image
python
dagster-io__dagster
python_modules/libraries/dagster-openai/dagster_openai/resources.py
{ "start": 5469, "end": 15804 }
class ____(ConfigurableResource): """This resource is wrapper over the `openai library <https://github.com/openai/openai-python>`_. By configuring this OpenAI resource, you can interact with OpenAI API and log its usage metadata in the asset metadata. Examples: .. code-block:: python ...
OpenAIResource
python
getsentry__sentry
tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py
{ "start": 76750, "end": 77259 }
class ____(AlertRuleCreateEndpointTestCrashRateAlert): method = "post" def setUp(self) -> None: super().setUp() self.valid_alert_rule["dataset"] = Dataset.Metrics.value for tag in [ SessionMRI.RAW_SESSION.value, SessionMRI.RAW_USER.value, "session.sta...
MetricsCrashRateAlertCreationTest
python
altair-viz__altair
tools/datasets/npm.py
{ "start": 857, "end": 3332 }
class ____: """https://www.jsdelivr.com/docs/data.jsdelivr.com#overview.""" _opener: ClassVar[OpenerDirector] = urllib.request.build_opener() def __init__( self, paths: PathMap, *, jsdelivr: Literal["jsdelivr"] = "jsdelivr", npm: Literal["npm"] = "npm", pack...
Npm
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/formatters/latex.py
{ "start": 16227, "end": 19306 }
class ____(Lexer): """ This lexer takes one lexer as argument, the lexer for the language being formatted, and the left and right delimiters for escaped text. First everything is scanned using the language lexer to obtain strings and comments. All other consecutive tokens are merged and the res...
LatexEmbeddedLexer
python
lazyprogrammer__machine_learning_examples
rl2/mountaincar/pg_tf_random.py
{ "start": 1388, "end": 7322 }
class ____: def __init__(self, ft, D, hidden_layer_sizes_mean=[], hidden_layer_sizes_var=[]): # save inputs for copy self.ft = ft self.D = D self.hidden_layer_sizes_mean = hidden_layer_sizes_mean self.hidden_layer_sizes_var = hidden_layer_sizes_var ##### model the mean ##### self.mean_la...
PolicyModel
python
run-llama__llama_index
llama-index-core/llama_index/core/node_parser/relational/hierarchical.py
{ "start": 2524, "end": 8529 }
class ____(NodeParser): """ Hierarchical node parser. Splits a document into a recursive hierarchy Nodes using a NodeParser. NOTE: this will return a hierarchy of nodes in a flat list, where there will be overlap between parent nodes (e.g. with a bigger chunk size), and child nodes per parent ...
HierarchicalNodeParser
python
doocs__leetcode
solution/3700-3799/3718.Smallest Missing Multiple of K/Solution.py
{ "start": 0, "end": 202 }
class ____: def missingMultiple(self, nums: List[int], k: int) -> int: s = set(nums) for i in count(1): x = k * i if x not in s: return x
Solution
python
pydantic__pydantic
pydantic-core/tests/test_json.py
{ "start": 12122, "end": 16977 }
class ____(metaclass=BedReprMeta): def __repr__(self): raise ValueError('bad repr') def __hash__(self): return 1 def test_bad_repr(): b = BadRepr() error_msg = '^Unable to serialize unknown type: <unprintable BedReprMeta object>$' with pytest.raises(PydanticSerializationError, ma...
BadRepr
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-form-a-target-string-given-a-dictionary.py
{ "start": 167, "end": 781 }
class ____(object): def numWays(self, words, target): """ :type words: List[str] :type target: str :rtype: int """ MOD = 10**9+7 dp = [0]*(len(target)+1) dp[0] = 1 for i in xrange(len(words[0])): count = collections.Counter(w[i] for...
Solution
python
google__pytype
pytype/rewrite/abstract/functions.py
{ "start": 11103, "end": 16808 }
class ____: """Representation of a Python function signature. Attributes: name: Name of the function. param_names: A tuple of positional parameter names. This DOES include positional-only parameters and does NOT include keyword-only parameters. posonly_count: Number of positional-only parameters....
Signature
python
fluentpython__example-code
20-descriptor/bulkfood/bulkfood_v3.py
{ "start": 1080, "end": 1410 }
class ____: weight = Quantity('weight') # <5> price = Quantity('price') # <6> def __init__(self, description, weight, price): # <7> self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.price # END LINEIT...
LineItem
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ArrowItem.py
{ "start": 115, "end": 5412 }
class ____(QtWidgets.QGraphicsPathItem): """ For displaying scale-invariant arrows. For arrows pointing to a location on a curve, see CurveArrow """ def __init__(self, parent=None, **opts): """ Arrows can be initialized with any keyword arguments accepted by t...
ArrowItem
python
pydantic__pydantic
pydantic/v1/dataclasses.py
{ "start": 661, "end": 8295 }
class ____: x: int ValidatedM = pydantic.dataclasses.dataclass(M) ``` We indeed still want to support equality, hashing, repr, ... as if it was the stdlib one! ```py assert isinstance(ValidatedM(x=1), M) assert ValidatedM(x=1) == M(x=1) ``` This means we **don't want to create a new dataclass that inherits from...
M
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/leaf_adds_virtual/package.py
{ "start": 216, "end": 486 }
class ____(Package): url = "http://www.example.com/" url = "http://www.example.com/2.0.tar.gz" version("2.0", md5="abcdef1234567890abcdef1234567890") version("1.0", md5="abcdef1234567890abcdef1234567890") depends_on("blas", when="@2.0")
LeafAddsVirtual
python
pytransitions__transitions
tests/test_async.py
{ "start": 941, "end": 28883 }
class ____(TestTransitions): @staticmethod async def await_false(): await asyncio.sleep(0.1) return False @staticmethod async def await_true(): await asyncio.sleep(0.1) return True @staticmethod async def cancel_soon(): await asyncio.sleep(1) ra...
TestAsync