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 | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/pfor.py | {
"start": 51585,
"end": 186697
} | class ____:
"""Implementation of rewrite of parallel-for loops.
This class takes a DAG or a set of DAGs representing the body of a
parallel-for loop, and adds new operations to the graph that implements
functionality equivalent to running that loop body for a specified number of
iterations. This new set of n... | PFor |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_percent_diff_between_inclusive_threshold_range.py | {
"start": 7913,
"end": 15746
} | class ____(
ProfileNumericColumnsDiffExpectation
):
"""Expect a statistic's percent delta for a given column of a DataProfiler percent difference report to be within the specified threshold, inclusive.
This expectation takes the percent difference report between the data it is called on and a DataProfiler ... | ExpectProfileNumericColumnsPercentDiffBetweenInclusiveThresholdRange |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py | {
"start": 45112,
"end": 48555
} | class ____(GKEOperatorMixin, KubernetesDeleteResourceOperator):
"""
Delete a resource in the specified Google Kubernetes Engine cluster.
This Operator assumes that the system has gcloud installed and has configured a
connection id with a service account.
.. seealso::
For more detail about ... | GKEDeleteCustomResourceOperator |
python | wandb__wandb | wandb/sdk/lib/redirect.py | {
"start": 19142,
"end": 20611
} | class ____(RedirectBase):
"""Patches the write method of current sys.stdout/sys.stderr.
Captures data in a raw form rather than using the emulator
"""
def __init__(
self,
src: Literal["stdout", "stderr"],
cbs: Iterable[Callable[[str], None]] = (),
) -> None:
super()... | StreamRawWrapper |
python | django__django | tests/syndication_tests/models.py | {
"start": 350,
"end": 601
} | class ____(models.Model):
title = models.CharField(max_length=200)
entry = models.ForeignKey(Entry, models.CASCADE)
updated = models.DateTimeField()
published = models.DateTimeField()
class Meta:
ordering = ["updated"]
| Article |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 88071,
"end": 88979
} | class ____(unittest.TestCase):
def test_same_seed_is_used_between_fuzzy_and_faker_generators(self):
class StudentFactory(factory.Factory):
one = factory.fuzzy.FuzzyDecimal(4.0)
two = factory.Faker('name')
three = factory.Faker('name', locale='it')
four = facto... | RepeatableRandomSeedFakerTests |
python | kamyu104__LeetCode-Solutions | Python/counting-bits.py | {
"start": 29,
"end": 572
} | class ____(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0]
for i in xrange(1, num + 1):
# Number of 1's in i = (i & 1) + number of 1's in (i / 2).
res.append((i & 1) + res[i >> 1])
return res
d... | Solution |
python | RaRe-Technologies__gensim | gensim/models/poincare.py | {
"start": 53366,
"end": 55354
} | class ____:
"""Stream relations for `PoincareModel` from a tsv-like file."""
def __init__(self, file_path, encoding='utf8', delimiter='\t'):
"""Initialize instance from file containing a pair of nodes (a relation) per line.
Parameters
----------
file_path : str
Path... | PoincareRelations |
python | paramiko__paramiko | paramiko/channel.py | {
"start": 47659,
"end": 48665
} | class ____(BufferedFile):
"""
A file-like wrapper around `.Channel`. A ChannelFile is created by calling
`Channel.makefile`.
.. warning::
To correctly emulate the file object created from a socket's `makefile
<python:socket.socket.makefile>` method, a `.Channel` and its
`.Chann... | ChannelFile |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/unit_tests/common.py | {
"start": 1494,
"end": 4259
} | class ____:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(MockGoogleAdsFieldService, cls).__new__(cls)
cls._instance.request_query = None
return cls._instance
def search_google_ads_fields(self, request):
self.request_quer... | MockGoogleAdsFieldService |
python | pypa__pip | src/pip/_internal/metadata/pkg_resources.py | {
"start": 1036,
"end": 1112
} | class ____(NamedTuple):
name: str
value: str
group: str
| EntryPoint |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v1.py | {
"start": 1733,
"end": 18433
} | class ____(tpu_embedding_base.TPUEmbeddingBase):
"""The TPUEmbedding mid level API running on TPU without Embedding accelerator.
NOTE: This mid level API is not intended for large embedding table lookup.
Embedding tables will be replicated across devices rather than sharding
across them. To do large embedding ... | TPUEmbeddingV0 |
python | pytorch__pytorch | torch/_higher_order_ops/wrap.py | {
"start": 753,
"end": 1254
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("wrap")
def __call__(self, func, *args, **kwargs):
# Dynamo already traces the body of HigherOrderOp beforehand when it
# so no need to trace into it.
import torch._dynamo # noqa: F401
from to... | Wrap |
python | pytorch__pytorch | test/dynamo/test_exc.py | {
"start": 507,
"end": 10619
} | class ____(LoggingTestCase):
maxDiff = None
def test_unsupported_real_stack(self):
# exercise Unsupported constructor and augment_exc_message
def fn002(x):
torch._dynamo.graph_break()
def fn001(x):
x = x + 1
fn002(x)
self.assertExpectedInlin... | ExcTests |
python | walkccc__LeetCode | solutions/2341. Maximum Number of Pairs in Array/2341.py | {
"start": 0,
"end": 230
} | class ____:
def numberOfPairs(self, nums: list[int]) -> list[int]:
ans = [0] * 2
count = collections.Counter(nums)
for i in range(101):
ans[0] += count[i] // 2
ans[1] += count[i] & 1
return ans
| Solution |
python | cython__cython | Cython/Build/Tests/TestInline.py | {
"start": 3489,
"end": 5695
} | class ____(unittest.TestCase):
def _run(self, code, setup_code=None, **kwargs):
timings, number = cymeit(code, setup_code=setup_code, **kwargs)
self.assertGreater(min(timings), 0)
# Guard that autoscaling leads to reasonable timings.
# Note: we cannot compare against the expected 0... | TestCymeit |
python | tensorflow__tensorflow | tensorflow/compiler/tests/rmsprop_test.py | {
"start": 1037,
"end": 5165
} | class ____(xla_test.XLATestCase):
def _rmsprop_update_numpy(self,
var,
g,
mg,
rms,
mom,
lr,
decay=0.9,
... | RmspropTest |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/emr/pyspark_step_launcher.py | {
"start": 9501,
"end": 20413
} | class ____(StepLauncher):
def __init__(
self,
region_name,
staging_bucket,
staging_prefix,
wait_for_logs,
action_on_failure,
cluster_id,
spark_config,
local_job_package_path,
deploy_local_job_package,
s3_job_package_path=None,
... | EmrPySparkStepLauncher |
python | yaml__pyyaml | setup.py | {
"start": 6655,
"end": 9990
} | class ____(_build_ext):
def finalize_options(self):
super().finalize_options()
pep517_config = ActiveConfigSettings.current()
build_config = pep517_config.get('pyyaml_build_config')
if build_config:
import json
build_config = json.loads(build_config)
... | build_ext |
python | TheAlgorithms__Python | maths/pi_monte_carlo_estimation.py | {
"start": 16,
"end": 2042
} | class ____:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def is_in_unit_circle(self) -> bool:
"""
True, if the point lies in the unit circle
False, otherwise
"""
return (self.x**2 + self.y**2) <= 1
@classmethod
def random... | Point |
python | spyder-ide__spyder | spyder/plugins/editor/plugin.py | {
"start": 1141,
"end": 44051
} | class ____(SpyderDockablePlugin):
"""
Editor plugin.
"""
NAME = 'editor'
REQUIRES = [Plugins.Application, Plugins.Console, Plugins.Preferences]
OPTIONAL = [
Plugins.Completions,
Plugins.Debugger,
Plugins.IPythonConsole,
Plugins.MainMenu,
Plugins.Projects,... | Editor |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/d.py | {
"start": 1043,
"end": 2297
} | class ____(stlink_task):
pass
@extension('.d', '.di', '.D')
def d_hook(self, node):
ext = Utils.destos_to_binfmt(self.env.DEST_OS) == 'pe' and 'obj' or 'o'
out = '%s.%d.%s' % (node.name, self.idx, ext)
def create_compiled_task(self, name, node):
task = self.create_task(name, node, node.parent... | dstlib |
python | getsentry__sentry | src/sentry/integrations/api/serializers/rest_framework/data_forwarder.py | {
"start": 633,
"end": 810
} | class ____(TypedDict, total=False):
queue_url: str
region: str
access_key: str
secret_key: str
message_group_id: str | None
s3_bucket: str | None
| SQSConfig |
python | readthedocs__readthedocs.org | readthedocs/domains/tests/test_tasks.py | {
"start": 586,
"end": 4909
} | class ____(TestCase):
def setUp(self):
self.user = get(User, email="user@example.com")
self.another_user = get(User, email="anotheruser@example.com")
self.project = get(Project, users=[self.user])
self.another_project = get(Project, users=[self.user, self.another_user])
self... | TestTasks |
python | keras-team__keras | keras/src/utils/file_utils_test.py | {
"start": 255,
"end": 1323
} | class ____(test_case.TestCase):
def test_path_to_string_with_string_path(self):
path = os.path.join(os.path.sep, "path", "to", "file.txt")
string_path = file_utils.path_to_string(path)
self.assertEqual(string_path, path)
def test_path_to_string_with_PathLike_object(self):
path =... | PathToStringTest |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 5973,
"end": 6164
} | class ____(CreateValues):
"""Check the creation of heterogeneous arrays (plain, single row)"""
_descr = Pdescr
multiple_rows = 0
_buffer = PbufferT[0]
| TestCreateValuesPlainSingle |
python | ipython__ipython | IPython/terminal/shortcuts/filters.py | {
"start": 4653,
"end": 10998
} | class ____(Filter):
"""A filter allowing to implement pass-through behaviour of keybindings.
Prompt toolkit key processor dispatches only one event per binding match,
which means that adding a new shortcut will suppress the old shortcut
if the keybindings are the same (unless one is filtered out).
... | PassThrough |
python | encode__starlette | starlette/datastructures.py | {
"start": 13086,
"end": 15397
} | class ____:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: BinaryIO,
*,
size: int | None = None,
filename: str | None = None,
headers: Headers | None = None,
) -> None:
self.filename = filename
... | UploadFile |
python | doocs__leetcode | solution/2200-2299/2225.Find Players With Zero or One Losses/Solution.py | {
"start": 0,
"end": 382
} | class ____:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
cnt = Counter()
for winner, loser in matches:
if winner not in cnt:
cnt[winner] = 0
cnt[loser] += 1
ans = [[], []]
for x, v in sorted(cnt.items()):
if v... | Solution |
python | pypa__pip | src/pip/_vendor/pygments/filters/__init__.py | {
"start": 31761,
"end": 32670
} | class ____(Filter):
"""Convert keywords to lowercase or uppercase or capitalize them, which
means first letter uppercase, rest lowercase.
This can be useful e.g. if you highlight Pascal code and want to adapt the
code to your styleguide.
Options accepted:
`case` : string
The casing to ... | KeywordCaseFilter |
python | walkccc__LeetCode | solutions/3335. Total Characters in String After Transformations I/3335-2.py | {
"start": 0,
"end": 1449
} | class ____:
def lengthAfterTransformations(self, s: str, t: int) -> int:
MOD = 1_000_000_007
def matrixMult(A: list[list[int]], B: list[list[int]]) -> list[list[int]]:
"""Returns A * B."""
sz = len(A)
C = [[0] * sz for _ in range(sz)]
for i in range(sz):
for j in range(sz):
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/framework/type_spec_test.py | {
"start": 5336,
"end": 5510
} | class ____:
"""CompositeTensor containing a nest of tensors."""
def __init__(self, x):
self.nest = x
@type_spec_registry.register("tf.NestOfTensorsSpec")
| NestOfTensors |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mysqldb.py | {
"start": 3442,
"end": 9886
} | class ____(MySQLDialect):
driver = "mysqldb"
supports_statement_cache = True
supports_unicode_statements = True
supports_sane_rowcount = True
supports_sane_multi_rowcount = True
supports_native_decimal = True
default_paramstyle = "format"
execution_ctx_cls = MySQLExecutionContext_mysql... | MySQLDialect_mysqldb |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 29462,
"end": 30051
} | class ____(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
The server SHOULD return a response with this status code if a
request included a Range request-header field, and none of the
range-specifier values in this field overlap the current extent
of the selected resource, and the ... | HTTPRequestRangeNotSatisfiable |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 2709,
"end": 2848
} | class ____(CookiecutterException):
"""
Exception for hook failures.
Raised when a hook script fails.
"""
| FailedHookException |
python | pandas-dev__pandas | pandas/core/arrays/boolean.py | {
"start": 7621,
"end": 13482
} | class ____(BaseMaskedArray):
"""
Array of boolean (True/False) data with missing values.
This is a pandas Extension array for boolean data, under the hood
represented by 2 numpy arrays: a boolean array with the data and
a boolean array with the mask (True indicating missing).
BooleanArray impl... | BooleanArray |
python | streamlit__streamlit | lib/tests/streamlit/elements/file_uploader_test.py | {
"start": 17324,
"end": 20091
} | class ____(DeltaGeneratorTestCase):
def test_stable_id_with_key(self):
"""Test that the widget ID is stable when a stable key is provided, unless whitelisted kwargs change."""
with patch(
"streamlit.elements.lib.utils._register_element_id",
return_value=MagicMock(),
)... | FileUploaderStableIdTest |
python | pypa__warehouse | tests/unit/accounts/test_security_policy.py | {
"start": 5603,
"end": 21706
} | class ____:
def test_verify(self):
assert verifyClass(
ISecurityPolicy,
security_policy.SessionSecurityPolicy,
)
def test_noops(self):
policy = security_policy.SessionSecurityPolicy()
with pytest.raises(NotImplementedError):
policy.authenticat... | TestSessionSecurityPolicy |
python | pallets__werkzeug | src/werkzeug/serving.py | {
"start": 2357,
"end": 4787
} | class ____(io.RawIOBase):
"""An input stream that handles Transfer-Encoding 'chunked'"""
def __init__(self, rfile: t.IO[bytes]) -> None:
self._rfile = rfile
self._done = False
self._len = 0
def readable(self) -> bool:
return True
def read_chunk_len(self) -> int:
... | DechunkedInput |
python | pypa__pipenv | pipenv/patched/pip/_internal/network/auth.py | {
"start": 1758,
"end": 2936
} | class ____(KeyRingBaseProvider):
"""Keyring interface which uses locally imported `keyring`"""
has_keyring = True
def __init__(self) -> None:
import keyring
self.keyring = keyring
def get_auth_info(self, url: str, username: Optional[str]) -> Optional[AuthInfo]:
# Support keyr... | KeyRingPythonProvider |
python | python__mypy | mypyc/test/test_external.py | {
"start": 223,
"end": 1832
} | class ____(unittest.TestCase):
# TODO: Get this to work on Windows.
# (Or don't. It is probably not a good use of time.)
@unittest.skipIf(sys.platform.startswith("win"), "rt tests don't work on windows")
def test_c_unit_test(self) -> None:
"""Run C unit tests in a subprocess."""
cppflags... | TestExternal |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project_views.py | {
"start": 13394,
"end": 20357
} | class ____(TestCase):
def setUp(self):
self.user = new(User, username="eric")
self.user.set_password("test")
self.user.save()
self.client.login(username="eric", password="test")
self.project = get(Project, slug="pip", users=[self.user])
def test_dashboard_number_of_queri... | TestPrivateViews |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_python_ast_rule.py | {
"start": 15565,
"end": 18941
} | class ____:
"""Test integration with the full validation pipeline."""
def test_integration_valid_docstring(self):
"""Test integration with valid Python code blocks."""
docstring = """
Function with valid Python examples.
Args:
name: The name parameter
... | TestIntegrationWithValidationPipeline |
python | getsentry__sentry | tests/sentry/seer/autofix/test_autofix.py | {
"start": 26085,
"end": 30920
} | class ____(TestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
# Create events with real tag data
# Event 1: production environment with user_role admin
self.store_event(
data={
"fingerprint": ["group-1"],
"environment": "pr... | TestGetAllTagsOverview |
python | conda__conda | tests/conftest.py | {
"start": 4579,
"end": 9351
} | class ____:
@staticmethod
def single_platform_export(env: Environment) -> str:
return "\n".join(
(
"# This is a single-platform export",
f"name: {env.name}",
f"single-platform: {env.platform}",
"packages:",
*(f"-... | Exporters |
python | docker__docker-py | docker/types/networks.py | {
"start": 2926,
"end": 4240
} | class ____(dict):
"""
Create an IPAM pool config dictionary to be added to the
``pool_configs`` parameter of
:py:class:`~docker.types.IPAMConfig`.
Args:
subnet (str): Custom subnet for this IPAM pool using the CIDR
notation. Defaults to ``None``.
iprange (str): Custom I... | IPAMPool |
python | wandb__wandb | wandb/sdk/launch/runner/sagemaker_runner.py | {
"start": 4221,
"end": 15268
} | class ____(AbstractRunner):
"""Runner class, uses a project to create a SagemakerSubmittedRun."""
def __init__(
self,
api: Api,
backend_config: Dict[str, Any],
environment: AwsEnvironment,
registry: AbstractRegistry,
) -> None:
"""Initialize the SagemakerRunn... | SageMakerRunner |
python | huggingface__transformers | src/transformers/models/fsmt/modeling_fsmt.py | {
"start": 7634,
"end": 10098
} | class ____(PreTrainedModel):
config: FSMTConfig
base_model_prefix = "model"
@torch.no_grad()
def _init_weights(self, module):
std = self.config.init_std
if isinstance(module, nn.Linear):
init.normal_(module.weight, mean=0.0, std=std)
if module.bias is not None:
... | PretrainedFSMTModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-chat/components.py | {
"start": 386,
"end": 1167
} | class ____(RecordExtractor):
"""
Unnesting nested bans: `visitor`, `ip_address`.
"""
def extract_records(
self,
response: requests.Response,
) -> Iterable[Mapping[str, Any]]:
response_data = response.json()
ip_address: List[Mapping[str, Any]] = response_data.get("ip_... | ZendeskChatBansRecordExtractor |
python | django__django | tests/forms_tests/tests/test_formsets.py | {
"start": 72214,
"end": 76962
} | class ____(SimpleTestCase):
def test_no_data_error(self):
formset = ArticleFormSet({})
self.assertIs(formset.is_valid(), False)
self.assertEqual(
formset.non_form_errors(),
[
"ManagementForm data is missing or has been tampered with. "
... | TestIsBoundBehavior |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/backfill.py | {
"start": 8356,
"end": 8642
} | class ____(graphene.ObjectType):
start = graphene.NonNull(graphene.String)
end = graphene.NonNull(graphene.String)
class Meta:
name = "PartitionRange"
def __init__(self, start: str, end: str):
super().__init__(start=start, end=end)
| GraphenePartitionRange |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1029653,
"end": 1030123
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateEnvironment"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "environment")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the ... | UpdateEnvironmentPayload |
python | openai__openai-python | src/openai/types/fine_tuning/job_list_events_params.py | {
"start": 200,
"end": 400
} | class ____(TypedDict, total=False):
after: str
"""Identifier for the last event from the previous pagination request."""
limit: int
"""Number of events to retrieve."""
| JobListEventsParams |
python | google__jax | jax/_src/tpu_custom_call.py | {
"start": 4019,
"end": 4358
} | class ____(enum.Enum):
# No side effects, can be deduplicated / removed if unused.
PURE = "pure"
# Cannot be deduplicated, but can be removed if unused.
DATAFLOW_SIDE_EFFECTING = "dataflow_side_effecting"
# Cannot be deduplicated or removed.
SIDE_EFFECTING = "side_effecting"
@dataclasses.dataclass(frozen=... | TpuSideEffectType |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_vml02.py | {
"start": 359,
"end": 2891
} | class ____(unittest.TestCase):
"""
Test assembling a complete Vml file.
"""
def test_assemble_xml_file(self):
"""Test writing a vml with no cell data."""
self.maxDiff = None
fh = StringIO()
vml = Vml()
vml._set_filehandle(fh)
button = ButtonType(1, 2, ... | TestAssembleVml |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_pickling.py | {
"start": 2016,
"end": 2655
} | class ____:
__pydantic_serializer__: SchemaSerializer
__pydantic_complete__ = True
def test_schema_serializer_not_reused_when_unpickling() -> None:
s = SchemaSerializer(
core_schema.model_schema(
cls=Model,
schema=core_schema.model_fields_schema(fields={}, model_name='Model... | Model |
python | PrefectHQ__prefect | tests/cli/test_work_pool.py | {
"start": 29614,
"end": 31458
} | class ____:
async def test_provision_infra(self, monkeypatch, push_work_pool, prefect_client):
client_res = await prefect_client.read_work_pool(push_work_pool.name)
assert client_res.base_job_template != FAKE_DEFAULT_BASE_JOB_TEMPLATE
mock_provision = AsyncMock()
class MockProvisio... | TestProvisionInfrastructure |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_poly_persistence.py | {
"start": 891,
"end": 2884
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global companies, people, engineers, managers, boss
companies = Table(
"companies",
metadata,
Column(
"company_id",
Integer,
primar... | PolymorphTest |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/checksum_common.py | {
"start": 185,
"end": 995
} | class ____(object):
DOCUMENTATION = r"""
options:
checksum_algorithm:
description:
- Algorithm to determine checksum of file.
- Will throw an error if the host is unable to use specified algorithm.
- The remote host has to support the hashing method specified, V(md5)
... | ModuleDocFragment |
python | django__django | tests/model_fields/test_integerfield.py | {
"start": 8924,
"end": 9093
} | class ____(IntegerFieldTests):
model = SmallIntegerModel
documented_range = (-32768, 32767)
rel_db_type_class = models.SmallIntegerField
| SmallIntegerFieldTests |
python | PyCQA__pylint | tests/functional/u/unsubscriptable_value.py | {
"start": 1712,
"end": 1800
} | class ____(type):
def __getitem__(cls, key):
return key + key
| MetaSubscriptable |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/hook.py | {
"start": 7580,
"end": 12370
} | class ____(HookContext):
def __init__(
self,
resources: Mapping[str, Any],
op: Optional[Union[OpDefinition, PendingNodeInvocation]],
run_id: Optional[str],
job_name: Optional[str],
op_exception: Optional[Exception],
instance: Optional["DagsterInstance"],
)... | UnboundHookContext |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/nios.py | {
"start": 288,
"end": 1986
} | class ____(CloudProvider):
"""Nios plugin. Sets up NIOS mock server for tests."""
# Default image to run the nios simulator.
#
# The simulator must be pinned to a specific version
# to guarantee CI passes with the version used.
#
# It's source source itself resides at:
# https://github.... | NiosProvider |
python | marshmallow-code__marshmallow | tests/test_schema.py | {
"start": 49150,
"end": 51311
} | class ____:
def test_errors_are_cleared_after_loading_collection(self):
def always_fail(val):
raise ValidationError("lol")
class MySchema(Schema):
foo = fields.Str(validate=always_fail)
schema = MySchema()
with pytest.raises(ValidationError) as excinfo:
... | TestFieldValidation |
python | huggingface__transformers | src/transformers/models/gpt2/modeling_gpt2.py | {
"start": 46450,
"end": 52153
} | class ____(GPT2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = GPT2Model(config)
self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
# Initialize weights and apply final processing
... | GPT2ForSequenceClassification |
python | django__django | tests/inspectdb/models.py | {
"start": 5304,
"end": 5478
} | class ____(models.Model):
pk = models.CompositePrimaryKey("column_1", "column_2")
column_1 = models.IntegerField()
column_2 = models.IntegerField()
| CompositePKModel |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 307557,
"end": 312894
} | class ____(StatNode):
# raise statement
#
# exc_type ExprNode or None
# exc_value ExprNode or None
# exc_tb ExprNode or None
# cause ExprNode or None
#
# set in FlowControl
# in_try_block bool
child_attrs = ["exc_type", "exc_value", "exc_tb", "cause"]
... | RaiseStatNode |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/tests/common/test_connection.py | {
"start": 2484,
"end": 8408
} | class ____:
"""Tests for verifying the database connection and required extensions.
These tests exercise ``check_connection`` with various mocked cursor
responses to validate behavior for installed extensions, missing
extensions, version mismatches, and broken cursors.
"""
def test_it_works(se... | TestCheckConnection |
python | joke2k__faker | faker/providers/company/ru_RU/__init__.py | {
"start": 514,
"end": 32960
} | class ____(CompanyProvider):
formats = (
"{{company_prefix}} «{{last_name}}»",
"{{company_prefix}} «{{last_name}} {{last_name}}»",
"{{company_prefix}} «{{last_name}}-{{last_name}}»",
"{{company_prefix}} «{{last_name}}, {{last_name}} и {{last_name}}»",
"{{last_name}} {{company... | Provider |
python | pytorch__pytorch | test/test_fx_passes.py | {
"start": 15190,
"end": 15627
} | class ____:
@staticmethod
def forward(x):
a = torch.neg(x)
return torch.add(a, a)
@staticmethod
def pattern(x):
a = torch.neg(x)
return torch.add(a, a)
test_cases = [
# match_output, match_placeholder, num_matches
TestCase(False, False, 1),
T... | SimpleFullGraphMatching |
python | huggingface__transformers | src/transformers/models/glm4v/video_processing_glm4v.py | {
"start": 2041,
"end": 10034
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 2 * 30000}
max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
do_resize = True
do_rescale = True
... | Glm4vVideoProcessor |
python | google__pytype | pytype/abstract/_interpreter_function.py | {
"start": 3594,
"end": 37319
} | class ____(_function_base.SignedFunction):
"""An abstract value representing a user-defined function.
Attributes:
name: Function name. Might just be something like "<lambda>".
code: A code object.
closure: Tuple of cells (cfg.Variable) containing the free variables this
closure binds to.
ctx:... | InterpreterFunction |
python | walkccc__LeetCode | solutions/1423. Maximum Points You Can Obtain from Cards/1423.py | {
"start": 0,
"end": 347
} | class ____:
def maxScore(self, cardPoints: list[int], k: int) -> int:
n = len(cardPoints)
summ = sum(cardPoints)
windowSum = sum(cardPoints[:n - k])
ans = summ - windowSum
for i in range(k):
windowSum -= cardPoints[i]
windowSum += cardPoints[i + n - k]
ans = max(ans, summ - wind... | Solution |
python | aio-libs__aiohttp | tests/test_web_response.py | {
"start": 36601,
"end": 44723
} | class ____(io.IOBase):
def __init__(self) -> None:
self._lines = [b"", b"", b"test"]
def read(self, size: int = -1) -> bytes:
return self._lines.pop()
@pytest.mark.parametrize(
"payload,expected",
(
("test", "test"),
(CustomIO(), "test"),
(io.StringIO("test"), ... | CustomIO |
python | tensorflow__tensorflow | tensorflow/python/types/internal.py | {
"start": 1019,
"end": 1170
} | class ____(object):
"""Interface for internal isinstance checks to framework/type_spec.py.
This helps to avoid circular dependencies.
"""
| TypeSpec |
python | instagram__MonkeyType | monkeytype/type_checking_imports_transformer.py | {
"start": 5688,
"end": 7745
} | class ____(CSTTransformer):
def __init__(
self,
import_items_to_be_removed: List[ImportItem],
) -> None:
super().__init__()
self.import_items_to_be_removed = import_items_to_be_removed
def leave_Import(
self, original_node: Import, updated_node: Import
) -> Union... | RemoveImportsTransformer |
python | dask__distributed | distributed/shuffle/_disk.py | {
"start": 3017,
"end": 8248
} | class ____(ShardsBuffer):
"""Accept, buffer, and write many small objects to many files
This takes in lots of small objects, writes them to a local directory, and
then reads them back when all writes are complete. It buffers these
objects in memory so that it can optimize disk access for larger writes... | DiskShardsBuffer |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/aws.py | {
"start": 510,
"end": 2646
} | class ____(CloudProvider):
"""AWS cloud provider plugin. Sets up cloud resources before delegation."""
def __init__(self, args: IntegrationConfig) -> None:
super().__init__(args)
self.uses_config = True
def filter(self, targets: tuple[IntegrationTarget, ...], exclude: list[str]) -> None:
... | AwsCloudProvider |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14849,
"end": 14961
} | class ____(QueryExecutionError):
"""
Exception raised when a column is missing.
"""
| QueryMissingColumn |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 8549,
"end": 20270
} | class ____(fixtures.TestBase):
def test_boolean(self):
"Exercise type specification for boolean type."
columns = [
# column type, args, kwargs, expected ddl
(Boolean, [], {}, "BIT")
]
metadata = MetaData()
table_args = ["test_mssql_boolean", metadata... | TypeDDLTest |
python | facelessuser__soupsieve | tests/test_level4/test_has.py | {
"start": 90,
"end": 4183
} | class ____(util.TestCase):
"""Test has selectors."""
MARKUP = """
<div id="0" class="aaaa">
<p id="1" class="bbbb"></p>
<p id="2" class="cccc"></p>
<p id="3" class="dddd"></p>
<div id="4" class="eeee">
<div id="5" class="ffff">
<div id="6" class="gggg">
... | TestHas |
python | huggingface__transformers | examples/pytorch/language-modeling/run_mlm.py | {
"start": 5631,
"end": 28510
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
... | DataTrainingArguments |
python | pytorch__pytorch | test/inductor/test_cpu_select_algorithm.py | {
"start": 4206,
"end": 4778
} | class ____(TestCase):
def _check_amx_counter(self, vec_amx):
if vec_amx:
self.assertTrue(counters["inductor"]["cpp_micro_gemm_amx_counter"] > 0)
else:
self.assertEqual(counters["inductor"]["cpp_micro_gemm_amx_counter"], 0)
def _check_brgemm_counter(self, vec_amx):
... | BaseTestSelectAlgorithm |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 80916,
"end": 82290
} | class ____(Request):
"""
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
"""
_service = "queues"
_action = "move_task_to_back"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"queue": {"description": "Queu... | MoveTaskToBackRequest |
python | encode__httpx | httpx/_transports/default.py | {
"start": 3944,
"end": 8667
} | class ____(BaseTransport):
def __init__(
self,
verify: ssl.SSLContext | str | bool = True,
cert: CertTypes | None = None,
trust_env: bool = True,
http1: bool = True,
http2: bool = False,
limits: Limits = DEFAULT_LIMITS,
proxy: ProxyTypes | None = None,... | HTTPTransport |
python | celery__celery | t/unit/app/test_schedules.py | {
"start": 9469,
"end": 19208
} | class ____:
def crontab(self, *args, **kwargs):
return crontab(*args, **dict(kwargs, app=self.app))
def next_occurrence(self, crontab, now):
crontab.nowfun = lambda: now
return now + crontab.remaining_estimate(now)
def test_next_minute(self):
next = self.next_occurrence(
... | test_crontab_remaining_estimate |
python | pytorch__pytorch | torch/_subclasses/meta_utils.py | {
"start": 30348,
"end": 88856
} | class ____(Generic[_TensorT]):
def __init__(self, *, copy_data: bool = False) -> None:
# Maps MetaStorageId to UntypedStorage
self.storage_memo: weakref.WeakValueDictionary[
MetaStorageId, torch.UntypedStorage
] = weakref.WeakValueDictionary()
# Maps MetaTensorId to torch... | MetaConverter |
python | kamyu104__LeetCode-Solutions | Python/open-the-lock.py | {
"start": 183,
"end": 1040
} | class ____(object):
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
dead = set(deadends)
q = ["0000"]
lookup = {"0000"}
depth = 0
while q:
next_q = []
for nod... | Solution |
python | fastapi__sqlmodel | sqlmodel/sql/_expression_select_cls.py | {
"start": 411,
"end": 1121
} | class ____(_Select[Tuple[_T]]):
inherit_cache = True
def where(self, *whereclause: Union[_ColumnExpressionArgument[bool], bool]) -> Self:
"""Return a new `Select` construct with the given expression added to
its `WHERE` clause, joined to the existing clause via `AND`, if any.
"""
... | SelectBase |
python | walkccc__LeetCode | solutions/2977. Minimum Cost to Convert String II/2977.py | {
"start": 0,
"end": 1904
} | class ____:
def minimumCost(
self,
source: str,
target: str,
original: list[str],
changed: list[str],
cost: list[int],
) -> int:
subLengths = set(len(s) for s in original)
subToId = self._getSubToId(original, changed)
subCount = len(subToId)
# dist[u][v] := the mi... | Solution |
python | walkccc__LeetCode | solutions/2945. Find Maximum Non-decreasing Array Length/2945.py | {
"start": 0,
"end": 921
} | class ____:
def findMaximumLength(self, nums: list[int]) -> int:
n = len(nums)
INF = 10_000_000_000
# prefix[i] := the sum of the first i nums
prefix = list(itertools.accumulate(nums, initial=0))
# dp[i] := the maximum number of elements in the increasing
# sequence after processing the first ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/masking-personal-information.py | {
"start": 29,
"end": 502
} | class ____(object):
def maskPII(self, S):
"""
:type S: str
:rtype: str
"""
if '@' in S:
first, after = S.split('@')
return "{}*****{}@{}".format(first[0], first[-1], after).lower()
digits = filter(lambda x: x.isdigit(), S)
local = "***... | Solution |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call.py | {
"start": 1028,
"end": 1364
} | class ____(BaseModel):
type: Literal["double_click"]
"""Specifies the event type.
For a double click action, this property is always set to `double_click`.
"""
x: int
"""The x-coordinate where the double click occurred."""
y: int
"""The y-coordinate where the double click occurred."""... | ActionDoubleClick |
python | sphinx-doc__sphinx | sphinx/writers/latex.py | {
"start": 1617,
"end": 1725
} | class ____(nodes.footnote):
"""Footnotes that are collected are assigned this class."""
| collected_footnote |
python | streamlit__streamlit | lib/tests/streamlit/runtime/state/widgets_test.py | {
"start": 23470,
"end": 24989
} | class ____(DeltaGeneratorTestCase):
@parameterized.expand(WIDGET_ELEMENTS)
def test_register_widget_called_with_valid_value_type(
self, _element_name: str, widget_func: ELEMENT_PRODUCER
):
with patch(
"streamlit.runtime.state.widgets.register_widget_from_metadata",
wr... | RegisterWidgetsTest |
python | pydata__xarray | xarray/coding/common.py | {
"start": 596,
"end": 1709
} | class ____:
"""Base class for encoding and decoding transformations on variables.
We use coders for transforming variables between xarray's data model and
a format suitable for serialization. For example, coders apply CF
conventions for how data should be represented in netCDF files.
Subclasses sh... | VariableCoder |
python | keras-team__keras | keras/src/tree/tree_api.py | {
"start": 824,
"end": 14559
} | class ____:
"""Special value for use with `traverse()`."""
pass
@keras_export("keras.tree.is_nested")
def is_nested(structure):
"""Checks if a given structure is nested.
Examples:
>>> keras.tree.is_nested(42)
False
>>> keras.tree.is_nested({"foo": 42})
True
Args:
struct... | MAP_TO_NONE |
python | walkccc__LeetCode | solutions/1763. Longest Nice Substring/1763.py | {
"start": 0,
"end": 551
} | class ____:
def longestNiceSubstring(self, s: str) -> str:
if len(s) < 2:
return ''
seen = set(s)
for i, c in enumerate(s):
# If both upper and lower case letters exists in the string, keep moving,
# else take the erroneous character as a partition and check for its left
# and ri... | Solution |
python | django-haystack__django-haystack | haystack/fields.py | {
"start": 15609,
"end": 15675
} | class ____(FacetField, MultiValueField):
pass
| FacetMultiValueField |
python | Textualize__textual | tests/directory_tree/test_early_show_root.py | {
"start": 87,
"end": 573
} | class ____(App[None]):
def compose(self) -> ComposeResult:
tree = DirectoryTree(".")
tree.show_root = True
yield tree
async def test_managed_to_set_show_root_before_mounted() -> None:
"""https://github.com/Textualize/textual/issues/2363"""
async with DirectoryTreeApp().run_test() a... | DirectoryTreeApp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.