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
mwaskom__seaborn
tests/test_relational.py
{ "start": 45291, "end": 63222 }
class ____(SharedAxesLevelTests, Helpers): func = staticmethod(scatterplot) def get_last_color(self, ax): colors = ax.collections[-1].get_facecolors() unique_colors = np.unique(colors, axis=0) assert len(unique_colors) == 1 return to_rgba(unique_colors.squeeze()) def test...
TestScatterPlotter
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/mapped_collection.py
{ "start": 1192, "end": 2470 }
class ____(Generic[_KT]): """Plain column getter, stores collection of Column objects directly. Serializes to a :class:`._SerializableColumnGetterV2` which has more expensive __call__() performance and some rare caveats. """ __slots__ = ("cols", "composite") def __init__(self, cols: ...
_PlainColumnGetter
python
geekcomputers__Python
XORcipher/test_XOR_cipher.py
{ "start": 403, "end": 3971 }
class ____(TestCase): """ Test XORCipher class. """ def setUp(self): """ The SetUp call with commented values in the event one needs to instantiate mocked objects regarding the XORCipher class. """ # key = mock.MagicMock() # self.XORCipher_1 = XORCipher(...
TestXORCipher
python
doocs__leetcode
solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution.py
{ "start": 0, "end": 381 }
class ____: def isPossibleDivide(self, nums: List[int], k: int) -> bool: if len(nums) % k: return False cnt = Counter(nums) for x in sorted(nums): if cnt[x]: for y in range(x, x + k): if cnt[y] == 0: return F...
Solution
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/bedrock.py
{ "start": 15905, "end": 21069 }
class ____(BedrockBaseSensor[BedrockHook]): """ Poll the batch inference job status until it reaches a terminal state; fails if creation fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:BedrockBatchInferenceSensor` :param ...
BedrockBatchInferenceSensor
python
pandas-dev__pandas
pandas/io/common.py
{ "start": 29929, "end": 30542 }
class ____(BytesIO, ABC): """ Some objects do not support multiple .write() calls (TarFile and ZipFile). This wrapper writes to the underlying buffer on close. """ buffer = BytesIO() @abstractmethod def write_to_buffer(self) -> None: ... def close(self) -> None: if self.closed...
_BufferedWriter
python
prabhupant__python-ds
data_structures/union_find/uf.py
{ "start": 131, "end": 1916 }
class ____: ''' Union-Find data structure along with required functions. Takes 'n' (integer) as input which is the total number of nodes in the structure. ''' def __init__ (self, n): self.ar = [None] * n for i in range(n): self.ar[i] = i self.size = [1] * n ...
Union_find
python
pandas-dev__pandas
setup.py
{ "start": 5388, "end": 7780 }
class ____(sdist_class): """Custom sdist that ensures Cython has compiled all pyx files to c.""" _pyxfiles = [ "pandas/_libs/arrays.pyx", "pandas/_libs/lib.pyx", "pandas/_libs/hashtable.pyx", "pandas/_libs/tslib.pyx", "pandas/_libs/index.pyx", "pandas/_libs/inter...
CheckSDist
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_with_skeleton.py
{ "start": 5312, "end": 5682 }
class ____: @bar @barfoo def bar() -> None: print("bar")""" text_node = TextNode( text=text, metadata={ "module": "example.foo", }, ) chunks: List[TextNode] = code_splitter.get_nodes_from_documents([text_node]) # This is the module scope ass...
Foo
python
crytic__slither
slither/detectors/shadowing/local.py
{ "start": 615, "end": 6587 }
class ____(AbstractDetector): """ Local variable shadowing """ ARGUMENT = "shadowing-local" HELP = "Local variables shadowing" IMPACT = DetectorClassification.LOW CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#local-variab...
LocalShadowing
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1583630, "end": 1585200 }
class ____(sgqlc.types.Type, UniformResourceLocatable, Node): """An executed workflow file for a workflow run.""" __schema__ = github_schema __field_names__ = ("path", "repository_file_url", "repository_name", "run", "viewer_can_push_repository", "viewer_can_read_repository") path = sgqlc.types.Field(s...
WorkflowRunFile
python
html5lib__html5lib-python
html5lib/tests/sanitizer.py
{ "start": 158, "end": 439 }
class ____(pytest.File): def collect(self): with codecs.open(str(self.fspath), "r", encoding="utf-8") as fp: tests = json.load(fp) for i, test in enumerate(tests): yield SanitizerTest.from_parent(self, name=str(i), test=test)
SanitizerFile
python
spyder-ide__spyder
spyder/plugins/explorer/widgets/main_widget.py
{ "start": 1563, "end": 15531 }
class ____(PluginMainWidget): """Explorer widget""" # --- Signals # ------------------------------------------------------------------------ sig_dir_opened = Signal(str, str) """ This signal is emitted to indicate a folder has been opened. Parameters ---------- directory: str ...
ExplorerWidget
python
ray-project__ray
python/ray/tests/chaos/streaming_llm.py
{ "start": 1039, "end": 2842 }
class ____: def __init__(self, llm): self.llm = llm.options(stream=True) @fastapi_app.post("/") async def handle_request(self, prompt: str) -> StreamingResponse: logger.info(f'Got prompt with size "{len(prompt)}"') return StreamingResponse(self.llm.remote(prompt), media_type="text/p...
Textbot
python
run-llama__llama_index
llama-index-core/llama_index/core/schema.py
{ "start": 32455, "end": 40435 }
class ____(Node): """ Generic interface for a data document. This document connects to data sources. """ def __init__(self, **data: Any) -> None: """ Keeps backward compatibility with old 'Document' versions. If 'text' was passed, store it in 'text_resource'. If 'd...
Document
python
bokeh__bokeh
src/bokeh/application/handlers/document_lifecycle.py
{ "start": 1446, "end": 2953 }
class ____(LifecycleHandler): ''' Calls on_session_destroyed callbacks defined on the Document. ''' def __init__(self) -> None: super().__init__() self._on_session_destroyed = _on_session_destroyed #----------------------------------------------------------------------------- # Dev API #--...
DocumentLifecycleHandler
python
py-pdf__pypdf
pypdf/papersizes.py
{ "start": 66, "end": 129 }
class ____(NamedTuple): width: int height: int
Dimensions
python
pypa__virtualenv
src/virtualenv/create/via_global_ref/api.py
{ "start": 685, "end": 4523 }
class ____(Creator, ABC): def __init__(self, options, interpreter) -> None: super().__init__(options, interpreter) self.symlinks = self._should_symlink(options) self.enable_system_site_package = options.system_site @staticmethod def _should_symlink(options): # Priority of wh...
ViaGlobalRefApi
python
python-poetry__poetry
src/poetry/mixology/version_solver.py
{ "start": 1486, "end": 5060 }
class ____: """ A cache of the valid dependencies. The key observation here is that during the search - except at backtracking - once we have decided that a dependency is invalid, we never need check it again. """ def __init__(self, provider: Provider) -> None: self._provider = pro...
DependencyCache
python
sympy__sympy
sympy/matrices/expressions/matexpr.py
{ "start": 18717, "end": 20833 }
class ____(Expr): parent = property(lambda self: self.args[0]) i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, n, m): n, m = map(_sympify, (n, m)) if isinstance(nam...
MatrixElement
python
pypa__pip
tests/functional/test_install_reqs.py
{ "start": 29861, "end": 31654 }
class ____: def test_install_local_project( self, script: PipTestEnvironment, data: TestData, common_wheels: Path ) -> None: uri = (data.src / "simplewheel-2.0").as_uri() script.pip( "install", "--no-index", "-e", f"simplewheel @ {uri}", "-f", common_wheels ) ...
TestEditableDirectURL
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 17278, "end": 17843 }
class ____(VarArray): """ Handles a variable-length array of numeric scalars. """ def parse(self, value, config=None, pos=None): if value.strip() == "": return ma.array([]), False parts = self._splitter(value, config, pos) parse = self._base.parse result = ...
ScalarVarArray
python
realpython__materials
python-inherit-list-userlist/number_list2.py
{ "start": 35, "end": 843 }
class ____(UserList): def __init__(self, iterable): super().__init__(self._validate_number(item) for item in iterable) def __setitem__(self, index, item): self.data[index] = self._validate_number(item) def insert(self, index, item): self.data.insert(index, self._validate_number(ite...
NumberList
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source_param.py
{ "start": 4607, "end": 4974 }
class ____(TypedDict, total=False): template: Required[Iterable[InputMessagesTemplateTemplate]] """A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}. """ type: Required[Literal["template"]] """The type of input mess...
InputMessagesTemplate
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_stats.py
{ "start": 1099, "end": 44713 }
class ____(APITestCase, SnubaTestCase, SearchIssueTestMixin): endpoint = "sentry-api-0-organization-events-stats" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.authed_user = self.user self.day_ago = before_now(days=1).replace(hour=10, minute=0, sec...
OrganizationEventsStatsEndpointTest
python
huggingface__transformers
src/transformers/models/sam2/modeling_sam2.py
{ "start": 29581, "end": 30838 }
class ____(nn.Module): def __init__(self, config: Sam2PromptEncoderConfig): super().__init__() self.mask_input_channels = config.mask_input_channels // 4 self.activation = ACT2FN[config.hidden_act] self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2) s...
Sam2MaskEmbedding
python
huggingface__transformers
tests/generation/test_continuous_batching.py
{ "start": 1261, "end": 25562 }
class ____(unittest.TestCase): @parameterized.expand( [ (None, None, "0"), (None, 4096, "0"), ("f", None, "0"), ("ffff", None, "0000"), ("sssss", 4096, "00000"), ("fs", 4096, "01"), ("ssfssf", 4096, "001221"), ("...
ContinuousBatchingTest
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/trainer/off_policy_trainer.py
{ "start": 881, "end": 10489 }
class ____(RLTrainer): """ The SACTrainer is an implementation of the SAC algorithm, with support for discrete actions and recurrent networks. """ def __init__( self, behavior_name: str, reward_buff_cap: int, trainer_settings: TrainerSettings, training: bool,...
OffPolicyTrainer
python
facebook__pyre-check
client/command_arguments.py
{ "start": 1737, "end": 1873 }
class ____(str, enum.Enum): _value_: str JSON = "json" SHARDED_JSON = "sharded-json" @dataclass(frozen=True)
TaintOutputFormat
python
PyCQA__pylint
tests/functional/c/class_scope.py
{ "start": 893, "end": 1099 }
class ____: """wrong""" class Result2: """result two""" OK = 0 def work(self) -> self.Result2: # [undefined-variable] """bad type hint""" return self.Result2.OK
Wrong
python
pandas-dev__pandas
pandas/tests/frame/methods/test_get_numeric_data.py
{ "start": 209, "end": 3379 }
class ____: def test_get_numeric_data_preserve_dtype(self): # get the numeric data obj = DataFrame({"A": [1, "2", 3.0]}, columns=Index(["A"], dtype="object")) result = obj._get_numeric_data() expected = DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[]) tm.assert_fra...
TestGetNumericData
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 22759, "end": 22886 }
class ____(Stmt): __slots__ = ("value",) @property def is_terminus(self): return self.value.is_terminus
Expr
python
walkccc__LeetCode
solutions/2589. Minimum Time to Complete All Tasks/2589.py
{ "start": 0, "end": 598 }
class ____: def findMinimumTime(self, tasks: list[list[int]]) -> int: MAX = 2000 running = [False] * (MAX + 1) # Sort tasks by end. for start, end, duration in sorted(tasks, key=lambda x: x[1]): neededDuration = (duration - sum(running[i] for i in range(start, end + 1)))...
Solution
python
wandb__wandb
wandb/sdk/launch/inputs/files.py
{ "start": 155, "end": 4685 }
class ____: """Singleton that read file overrides json from environment variables.""" _instance = None def __new__(cls): if cls._instance is None: cls._instance = object.__new__(cls) cls._instance.overrides = {} cls._instance.load() return cls._instance ...
FileOverrides
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/utils.py
{ "start": 2782, "end": 2995 }
class ____(ContextManager[None]): """ (contextlib.nested is not available on Py3) """ def __enter__(self) -> None: pass def __exit__(self, *a: object) -> None: pass
DummyContext
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 329823, "end": 330059 }
class ____(Response): """ Response of tasks.ping endpoint. """ _service = "tasks" _action = "ping" _version = "2.13" _schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
PingResponse
python
aio-libs__aiohttp
aiohttp/tracing.py
{ "start": 8774, "end": 8909 }
class ____: """Parameters sent by the `on_connection_create_end` signal""" @frozen_dataclass_decorator
TraceConnectionCreateEndParams
python
django__django
tests/auth_tests/urls.py
{ "start": 2677, "end": 2797 }
class ____(LoginView): def get_default_redirect_url(self): return "/custom/"
CustomDefaultRedirectURLLoginView
python
ansible__ansible
test/lib/ansible_test/_internal/cli/actions.py
{ "start": 3080, "end": 3367 }
class ____(CompositeAction): """Composite action parser for a network SSH target.""" def create_parser(self) -> NamespaceParser: """Return a namespace parser to parse the argument associated with this action.""" return NetworkSshTargetParser()
NetworkSshTargetAction
python
MongoEngine__mongoengine
docs/code/tumblelog.py
{ "start": 574, "end": 626 }
class ____(Post): content = StringField()
TextPost
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_composite.py
{ "start": 3284, "end": 3621 }
class ____(list): pass @given(st.data(), st.lists(st.integers()).map(MyList)) def test_does_not_change_arguments(data, ls): # regression test for issue #1017 or other argument mutation @st.composite def strat(draw, arg): draw(st.none()) return arg ex = data.draw(strat(ls)) ass...
MyList
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 94845, "end": 95629 }
class ____(sgqlc.types.Enum): """The bypass mode for a rule or ruleset. Enumeration Choices: * `NONE`: Bypassing is disabled * `ORGANIZATION`: Those with bypass permission at the organization level can bypass * `ORGANIZATION_ALWAYS`: Those with bypass permission at the organization lev...
RuleBypassMode
python
falconry__falcon
tests/test_hello.py
{ "start": 2894, "end": 2966 }
class ____: def on_get(self, req, resp): pass
NoStatusResource
python
PrefectHQ__prefect
src/prefect/cli/deploy/_models.py
{ "start": 409, "end": 628 }
class ____(BaseModel): model_config = ConfigDict(extra="ignore") name: Optional[str] = None work_queue_name: Optional[str] = None job_variables: Dict[str, Any] = Field(default_factory=dict)
WorkPoolConfig
python
euske__pdfminer
pdfminer/converter.py
{ "start": 4658, "end": 4912 }
class ____(PDFLayoutAnalyzer): def __init__(self, rsrcmgr, outfp, pageno=1, laparams=None): PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams) self.outfp = outfp return ## TextConverter ##
PDFConverter
python
docker__docker-py
docker/errors.py
{ "start": 4066, "end": 4240 }
class ____(DockerException): def __init__(self, reason, build_log): super().__init__(reason) self.msg = reason self.build_log = build_log
BuildError
python
kamyu104__LeetCode-Solutions
Python/create-target-array-in-the-given-order.py
{ "start": 31, "end": 536 }
class ____(object): def createTargetArray(self, nums, index): """ :type nums: List[int] :type index: List[int] :rtype: List[int] """ for i in xrange(len(nums)): for j in xrange(i): if index[j] >= index[i]: index[j] += 1 ...
Solution
python
cookiecutter__cookiecutter
tests/test_prompt.py
{ "start": 14121, "end": 17409 }
class ____: """Class to unite choices prompt related tests.""" def test_should_invoke_read_user_choice(self, mocker) -> None: """Verify correct function called for select(list) variables.""" prompt_choice = mocker.patch( 'cookiecutter.prompt.prompt_choice_for_config', wr...
TestReadUserChoice
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 43854, "end": 44019 }
class ____(Protocol[_T_co]): def __call__( s, cls: Any, / ) -> Union[_HasClauseElement[_T_co], SQLColumnExpression[_T_co]]: ...
_HybridExprCallableType
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/duplicate_bases.py
{ "start": 88, "end": 114 }
class ____(A, A): ...
F1
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 23515, "end": 23628 }
class ____(lock_tests.SemaphoreTests): semtype = staticmethod(threading.Semaphore) @skipDueToHang
SemaphoreTests
python
tensorflow__tensorflow
tensorflow/python/ops/math_ops_test.py
{ "start": 49102, "end": 49967 }
class ____(test_util.TensorFlowTestCase): allowed_dtypes = [ dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128 ] def testBasic(self): for dtype in self.allowed_dtypes: x = constant_op.constant([1.0, 2.0, 0.0, 4.0], dtype=dtype) y = math_ops.reciproc...
ReciprocalNoNanTest
python
facebookresearch__faiss
tests/torch_test_contrib.py
{ "start": 13276, "end": 14082 }
class ____(unittest.TestCase): def test_python_kmeans(self): """ Test the python implementation of kmeans """ ds = datasets.SyntheticDataset(32, 10000, 0, 0) x = ds.get_train() # bad distribution to stress-test split code xt = x[:10000].copy() xt[:5000] = x[0] ...
TestClustering
python
protocolbuffers__protobuf
python/google/protobuf/internal/type_checkers.py
{ "start": 6355, "end": 7502 }
class ____(object): """Checker used for enum fields. Performs type-check and range check.""" def __init__(self, enum_type): self._enum_type = enum_type def CheckValue(self, proposed_value): global _BoolWarningCount if type(proposed_value) == bool and _BoolWarningCount > 0: _BoolWarningCount ...
EnumValueChecker
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 2682, "end": 2809 }
class ____(Generic[_T_co], SQLRole): """element-typed form of ColumnsClauseRole""" __slots__ = ()
TypedColumnsClauseRole
python
PyCQA__pylint
tests/functional/i/invalid/invalid_hash_returned.py
{ "start": 568, "end": 696 }
class ____: """ __hash__ returns a dict """ def __hash__(self): # [invalid-hash-returned] return {}
FirstBadHash
python
openai__openai-python
src/openai/types/responses/tool.py
{ "start": 5684, "end": 6031 }
class ____(BaseModel): container: CodeInterpreterContainer """The code interpreter container. Can be a container ID or an object that specifies uploaded file IDs to make available to your code. """ type: Literal["code_interpreter"] """The type of the code interpreter tool. Always `code_int...
CodeInterpreter
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/dep_operators.py
{ "start": 7552, "end": 8885 }
class ____(DepsAutomationCondition[T_EntityKey]): @property def base_name(self) -> str: return "ANY_DEPS_MATCH" @property def operator_type(self) -> OperatorType: return "or" async def evaluate( # pyright: ignore[reportIncompatibleMethodOverride] self, context: AutomationC...
AnyDepsCondition
python
pypa__warehouse
tests/unit/admin/views/test_organizations.py
{ "start": 52379, "end": 57463 }
class ____: def test_delete_manual_activation_success(self, db_request, monkeypatch): organization = OrganizationFactory.create(name="test-org") OrganizationManualActivationFactory.create(organization=organization) db_request.matchdict = {"organization_id": str(organization.id)} db_...
TestDeleteManualActivation
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py
{ "start": 20380, "end": 22787 }
class ____: @mock.patch( "airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook" ) def test_job_run(self, mock_hook): mock_hook.return_value.run_transfer_job.return_value = VALID_OPERATION op = CloudDataTransferServiceRunJobOperator( ...
TestGcpStorageTransferJobRunOperator
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qobserver_test.py
{ "start": 3262, "end": 4284 }
class ____(op_bench.TorchBenchmarkBase): def init(self, C, M, N, dtype, qscheme, op_func, device): self.f_input = torch.rand(C, M, N, device=device) self.q_observer = op_func(dtype=dtype, qscheme=qscheme).to(device) self.q_observer(self.f_input) self.inputs = {} def forward(self...
QObserverBenchmarkCalculateQparams
python
ansible__ansible
lib/ansible/module_utils/facts/network/aix.py
{ "start": 5892, "end": 5988 }
class ____(NetworkCollector): _fact_class = AIXNetwork _platform = 'AIX'
AIXNetworkCollector
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_deprecation.py
{ "start": 528, "end": 603 }
class ____: @deprecated() def __init__(self): pass
MockClass3
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 3292, "end": 3834 }
class ____(PipenvException): def __init__(self, contents="", error_text=""): self.error_text = error_text self.contents = contents PipenvException.__init__(self, contents) def show(self, file=None): console = Console(stderr=True, file=file, highlight=False) console.print...
JSONParseError
python
yandexdataschool__Practical_RL
week06_policy_based/atari_wrappers.py
{ "start": 10707, "end": 11227 }
class ____(SummariesBase): """Writes env summaries using Tensorboard.""" def __init__(self, env, prefix=None, running_mean_size=100, step_var=None): super().__init__(env, prefix, running_mean_size, step_var) self.writer = SummaryWriter(f"logs/{self.prefix}") def add_summary(self, name, val...
TensorboardSummaries
python
pypa__pipenv
pipenv/vendor/plette/models/hashes.py
{ "start": 51, "end": 1853 }
class ____(DataModel): """A hash. """ item_class = "Hash" __SCHEMA__ = { } __OPTIONAL__ = { "name": str, "md5": str, "sha256": str, "digest": str, } def __init__(self, data): self.validate(data) self._data = data if "name" in dat...
Hash
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 43393, "end": 43486 }
class ____(Structure): _fields_ = (("magic", p_uint32), ("nfat_arch", p_uint32))
fat_header
python
apache__airflow
providers/mysql/tests/unit/mysql/hooks/test_mysql.py
{ "start": 19188, "end": 21686 }
class ____: def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} dag = DAG(TEST_DAG_ID, schedule=None, default_args=args) self.dag = dag def teardown_method(self): drop_tables = {"test_mysql_to_mysql", "test_airflow"} with closing(MySqlHook().g...
TestMySql
python
pytorch__pytorch
torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py
{ "start": 950, "end": 5737 }
class ____: """Container for manipulating Callgrind results. It supports: 1) Addition and subtraction to combine or diff results. 2) Tuple-like indexing. 3) A `denoise` function which strips CPython calls which are known to be non-deterministic and quite noisy. 4) Two...
FunctionCounts
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 382, "end": 638 }
class ____(Event): name: str = "create_experiment" @classmethod def parse_result(cls, result: Any) -> dict[str, Any] | None: # create_experiment API returns the experiment id return {"experiment_id": result}
CreateExperimentEvent
python
great-expectations__great_expectations
tests/metrics/test_metric.py
{ "start": 3553, "end": 4814 }
class ____: @pytest.mark.unit def test_two_identical_metrics_with_same_batch_id_returns_same_metric_id(self): metric_1 = ColumnValuesAbove( column=COLUMN, min_value=42, ) metric_2 = ColumnValuesAbove( column=COLUMN, min_value=42, ) ...
TestMetricIdFromBatch
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format03.py
{ "start": 350, "end": 2750 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format03.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = ...
TestCompareXLSXFiles
python
ray-project__ray
python/ray/tests/test_memory_pressure.py
{ "start": 2760, "end": 18565 }
class ____: def __init__(self): self.leaks = [] def allocate(self, allocate_bytes: int, sleep_time_ms: int = 0): # divide by 8 as each element in the array occupies 8 bytes new_list = [0] * ceil(allocate_bytes / 8) self.leaks.append(new_list) time.sleep(sleep_time_ms / ...
Leaker
python
getsentry__sentry
tests/sentry/auth/services/test_model.py
{ "start": 241, "end": 898 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization() def test_serializes_correct_fields(self) -> None: internal_app = self.create_internal_integration(organization=self.org) api_token = self.create_internal_integrati...
TestRpcApiToken
python
tensorflow__tensorflow
tensorflow/python/client/session.py
{ "start": 9020, "end": 11808 }
class ____(object): """Definition of the interface provided by fetch mappers. Fetch mappers are utility classes used by the _FetchHandler to handle arbitrary structures for the `fetch` argument to `Session.run()`. The `fetch` argument can be of various shapes: single tensor or op, list of fetches, tuple of ...
_FetchMapper
python
django__django
tests/many_to_one/models.py
{ "start": 769, "end": 992 }
class ____(models.Model): id = models.BigAutoField(primary_key=True) country = models.ForeignKey( Country, models.CASCADE, related_name="cities", null=True ) name = models.CharField(max_length=50)
City
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/dagster_run.py
{ "start": 4498, "end": 4812 }
class ____(IHaveNew): """Utility class to help calculate the immediate impact of launching a run on the op concurrency slots that will be available for other runs. """ root_key_counts: Mapping[str, int] has_unconstrained_root_nodes: bool all_pools: Optional[Set[str]] = None
RunOpConcurrency
python
getsentry__sentry
src/sentry/web/frontend/js_sdk_loader.py
{ "start": 1251, "end": 1425 }
class ____(TypedDict): isLazy: bool config: NotRequired[SdkConfig] jsSdkUrl: NotRequired[str] publicKey: NotRequired[str | None] @region_silo_view
LoaderContext
python
walkccc__LeetCode
solutions/628. Maximum Product of Three Numbers/628-2.py
{ "start": 0, "end": 613 }
class ____: def maximumProduct(self, nums: list[int]) -> int: min1 = inf # the minimum min2 = inf # the second minimum max1 = -inf # the maximum max2 = -inf # the second maximum max3 = -inf # the third maximum for num in nums: if num <= min1: min2 = min1 min1 = nu...
Solution
python
numba__numba
numba/tests/test_errormodels.py
{ "start": 86, "end": 585 }
class ____(unittest.TestCase): def test_div_by_zero_python(self): @jit # python model is the default def model_python(val): return 1 / val with self.assertRaises(ZeroDivisionError): model_python(0) def test_div_by_zero_numpy(self): @jit(error_model='n...
TestErrorModel
python
ansible__ansible
lib/ansible/_internal/ansible_collections/ansible/_protomatter/plugins/action/debug.py
{ "start": 359, "end": 1469 }
class ____(ActionBase): TRANSFERS_FILES = False _requires_connection = False @classmethod def finalize_task_arg(cls, name: str, value: t.Any, templar: TemplateEngine, context: t.Any) -> t.Any: if name == 'expression': return value return super().finalize_task_arg(name, valu...
ActionModule
python
getsentry__sentry
tests/sentry/uptime/test_models.py
{ "start": 1344, "end": 2354 }
class ____(UptimeTestCase): def test(self) -> None: self.create_uptime_subscription(host_provider_name="prov1") self.create_uptime_subscription(host_provider_name="prov1") self.create_uptime_subscription(host_provider_name="prov2") self.create_uptime_subscription(host_provider_name="...
GetTopHostingProviderNamesTest
python
django__django
django/db/models/expressions.py
{ "start": 63274, "end": 64351 }
class ____(Subquery): template = "EXISTS(%(subquery)s)" output_field = fields.BooleanField() empty_result_set_value = False def __init__(self, queryset, **kwargs): super().__init__(queryset, **kwargs) self.query = self.query.exists() def select_format(self, compiler, sql, params): ...
Exists
python
modin-project__modin
modin/core/execution/dispatching/factories/dispatcher.py
{ "start": 1205, "end": 1370 }
class ____(AttributeError): """ ``FactoryNotFound`` exception class. Raise when no matching factory could be found. """ pass
FactoryNotFoundError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 8924, "end": 9044 }
class ____(IncrementalShopifyStreamWithDeletedEvents): data_field = "pages" deleted_events_api_name = "Page"
Pages
python
pytorch__pytorch
torch/utils/data/datapipes/iter/grouping.py
{ "start": 4831, "end": 12441 }
class ____(IterDataPipe[DataChunk]): r""" Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``. (functional name: ``groupby``). The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the ...
GrouperIterDataPipe
python
catalyst-team__catalyst
catalyst/contrib/data/sampler_inbatch.py
{ "start": 3845, "end": 5251 }
class ____(InBatchTripletsSampler): """ This sampler selects all the possible triplets for the given labels """ def __init__(self, max_output_triplets: int = maxsize): """ Args: max_output_triplets: with the strategy of choosing all the triplets, their number...
AllTripletsSampler
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 13707, "end": 16279 }
class ____(test.TestCase, parameterized.TestCase): def _buildParams(self, data, dtype): data = data.astype(dtype.as_numpy_dtype) # For complex types, add an index-dependent imaginary component so we can # tell we got the right value. if dtype.is_complex: return data + 10j * data return data...
GatherTest
python
django-haystack__django-haystack
haystack/generic_views.py
{ "start": 3415, "end": 3865 }
class ____(SearchMixin, FormView): """A view class for searching a Haystack managed search index""" def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates a blank version of the form. """ form_class = self.get_form_class() form = self.get_form...
SearchView
python
tornadoweb__tornado
tornado/template.py
{ "start": 20226, "end": 20949 }
class ____(_Node): def __init__(self, name: str, body: _Node, template: Template, line: int) -> None: self.name = name self.body = body self.template = template self.line = line def each_child(self) -> Iterable["_Node"]: return (self.body,) def generate(self, writer...
_NamedBlock
python
kevin1024__vcrpy
vcr/stubs/boto3_stubs.py
{ "start": 332, "end": 1203 }
class ____(VCRHTTPSConnection, VerifiedHTTPSConnection): _baseclass = VerifiedHTTPSConnection def __init__(self, *args, **kwargs): kwargs.pop("strict", None) # need to temporarily reset here because the real connection # inherits from the thing that we are mocking out. Take out ...
VCRRequestsHTTPSConnection
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_ohio_zip.py
{ "start": 727, "end": 1719 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_ohio_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(c...
ColumnValuesToBeValidOhioZip
python
huggingface__transformers
tests/models/owlvit/test_modeling_owlvit.py
{ "start": 10591, "end": 12222 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (OwlViTTextModel,) if is_torch_available() else () def setUp(self): self.model_tester = OwlViTTextModelTester(self) self.config_tester = ConfigTester(self, config_class=OwlViTTextConfig, hidden_size=37) def test_config(se...
OwlViTTextModelTest
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 3915, "end": 4055 }
class ____(GeoFunc): @cached_property def output_field(self): return GeometryField(srid=self.geo_field.srid)
GeomOutputGeoFunc
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassReplace1.py
{ "start": 510, "end": 780 }
class ____(NamedTuple): a: int b: str c: str = "" nt1 = NT1(1, "") nt1_clone = nt1.__replace__(c="") reveal_type(nt1_clone, expected_text="NT1") # This should generate an error. nt1.__replace__(b=2) # This should generate an error. nt1.__replace__(d="")
NT1
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 3976, "end": 12629 }
class ____(torch._dynamo.test_case.TestCaseWithNestedGraphBreaks): def _assert_wrap_fallback(self, func, args, setup=lambda: None): counters.clear() backend = EagerAndRecordGraphs() cnt = CompileCounterWithBackend(backend) setup() expected = func(*args) setup() ...
HigherOrderOpTests
python
conda__conda
conda/models/match_spec.py
{ "start": 41446, "end": 42890 }
class ____(GlobStrMatch): def __init__(self, value): self._re_match = None try: if isinstance(value, str): if value.startswith("^") and value.endswith("$"): self._re_match = re.compile(value).match elif "*" in value: ...
ChannelMatch
python
django__django
django/template/defaulttags.py
{ "start": 17027, "end": 18090 }
class ____(Node): def __init__(self, val_expr, max_expr, max_width, asvar=None): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width self.asvar = asvar def render(self, context): try: value = self.val_expr.resolve(context) ...
WidthRatioNode
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 49950, "end": 50885 }
class ____(test.TestCase): def testTranspose(self): if np.__version__ == "1.13.0": self.skipTest("numpy 1.13.0 bug") with test_util.force_cpu(): np.random.seed(1618) shapes = [np.random.randint(1, 10, size=rank) for rank in range(1, 6)] for shape in shapes: for dtype in [np.i...
SparseTransposeTest
python
pytorch__pytorch
test/distributed/checkpoint/e2e/test_e2e_save_and_load.py
{ "start": 3025, "end": 4495 }
class ____: step: int = 0 current_loss: float = -1 losses: list[float] = field(default_factory=list) def state_dict(self) -> dict[str, Any]: loss_bytes = BytesIO() torch.save(self.losses, loss_bytes) return { "step": torch.tensor(self.step, dtype=torch.int32), ...
TestTrainState