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
doocs__leetcode
solution/3300-3399/3339.Find the Number of K-Even Arrays/Solution3.py
{ "start": 0, "end": 505 }
class ____: def countOfArrays(self, n: int, m: int, k: int) -> int: f = [[0] * 2 for _ in range(k + 1)] cnt0 = m // 2 cnt1 = m - cnt0 mod = 10**9 + 7 f[0][1] = 1 for _ in range(n): g = [[0] * 2 for _ in range(k + 1)] for j in range(k + 1): ...
Solution
python
pandas-dev__pandas
pandas/tests/arithmetic/test_timedelta64.py
{ "start": 5415, "end": 8971 }
class ____: # TODO: All of these need to be parametrized over box @pytest.mark.parametrize("dtype", [None, object]) def test_comp_nat(self, dtype): left = TimedeltaIndex([Timedelta("1 days"), NaT, Timedelta("3 days")]) right = TimedeltaIndex([NaT, NaT, Timedelta("3 days")]) lhs, rh...
TestTimedelta64ArrayComparisons
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 91135, "end": 93070 }
class ____(fixtures.DeclarativeMappedTest): """test for #5210""" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Parent(Base, ComparableEntity): __tablename__ = "parents" id = Column(Integer, primary_key=True) child_type = Column(...
M2ODontLoadSiblingTest
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 59533, "end": 62057 }
class ____(WebTestCase): def get_handlers(self): class MyStaticFileHandler(StaticFileHandler): @classmethod def make_static_url(cls, settings, path): version_hash = cls.get_version(settings, path) extension_index = path.rindex(".") befo...
CustomStaticFileTest
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 21261, "end": 22254 }
class ____(TestCase): def test_basics(self): word = tuple('love') for _ in range(20): d = mi.random_derangement(word) self.assertEqual(len(d), len(word)) # Same size self.assertEqual(set(d), set(word)) # Same values self.assertFalse(any(map(eq, d, wo...
TestRandomDerangement
python
pytorch__pytorch
torch/ao/ns/fx/graph_matcher.py
{ "start": 6892, "end": 7007 }
class ____(Exception): """ Exception raised when two graphs cannot be matched. """
GraphMatchingException
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_types.py
{ "start": 1544, "end": 4032 }
class ____: supports_whereclause = True @testing.fixture def literal_round_trip(self, metadata, connection): """test literal rendering""" # for literal, we test the literal render in an INSERT # into a typed column. we can then SELECT it back as its # official type; ideall...
_LiteralRoundTripFixture
python
spyder-ide__spyder
spyder/plugins/editor/widgets/tabswitcher.py
{ "start": 421, "end": 4079 }
class ____(QListWidget, SpyderShortcutsMixin): """Show tabs in mru order and change between them.""" CONF_SECTION = "editor" def __init__(self, parent, stack_history, tabs): QListWidget.__init__(self, parent) self.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) self.editor = pa...
TabSwitcherWidget
python
ray-project__ray
python/ray/tune/utils/release_test_util.py
{ "start": 274, "end": 859 }
class ____(Callback): def __init__(self): self.last_update = 0 self.update_interval = 60 def on_step_end(self, iteration, trials, **kwargs): if time.time() - self.last_update > self.update_interval: now = time.time() result = { "last_update": now,...
ProgressCallback
python
run-llama__llama_index
llama-index-core/llama_index/core/readers/base.py
{ "start": 2106, "end": 7436 }
class ____(ABC): # pragma: no cover """ Mixin for readers that provide access to different types of resources. Resources refer to specific data entities that can be accessed by the reader. Examples of resources include files for a filesystem reader, channel IDs for a Slack reader, or pages for a Notio...
ResourcesReaderMixin
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder12.py
{ "start": 283, "end": 463 }
class ____(Generic[T]): pass def func1(c: Callable[[A], None], v: A): pass def func2(c: ClassA[B]) -> None: pass def func3(c: ClassA[int]): func1(func2, c)
ClassA
python
huggingface__transformers
src/transformers/models/ministral/modular_ministral.py
{ "start": 11902, "end": 11959 }
class ____(Qwen2ForCausalLM): pass
MinistralForCausalLM
python
ansible__ansible
lib/ansible/plugins/lookup/varnames.py
{ "start": 1689, "end": 2536 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): if variables is None: raise AnsibleError('No variables available to search') self.set_options(var_options=variables, direct=kwargs) ret = [] variable_names = list(variables.keys()) for ter...
LookupModule
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 205264, "end": 208269 }
class ____(ParseElementEnhance): def __init__( self, expr: Union[str, ParserElement], stop_on: typing.Optional[Union[ParserElement, str]] = None, **kwargs, ) -> None: stopOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument( kwargs, "stopOn", No...
_MultipleMatch
python
dateutil__dateutil
tests/test_tz.py
{ "start": 95318, "end": 96588 }
class ____: def test_enter_fold_default(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32)) assert dt.fold == 1 def test_enter_fold(self): dt = tz.enfold(datetime(2020, 1, 19, 3, 32), fold=1) assert dt.fold == 1 def test_exit_fold(self): dt = tz.enfold(datetime(20...
TestEnfold
python
ray-project__ray
python/ray/autoscaler/_private/cluster_dump.py
{ "start": 855, "end": 1359 }
class ____: def __init__( self, logs: bool = True, debug_state: bool = True, pip: bool = True, processes: bool = True, processes_verbose: bool = True, processes_list: Optional[List[Tuple[str, bool]]] = None, ): self.logs = logs self.debug_s...
GetParameters
python
astropy__astropy
astropy/visualization/wcsaxes/tests/test_formatter_locator.py
{ "start": 16373, "end": 22132 }
class ____: def test_no_options(self): fl = ScalarFormatterLocator(unit=u.m) assert fl.values is None assert fl.number == 5 assert fl.spacing is None def test_too_many_options(self): MESSAGE = r"At most one of values/number/spacing can be specified" with pytest....
TestScalarFormatterLocator
python
faif__python-patterns
tests/structural/test_adapter.py
{ "start": 89, "end": 1058 }
class ____(unittest.TestCase): def setUp(self): self.dog = Dog() self.cat = Cat() self.human = Human() self.car = Car() def test_dog_shall_bark(self): noise = self.dog.bark() expected_noise = "woof!" self.assertEqual(noise, expected_noise) def test_c...
ClassTest
python
pytorch__pytorch
torch/ao/quantization/observer.py
{ "start": 68154, "end": 80311 }
class ____(ABC, torch.nn.Module): """Observer module for affine quantization (https://github.com/pytorch/ao/tree/main/torchao/quantization#affine-quantization) Args: `granularity` and `block_size`: The granularity of the quantization, must specify at least one, if both are specified `block_size` ...
AffineQuantizedObserverBase
python
kamyu104__LeetCode-Solutions
Python/substring-with-concatenation-of-all-words.py
{ "start": 1442, "end": 2387 }
class ____(object): def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ result, m, n, k = [], len(s), len(words), len(words[0]) if m < n*k: return result lookup = collections.defaultdict(int) ...
Solution2
python
gevent__gevent
src/greentest/3.10/test_asyncore.py
{ "start": 577, "end": 739 }
class ____: def __init__(self): self.closed = False def close(self): self.closed = True def fileno(self): return 42
dummysocket
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_pass.py
{ "start": 899, "end": 1017 }
class ____: '''The same goes for class stubs: docstring, or `pass`, but not both. ''' # No problem
DocstringOnly
python
py-pdf__pypdf
pypdf/constants.py
{ "start": 17486, "end": 19217 }
class ____: """§7.7.2 of the 1.7 and 2.0 references.""" TYPE = "/Type" # name, required; must be /Catalog VERSION = "/Version" # name EXTENSIONS = "/Extensions" # dictionary, optional; ISO 32000-1 PAGES = "/Pages" # dictionary, required PAGE_LABELS = "/PageLabels" # number tree, optional ...
CatalogDictionary
python
kamyu104__LeetCode-Solutions
Python/largest-component-size-by-common-factor.py
{ "start": 2446, "end": 3356 }
class ____(object): def largestComponentSize(self, A): """ :type A: List[int] :rtype: int """ def prime_factors(x): # prime factor decomposition result = [] p = 2 while p*p <= x: if x%p == 0: while x%p =...
Solution2
python
huggingface__transformers
src/transformers/models/qwen3_vl/modular_qwen3_vl.py
{ "start": 29712, "end": 34580 }
class ____(Qwen3VLPreTrainedModel, Qwen3Model): config: Qwen3VLTextConfig _no_split_modules = ["Qwen3VLTextDecoderLayer"] def __init__(self, config: Qwen3VLTextConfig): super().__init__(config) del self.has_sliding_layers def _deepstack_process( self, hidden_states: torch.Tenso...
Qwen3VLTextModel
python
sympy__sympy
sympy/codegen/fnodes.py
{ "start": 953, "end": 1484 }
class ____(Token): """ Represents a 'program' block in Fortran. Examples ======== >>> from sympy.codegen.ast import Print >>> from sympy.codegen.fnodes import Program >>> prog = Program('myprogram', [Print([42])]) >>> from sympy import fcode >>> print(fcode(prog, source_format='free'))...
Program
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/_internal/expandinput.py
{ "start": 8799, "end": 11040 }
class ____(ResolveMixin): """ Storage type of a mapped operator's mapped kwargs. This is created from ``expand_kwargs(xcom_arg)``. """ value: OperatorExpandKwargsArgument EXPAND_INPUT_TYPE: ClassVar[str] = "list-of-dicts" def get_parse_time_mapped_ti_count(self) -> int: if isinst...
ListOfDictsExpandInput
python
kamyu104__LeetCode-Solutions
Python/meeting-rooms-ii.py
{ "start": 422, "end": 1210 }
class ____(object): # @param {Interval[]} intervals # @return {integer} def minMeetingRooms(self, intervals): starts, ends = [], [] for start, end in intervals: starts.append(start) ends.append(end) starts.sort() ends.sort() s, e = 0, 0 ...
Solution2
python
ZoranPandovski__al-go-rithms
data_structures/binary_indexed_tree/Python/FenwickTree.py
{ "start": 497, "end": 1685 }
class ____: # To intialize list of num_of_elements+1 size def initialize(self,num_of_elements): for i in range(num_of_elements+1): array.append(0) bit.append(0) def update(self,x,delta): while x<=num_of_elements: bit[x]=bit[x]+delta # x&(-x) gives the last set bit in a number x x=x+(x&-x) def qu...
FenwickTree
python
zarr-developers__zarr-python
tests/test_dtype/test_npy/test_int.py
{ "start": 5033, "end": 5996 }
class ____(BaseTestZDType): test_cls = UInt16 scalar_type = np.uint16 valid_dtype = (np.dtype(">u2"), np.dtype("<u2")) invalid_dtype = ( np.dtype(np.int8), np.dtype(np.int16), np.dtype(np.float64), ) valid_json_v2 = ( {"name": ">u2", "object_codec_id": None}, ...
TestUInt16
python
great-expectations__great_expectations
contrib/time_series_expectations/time_series_expectations/expectations/prophet_model_deserializer.py
{ "start": 370, "end": 770 }
class ____: """A class for deserializing a Prophet model from JSON""" def get_model( self, model_json: str, ) -> Prophet: if not model_from_json: raise ImportError( # noqa: TRY003 "Unable to import Prophet. Please install prophet to use this Expectation....
ProphetModelDeserializer
python
pyca__cryptography
tests/hazmat/asn1/test_serialization.py
{ "start": 3562, "end": 4601 }
class ____: def test_utc_time(self) -> None: assert_roundtrips( [ ( asn1.UtcTime( datetime.datetime( 2019, 12, 16, 3, ...
TestUtcTime
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 35639, "end": 36695 }
class ____(IntegrationMixin, GenericView): """ Resync a project webhook. The signal will add a success/failure message on the request. """ def post(self, request, *args, **kwargs): if "integration_pk" in kwargs: integration = self.get_integration() update_webhook(se...
IntegrationWebhookSync
python
getsentry__sentry
src/sentry/models/deletedproject.py
{ "start": 238, "end": 1198 }
class ____(DeletedEntry): """ This model tracks an intent to delete. If an org is marked pending_delete through the UI, a deletedproject is created to log this deletion. This model does not account for aborted or failed deletions and is currently unable to log deletions that occur implicitly (i.e. ...
DeletedProject
python
tensorflow__tensorflow
tensorflow/python/ops/structured/structured_tensor_slice_test.py
{ "start": 4581, "end": 11517 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def assertAllEqual(self, a, b, msg=None): if not (isinstance(a, structured_tensor.StructuredTensor) or isinstance(b, structured_tensor.StructuredTensor)): super(StructuredTensorSliceTest, self).ass...
StructuredTensorSliceTest
python
scipy__scipy
scipy/stats/_covariance.py
{ "start": 16812, "end": 18374 }
class ____(Covariance): __class_getitem__ = None def __init__(self, precision, covariance=None): precision = self._validate_matrix(precision, 'precision') if covariance is not None: covariance = self._validate_matrix(covariance, 'covariance') message = "`precision.shape...
CovViaPrecision
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_legacy_class_based/_documenters.py
{ "start": 53583, "end": 54358 }
class ____(FunctionDocumenter): """Specialized Documenter subclass for decorator functions.""" objtype = 'decorator' # must be lower than FunctionDocumenter priority = -1 def format_args(self, **kwargs: Any) -> str: args = super().format_args(**kwargs) if ',' in args: ...
DecoratorDocumenter
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 57802, "end": 58253 }
class ____(WorkQueueCommandAction): """Resumes a Work Queue""" type: Literal["resume-work-queue"] = "resume-work-queue" _action_description: ClassVar[str] = "Resuming work queue" async def command( self, orchestration: "OrchestrationClient", work_queue_id: UUID, trigge...
ResumeWorkQueue
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 8581, "end": 8709 }
class ____(TransactionError): """ Raised when a transaction error occurs in a virtual machine. """
VirtualMachineError
python
python__mypy
mypy/test/testinfer.py
{ "start": 7526, "end": 13856 }
class ____(Suite): """Test cases for checker.group_comparison_operands.""" def literal_keymap(self, assignable_operands: dict[int, NameExpr]) -> dict[int, Key]: output: dict[int, Key] = {} for index, expr in assignable_operands.items(): output[index] = ("FakeExpr", expr.name) ...
OperandComparisonGroupingSuite
python
astropy__astropy
astropy/cosmology/_src/flrw/lambdacdm.py
{ "start": 22294, "end": 27780 }
class ____(FlatFLRWMixin, LambdaCDM): """FLRW cosmology with a cosmological constant and no curvature. This has no additional attributes beyond those of FLRW. Parameters ---------- H0 : float or scalar quantity-like ['frequency'] Hubble constant at z = 0. If a float, must be in [km/sec/Mpc...
FlatLambdaCDM
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
{ "start": 11959, "end": 14251 }
class ____(_ComputableMask): """Lazy local mask, prevents model from attending to tokens outside window. Attributes: window_size: Size of the two sides of the local window (None identifies no limit for the given side). offset: Offset of q start wrt kv. A positive offset shifts the bottom triang...
LocalMask
python
apache__airflow
airflow-core/tests/unit/always/test_project_structure.py
{ "start": 39988, "end": 40148 }
class ____(ExampleCoverageTest): PROVIDER = "elasticsearch" CLASS_DIRS = {"hooks"} CLASS_SUFFIXES = ["Hook"]
TestElasticsearchProviderProjectStructure
python
pyparsing__pyparsing
examples/statemachine/trafficLightDemo.py
{ "start": 150, "end": 550 }
class ____(trafficlightstate.TrafficLightStateMixin): def __init__(self): self.initialize_state(trafficlightstate.Red) def change(self): self._state = self._state.next_state() light = TrafficLight() for i in range(10): print("{} {}".format(light, ("STOP", "GO")[light.cars_can_go])) li...
TrafficLight
python
openai__gym
gym/envs/box2d/car_racing.py
{ "start": 1457, "end": 2981 }
class ____(contactListener): def __init__(self, env, lap_complete_percent): contactListener.__init__(self) self.env = env self.lap_complete_percent = lap_complete_percent def BeginContact(self, contact): self._contact(contact, True) def EndContact(self, contact): se...
FrictionDetector
python
getsentry__sentry
src/sentry/incidents/typings/metric_detector.py
{ "start": 2744, "end": 5522 }
class ____: name: str action_identifier_id: int threshold_type: AlertRuleThresholdType | None | AnomalyDetectionThresholdType detection_type: AlertRuleDetectionType comparison_delta: int | None sensitivity: str | None resolve_threshold: float | None alert_threshold: float | None @cl...
AlertContext
python
pandas-dev__pandas
pandas/tests/indexes/timedeltas/methods/test_shift.py
{ "start": 146, "end": 2756 }
class ____: # ------------------------------------------------------------- # TimedeltaIndex.shift is used by __add__/__sub__ def test_tdi_shift_empty(self): # GH#9903 idx = TimedeltaIndex([], name="xxx") tm.assert_index_equal(idx.shift(0, freq="h"), idx) tm.assert_index_equ...
TestTimedeltaIndexShift
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/backfill.py
{ "start": 8642, "end": 9250 }
class ____(graphene.ObjectType): assetKey = graphene.NonNull(GrapheneAssetKey) partitionRange = graphene.Field(GraphenePartitionRange) class Meta: name = "AssetPartitionRange" def __init__(self, asset_key: AssetKey, partition_range: Optional[PartitionKeyRange]): super().__init__( ...
GrapheneAssetPartitionRange
python
ray-project__ray
rllib/examples/envs/classes/stateless_cartpole.py
{ "start": 109, "end": 1332 }
class ____(CartPoleEnv): """Partially observable variant of the CartPole gym environment. https://github.com/openai/gym/blob/master/gym/envs/classic_control/ cartpole.py We delete the x- and angular velocity components of the state, so that it can only be solved by a memory enhanced model (policy)...
StatelessCartPole
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 22634, "end": 24345 }
class ____(TorchDistributionWrapper): """Dirichlet distribution for continuous actions that are between [0,1] and sum to 1. e.g. actions that represent resource allocation.""" def __init__(self, inputs, model): """Input is a tensor of logits. The exponential of logits is used to parame...
TorchDirichlet
python
doocs__leetcode
solution/0400-0499/0402.Remove K Digits/Solution.py
{ "start": 0, "end": 315 }
class ____: def removeKdigits(self, num: str, k: int) -> str: stk = [] remain = len(num) - k for c in num: while k and stk and stk[-1] > c: stk.pop() k -= 1 stk.append(c) return ''.join(stk[:remain]).lstrip('0') or '0'
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py
{ "start": 5235, "end": 6904 }
class ____: """A record representing all content in an Airbyte workspace. This applies to both Airbyte OSS and Cloud. """ connections_by_id: Mapping[str, AirbyteConnection] destinations_by_id: Mapping[str, AirbyteDestination] @cached_method def to_airbyte_connection_table_props_data(self) ...
AirbyteWorkspaceData
python
mlflow__mlflow
tests/langchain/sample_code/openai_agent.py
{ "start": 294, "end": 1833 }
class ____(ChatOpenAI, extra="allow"): # In normal LangChain tests, we use the fake OpenAI server to mock the OpenAI REST API. # The fake server returns the input payload as it is. However, for agent tests, the # response should be a specific format so that the agent can parse it correctly. # Also, mock...
FakeOpenAI
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 33086, "end": 34192 }
class ____(TestCase): def test_basic(self): self.assertEqual( list(mi.sieve(67)), [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
SieveTests
python
eriklindernoren__ML-From-Scratch
mlfromscratch/unsupervised_learning/principal_component_analysis.py
{ "start": 129, "end": 1247 }
class ____(): """A method for doing dimensionality reduction by transforming the feature space to a lower dimensionality, removing correlation between features and maximizing the variance along each feature axis. This class is also used throughout the project to plot data. """ def transform(self...
PCA
python
euske__pdfminer
tools/runapp.py
{ "start": 267, "end": 3528 }
class ____(SimpleHTTPRequestHandler): APP_CLASS = None def do_POST(self): return self.run_cgi() def send_head(self): return self.run_cgi() def run_cgi(self): rest = self.path i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] ...
WebAppHandler
python
pytorch__pytorch
torch/_dynamo/convert_frame.py
{ "start": 18262, "end": 19023 }
class ____: error_on_graph_break: Optional[bool] = None def get_compile_id( frame_state: dict[str, Union[int, FrameStateSizeEntry]], ) -> CompileId: global FRAME_COUNTER if "_id" not in frame_state: frame_state["_id"] = FRAME_COUNTER FRAME_COUNTER += 1 frame_id = frame_state["_id"]...
ConvertFrameBox
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_3.py
{ "start": 266, "end": 313 }
class ____(C): x: UUID import collections
D
python
cython__cython
Cython/Compiler/Optimize.py
{ "start": 50284, "end": 61490 }
class ____(Visitor.EnvTransform): """ This transformation tries to turn long if statements into C switch statements. The requirement is that every clause be an (or of) var == value, where the var is common among all clauses and both var and value are ints. """ NO_MATCH = (None, None, None) ...
SwitchTransform
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 29872, "end": 30255 }
class ____(Expr): """If created with an import name the import name is returned on node access. For example ``ImportedName('cgi.escape')`` returns the `escape` function from the cgi module on evaluation. Imports are optimized by the compiler so there is no need to assign them to local variables. "...
ImportedName
python
ansible__ansible
test/lib/ansible_test/_internal/cli/parsers/host_config_parsers.py
{ "start": 9569, "end": 10310 }
class ____(PairParser): """Composite argument parser for a network inventory.""" def create_namespace(self) -> t.Any: """Create and return a namespace.""" return NetworkInventoryConfig() def get_left_parser(self, state: ParserState) -> Parser: """Return the parser for the left side...
NetworkInventoryParser
python
apache__airflow
providers/apache/kafka/tests/unit/apache/kafka/triggers/test_await_message.py
{ "start": 4395, "end": 5289 }
class ____: @pytest.mark.usefixtures("collect_queue_param_deprecation_warning") def test_provider_integrations_with_queue_param(self, cleanup_providers_manager): queue = "kafka://localhost:9092/topic1" from airflow.providers.common.messaging.triggers.msg_queue import MessageQueueTrigger ...
TestMessageQueueTrigger
python
pennersr__django-allauth
allauth/headless/account/inputs.py
{ "start": 8962, "end": 9038 }
class ____(RequestLoginCodeForm, inputs.Input): pass
RequestLoginCodeInput
python
doocs__leetcode
solution/3400-3499/3481.Apply Substitutions/Solution.py
{ "start": 0, "end": 488 }
class ____: def applySubstitutions(self, replacements: List[List[str]], text: str) -> str: def dfs(s: str) -> str: i = s.find("%") if i == -1: return s j = s.find("%", i + 1) if j == -1: return s key = s[i + 1 : j] ...
Solution
python
mlflow__mlflow
mlflow/gateway/utils.py
{ "start": 8404, "end": 11153 }
class ____: def __init__(self, index: int): self._index = index @property def index(self): return self._index @classmethod def decode(cls, encoded_token: str): try: decoded_token = base64.b64decode(encoded_token) parsed_token = json.loads(decoded_tok...
SearchRoutesToken
python
ray-project__ray
python/ray/llm/_internal/serve/core/protocol.py
{ "start": 445, "end": 639 }
class ____(Protocol): @classmethod def get_deployment_options(cls, **kwargs) -> Dict[str, Any]: """Get the default deployment options for the this deployment."""
DeploymentProtocol
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 500603, "end": 502747 }
class ____(sgqlc.types.Type): """This aggregates commits made by a user within one repository.""" __schema__ = github_schema __field_names__ = ("contributions", "repository", "resource_path", "url") contributions = sgqlc.types.Field( sgqlc.types.non_null("CreatedCommitContributionConnection"), ...
CommitContributionsByRepository
python
pytorch__pytorch
test/distributed/_shard/sharding_spec/test_sharding_spec.py
{ "start": 21822, "end": 23991 }
class ____(ShardedTensorTestBase): def test_custom_sharding_spec(self): ranks = [ "rank:0/cuda:0", "rank:1/cuda:1", "rank:2/cuda:2", "rank:3/cuda:3", ] grid_spec = GridShardingSpec(grid_size=4, placements=ranks) tensor_properties = Te...
TestCustomShardingSpec
python
pytorch__pytorch
torch/optim/asgd.py
{ "start": 511, "end": 16542 }
class ____(Optimizer): def __init__( self, params: ParamsT, lr: Union[float, Tensor] = 1e-2, lambd: float = 1e-4, alpha: float = 0.75, t0: float = 1e6, weight_decay: float = 0, foreach: Optional[bool] = None, maximize: bool = False, dif...
ASGD
python
dagster-io__dagster
python_modules/dagster/dagster/_vendored/croniter/croniter.py
{ "start": 4930, "end": 47931 }
class ____(object): MONTHS_IN_YEAR = 12 # This helps with expanding `*` fields into `lower-upper` ranges. Each item # in this tuple maps to the corresponding field index RANGES = ( (0, 59), (0, 23), (1, 31), (1, 12), (0, 6), (0, 59), (1970, 2099),...
croniter
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 11096, "end": 11417 }
class ____(models.Model): changed_by = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) history = HistoricalRecords() @property def _history_user(self): try: return self.changed_by except User.DoesNotExist: return None
Document
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/sensors/databricks_partition.py
{ "start": 1424, "end": 9940 }
class ____(BaseSensorOperator): """ Sensor to detect the presence of table partitions in Databricks. :param databricks_conn_id: Reference to :ref:`Databricks connection id<howto/connection:databricks>` (templated), defaults to DatabricksSqlHook.default_conn_name. :param sql_warehouse_na...
DatabricksPartitionSensor
python
sympy__sympy
sympy/solvers/diophantine/diophantine.py
{ "start": 32927, "end": 35586 }
class ____(DiophantineEquationType): """ Representation of the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean >>> from sympy.ab...
GeneralPythagorean
python
getsentry__sentry
src/sentry/users/services/usersocialauth/service.py
{ "start": 548, "end": 2231 }
class ____(RpcService): key = "usersocialauth" local_mode = SiloMode.CONTROL @classmethod def get_local_implementation(cls) -> RpcService: from sentry.users.services.usersocialauth.impl import DatabaseBackedUserSocialAuthService return DatabaseBackedUserSocialAuthService() @rpc_me...
UserSocialAuthService
python
huggingface__transformers
src/transformers/models/superglue/image_processing_superglue.py
{ "start": 5122, "end": 22061 }
class ____(BaseImageProcessor): r""" Constructs a SuperGlue image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by `do_resize` in the `preproce...
SuperGlueImageProcessor
python
scrapy__scrapy
tests/test_crawler.py
{ "start": 19940, "end": 20638 }
class ____(TestBaseCrawler): def test_spider_manager_verify_interface(self): settings = Settings( { "SPIDER_LOADER_CLASS": SpiderLoaderWithWrongInterface, } ) with pytest.raises(MultipleInvalid): AsyncCrawlerRunner(settings) def test_c...
TestAsyncCrawlerRunner
python
realpython__materials
python-enum/cardinals.py
{ "start": 134, "end": 402 }
class ____(Enum): def _generate_next_value_(name, start, count, last_values): return name[0] NORTH = auto() SOUTH = auto() EAST = auto() WEST = auto() for point in CardinalDirection: print(point.name, "->", point.value)
CardinalDirection
python
huggingface__transformers
src/transformers/models/time_series_transformer/modeling_time_series_transformer.py
{ "start": 42179, "end": 60178 }
class ____(TimeSeriesTransformerPreTrainedModel): def __init__(self, config: TimeSeriesTransformerConfig): super().__init__(config) if config.scaling == "mean" or config.scaling is True: self.scaler = TimeSeriesMeanScaler(config) elif config.scaling == "std": self.sc...
TimeSeriesTransformerModel
python
dagster-io__dagster
python_modules/dagster/dagster/_cli/proxy_server_manager.py
{ "start": 1067, "end": 5938 }
class ____(AbstractContextManager): """Context manager that manages the lifecycle of a set of proxy code servers targeting a passed-in load target.""" def __init__( self, instance: DagsterInstance, workspace_load_target: WorkspaceLoadTarget, code_server_log_level: str = "INFO", ...
ProxyServerManager
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image49.py
{ "start": 315, "end": 1678 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image49.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(...
TestCompareXLSXFiles
python
jina-ai__jina
tests/integration/docarray_v2/csp/SampleExecutor/executor.py
{ "start": 920, "end": 1866 }
class ____(Executor): @requests(on="/encode") def foo(self, docs: DocList[TextDoc], **kwargs) -> DocList[EmbeddingResponseModel]: ret = [] for doc in docs: ret.append( EmbeddingResponseModel( id=doc.id, text=doc.text, ...
SampleExecutor
python
getsentry__sentry
src/sentry/notifications/notification_action/action_handler_registry/sentry_app_handler.py
{ "start": 602, "end": 2124 }
class ____(ActionHandler): group = ActionHandler.Group.OTHER config_schema = { "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "The configuration schema for a Sentry App Action", "type": "object", "properties": { "target_identifier": {"type"...
SentryAppActionHandler
python
jazzband__django-pipeline
pipeline/finders.py
{ "start": 537, "end": 833 }
class ____(BaseStorageFinder): storage = staticfiles_storage def find(self, path, **kwargs): if not settings.PIPELINE_ENABLED: return super().find(path, **kwargs) else: return [] def list(self, ignore_patterns): return []
PipelineFinder
python
django__django
tests/forms_tests/tests/test_formsets.py
{ "start": 1067, "end": 1581 }
class ____(BaseFormSet): def clean(self): seen_drinks = [] for drink in self.cleaned_data: if drink["name"] in seen_drinks: raise ValidationError("You may only specify a drink once.") seen_drinks.append(drink["name"]) # A FormSet that takes a list of favor...
BaseFavoriteDrinksFormSet
python
falconry__falcon
falcon/inspect.py
{ "start": 18959, "end": 28140 }
class ____(InspectVisitor): """Visitor that returns a string representation of the info class. This is used automatically by calling ``to_string()`` on the info class. It can also be used directly by calling ``StringVisitor.process(info_instance)``. Args: verbose (bool, optional): Adds more in...
StringVisitor
python
protocolbuffers__protobuf
python/google/protobuf/internal/text_format_test.py
{ "start": 28324, "end": 43047 }
class ____(TextFormatBase): def testParseAllFields(self, message_module): message = message_module.TestAllTypes() test_util.SetAllFields(message) ascii_text = text_format.MessageToString(message) parsed_message = message_module.TestAllTypes() text_format.Parse(ascii_text, parsed_message) sel...
TextFormatParserTests
python
great-expectations__great_expectations
great_expectations/experimental/metric_repository/metric_retriever.py
{ "start": 1147, "end": 13060 }
class ____(abc.ABC): """A MetricRetriever is responsible for retrieving metrics for a batch of data. It is an ABC that contains base logic and methods share by both the ColumnDescriptiveMetricsMetricReceiver and MetricListMetricRetriver. """ # noqa: E501 # FIXME CoP def __init__(self, context: Abstrac...
MetricRetriever
python
jazzband__django-oauth-toolkit
oauth2_provider/settings.py
{ "start": 7255, "end": 12842 }
class ____: """ A settings object, that allows OAuth2 Provider settings to be accessed as properties. Any setting with string import paths will be automatically resolved and return the class, rather than the string literal. """ def __init__(self, user_settings=None, defaults=None, import_strin...
OAuth2ProviderSettings
python
huggingface__transformers
tests/models/edgetam/test_modeling_edgetam.py
{ "start": 2546, "end": 4094 }
class ____: def __init__( self, hidden_size=32, hidden_act="relu", mlp_dim=64, num_hidden_layers=2, num_attention_heads=4, attention_downsample_rate=2, num_multimask_outputs=3, iou_head_depth=3, iou_head_hidden_dim=32, ): se...
EdgeTamMaskDecoderTester
python
davidhalter__jedi
test/completion/pep0484_basic.py
{ "start": 3110, "end": 3438 }
class ____: def __init__(self, x): self.x: int = x self.y: int = '' #? int() self.x #? int() self.y #? int() self.y self.z: int self.z = '' #? str() int() self.z self.w: float #? float() self.w
NotCalledClass
python
pytorch__pytorch
test/dynamo/test_backends.py
{ "start": 4983, "end": 5418 }
class ____(torch._dynamo.test_case.TestCase): def test_inplace_normalize(self): def fn(a, b): x = torch.cos(a) x += b return torch.sin(x) a = torch.randn(10) b = torch.randn(10).to(torch.float64) ref = fn(a, b) optimized_fn = torch.compi...
NormalizeIRTests
python
coleifer__peewee
playhouse/sqliteq.py
{ "start": 5224, "end": 9884 }
class ____(SqliteExtDatabase): WAL_MODE_ERROR_MESSAGE = ('SQLite must be configured to use the WAL ' 'journal mode when using this feature. WAL mode ' 'allows one or more readers to continue reading ' 'while another connection...
SqliteQueueDatabase
python
kamyu104__LeetCode-Solutions
Python/make-string-anti-palindrome.py
{ "start": 59, "end": 800 }
class ____(object): def makeAntiPalindrome(self, s): """ :type s: str :rtype: str """ cnt = [0]*26 for x in s: cnt[ord(x)-ord('a')] += 1 if max(cnt) > len(s)//2: return "-1" result = [i for i, x in enumerate(cnt) for _ in xrange...
Solution
python
pypa__virtualenv
src/virtualenv/app_data/read_only.py
{ "start": 882, "end": 1113 }
class ____(PyInfoStoreDisk): def write(self, content): # noqa: ARG002 msg = "read-only app data python info cannot be updated" raise RuntimeError(msg) __all__ = [ "ReadOnlyAppData", ]
_PyInfoStoreDiskReadOnly
python
tensorflow__tensorflow
tensorflow/python/tools/optimize_for_inference_test.py
{ "start": 1651, "end": 31601 }
class ____(test.TestCase): def create_node_def(self, op, name, inputs): new_node = node_def_pb2.NodeDef() new_node.op = op new_node.name = name for input_name in inputs: new_node.input.extend([input_name]) return new_node def create_constant_node_def(self, name, value, dtype, shape=None)...
OptimizeForInferenceTest
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0017_builds_deterministic_order_index.py
{ "start": 149, "end": 534 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0016_add_mkdocs_html_doctype"), ] operations = [ migrations.AddIndex( model_name="build", index=models.Index( fields=["version", "state", "type"], name="buil...
Migration
python
pytorch__pytorch
test/test_torch.py
{ "start": 282456, "end": 290402 }
class ____(TestCase): exact_dtype = True # FIXME: move to indexing test suite @onlyCUDA def test_index_add_bfloat16(self, device): inp_tensor = torch.randn(5, 3, device='cpu').bfloat16() t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu') inde...
TestDevicePrecision
python
numba__numba
numba/cpython/listobj.py
{ "start": 15058, "end": 42953 }
class ____(_ListPayloadMixin): def __init__(self, context, builder, iter_type, iter_val): self._context = context self._builder = builder self._ty = iter_type self._iter = context.make_helper(builder, iter_type, iter_val) self._datamodel = context.data_model_manager[iter_typ...
ListIterInstance
python
python-attrs__attrs
tests/test_cmp.py
{ "start": 8878, "end": 9899 }
class ____: """ Tests for dunder attributes of unnamed classes. """ cls = cmp_using(eq=lambda a, b: a == b) def test_class(self): """ Class name and qualified name should be well behaved. """ assert self.cls.__name__ == "Comparable" assert self.cls.__qualnam...
TestDundersUnnamedClass
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_queried_column_pair_values_to_have_diff.py
{ "start": 669, "end": 5629 }
class ____(QueryExpectation): """Expect the frequency of occurrences of a specified value in a queried column to be at least <mostly> percent of values in that column.""" metric_dependencies = ("query.column_pair",) query = """ SELECT {column_A} - {column_B} as diff FROM {batch} ...
ExpectQueriedColumnPairValuesToHaveDiff