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
aimacode__aima-python
utils.py
{ "start": 19555, "end": 21732 }
class ____: """A Queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is 'min', the item with minimum f(x) is returned first; if order is 'max', then it is the item with maximum f(x). Also supports dict-like lookup.""" def __init__(self, ord...
PriorityQueue
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-upgradable-servers.py
{ "start": 55, "end": 564 }
class ____(object): def maxUpgrades(self, count, upgrade, sell, money): """ :type count: List[int] :type upgrade: List[int] :type sell: List[int] :type money: List[int] :rtype: List[int] """ # let x be the number of sold servers # (c-x)*u <= m+...
Solution
python
pyca__cryptography
src/cryptography/hazmat/primitives/_cipheralgorithm.py
{ "start": 356, "end": 882 }
class ____(metaclass=abc.ABCMeta): @property @abc.abstractmethod def name(self) -> str: """ A string naming this mode (e.g. "AES", "Camellia"). """ @property @abc.abstractmethod def key_sizes(self) -> frozenset[int]: """ Valid key sizes for this algorithm...
CipherAlgorithm
python
PyCQA__pylint
doc/data/messages/t/too-many-public-methods/good.py
{ "start": 229, "end": 281 }
class ____: def launch(self): pass
Missile
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/event_frequency_query_handlers.py
{ "start": 1960, "end": 11293 }
class ____(ABC): intervals: ClassVar[dict[str, tuple[str, timedelta]]] = STANDARD_INTERVALS def get_query_window(self, end: datetime, duration: timedelta) -> tuple[datetime, datetime]: """ Calculate the start and end times for the query. "duration" is the length of the window we're quer...
BaseEventFrequencyQueryHandler
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/serialized_objects.py
{ "start": 8335, "end": 12131 }
class ____(Generic[T_EntityKey]): """Incremental state calculated during the evaluation of a AutomationCondition. This may be used on the subsequent evaluation to make the computation more efficient. Args: previous_requested_subset: The subset that was requested for this asset on the previous tick....
AutomationConditionCursor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-search-console/components.py
{ "start": 2994, "end": 4624 }
class ____(RecordTransformation): """ A record transformation that remaps each value in the keys array back to its associated dimension. The reason this is a custom component is because we're unable to use list comprehension and and enumerate() is not a valid function in our Jinja contact so can't i...
CustomReportExtractDimensionsFromKeys
python
sphinx-doc__sphinx
tests/roots/test-ext-inheritance_diagram/test.py
{ "start": 91, "end": 132 }
class ____(DocSubDir1): pass
DocSubDir2
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/zero_scrollbar_size.py
{ "start": 80, "end": 314 }
class ____(App): DEFAULT_CSS = """ Screen { scrollbar-size: 0 0; } """ def compose(self) -> ComposeResult: yield Static("Hello, world!\n" * 100) if __name__ == "__main__": TestApp().run()
TestApp
python
doocs__leetcode
solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/Solution.py
{ "start": 0, "end": 1050 }
class ____: def minDays(self, grid: List[List[int]]) -> int: if self.count(grid) != 1: return 0 m, n = len(grid), len(grid[0]) for i in range(m): for j in range(n): if grid[i][j] == 1: grid[i][j] = 0 if self.coun...
Solution
python
bottlepy__bottle
test/test_multipart.py
{ "start": 2410, "end": 7812 }
class ____(BaseMultipartTest): def assertIterline(self, data, *expected, **options): self.assertEqual( list(bottle._MultipartParser(BytesIO(bottle.tob(data)), 'foo', **options)._lineiter()), [(bottle.tob(l), bottle.tob(nl)) for l,nl in expected]) def test_iterlines(self): ...
TestMultipartParser
python
ansible__ansible
lib/ansible/module_utils/facts/network/netbsd.py
{ "start": 1643, "end": 1748 }
class ____(NetworkCollector): _fact_class = NetBSDNetwork _platform = 'NetBSD'
NetBSDNetworkCollector
python
MongoEngine__mongoengine
tests/fields/test_datetime_field.py
{ "start": 6498, "end": 7102 }
class ____(MongoDBTestCase): def test_datetime_tz_aware_mark_as_changed(self): # Reset the connections connection._connection_settings = {} connection._connections = {} connection._dbs = {} connect(db="mongoenginetest", tz_aware=True) class LogEntry(Document): ...
TestDateTimeTzAware
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_percent_diff_greater_than_or_equal_to_threshold.py
{ "start": 7758, "end": 15049 }
class ____( ProfileNumericColumnsDiffExpectation ): """Expect a statistic's percent delta for a given column of a DataProfiler percent difference report to be greater than or equal to the specified threshold. This expectation takes the percent difference report between the data it is called on and a DataPr...
ExpectProfileNumericColumnsPercentDiffGreaterThanOrEqualToThreshold
python
jazzband__django-oauth-toolkit
tests/test_authorization_code.py
{ "start": 20771, "end": 26701 }
class ____(BaseTest): def test_login(self): """ Test login page is rendered if user is not authenticated """ self.oauth2_settings.PKCE_REQUIRED = False query_data = { "client_id": self.application.client_id, "response_type": "code", "state...
TestOIDCAuthorizationCodeView
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/naming_test.py
{ "start": 819, "end": 1750 }
class ____(test.TestCase): def test_new_symbol_tracks_names(self): namer = naming.Namer({}) self.assertEqual('temp', namer.new_symbol('temp', set())) self.assertItemsEqual(('temp',), namer.generated_names) def test_new_symbol_avoids_duplicates(self): namer = naming.Namer({}) self.assertEqual('...
NamerTest
python
huggingface__transformers
tests/models/segformer/test_modeling_segformer.py
{ "start": 13684, "end": 18634 }
class ____(unittest.TestCase): @slow def test_inference_image_segmentation_ade(self): # only resize + normalize image_processor = SegformerImageProcessor( image_scale=(512, 512), keep_ratio=False, align=False, do_random_crop=False ) model = SegformerForSemanticSegment...
SegformerModelIntegrationTest
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 7635, "end": 8243 }
class ____(nodes.Part, nodes.Inline, nodes.FixedTextElement): """Node for a general type parameter list. As default the type parameters list is written in line with the rest of the signature. Set ``multi_line_parameter_list = True`` to describe a multi-line type parameters list. In that case each type ...
desc_type_parameter_list
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 561479, "end": 561804 }
class ____(sgqlc.types.Type): """Autogenerated return type of DeleteRef""" __schema__ = github_schema __field_names__ = ("client_mutation_id",) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
DeleteRefPayload
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 22310, "end": 24272 }
class ____( NamedTuple( "_ExpectationResult", [ ("success", PublicAttr[bool]), ("label", PublicAttr[Optional[str]]), ("description", PublicAttr[Optional[str]]), ("metadata", PublicAttr[Mapping[str, MetadataValue]]), ], ) ): """Event cor...
ExpectationResult
python
aio-libs__aiohttp
tests/test_proxy_functional.py
{ "start": 670, "end": 32209 }
class ____(TypedDict): status: int headers: dict[str, str] | None body: bytes | None if sys.version_info >= (3, 11) and TYPE_CHECKING: from typing import Unpack async def get_request( method: str = "GET", *, url: str | URL, trust_env: bool = False, **kwargs...
_ResponseArgs
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 29129, "end": 31270 }
class ____(Response): """ :param scroll_id: Scroll ID for getting more results :type scroll_id: str :param metrics: Debug image events grouped by tasks and iterations :type metrics: Sequence[DebugImagesResponseTaskMetrics] """ _service = "events" _action = "debug_images" _version = ...
DebugImagesResponse
python
pydantic__pydantic
tests/mypy/outputs/mypy-default_ini/plugin_success.py
{ "start": 6696, "end": 6953 }
class ____(BaseModel): model_config = ConfigDict(validate_by_alias=False, validate_by_name=True) my_field: str = Field(alias='my_alias') m1 = Model1(my_field='foo') # MYPY: error: Unexpected keyword argument "my_field" for "Model1" [call-arg]
Model1
python
django__django
tests/template_tests/test_base.py
{ "start": 1614, "end": 2151 }
class ____(SimpleTestCase): def test_lazy_template_string(self): template_string = gettext_lazy("lazy string") self.assertEqual(Template(template_string).render(Context()), template_string) def test_repr(self): template = Template( "<html><body>\n" "{% if test %}...
TemplateTests
python
davidhalter__jedi
jedi/inference/gradual/typing.py
{ "start": 8802, "end": 8912 }
class ____(ProxyTypingValue, _TypingClassMixin): index_class = TypingClassWithGenerics
ProxyTypingClassValue
python
realpython__materials
python-import/finders_and_loaders/ban_importer.py
{ "start": 57, "end": 273 }
class ____: @classmethod def find_spec(cls, name, path, target=None): if name in BANNED_MODULES: raise ModuleNotFoundError(f"{name!r} is banned") sys.meta_path.insert(0, BanFinder)
BanFinder
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_I.py
{ "start": 65, "end": 1082 }
class ____(Benchmark): r""" Infinity objective function. This class defines the Infinity [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Infinity}}(x) = \sum_{i=1}^{n} x_i^{6} \left [ \sin\left ( \frac{1}{x_i} \r...
Infinity
python
conda__conda
conda/core/path_actions.py
{ "start": 2447, "end": 5421 }
class ____: """Base class for path manipulation actions, including linking, unlinking, and others. Pre and post-transaction plugins should inherit this class to implement their own verification, execution, reversing, and cleanup steps. These methods are guaranteed to be called in the following order: ...
Action
python
google__jax
tests/pallas/tpu_sparsecore_pallas_test.py
{ "start": 2733, "end": 2995 }
class ____(): COMPILER_OPTIONS = {"xla_tpu_use_tc_device_shape_on_sc": "true"} def setUp(self): super().setUp() if jtu.is_cloud_tpu(): # TODO(apaszke,slebedev): Fix those. self.skipTest("Many tests are failing on Cloud TPUs")
TCTilingMixin
python
doocs__leetcode
solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/Solution.py
{ "start": 0, "end": 314 }
class ____: def divideArray(self, nums: List[int], k: int) -> List[List[int]]: nums.sort() ans = [] n = len(nums) for i in range(0, n, 3): t = nums[i : i + 3] if t[2] - t[0] > k: return [] ans.append(t) return ans
Solution
python
pytorch__pytorch
torch/_inductor/template_heuristics/aten.py
{ "start": 1875, "end": 2396 }
class ____(ATenConfigHeuristics): def get_extra_kwargs( self, kernel_inputs: KernelInputs, op_name: str, ) -> dict[str, Any]: kwargs = super().get_extra_kwargs(kernel_inputs, op_name) alpha = kernel_inputs.get_scalar("alpha") beta = kernel_inputs.get_scalar("beta"...
ATenAddMMConfigHeuristics
python
wandb__wandb
wandb/vendor/pygments/lexers/configs.py
{ "start": 824, "end": 1612 }
class ____(RegexLexer): """ Lexer for configuration files in INI style. """ name = 'INI' aliases = ['ini', 'cfg', 'dosini'] filenames = ['*.ini', '*.cfg', '*.inf'] mimetypes = ['text/x-ini', 'text/inf'] tokens = { 'root': [ (r'\s+', Text), (r'[;#].*', Co...
IniLexer
python
python-openxml__python-docx
src/docx/opc/parts/coreprops.py
{ "start": 458, "end": 1775 }
class ____(XmlPart): """Corresponds to part named ``/docProps/core.xml``. The "core" is short for "Dublin Core" and contains document metadata relatively common across documents of all types, not just DOCX. """ @classmethod def default(cls, package: OpcPackage): """Return a new |CorePr...
CorePropertiesPart
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/resource_requirement.py
{ "start": 3235, "end": 3445 }
class ____(ABC): @abstractmethod def with_resources( self, resource_defs: Mapping[str, "ResourceDefinition"] ) -> "ResourceAddable": raise NotImplementedError() @record
ResourceAddable
python
openai__openai-python
src/openai/resources/beta/threads/messages.py
{ "start": 1149, "end": 13584 }
class ____(SyncAPIResource): @cached_property def with_raw_response(self) -> MessagesWithRawResponse: """ 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://www.github....
Messages
python
getsentry__sentry
tests/sentry/integrations/pagerduty/test_integration.py
{ "start": 784, "end": 9903 }
class ____(IntegrationTestCase): provider = PagerDutyIntegrationProvider base_url = "https://app.pagerduty.com" def setUp(self) -> None: super().setUp() self.app_id = "app_1" self.account_slug = "test-app" self._stub_pagerduty() def _stub_pagerduty(self): option...
PagerDutyIntegrationTest
python
tensorflow__tensorflow
tensorflow/python/ops/bincount_ops_test.py
{ "start": 13107, "end": 13785 }
class ____(test.TestCase, parameterized.TestCase): @test_util.run_v1_only("Test security error") def testSparseCountSparseOutputBadIndicesShapeTooSmall(self): indices = [1] values = [[1]] weights = [] dense_shape = [10] with self.assertRaisesRegex(ValueError, "Sh...
RawOpsHeapOobTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linalg_ops_test.py
{ "start": 16068, "end": 16156 }
class ____(test.TestCase, _LUReconstruct): use_static_shape = False
LUReconstructDynamic
python
HIPS__autograd
examples/convnet.py
{ "start": 4810, "end": 4899 }
class ____(full_layer): def nonlinearity(self, x): return np.tanh(x)
tanh_layer
python
HypothesisWorks__hypothesis
hypothesis-python/tests/attrs/test_attrs.py
{ "start": 1100, "end": 2097 }
class ____: n = attr.ib() def test_jsonable_attrs(): obj = AttrsClass(n=10) assert to_jsonable(obj, avoid_realization=False) == {"n": 10} def test_hypothesis_is_not_the_first_to_import_attrs(testdir): # We only import attrs if the user did so first. test_path = testdir.makepyfile( """ ...
AttrsClass
python
apache__airflow
scripts/ci/testing/summarize_captured_warnings.py
{ "start": 3143, "end": 10810 }
class ____: category: str message: str filename: str lineno: int when: str node_id: str | None @property def unique_warning(self) -> str: return _unique_key(self.category, self.message, self.filename, str(self.lineno)) @property def unique_key(self) -> str: retu...
CapturedWarnings
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 56604, "end": 56929 }
class ____(SemiIncrementalMixin, GithubStream): """ API docs: https://docs.github.com/en/rest/deployments/deployments?apiVersion=2022-11-28#list-deployments """ def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str: return f"repos/{stream_slice['repository']}/deployments"
Deployments
python
walkccc__LeetCode
solutions/329. Longest Increasing Path in a Matrix/329.py
{ "start": 0, "end": 584 }
class ____: def longestIncreasingPath(self, matrix: list[list[int]]) -> int: m = len(matrix) n = len(matrix[0]) @functools.lru_cache(None) def dfs(i: int, j: int, prev: int) -> int: if i < 0 or i == m or j < 0 or j == n: return 0 if matrix[i][j] <= prev: return 0 cu...
Solution
python
coleifer__peewee
playhouse/pool.py
{ "start": 2360, "end": 9700 }
class ____(object): def __init__(self, database, max_connections=20, stale_timeout=None, timeout=None, **kwargs): self._max_connections = make_int(max_connections) self._stale_timeout = make_int(stale_timeout) self._wait_timeout = make_int(timeout) if self._wait_time...
PooledDatabase
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 103699, "end": 104139 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(EnterpriseServerInstallationOrderField), graphql_name="field", ) direction = sgqlc.t...
EnterpriseServerInstallationOrder
python
pandas-dev__pandas
pandas/core/computation/pytables.py
{ "start": 12849, "end": 13453 }
class ____(ops.UnaryOp): def prune(self, klass): if self.op != "~": raise NotImplementedError("UnaryOp only support invert type ops") operand = self.operand operand = operand.prune(klass) if operand is not None and ( (issubclass(klass, ConditionBinOp) and op...
UnaryOp
python
kamyu104__LeetCode-Solutions
Python/matrix-cells-in-distance-order.py
{ "start": 33, "end": 698 }
class ____(object): def allCellsDistOrder(self, R, C, r0, c0): """ :type R: int :type C: int :type r0: int :type c0: int :rtype: List[List[int]] """ def append(R, C, r, c, result): if 0 <= r < R and 0 <= c < C: result.append...
Solution
python
fluentpython__example-code-2e
24-class-metaprog/persistent/persistlib.py
{ "start": 1800, "end": 4112 }
class ____: _TABLE_NAME: ClassVar[str] _TABLE_READY: ClassVar[bool] = False @classmethod def _fields(cls) -> dict[str, type]: return { name: py_type for name, py_type in get_type_hints(cls).items() if not name.startswith('_') } def __init_subclas...
Persistent
python
getsentry__sentry
tests/sentry/search/test_utils.py
{ "start": 2739, "end": 6111 }
class ____(TestCase): def test_ms(self) -> None: assert parse_duration("123", "ms") == 123 def test_sec(self) -> None: assert parse_duration("456", "s") == 456000 def test_minutes(self) -> None: assert parse_duration("789", "min") == 789 * 60 * 1000 assert parse_duration("7...
TestParseDuration
python
django__django
tests/admin_views/test_nav_sidebar.py
{ "start": 4268, "end": 9019 }
class ____(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) self.admin_lo...
SeleniumTests
python
pexpect__pexpect
tests/test_misc.py
{ "start": 1319, "end": 13616 }
class ____(PexpectTestCase.PexpectTestCase): def test_isatty(self): " Test isatty() is True after spawning process on most platforms. " child = pexpect.spawn('cat') if not child.isatty() and sys.platform.lower().startswith('sunos'): if hasattr(unittest, 'SkipTest'): ...
TestCaseMisc
python
marshmallow-code__marshmallow
tests/base.py
{ "start": 1934, "end": 3625 }
class ____: SPECIES = "Homo sapiens" def __init__( self, name, *, age=0, id_=None, homepage=None, email=None, registered=True, time_registered=None, birthdate=None, birthtime=None, balance=100, sex=GenderEnu...
User
python
jina-ai__jina
tests/integration/hot_reload/my_executor_3_new.py
{ "start": 38, "end": 169 }
class ____(Executor): @requests def x(self, docs, **kwargs): for doc in docs: doc.text = 'AAfterReload'
A
python
mlflow__mlflow
mlflow/entities/model_registry/model_version_search.py
{ "start": 58, "end": 863 }
class ____(ModelVersion): def __init__(self, *args, **kwargs): kwargs["tags"] = [] kwargs["aliases"] = [] super().__init__(*args, **kwargs) def tags(self): raise Exception( "UC Model Versions gathered through search_model_versions do not have tags. " "Ple...
ModelVersionSearch
python
huggingface__transformers
src/transformers/models/llava/image_processing_llava_fast.py
{ "start": 1181, "end": 6233 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"shortest_edge": 224} default_to_square = False crop_size = {"height": 224, "width": 224} do_pad = False do_resize = True do_center_crop = True ...
LlavaImageProcessorFast
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/stats.py
{ "start": 4727, "end": 7032 }
class ____(StatsWriter): def __init__(self): self.training_start_time = time.time() # If self-play, we want to print ELO as well as reward self.self_play = False self.self_play_team = -1 self.rank = get_rank() def write_stats( self, category: str, values: Dict[st...
ConsoleWriter
python
Pylons__pyramid
src/pyramid/config/zca.py
{ "start": 55, "end": 889 }
class ____: def hook_zca(self): """Call :func:`zope.component.getSiteManager.sethook` with the argument :data:`pyramid.threadlocal.get_current_registry`, causing the :term:`Zope Component Architecture` 'global' APIs such as :func:`zope.component.getSiteManager`, :func:`zope.c...
ZCAConfiguratorMixin
python
PrefectHQ__prefect
src/prefect/settings/legacy.py
{ "start": 480, "end": 5693 }
class ____: """Mimics the old Setting object for compatibility with existing code.""" def __init__( self, name: str, default: Any, type_: Any, accessor: Optional[str] = None ): self._name = name self._default = default self._type = type_ if accessor is None: ...
Setting
python
pytorch__pytorch
torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py
{ "start": 3789, "end": 12226 }
class ____(ActivationWrapper): """ An ``nn.Module`` that wraps another ``nn.Module`` with checkpointing. Note that this module is not meant to be used directly but instead, it is to be used through the ``checkpoint_wrapper`` function. """ def __init__( self, mod: torch.nn.Modul...
CheckpointWrapper
python
readthedocs__readthedocs.org
readthedocs/invitations/views.py
{ "start": 808, "end": 1597 }
class ____(PrivateViewMixin, UserPassesTestMixin, DeleteView): """ Revoke invitation view. An invitation is revoked by simple deleting it. """ model = Invitation pk_url_kwarg = "invitation_pk" http_method_names = ["post"] def form_valid(self, form): invitation = self.get_objec...
RevokeInvitation
python
tiangolo__fastapi
tests/test_skip_defaults.py
{ "start": 363, "end": 2071 }
class ____(BaseModel): w: Optional[str] = None x: Optional[str] = None y: str = "y" z: str = "z" @app.get("/", response_model=Model, response_model_exclude_unset=True) def get_root() -> ModelSubclass: return ModelSubclass(sub={}, y=1, z=0) @app.get( "/exclude_unset", response_model=ModelDefa...
ModelDefaults
python
doocs__leetcode
solution/2300-2399/2369.Check if There is a Valid Partition For The Array/Solution.py
{ "start": 0, "end": 559 }
class ____: def validPartition(self, nums: List[int]) -> bool: @cache def dfs(i: int) -> bool: if i >= n: return True a = i + 1 < n and nums[i] == nums[i + 1] b = i + 2 < n and nums[i] == nums[i + 1] == nums[i + 2] c = ( ...
Solution
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 12887, "end": 13417 }
class ____(graphene.Mutation): """Cancels a set of partition backfill runs.""" Output = graphene.NonNull(GrapheneCancelBackfillResult) class Arguments: backfillId = graphene.NonNull(graphene.String) class Meta: name = "CancelBackfillMutation" @capture_error @require_permissio...
GrapheneCancelBackfillMutation
python
kamyu104__LeetCode-Solutions
Python/evaluate-division.py
{ "start": 2483, "end": 3041 }
class ____(object): def calcEquation(self, equations, values, queries): """ :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] """ union_find = UnionFind() for (a, b), k in itertools.izip(equat...
Solution
python
great-expectations__great_expectations
great_expectations/data_context/store/query_store.py
{ "start": 884, "end": 5436 }
class ____(Store): """SqlAlchemyQueryStore stores queries by name, and makes it possible to retrieve the resulting value by query name.""" # noqa: E501 # FIXME CoP _key_class: ClassVar[Type] = StringKey def __init__( self, credentials, queries=None, store_backend=None,...
SqlAlchemyQueryStore
python
huggingface__transformers
src/transformers/models/wav2vec2/modeling_wav2vec2.py
{ "start": 18865, "end": 22235 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
Wav2Vec2Attention
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 42770, "end": 44839 }
class ____(Base): pass """ ) ta = TypeAdapter(mod_2.Sub) assert ta.validate_python({'f': '1'}) == {'f': 1} def test_parameterized_with_annotated_forward_refs() -> None: T = TypeVar('T') class Parent(BaseModel, Generic[T]): a: T b: 'MyAnnotated[T, 1]' c: Annot...
Sub
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2.py
{ "start": 22952, "end": 26343 }
class ____(Initializer): """Initializer that generates an orthogonal matrix. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. If the shape of the tensor to initialize is two-dimensional...
Orthogonal
python
pytorch__pytorch
torch/utils/benchmark/utils/fuzzer.py
{ "start": 14125, "end": 18778 }
class ____: def __init__( self, parameters: list[FuzzedParameter | list[FuzzedParameter]], tensors: list[FuzzedTensor | list[FuzzedTensor]], constraints: list[Callable] | None = None, seed: int | None = None ) -> None: """ Args: parameters: ...
Fuzzer
python
ray-project__ray
rllib/core/models/base.py
{ "start": 6446, "end": 10138 }
class ____(Model, abc.ABC): """The framework-agnostic base class for all RLlib encoders. Encoders are used to transform observations to a latent space. Therefore, their `input_specs` contains the observation space dimensions. Similarly, their `output_specs` contains the latent space dimensions. Enc...
Encoder
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 4541, "end": 5318 }
class ____(StringFormatter): ''' Display numeric values from continuous ranges as "basic numbers", using scientific notation when appropriate by default. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwarg...
ScientificFormatter
python
doocs__leetcode
solution/1100-1199/1168.Optimize Water Distribution in a Village/Solution2.py
{ "start": 624, "end": 1076 }
class ____: def minCostToSupplyWater( self, n: int, wells: List[int], pipes: List[List[int]] ) -> int: for i, w in enumerate(wells, 1): pipes.append([0, i, w]) pipes.sort(key=lambda x: x[2]) uf = UnionFind(n + 1) ans = 0 for a, b, c in pipes: ...
Solution
python
pandas-dev__pandas
pandas/plotting/_misc.py
{ "start": 22046, "end": 24868 }
class ____(dict): """ Stores pandas plotting options. Allows for parameter aliasing so you can just use parameter names that are the same as the plot function parameters, but is stored in a canonical format that makes it easy to breakdown into groups later. See Also -------- plotting.r...
_Options
python
django__django
django/core/files/storage/memory.py
{ "start": 649, "end": 977 }
class ____: def _initialize_times(self): self.created_time = now() self.accessed_time = self.created_time self.modified_time = self.created_time def _update_accessed_time(self): self.accessed_time = now() def _update_modified_time(self): self.modified_time = now() ...
TimingMixin
python
keras-team__keras
keras/src/ops/symbolic_arguments_test.py
{ "start": 164, "end": 3623 }
class ____(testing.TestCase): # Testing multiple args and empty kwargs def test_args(self): shape = (2, 3, 4) a = KerasTensor(shape=shape) b = KerasTensor(shape=shape) args = SymbolicArguments( ( a, b, ), {}, ...
SymbolicArgumentsTest
python
getsentry__sentry
src/sentry/db/models/fields/bounded.py
{ "start": 2396, "end": 2806 }
class ____(models.PositiveBigIntegerField): description = _("Positive big integer") MAX_VALUE = I64_MAX def get_internal_type(self) -> str: return "PositiveBigIntegerField" def get_prep_value(self, value: int) -> int: if value: value = int(value) assert value <...
BoundedPositiveBigIntegerField
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 198432, "end": 199840 }
class ____(TestCase): def test_basic(self): self.assertTrue(mi.iequals("abc", iter("abc"))) self.assertTrue(mi.iequals(range(3), [0, 1, 2])) self.assertFalse(mi.iequals("abc", [0, 1, 2])) def test_no_iterables(self): self.assertTrue(mi.iequals()) def test_one_iterable(self)...
IequalsTests
python
sphinx-doc__sphinx
tests/roots/test-ext-autosummary-imported_members/autosummary_dummy_package/autosummary_dummy_module.py
{ "start": 0, "end": 86 }
class ____: """Bar class""" pass def foo(): """Foo function""" pass
Bar
python
spyder-ide__spyder
spyder/config/user.py
{ "start": 984, "end": 4536 }
class ____(cp.ConfigParser, object): """ Class used to save defaults to a file and as UserConfig base class. """ def __init__(self, name, path): """ Class used to save defaults to a file and as UserConfig base class. """ super().__init__(interpolation=None) self...
DefaultsConfig
python
getsentry__sentry
src/sentry/new_migrations/monkey/fields.py
{ "start": 894, "end": 3916 }
class ____(RemoveField): def __init__(self, *args, deletion_action: DeletionAction, **kwargs): super().__init__(*args, **kwargs) self.deletion_action = deletion_action def state_forwards(self, app_label: str, state: SentryProjectState) -> None: # type: ignore[override] if self.deletion...
SafeRemoveField
python
MorvanZhou__Reinforcement-learning-with-tensorflow
experiments/Solve_BipedalWalker/DDPG.py
{ "start": 1418, "end": 4406 }
class ____(object): def __init__(self, sess, action_dim, action_bound, learning_rate, t_replace_iter): self.sess = sess self.a_dim = action_dim self.action_bound = action_bound self.lr = learning_rate self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 ...
Actor
python
pytorch__pytorch
test/distributed/_pycute/test_right_inverse.py
{ "start": 2093, "end": 3505 }
class ____(TestCase): def helper_test_right_inverse(self, layout): inv_layout = right_inverse(layout) _LOGGER.debug(f"{layout} => {inv_layout}") for i in range(size(inv_layout)): self.assertEqual(layout(inv_layout(i)), i) def test_right_inverse(self): test = Layo...
TestRightInverse
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_backend.py
{ "start": 59420, "end": 61152 }
class ____(TestCase): def setUp(self): super().setUp() # Wipe it clean. self.raw_solr = pysolr.Solr(settings.HAYSTACK_CONNECTIONS["solr"]["URL"]) clear_solr_index() # Stow. self.old_ui = connections["solr"].get_unified_index() self.ui = UnifiedIndex() ...
SolrBoostBackendTestCase
python
huggingface__transformers
src/transformers/models/chameleon/modeling_chameleon.py
{ "start": 8238, "end": 10794 }
class ____(nn.LayerNorm): """ LayerNorm but computes stats only over the last dim because Chameleon applies gamma and beta from each shard separately to each head, instead of reducing. We can apply each head's own gamma/beta by repeat-interleaving weights from each shard, but the stats have to be comput...
ChameleonLayerNorm
python
joke2k__faker
faker/providers/date_time/pt_BR/__init__.py
{ "start": 46, "end": 803 }
class ____(DateTimeProvider): DAY_NAMES = { "0": "domingo", "1": "segunda-feira", "2": "terça-feira", "3": "quarta-feira", "4": "quinta-feira", "5": "sexta-feira", "6": "sábado", } MONTH_NAMES = { "01": "janeiro", "02": "fevereiro", ...
Provider
python
streamlit__streamlit
lib/tests/streamlit/web/server/routes_test.py
{ "start": 8808, "end": 9629 }
class ____(tornado.testing.AsyncHTTPTestCase): def get_app(self): return tornado.web.Application( [ ( r"^/(?!/)(.*)", RemoveSlashHandler, ) ] ) def test_parse_url_path_301(self): paths = ["/p...
RemoveSlashHandlerTest
python
zarr-developers__zarr-python
src/zarr/core/array_spec.py
{ "start": 902, "end": 2727 }
class ____: """ A model of the runtime configuration of an array. Parameters ---------- order : MemoryOrder The memory layout of the arrays returned when reading data from the store. write_empty_chunks : bool If True, empty chunks will be written to the store. """ order...
ArrayConfig
python
allegroai__clearml
clearml/backend_api/services/v2_23/queues.py
{ "start": 61173, "end": 63892 }
class ____(Response): """ Response of queues.get_next_task endpoint. :param entry: Entry information :type entry: Entry :param task_info: Info about the returned task. Returned only if get_task_info is set to True :type task_info: dict """ _service = "queues" _action = "get...
GetNextTaskResponse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 7537, "end": 8051 }
class ____: cursor_field = "date" def request_params( self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None ) -> MutableMapping[str, Any]: params = super().request_params(stream_state, stream_slice, next_page_token) ...
AggregateDataMixin
python
anthropics__anthropic-sdk-python
src/anthropic/_response.py
{ "start": 20588, "end": 21727 }
class ____(AnthropicError): """ Attempted to read or stream content, but the content has already been streamed. This can happen if you use a method like `.iter_lines()` and then attempt to read th entire response body afterwards, e.g. ```py response = await client.post(...) async for l...
StreamAlreadyConsumed
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_bigquery.py
{ "start": 11979, "end": 12582 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook") def test_execute(self, mock_hook): operator = BigQueryDeleteDatasetOperator( task_id=TASK_ID, dataset_id=TEST_DATASET, project_id=TEST_GCP_PROJECT_ID, delete_contents...
TestBigQueryDeleteDatasetOperator
python
pytorch__pytorch
torchgen/api/autograd.py
{ "start": 8860, "end": 9554 }
class ____: name: str type: Type # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove. cpp_type: str # Represents a differentiable `Return`. # How it it different from the `Return` type? # - The name in `Return` is optional. Here it is always populated using the same #...
DifferentiableInput
python
pola-rs__polars
py-polars/src/polars/expr/list.py
{ "start": 622, "end": 50636 }
class ____: """Namespace for list related expressions.""" _accessor = "list" def __init__(self, expr: Expr) -> None: self._pyexpr = expr._pyexpr def __getitem__(self, item: int) -> Expr: return self.get(item) def all(self) -> Expr: """ Evaluate whether all boolean...
ExprListNameSpace
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 2056, "end": 4009 }
class ____(object): def __init__(self): self.functions = OrderedDict() self.dependencies = OrderedDict() self.values = OrderedDict() def clear(self): self.values = OrderedDict() def __iter__(self): return self.functions.__iter__() def __getitem__(self, item): ...
MetafeatureFunctions
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_exclude_lists_audit.py
{ "start": 371, "end": 2887 }
class ____: """Test suite for _audit_exclude_missing_public function.""" def test_audit_exclude_missing_public_all_valid(self): """Test audit when all EXCLUDE_MISSING_PUBLIC entries are still valid.""" # Mock validator with no symbols having @public decorators mock_validator = Mock() ...
TestAuditExcludeMissingPublic
python
kamyu104__LeetCode-Solutions
Python/lowest-common-ancestor-of-a-binary-search-tree.py
{ "start": 29, "end": 458 }
class ____(object): # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s <= root.val <= b: # Keep searching since root is outside of [s, b]. ...
Solution
python
doocs__leetcode
solution/2900-2999/2936.Number of Equal Numbers Blocks/Solution.py
{ "start": 145, "end": 539 }
class ____(object): def countBlocks(self, nums: Optional["BigArray"]) -> int: i, n = 0, nums.size() ans = 0 while i < n: ans += 1 x = nums.at(i) if i + 1 < n and nums.at(i + 1) != x: i += 1 else: i += bisect_left...
Solution
python
pydata__xarray
xarray/core/treenode.py
{ "start": 349, "end": 461 }
class ____(Exception): """Raised when user attempts to create an invalid tree in some way."""
InvalidTreeError
python
pallets__werkzeug
src/werkzeug/sansio/multipart.py
{ "start": 318, "end": 383 }
class ____(Event): data: bytes @dataclass(frozen=True)
Preamble
python
getsentry__sentry
src/sentry/users/api/serializers/authenticator.py
{ "start": 2819, "end": 3736 }
class ____(AuthenticatorInterfaceSerializer): def serialize( self, obj: AuthenticatorInterface, attrs: Mapping[str, Any], user: User | RpcUser | AnonymousUser, **kwargs: Any, ) -> SmsInterfaceSerializerResponse: data = cast(SmsInterfaceSerializerResponse, super()....
SmsInterfaceSerializer