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 | Netflix__metaflow | test/core/tests/switch_nested.py | {
"start": 82,
"end": 1024
} | class ____(MetaflowTest):
"""
Tests a switch that leads to another switch.
"""
PRIORITY = 2
ONLY_GRAPHS = ["nested_switch"]
@steps(0, ["start-nested"], required=True)
def step_start(self):
self.condition1 = "case1"
self.condition2 = "case2_2"
@steps(0, ["switch-nested"... | NestedSwitchTest |
python | readthedocs__readthedocs.org | readthedocs/search/tests/test_parsers.py | {
"start": 500,
"end": 14255
} | class ____:
def setup_method(self):
self.project = get(
Project,
slug="test",
main_language_project=None,
)
self.version = self.project.versions.first()
def _mock_open(self, content):
@contextmanager
def f(*args, **kwargs):
... | TestParsers |
python | sympy__sympy | sympy/assumptions/predicates/sets.py | {
"start": 4428,
"end": 5201
} | class ____(Predicate):
r"""
Extended real predicate.
Explanation
===========
``Q.extended_real(x)`` is true iff ``x`` is a real number or
`\{-\infty, \infty\}`.
See documentation of ``Q.real`` for more information about related
facts.
Examples
========
>>> from sympy imp... | ExtendedRealPredicate |
python | ray-project__ray | release/train_tests/benchmark/image_classification/parquet/parquet_iterable_dataset.py | {
"start": 670,
"end": 9397
} | class ____(S3ParquetReader, IterableDataset):
"""An iterable dataset that loads images from S3-stored Parquet files.
This dataset:
1. Reads Parquet files from S3 one row group at a time
2. Processes images with optional random transforms
3. Yields (image, label) tensors
4. Supports row limits p... | S3ParquetImageIterableDataset |
python | doocs__leetcode | solution/1700-1799/1773.Count Items Matching a Rule/Solution.py | {
"start": 0,
"end": 230
} | class ____:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
i = 0 if ruleKey[0] == 't' else (1 if ruleKey[0] == 'c' else 2)
return sum(v[i] == ruleValue for v in items)
| Solution |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 41462,
"end": 42040
} | class ____:
collective_axes: tuple[str | tuple[str, ...], ...]
num_barriers: int = 1
num_arrivals: int = 1
orders_tensor_core: bool = False
def get_array_aval(self) -> jax_core.ShapedArray:
raise ValueError("Cluster barriers are not arrays")
def get_ref_aval(self) -> state.AbstractRef:
aval = jax_... | ClusterBarrier |
python | getsentry__sentry | src/sentry/integrations/msteams/webhook.py | {
"start": 26463,
"end": 28837
} | class ____(MessagingIntegrationCommandDispatcher[AdaptiveCard]):
data: dict[str, Any]
@property
def integration_spec(self) -> MessagingIntegrationSpec:
return MsTeamsMessagingSpec()
@property
def conversation_id(self) -> str:
return self.data["conversation"]["id"]
@property
... | MsTeamsCommandDispatcher |
python | allegroai__clearml | examples/router/simple_webserver.py | {
"start": 476,
"end": 994
} | class ____(BaseModel):
name: str
description: str
@app.get("/")
def read_root():
return {"message": "Welcome to the FastAPI application!"}
@app.get("/serve/{action}", response_model=Item)
def read_item(action: str):
if action in actions:
return actions[action]
else:
raise HTTPExc... | Item |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_s3.py | {
"start": 37746,
"end": 39896
} | class ____:
@mock.patch.object(S3Hook, "load_string")
def test_execute_if_data_is_string(self, mock_load_string):
data = "data"
operator = S3CreateObjectOperator(
task_id="test-s3-operator",
s3_bucket=BUCKET_NAME,
s3_key=S3_KEY,
data=data,
... | TestS3CreateObjectOperator |
python | tiangolo__fastapi | tests/test_custom_schema_fields.py | {
"start": 286,
"end": 1725
} | class ____(BaseModel):
name: str
if PYDANTIC_V2:
description: Annotated[
Optional[str], WithJsonSchema({"type": ["string", "null"]})
] = None
model_config = {
"json_schema_extra": {
"x-something-internal": {"level": 4},
}
}
... | Item |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 1417,
"end": 1520
} | class ____(test_factory()):
fe_type = types.Tuple([types.int32, types.float32])
| TestTupleInt32Float32 |
python | keras-team__keras | integration_tests/dataset_tests/imdb_test.py | {
"start": 88,
"end": 1831
} | class ____(testing.TestCase):
def test_load_data_default(self):
(x_train, y_train), (x_test, y_test) = imdb.load_data()
self.assertIsInstance(x_train, np.ndarray)
self.assertIsInstance(y_train, np.ndarray)
self.assertIsInstance(x_test, np.ndarray)
self.assertIsInstance(y_test... | ImdbLoadDataTest |
python | google__pytype | pytype/tests/test_utils.py | {
"start": 6833,
"end": 7287
} | class ____:
"""Mixin providing utils for tests on the collections module."""
_HAS_DYNAMIC_ATTRIBUTES = True
def _testCollectionsObject(self, obj, good_arg, bad_arg, error): # pylint: disable=invalid-name
result = self.CheckWithErrors(f"""
import collections
def f(x: collections.{obj}): ...
... | TestCollectionsMixin |
python | kamyu104__LeetCode-Solutions | Python/maximum-and-sum-of-array.py | {
"start": 2199,
"end": 2656
} | class ____(object):
def maximumANDSum(self, nums, numSlots):
"""
:type nums: List[int]
:type numSlots: int
:rtype: int
"""
adj = [[-((nums[i] if i < len(nums) else 0) & (1+x//2)) for x in xrange(2*numSlots)] for i in xrange(2*numSlots)]
return -sum(adj[i][j] f... | Solution2 |
python | pola-rs__polars | py-polars/tests/unit/interchange/test_from_dataframe.py | {
"start": 8322,
"end": 20391
} | class ____(PolarsColumn):
"""Helper class that allows patching certain PolarsColumn properties."""
describe_null: tuple[ColumnNullType, Any] = (ColumnNullType.USE_BITMASK, 0)
describe_categorical: dict[str, Any] = {} # type: ignore[assignment] # noqa: RUF012
null_count = 0
def test_column_to_series... | PatchableColumn |
python | donnemartin__interactive-coding-challenges | bit_manipulation/bits_to_flip/test_bits_to_flip.py | {
"start": 18,
"end": 405
} | class ____(unittest.TestCase):
def test_bits_to_flip(self):
bits = Bits()
a = int('11101', base=2)
b = int('01111', base=2)
expected = 2
self.assertEqual(bits.bits_to_flip(a, b), expected)
print('Success: test_bits_to_flip')
def main():
test = TestBits()
te... | TestBits |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_requests_invite_index.py | {
"start": 1353,
"end": 4927
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
"POST": ApiPublishStatus.UNKNOWN,
}
permission_classes = (InviteRequestPermissions,)
def get(self, request: Request, organization: Organization) -> Response:
queryset = OrganizationMember.objec... | OrganizationInviteRequestIndexEndpoint |
python | django__django | tests/admin_scripts/tests.py | {
"start": 51369,
"end": 53722
} | class ____(AdminScriptTestCase):
"""
Tests for manage.py when using the default settings.py file containing
runtime errors.
"""
def write_settings_with_import_error(self, filename):
settings_file_path = os.path.join(self.test_dir, filename)
with open(settings_file_path, "w") as sett... | ManageSettingsWithSettingsErrors |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25686,
"end": 25812
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Alpine'
strategy_class = AlpineStrategy
| AlpineLinuxHostname |
python | pypa__setuptools | setuptools/config/_apply_pyprojecttoml.py | {
"start": 18087,
"end": 19120
} | class ____(SetuptoolsWarning):
_SUMMARY = "`{field}` defined outside of `pyproject.toml` is ignored."
_DETAILS = """
The following seems to be defined outside of `pyproject.toml`:
`{field} = {value!r}`
According to the spec (see the link below), however, setuptools CANNOT
consider this value ... | _MissingDynamic |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 14931,
"end": 31582
} | class ____:
def setup_method(self):
self.instance = hook.GoogleBaseHook()
@mock.patch(MODULE_NAME + ".get_credentials_and_project_id", return_value=("CREDENTIALS", "PROJECT_ID"))
def test_get_credentials_and_project_id_with_default_auth(self, mock_get_creds_and_proj_id):
self.instance.extra... | TestGoogleBaseHook |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 25678,
"end": 25950
} | class ____(BaseModel):
key: str
dag_id: str
run_id: str
task_id: str
start: int | None
stop: int | None
step: int | None
include_prior_dates: bool = False
type: Literal["GetXComSequenceSlice"] = "GetXComSequenceSlice"
| GetXComSequenceSlice |
python | bokeh__bokeh | src/bokeh/core/property_mixins.py | {
"start": 7421,
"end": 7993
} | class ____(HasProps):
''' Properties relevant to rendering fill regions.
Mirrors the BokehJS ``properties.HatchVector`` class.
'''
hatch_color = ColorSpec(default="black", help=_color_help % "hatching")
hatch_alpha = AlphaSpec(help=_alpha_help % "hatching")
hatch_scale = FloatSpec(default=12.... | HatchProps |
python | jazzband__django-pipeline | pipeline/storage.py | {
"start": 3030,
"end": 3077
} | class ____:
packing = False
| NonPackagingMixin |
python | google__jax | tests/pallas/triton_pallas_test.py | {
"start": 1864,
"end": 17089
} | class ____(PallasBaseTest):
INTERPRET = False
@parameterized.product(src_dtype=DTYPE_LIST, dst_dtype=DTYPE_LIST)
def test_fp_dtype_cast(self, src_dtype, dst_dtype):
if src_dtype == dst_dtype:
self.skipTest("No need to test the same dtype")
if dtypes.itemsize_bits(src_dtype) == 8 and dtypes.itemsize... | TritonPallasTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance5.py | {
"start": 292,
"end": 392
} | class ____(Protocol):
name: str
def method1(self) -> int: ...
@runtime_checkable
| DataProtocol |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/traceback.py | {
"start": 6878,
"end": 7070
} | class ____:
exc_type: str
exc_value: str
syntax_error: Optional[_SyntaxError] = None
is_cause: bool = False
frames: List[Frame] = field(default_factory=list)
@dataclass
| Stack |
python | cython__cython | Demos/benchmarks/bm_richards_cclass.py | {
"start": 1106,
"end": 1189
} | class ____(TaskRec):
def __init__(self):
self.pending = None
| DeviceTaskRec |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/plugin.py | {
"start": 2970,
"end": 12397
} | class ____(BasePlugin[PluginConfig]):
"""An `mkdocs` plugin.
This plugin defines the following event hooks:
- `on_config`
- `on_env`
- `on_post_build`
Check the [Developing Plugins](https://www.mkdocs.org/user-guide/plugins/#developing-plugins) page of `mkdocs`
for more information about ... | MkdocstringsPlugin |
python | PyCQA__pylint | pylint/reporters/progress_reporters.py | {
"start": 233,
"end": 1083
} | class ____:
"""Progress reporter."""
def __init__(self, is_verbose: bool = True) -> None:
self._is_verbose = is_verbose
self._ast_count = 0
self._lint_counter = 0
def start_get_asts(self) -> None:
self._print_message("Get ASTs.")
def get_ast_for_file(self, filename: st... | ProgressReporter |
python | vyperlang__vyper | vyper/venom/basicblock.py | {
"start": 2874,
"end": 3617
} | class ____:
"""
IROperand represents an IR operand. An operand is anything that can be
operated by instructions. It can be a literal, a variable, or a label.
"""
value: Any
_hash: Optional[int] = None
def __init__(self, value: Any) -> None:
self.value = value
self._hash = N... | IROperand |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 10126,
"end": 11070
} | class ____(CohereRotaryEmbedding):
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = ... | Cohere2RotaryEmbedding |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/s3_to_sftp.py | {
"start": 1205,
"end": 3857
} | class ____(BaseOperator):
"""
This operator enables the transferring of files from S3 to a SFTP server.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3ToSFTPOperator`
:param sftp_conn_id: The sftp connection id. The name ... | S3ToSFTPOperator |
python | walkccc__LeetCode | solutions/3508. Implement Router/3508.py | {
"start": 126,
"end": 1715
} | class ____:
def __init__(self, memoryLimit: int):
self.memoryLimit = memoryLimit
self.uniquePackets: set[Packet] = set()
self.packetQueue: collections.deque[Packet] = collections.deque()
self.destinationTimestamps = collections.defaultdict(list)
self.processedPacketIndex = collections.Counter()
... | Router |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 10052,
"end": 10213
} | class ____(tuple):
def __new__(cls: type[NonGeneric1], *args, **kwargs) -> NonGeneric1: ...
def __enter__(self: NonGeneric1) -> NonGeneric1: ...
| NonGeneric1 |
python | numpy__numpy | benchmarks/benchmarks/bench_lib.py | {
"start": 2455,
"end": 4309
} | class ____(Benchmark):
"""Benchmarks for nan functions"""
param_names = ["array_size", "percent_nans"]
params = [
# sizes of the 1D arrays
[200, int(2e5)],
# percent of np.nan in arrays
[0, 0.1, 2., 50., 90.],
]
def setup(self, array_size, pe... | Nan |
python | keras-team__keras | keras/src/legacy/layers.py | {
"start": 316,
"end": 1923
} | class ____(Layer):
"""DEPRECATED."""
def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
super().__init__(**kwargs)
self.rate = rate
self.seed = seed
self.noise_shape = noise_shape
self.seed_generator = backend.random.SeedGenerator(seed)
self.support... | AlphaDropout |
python | ray-project__ray | release/train_tests/benchmark/image_classification/factory.py | {
"start": 11696,
"end": 14220
} | class ____(BenchmarkFactory):
def get_dataloader_factory(self) -> BaseDataLoaderFactory:
dataloader_type = self.benchmark_config.dataloader_type
task_config = self.benchmark_config.task_config
assert isinstance(task_config, ImageClassificationConfig)
data_dirs = get_imagenet_data_di... | ImageClassificationFactory |
python | getsentry__sentry | tests/sentry/rules/conditions/test_event_attribute.py | {
"start": 387,
"end": 35899
} | class ____(RuleTestCase):
rule_cls = EventAttributeCondition
def get_event(self, **kwargs):
data = {
"message": "hello world",
"request": {"method": "GET", "url": "http://example.com/"},
"user": {
"id": "1",
"ip_address": "127.0.0.1",
... | EventAttributeConditionTest |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serde.py | {
"start": 5638,
"end": 5727
} | class ____:
x: int
y: Y
u: tuple
w: W
__version__: ClassVar[int] = 1
| T |
python | pennersr__django-allauth | allauth/socialaccount/providers/wahoo/provider.py | {
"start": 434,
"end": 1498
} | class ____(OAuth2Provider):
id = "wahoo"
name = "Wahoo"
account_class = WahooAccount
oauth2_adapter_class = WahooOAuth2Adapter
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
extra_common = super(WahooProvider, self).extract_common_fie... | WahooProvider |
python | getsentry__sentry | src/sentry/exceptions.py | {
"start": 98,
"end": 146
} | class ____(InvalidData):
pass
| InvalidInterface |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 1018,
"end": 1643
} | class ____(View):
def post(self, request, *args, **kwargs):
default_user = CustomUser.objects.create_superuser(
"test_user", "test_user@example.com", "pass"
)
# Bulk create objects with history
poll_info_list = [
{"question": "1", "pub_date": date(2020, 1, 1)}... | PollBulkCreateWithDefaultUserView |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 39830,
"end": 40850
} | class ____(stages.Lowering):
_hlo: ir.Module
_executable: PmapExecutable | None
def __init__(self, hlo: ir.Module, const_args: list[ArrayLike],
**compile_args):
self._executable = None
self._hlo = hlo
self.const_args = const_args
self.compile_args = compile_args
# -- stages.Lowe... | PmapComputation |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 48919,
"end": 49967
} | class ____(unittest.TestCase):
@unittest.skipUnless(
hasattr(signal, "pidfd_send_signal"),
"pidfd support not built in",
)
def test_pidfd_send_signal(self):
with self.assertRaises(OSError) as cm:
signal.pidfd_send_signal(0, signal.SIGINT)
if cm.exception.errno ==... | PidfdSignalTest |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/event_stripper.py | {
"start": 266,
"end": 8606
} | class ____(Enum):
def __init__(self, explanation: str = "") -> None:
self.explanation = explanation
"""Keeps the event data if it is of type str, int, float, bool."""
SIMPLE_TYPE = auto()
"""Keeps the event data if it is a mapping with string keys and string values."""
MAP_WITH_STRINGS = a... | Allow |
python | django-extensions__django-extensions | django_extensions/templatetags/indent_text.py | {
"start": 61,
"end": 1726
} | class ____(template.Node):
def __init__(self, nodelist, indent_level, if_statement):
self.nodelist = nodelist
self.indent_level = template.Variable(indent_level)
if if_statement:
self.if_statement = template.Variable(if_statement)
else:
self.if_statement = Non... | IndentByNode |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 4892,
"end": 5099
} | class ____(ClientConnectorError):
"""Proxy connection error.
Raised in :class:`aiohttp.connector.TCPConnector` if
connection to proxy can not be established.
"""
| ClientProxyConnectionError |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 4274,
"end": 4650
} | class ____(django_test.TestCase):
def reset_database_sequences(self, *models):
using = factory.django.DEFAULT_DB_ALIAS
with connections[using].cursor() as cursor:
sequence_sql = connections[using].ops.sequence_reset_sql(color.no_style(), models)
for command in sequence_sql:
... | DjangoResetTestCase |
python | ray-project__ray | rllib/evaluation/env_runner_v2.py | {
"start": 1718,
"end": 4634
} | class ____:
"""Sampler perf stats that will be included in rollout metrics."""
def __init__(self, ema_coef: Optional[float] = None):
# If not None, enable Exponential Moving Average mode.
# The way we update stats is by:
# updated = (1 - ema_coef) * old + ema_coef * new
# In... | _PerfStats |
python | kamyu104__LeetCode-Solutions | Python/power-of-four.py | {
"start": 525,
"end": 811
} | class ____(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
num = bin(num)
return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else False
| Solution3 |
python | davidhalter__parso | parso/python/errors.py | {
"start": 31947,
"end": 34252
} | class ____(SyntaxRule):
@property
def message(self):
if self._normalizer.version < (3, 7):
return "Generator expression must be parenthesized if not sole argument"
else:
return "Generator expression must be parenthesized"
def is_issue(self, node):
arg_set = s... | _ArglistRule |
python | numba__numba | numba/np/arrayobj.py | {
"start": 24990,
"end": 25647
} | class ____(Indexer):
"""
Compute indices from a single integer.
"""
def __init__(self, context, builder, idx):
self.context = context
self.builder = builder
self.idx = idx
self.ll_intp = self.context.get_value_type(types.intp)
def prepare(self):
pass
de... | IntegerIndexer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 234312,
"end": 235082
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"color",
"contribution_count",
"contribution_level",
"date",
"weekday",
)
color = sgqlc.types.Field(sgqlc.types.non_null(String), grap... | ContributionCalendarDay |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/prompt_selector.py | {
"start": 589,
"end": 2001
} | class ____(BasePromptSelector):
"""Prompt collection that goes through conditionals."""
default_prompt: BasePromptTemplate
"""Default prompt to use if no conditionals match."""
conditionals: list[
tuple[Callable[[BaseLanguageModel], bool], BasePromptTemplate]
] = Field(default_factory=list)... | ConditionalPromptSelector |
python | spyder-ide__spyder | spyder/utils/syntaxhighlighters.py | {
"start": 69012,
"end": 72178
} | class ____(BaseSH):
"""Base class for CSS and HTML syntax highlighters"""
NORMAL = 0
COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
BaseSH.__init__(self, parent, font, color_scheme)
def highlight_block(self, text):
"""Implement highlight specific for CSS and... | BaseWebSH |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/pipeline.py | {
"start": 275,
"end": 547
} | class ____(graphene.Union):
class Meta:
types = (
GraphenePipeline,
GraphenePipelineNotFoundError,
GrapheneInvalidSubsetError,
GraphenePythonError,
)
name = "PipelineOrError"
| GraphenePipelineOrError |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 4399,
"end": 5159
} | class ____(db.Model):
__tablename__ = "organization_terms_of_service_engagements"
__table_args__ = (
Index(
"organization_terms_of_service_engagements_org_id_revision_idx",
"organization_id",
"revision",
),
)
__repr__ = make_repr("organization_id")
... | OrganizationTermsOfServiceEngagement |
python | kamyu104__LeetCode-Solutions | Python/bulls-and-cows.py | {
"start": 156,
"end": 651
} | class ____(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A, B = 0, 0
lookup = defaultdict(int)
for s, g in izip(secret, guess):
if s == g:
A += 1
else:
... | Solution |
python | keras-team__keras | keras/src/utils/dataset_utils_test.py | {
"start": 2207,
"end": 6061
} | class ____(test_case.TestCase):
@parameterized.named_parameters(
named_product(
dataset_type=["list", "tuple", "tensorflow", "torch"],
features_shape=[(2,), (100, 2), (10, 10, 2)],
preferred_backend=[None, "tensorflow", "torch"],
)
)
def test_split_dataset... | DatasetUtilsTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/test_connection_wrapper.py | {
"start": 2787,
"end": 20554
} | class ____:
@pytest.mark.parametrize("extra", [{"foo": "bar", "spam": "egg"}, '{"foo": "bar", "spam": "egg"}', None])
def test_values_from_connection(self, extra):
mock_conn = mock_connection_factory(
login="mock-login",
password="mock-password",
extra=extra,
... | TestAwsConnectionWrapper |
python | pypa__setuptools | setuptools/_distutils/tests/test_dist.py | {
"start": 8721,
"end": 18793
} | class ____(support.TempdirManager):
def format_metadata(self, dist):
sio = io.StringIO()
dist.metadata.write_pkg_file(sio)
return sio.getvalue()
def test_simple_metadata(self):
attrs = {"name": "package", "version": "1.0"}
dist = Distribution(attrs)
meta = self.f... | TestMetadata |
python | walkccc__LeetCode | solutions/2959. Number of Possible Sets of Closing Branches/2959.py | {
"start": 0,
"end": 1257
} | class ____:
def numberOfSets(
self,
n: int,
maxDistance: int,
roads: list[list[int]],
) -> int:
return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance
for mask in range(1 << n))
def _floydWarshall(
self,
n: int,
maxDistanceThreshold... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/state.py | {
"start": 1096,
"end": 2466
} | class ____(
NamedTuple(
"_PastExecutionState",
[
("run_id", str),
("produced_outputs", set[StepOutputHandle]),
# PastExecutionState, but no cycles allowed in NT
("parent_state", Optional[object]),
],
)
):
"""Information relevant to exec... | PastExecutionState |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/env_manager.py | {
"start": 719,
"end": 1170
} | class ____(NamedTuple):
current_all_step_result: AllStepResult
worker_id: int
brain_name_to_action_info: Dict[BehaviorName, ActionInfo]
environment_stats: EnvironmentStats
@property
def name_behavior_ids(self) -> Iterable[BehaviorName]:
return self.current_all_step_result.keys()
@s... | EnvironmentStep |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/databricks_sql_datasource.py | {
"start": 1716,
"end": 1914
} | class ____(pydantic.UrlError):
"""
Custom Pydantic error for missing query in DatabricksDsn.
"""
code = "url.query"
msg_template = "URL query is invalid or missing"
| _UrlQueryError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 756799,
"end": 757615
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"email",
"enterprise",
"invitee",
"inviter",
"role",
)
created_at = sgqlc.types.Field(
sgqlc.types... | EnterpriseAdministratorInvitation |
python | ray-project__ray | python/ray/serve/tests/test_config_files/test_dag/dir/subdir/a/add_and_sub.py | {
"start": 889,
"end": 1445
} | class ____:
def __init__(self, adder: DeploymentHandle, subtractor: DeploymentHandle):
self.adder = adder
self.subtractor = subtractor
async def __call__(self, request: starlette.requests.Request) -> int:
op, input = await request.json()
if op == Operation.ADD:
retu... | Router |
python | sympy__sympy | sympy/physics/quantum/hilbert.py | {
"start": 16499,
"end": 19632
} | class ____(HilbertSpace):
"""An exponentiated Hilbert space [1]_.
Tensor powers (repeated tensor products) are represented by the
operator ``**`` Identical Hilbert spaces that are multiplied together
will be automatically combined into a single tensor power object.
Any Hilbert space, product, or s... | TensorPowerHilbertSpace |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/fc.py | {
"start": 1771,
"end": 4173
} | class ____(Task.Task):
color = 'GREEN'
run_str = '${FC} ${FCFLAGS} ${FCINCPATH_ST:INCPATHS} ${FCDEFINES_ST:DEFINES} ${_FCMODOUTFLAGS} ${FC_TGT_F}${TGT[0].abspath()} ${FC_SRC_F}${SRC[0].abspath()} ${FCPPFLAGS}'
vars = ["FORTRANMODPATHFLAG"]
def scan(self):
tmp = fc_scan.fortran_parser(self.gener... | fc |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 89047,
"end": 91631
} | class ____(Request):
"""
Archive tasks
:param ids: Entities to move
:type ids: Sequence[str]
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"... | ArchiveManyRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1293286,
"end": 1295840
} | class ____(sgqlc.types.Type, Node):
"""Information for an uploaded package."""
__schema__ = github_schema
__field_names__ = ("latest_version", "name", "package_type", "repository", "statistics", "version", "versions")
latest_version = sgqlc.types.Field("PackageVersion", graphql_name="latestVersion")
... | Package |
python | readthedocs__readthedocs.org | readthedocs/audit/migrations/0004_change_ip_field_type.py | {
"start": 149,
"end": 547
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("audit", "0003_update_ordering"),
]
operations = [
migrations.AlterField(
model_name="auditlog",
name="ip",
field=models.CharField(
blank=True, max_length=2... | Migration |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_wrappers__embed.py | {
"start": 1796,
"end": 2661
} | class ____:
def test_render(self) -> None:
assert bew.wrap_in_script_tag("code\nmorecode") == """
<script type="text/javascript">
code
morecode
</script>\
"""
#-----------------------------------------------------------------------------
# Private API
#--------------------------------------------------... | Test_wrap_in_script_tag |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_time.py | {
"start": 300,
"end": 950
} | class ____(BaseTestZDType):
def json_scalar_equals(self, scalar1: object, scalar2: object) -> bool:
# This method gets overridden here to support the equivalency between NaT and
# -9223372036854775808 fill values
nat_scalars = (-9223372036854775808, "NaT")
if scalar1 in nat_scalars a... | _TestTimeBase |
python | readthedocs__readthedocs.org | readthedocs/integrations/migrations/0015_add_github_app_integration.py | {
"start": 149,
"end": 1227
} | class ____(migrations.Migration):
safe = Safe.always()
dependencies = [
("integrations", "0014_add_index_speedup"),
]
operations = [
migrations.CreateModel(
name="GitHubAppIntegration",
fields=[],
options={
"proxy": True,
... | Migration |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_ticketing.py | {
"start": 1501,
"end": 1643
} | class ____(BaseTicketingActionValidatorTest):
__test__ = True
provider = Action.Type.GITHUB_ENTERPRISE
| TestGithubEnterpriseActionValidator |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks.py | {
"start": 3024,
"end": 5229
} | class ____(_HookTimer):
"""Timer that triggers at most once every N seconds or once every N steps.
This symbol is also exported to v2 in tf.estimator namespace. See
https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/hooks/basic_session_run_hooks.py
"""
def __init__(sel... | SecondOrStepTimer |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 60837,
"end": 61180
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["UpdateResult"] = Field(default=None, descripti... | InlineResponse2005 |
python | jazzband__django-oauth-toolkit | tests/migrations/0001_initial.py | {
"start": 92,
"end": 1448
} | class ____(migrations.Migration):
initial = True
dependencies = [
]
run_before = [
('oauth2_provider', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='BaseTestApplication',
fields=[
('id', models.BigAutoField(auto_create... | Migration |
python | astropy__astropy | astropy/cosmology/_src/tests/io/base.py | {
"start": 6036,
"end": 7433
} | class ____(IODirectTestBase, ToFromTestMixinBase):
"""Directly test ``read/write_<format>``.
These functions are not public API and are discouraged from public use, in
favor of ``Cosmology.read/write(..., format="<format>")``. They are tested
because they are used internally and because some tests for ... | ReadWriteDirectTestBase |
python | readthedocs__readthedocs.org | readthedocs/organizations/forms.py | {
"start": 7969,
"end": 8492
} | class ____(forms.ModelForm):
"""Form to manage access of teams to projects."""
class Meta:
model = Team
fields = ["projects"]
def __init__(self, *args, **kwargs):
self.organization = kwargs.pop("organization", None)
super().__init__(*args, **kwargs)
self.fields["pro... | OrganizationTeamProjectForm |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 14038,
"end": 14559
} | class ____(VOTableSpecWarning):
"""Invalid astroYear.
As astro year field is a Besselian or Julian year matching the
regular expression::
^[JB]?[0-9]+([.][0-9]*)?$
Defined in this XML Schema snippet::
<xs:simpleType name="astroYear">
<xs:restriction base="xs:token">
... | W07 |
python | kamyu104__LeetCode-Solutions | Python/minimum-size-subarray-in-infinite-array.py | {
"start": 60,
"end": 801
} | class ____(object):
def minSizeSubarray(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
INF = float("inf")
q, target = divmod(target, sum(nums))
if not target:
return q*len(nums)
result = INF
... | Solution |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/javaw.py | {
"start": 8881,
"end": 13193
} | class ____(Task.Task):
color = 'BLUE'
def __str__(self):
return '%s: %s -> %s\n' % (self.__class__.__name__, self.generator.srcdir, self.generator.javadoc_output)
def run(self):
env = self.env
bld = self.generator.bld
wd = bld.bldnode
srcpath = self.generator.path.a... | javadoc |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_optimizer.py | {
"start": 1158,
"end": 8642
} | class ____(optimizer.Optimizer):
"""An optimizer that averages gradients across TPU shards."""
def __init__(self,
opt,
reduction=losses.Reduction.MEAN,
name="CrossShardOptimizer",
group_assignment=None):
"""Construct a new cross-shard optimizer.
... | CrossShardOptimizer |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/plugins/hive.py | {
"start": 964,
"end": 1146
} | class ____(AirflowPlugin):
"""Hive plugin - delivering macros used by users that use the provider."""
name = "hive"
macros = [max_partition, closest_ds_partition]
| HivePlugin |
python | scipy__scipy | scipy/optimize/tests/test_trustregion_krylov.py | {
"start": 520,
"end": 6571
} | class ____:
def test_for_the_easy_case(self):
# `H` is chosen such that `g` is not orthogonal to the
# eigenvector associated with the smallest eigenvalue.
H = np.array([[1.0, 0.0, 4.0],
[0.0, 2.0, 0.0],
[4.0, 0.0, 3.0]])
g = np.array([5.... | TestKrylovQuadraticSubproblem |
python | apache__thrift | lib/py/setup.py | {
"start": 1528,
"end": 4544
} | class ____(build_ext):
def run(self):
try:
build_ext.run(self)
except DistutilsPlatformError:
raise BuildFailed()
def build_extension(self, ext):
try:
build_ext.build_extension(self, ext)
except ext_errors:
raise BuildFailed()
de... | ve_build_ext |
python | faif__python-patterns | patterns/behavioral/specification.py | {
"start": 2113,
"end": 2222
} | class ____:
def __init__(self, super_user: bool = False) -> None:
self.super_user = super_user
| User |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 664769,
"end": 665479
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Gist."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("GistEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.... | GistConnection |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/winres.py | {
"start": 1392,
"end": 2097
} | class ____(Task.Task):
run_str = '${WINRC} ${WINRCFLAGS} ${CPPPATH_ST:INCPATHS} ${DEFINES_ST:DEFINES} ${WINRC_TGT_F} ${TGT} ${WINRC_SRC_F} ${SRC}'
color = 'BLUE'
def scan(self):
tmp = rc_parser(self.generator.includes_nodes)
tmp.start(self.inputs[0], self.env)
return (tmp.nodes, tmp... | winrc |
python | django__django | tests/utils_tests/test_autoreload.py | {
"start": 6470,
"end": 10801
} | class ____(SimpleTestCase):
@mock.patch.dict(sys.modules, {"__main__": django.__main__})
@mock.patch("sys.argv", [django.__main__.__file__, "runserver"])
@mock.patch("sys.warnoptions", [])
@mock.patch("sys._xoptions", {})
def test_run_as_module(self):
self.assertEqual(
autoreload... | TestChildArguments |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 340,
"end": 1287
} | class ____:
"""Base class for all converters.
.. versionchanged:: 2.3
``part_isolating`` defaults to ``False`` if ``regex`` contains a ``/``.
"""
regex = "[^/]+"
weight = 100
part_isolating = True
def __init_subclass__(cls, **kwargs: t.Any) -> None:
super().__init_subclass... | BaseConverter |
python | graphql-python__graphene | graphene/tests/issues/test_720.py | {
"start": 694,
"end": 795
} | class ____(MyInputClass):
class Meta:
fields = dict(x=graphene.Field(graphene.Int))
| MyInput |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 7527,
"end": 8941
} | class ____(SpanToken):
"""
Raw text token.
This is an inline token without children.
RawText is the only token that accepts a string for its constructor,
instead of a match object. Also, all recursions should bottom out here.
"""
def __init__(self, content):
self.content = content
... | RawText |
python | viewflow__viewflow | viewflow/fsm/viewset.py | {
"start": 711,
"end": 3089
} | class ____(UpdateModelView):
template_name_suffix = "_transition"
def get_transition_fields(self, request, obj, slug):
return self.viewset.get_transition_fields(request, obj, slug)
def get_object_data(self):
"""List of object fields to display.
Choice fields values are expanded to ... | ModelTransitionView |
python | jazzband__django-simple-history | simple_history/tests/tests/test_utils.py | {
"start": 19021,
"end": 21589
} | class ____(TestCase):
def setUp(self):
self.data = [
PollWithAlternativeManager(
id=1, question="Question 1", pub_date=timezone.now()
),
PollWithAlternativeManager(
id=2, question="Question 2", pub_date=timezone.now()
),
... | BulkUpdateWithHistoryAlternativeManagersTestCase |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 3273,
"end": 5352
} | class ____(abc.ABC):
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
*,
expect_handler: _ExpectHandler | None = None,
resource: AbstractResource | None = None,
) -> None:
if expect_handler is None:
expect_handler = _defa... | AbstractRoute |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 7898,
"end": 8012
} | class ____(BiffRecord):
_REC_ID = 0x00E2
def __init__(self):
self._rec_data = b''
| InteraceEndRecord |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.