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 | huggingface__transformers | tests/models/markuplm/test_modeling_markuplm.py | {
"start": 1294,
"end": 9484
} | class ____:
"""You can also import this e.g from .test_modeling_markuplm import MarkupLMModelTester"""
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
... | MarkupLMModelTester |
python | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 20541,
"end": 25107
} | class ____:
@pytest.mark.parametrize("selected_project", [None, "foo"])
def test_creation(self, selected_project):
user_id = pretend.stub()
macaroon_service = pretend.stub(get_macaroon_by_description=lambda *a: None)
project_names = ["foo"]
form = forms.CreateMacaroonForm(
... | TestCreateMacaroonForm |
python | plotly__plotly.py | plotly/graph_objs/layout/polar/radialaxis/_autorangeoptions.py | {
"start": 235,
"end": 5919
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.polar.radialaxis"
_path_str = "layout.polar.radialaxis.autorangeoptions"
_valid_props = {
"clipmax",
"clipmin",
"include",
"includesrc",
"maxallowed",
"minallowed",
}
@property
def c... | Autorangeoptions |
python | spyder-ide__spyder | spyder/plugins/externalterminal/widgets/run_conf.py | {
"start": 932,
"end": 4035
} | class ____(RunExecutorConfigurationGroup):
"""External terminal Python run configuration options."""
def __init__(self, parent, context: Context, input_extension: str,
input_metadata: RunConfigurationMetadata):
super().__init__(parent, context, input_extension, input_metadata)
... | ExternalTerminalPyConfiguration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 922470,
"end": 922858
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("ReleaseAsset", graphql_na... | ReleaseAssetEdge |
python | ray-project__ray | python/ray/tune/schedulers/pbt.py | {
"start": 8881,
"end": 42957
} | class ____(FIFOScheduler):
"""Implements the Population Based Training (PBT) algorithm.
https://www.deepmind.com/blog/population-based-training-of-neural-networks
PBT trains a group of models (or agents) in parallel. Periodically, poorly
performing models clone the state of the top performers, and a r... | PopulationBasedTraining |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/cli/parser.py | {
"start": 5201,
"end": 10811
} | class ____(CustomOptionParser):
"""Custom option parser which updates its defaults by checking the
configuration files and environmental variables"""
def __init__(
self,
*args: Any,
name: str,
isolated: bool = False,
**kwargs: Any,
) -> None:
self.name = ... | ConfigOptionParser |
python | geekcomputers__Python | encrypter-decrypter-gui.py | {
"start": 1096,
"end": 8645
} | class ____:
def __init__(self, parent):
self.parent = parent
# ========== Data Key ==========
self.data_dic = {
"A": "Q",
"B": "W",
"C": "E",
"D": "R",
"E": "T",
"F": "Y",
"G": "U",
"H": "I",
... | Notebook |
python | kamyu104__LeetCode-Solutions | Python/minimum-falling-path-sum.py | {
"start": 31,
"end": 326
} | class ____(object):
def minFallingPathSum(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
for i in xrange(1, len(A)):
for j in xrange(len(A[i])):
A[i][j] += min(A[i-1][max(j-1, 0):j+2])
return min(A[-1])
| Solution |
python | EpistasisLab__tpot | tpot/search_spaces/pipelines/wrapper.py | {
"start": 5024,
"end": 6169
} | class ____(SearchSpace):
def __init__(
self,
method: type,
space: ConfigurationSpace,
estimator_search_space: SearchSpace,
hyperparameter_parser: callable = None,
wrapped_param_name: str = None
) -> None:
"""
... | WrapperPipeline |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/custom_param_types.py | {
"start": 8878,
"end": 9513
} | class ____(BetterChoice):
"""Extends choice with dynamic version number."""
def __init__(self, *args):
super().__init__(*args)
self.all_choices = [*self.choices, "<airflow_version>", "<owner/repo:branch>", "<pr_number>"]
def convert(self, value, param, ctx):
if re.match(r"^\d*\.\d*... | UseAirflowVersionType |
python | ipython__ipython | IPython/core/alias.py | {
"start": 4859,
"end": 4907
} | class ____(AliasError):
pass
| InvalidAliasError |
python | joke2k__faker | faker/providers/address/fr_FR/__init__.py | {
"start": 71,
"end": 11925
} | class ____(AddressProvider):
city_suffixes = (
"Ville",
"Bourg",
"-les-Bains",
"-sur-Mer",
"-la-Forêt",
"boeuf",
"nec",
"dan",
)
city_prefixes = ("Saint", "Sainte")
street_prefixes = ("rue", "rue", "chemin", "avenue", "boulevard")
city_... | Provider |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 644726,
"end": 645207
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("team", "team_name", "team_resource_path", "team_url")
team = sgqlc.types.Field("Team", graphql_name="team")
team_name = sgqlc.types.Field(String, graphql_name="teamName"... | TeamAuditEntryData |
python | huggingface__transformers | src/transformers/models/swin2sr/modeling_swin2sr.py | {
"start": 4843,
"end": 6164
} | class ____(nn.Module):
def __init__(self, config, normalize_patches=True):
super().__init__()
num_channels = config.embed_dim
image_size, patch_size = config.image_size, config.patch_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, i... | Swin2SRPatchEmbeddings |
python | graphql-python__graphene | graphene/relay/tests/test_global_id.py | {
"start": 181,
"end": 245
} | class ____(Node):
class Meta:
name = "Node"
| CustomNode |
python | getsentry__sentry | src/sentry/tempest/endpoints/tempest_credentials_details.py | {
"start": 600,
"end": 1550
} | class ____(ProjectEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.GDX
permission_classes = (TempestCredentialsPermission,)
def delete(self, request: Request, project: Project, tempest_credentials_id: int) -> Response:
if not has_tempest_access(p... | TempestCredentialsDetailsEndpoint |
python | celery__celery | t/unit/backends/test_rpc.py | {
"start": 181,
"end": 546
} | class ____:
def get_backend(self):
return RPCBackend(app=self.app)
def get_consumer(self):
return self.get_backend().result_consumer
def test_drain_events_before_start(self):
consumer = self.get_consumer()
# drain_events shouldn't crash when called before start
cons... | test_RPCResultConsumer |
python | ansible__ansible | test/integration/targets/protomatter/action_plugins/transform_factory.py | {
"start": 84,
"end": 314
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
self._display.deprecated("a deprecation warning", version="2.99")
self._display.warning("a warning")
return dict(changed=False)
| ActionModule |
python | gwtw__py-sorting | test/base_positive_integer_sort_test.py | {
"start": 0,
"end": 1104
} | class ____(object):
def test_sorts_empty_array(self):
self.assertEqual([], self.sort([]))
def test_sorts_small_sorted_array(self):
self.assertEqual([1,2,3,4,5], self.sort([1,2,3,4,5]))
def test_sorts_small_reverse_sorted_array(self):
self.assertEqual([1,2,3,4,5], self.sort([5,4,3,2,1]))
def test_... | BasePositiveIntegerSortTest |
python | pytorch__pytorch | torch/distributed/checkpoint/_pg_transport.py | {
"start": 1981,
"end": 6154
} | class ____:
"""
This is the metadata for a state dict that is used to transfer checkpoints.
It contains the step, the pytree spec of the state dict and the metadata for
each tensor in the state dict.
This must be pickleable so that it can be sent over the wire.
Args:
step: the step of ... | _StateDictMeta |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 9031,
"end": 10149
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("el_GR")
Faker.seed(0)
def test_vat_id(self):
for _ in range(100):
prefix = random.choice([True, False])
vat_id = self.fake.vat_id(prefix=prefix)
assert re.search(r"^(EL)?\d{9}$", vat_i... | TestElGr |
python | django-import-export__django-import-export | tests/core/models.py | {
"start": 4707,
"end": 4983
} | class ____(models.Model):
catid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "UUID categories"
| UUIDCategory |
python | allegroai__clearml | clearml/backend_api/services/v2_23/auth.py | {
"start": 19275,
"end": 20170
} | class ____(Response):
"""
Response of auth.login endpoint.
:param token: Token string
:type token: str
"""
_service = "auth"
_action = "login"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {"token": {"description": "Token string", "type": ["string",... | LoginResponse |
python | doocs__leetcode | solution/0000-0099/0039.Combination Sum/Solution.py | {
"start": 0,
"end": 525
} | class ____:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if s < candidates[i]:
return
for j in range(i, len(candidates)):
... | Solution |
python | getsentry__sentry | src/sentry/rules/processing/buffer_processing.py | {
"start": 671,
"end": 1737
} | class ____(Protocol):
def get_hash(self, model: type[models.Model], field: dict[str, Any]) -> dict[str, str]: ...
def get_hash_length(self, model: type[models.Model], field: dict[str, Any]) -> int: ...
def push_to_hash_bulk(
self, model: type[models.Model], filters: dict[str, Any], data: dict[str... | BufferProtocol |
python | realpython__materials | python-class/stack.py | {
"start": 0,
"end": 358
} | class ____:
def __init__(self, items=None):
if items is None:
self._items = []
else:
self._items = list(items)
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def __repr__(self) -> str:
return f"{ty... | Stack |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/execute_step.py | {
"start": 3032,
"end": 30676
} | class ____(Output):
"""This is a marker subclass that represents an Output that was produced from an AssetResult."""
def _process_asset_results_to_events(
step_context: StepExecutionContext,
user_event_sequence: Iterator[OpOutputUnion],
) -> Iterator[OpOutputUnion]:
"""Handle converting MaterializeRes... | AssetResultOutput |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 56291,
"end": 57719
} | class ____(Response):
"""
Response of queues.get_default endpoint.
:param id: Queue id
:type id: str
:param name: Queue name
:type name: str
"""
_service = "queues"
_action = "get_default"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
... | GetDefaultResponse |
python | getsentry__sentry | src/sentry/backup/dependencies.py | {
"start": 3022,
"end": 3769
} | class ____(Enum):
"""Kinds of foreign fields that we care about."""
# Uses our `FlexibleForeignKey` wrapper.
FlexibleForeignKey = auto()
# Uses our `HybridCloudForeignKey` wrapper.
HybridCloudForeignKey = auto()
# Uses our `OneToOneCascadeDeletes` wrapper.
OneToOneCascadeDeletes = auto()
... | ForeignFieldKind |
python | django-extensions__django-extensions | tests/auth/test_mixins.py | {
"start": 546,
"end": 657
} | class ____(ModelUserFieldPermissionMixin, EmptyResponseView):
model_permission_user_field = "owner"
| OwnerView |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 14781,
"end": 16597
} | class ____(RegexLexer):
"""
Generic `myghty templates`_ lexer. Code that isn't Myghty
markup is yielded as `Token.Other`.
.. versionadded:: 0.6
.. _myghty templates: http://www.myghty.org/
"""
name = 'Myghty'
aliases = ['myghty']
filenames = ['*.myt', 'autodelegate']
mimetypes... | MyghtyLexer |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 21666,
"end": 22437
} | class ____(Instruction):
def __init__(self, parent, vector, index, name=''):
if not isinstance(vector.type, types.VectorType):
raise TypeError("vector needs to be of VectorType.")
if not isinstance(index.type, types.IntType):
raise TypeError("index needs to be of IntType.")
... | ExtractElement |
python | keras-team__keras | keras/src/ops/operation_test.py | {
"start": 850,
"end": 1210
} | class ____(operation.Operation):
def __init__(self, alpha, *, beta=1.0, name=None):
super().__init__(name=name)
self.alpha = alpha
self.beta = beta
def call(self, x):
return self.alpha * x + self.beta
def compute_output_spec(self, x):
return keras_tensor.KerasTensor... | OpWithCustomConstructor |
python | pandas-dev__pandas | pandas/tests/reshape/merge/test_merge.py | {
"start": 79934,
"end": 111474
} | class ____:
@pytest.mark.parametrize(
"how, sort, expected",
[
("inner", False, DataFrame({"a": [20, 10], "b": [200, 100]}, index=[2, 1])),
("inner", True, DataFrame({"a": [10, 20], "b": [100, 200]}, index=[1, 2])),
(
"left",
False,... | TestMergeOnIndexes |
python | MongoEngine__mongoengine | mongoengine/base/fields.py | {
"start": 876,
"end": 11844
} | class ____:
"""A base class for fields in a MongoDB document. Instances of this class
may be added to subclasses of `Document` to define a document's schema.
"""
name = None # set in TopLevelDocumentMetaclass
_geo_index = False
_auto_gen = False # Call `generate` to generate a value
_thre... | BaseField |
python | getsentry__sentry-python | tests/integrations/beam/test_beam.py | {
"start": 3941,
"end": 6006
} | class ____(OutputHandler):
def process_outputs(
self, windowed_input_element, results, watermark_estimator=None
):
self.handle_process_outputs(
windowed_input_element, results, watermark_estimator
)
def handle_process_outputs(
self, windowed_input_element, result... | _OutputHandler |
python | django-haystack__django-haystack | test_haystack/elasticsearch7_tests/test_backend.py | {
"start": 5668,
"end": 6337
} | class ____(
indexes.SearchIndex, indexes.Indexable
):
text = indexes.CharField(document=True, default="")
name = indexes.CharField(faceted=True)
is_active = indexes.BooleanField(faceted=True)
post_count = indexes.IntegerField()
post_count_i = indexes.FacetIntegerField(facet_for="post_count")
... | Elasticsearch7ComplexFacetsMockSearchIndex |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | {
"start": 10323,
"end": 11170
} | class ____(functions.GenericFunction[_T]):
inherit_cache = True
def __init__(self, *args, **kwargs):
args = list(args)
if len(args) > 1:
initial_arg = coercions.expect(
roles.ExpressionElementRole,
args.pop(0),
name=getattr(self, "name... | _regconfig_fn |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 1041,
"end": 2066
} | class ____(TestBase):
def testRegister(self):
reversion.register(TestModel)
self.assertTrue(reversion.is_registered(TestModel))
def testRegisterDecorator(self):
@reversion.register()
class TestModelDecorater(models.Model):
pass
self.assertTrue(reversion.is_r... | RegisterTest |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_business_month.py | {
"start": 957,
"end": 3909
} | class ____:
def test_offsets_compare_equal(self):
# root cause of #456
offset1 = BMonthBegin()
offset2 = BMonthBegin()
assert not offset1 != offset2
offset_cases = []
offset_cases.append(
(
BMonthBegin(),
{
datetime(2008, 1, 1)... | TestBMonthBegin |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/test_base_data_condition_group.py | {
"start": 4795,
"end": 7106
} | class ____(TestBaseDataConditionGroupValidator):
def test_update(self) -> None:
self.valid_data["conditions"] = [
{
"type": Condition.EQUAL,
"comparison": 1,
"conditionResult": True,
}
]
validator = BaseDataConditionGrou... | TestBaseDataConditionGroupValidatorUpdate |
python | doocs__leetcode | solution/3100-3199/3158.Find the XOR of Numbers Which Appear Twice/Solution.py | {
"start": 0,
"end": 172
} | class ____:
def duplicateNumbersXOR(self, nums: List[int]) -> int:
cnt = Counter(nums)
return reduce(xor, [x for x, v in cnt.items() if v == 2], 0)
| Solution |
python | apache__thrift | test/py/TestClient.py | {
"start": 15900,
"end": 16117
} | class ____(MultiplexedOptionalTest):
def get_protocol(self, transport):
return make_pedantic(TCompactProtocol.TCompactProtocolAcceleratedFactory(fallback=False).getProtocol(transport))
| AcceleratedCompactTest |
python | euske__pdfminer | pdfminer/pdfdevice.py | {
"start": 1096,
"end": 3674
} | class ____(PDFDevice):
def render_string(self, textstate, seq):
matrix = mult_matrix(textstate.matrix, self.ctm)
font = textstate.font
fontsize = textstate.fontsize
scaling = textstate.scaling * .01
charspace = textstate.charspace * scaling
wordspace = textstate.word... | PDFTextDevice |
python | spyder-ide__spyder | spyder/plugins/console/utils/interpreter.py | {
"start": 1074,
"end": 11978
} | class ____(InteractiveConsole, threading.Thread):
"""Interpreter, executed in a separate thread"""
p1 = ">>> "
p2 = "... "
def __init__(self, namespace=None, exitfunc=None,
Output=None, WidgetProxy=None, debug=False):
"""
namespace: locals send to InteractiveConsole obje... | Interpreter |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 20293,
"end": 21715
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = ChineseCLIPTextAttention(config)
self.intermediate = ChineseCLIPTextIntermediate(config)
... | ChineseCLIPTextLayer |
python | huggingface__transformers | src/transformers/data/processors/squad.py | {
"start": 23045,
"end": 23153
} | class ____(SquadProcessor):
train_file = "train-v2.0.json"
dev_file = "dev-v2.0.json"
| SquadV2Processor |
python | Textualize__textual | src/textual/fuzzy.py | {
"start": 404,
"end": 4794
} | class ____:
"""Performs a fuzzy search.
Unlike a regex solution, this will finds all possible matches.
"""
def __init__(
self, case_sensitive: bool = False, *, cache_size: int = 1024 * 4
) -> None:
"""Initialize fuzzy search.
Args:
case_sensitive: Is the match ... | FuzzySearch |
python | pypa__twine | twine/utils.py | {
"start": 12200,
"end": 12981
} | class ____(argparse.Action):
"""Set boolean flag from environment variable."""
def __init__(self, env: str, **kwargs: Any) -> None:
default = self.bool_from_env(os.environ.get(env))
self.env = env
super().__init__(default=default, nargs=0, **kwargs)
def __call__(
self,
... | EnvironmentFlag |
python | pytorch__pytorch | torch/_inductor/runtime/hints.py | {
"start": 607,
"end": 699
} | class ____(Enum):
INNER = 0
OUTER = 1
OUTER_TINY = 2
DEFAULT = 3
| ReductionHint |
python | ansible__ansible | lib/ansible/module_utils/facts/system/apparmor.py | {
"start": 826,
"end": 1297
} | class ____(BaseFactCollector):
name = 'apparmor'
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
facts_dict = {}
apparmor_facts = {}
if os.path.exists('/sys/kernel/security/apparmor'):
apparmor_facts['status'] = 'enabled'
... | ApparmorFactCollector |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py | {
"start": 9743,
"end": 10947
} | class ____(PreTrainedConfig):
model_type = "qwen3_vl_moe"
base_config_key = "vision_config"
def __init__(
self,
depth=27,
hidden_size=1152,
hidden_act="gelu_pytorch_tanh",
intermediate_size=4304,
num_heads=16,
in_channels=3,
patch_size=16,
... | Qwen3VLMoeVisionConfig |
python | pypa__setuptools | setuptools/tests/test_core_metadata.py | {
"start": 9352,
"end": 13438
} | class ____:
def base_example(self):
attrs = dict(
**EXAMPLE_BASE_INFO,
# Example with complex requirement definition
python_requires=">=3.8",
install_requires="""
packaging==23.2
more-itertools==8.8.0; extra == "other"
jarac... | TestParityWithMetadataFromPyPaWheel |
python | readthedocs__readthedocs.org | readthedocs/core/mixins.py | {
"start": 2883,
"end": 3396
} | class ____(DeleteView):
"""Delete view that shows a message after queuing an object for deletion."""
success_message = None
def post(self, request, *args, **kwargs):
self.object = self.get_object()
delete_object.delay(
model_name=self.object._meta.label,
pk=self.obj... | AsyncDeleteViewWithMessage |
python | getsentry__sentry | src/sentry/snuba/trace.py | {
"start": 1715,
"end": 1873
} | class ____(TypedDict):
description: str
event_id: str
event_type: str
project_id: int
project_slug: str
transaction: str
| SerializedEvent |
python | joke2k__faker | faker/providers/phone_number/fr_FR/__init__.py | {
"start": 49,
"end": 4872
} | class ____(PhoneNumberProvider):
formats = (
"+33 (0){{area_code_with_separator}} ## ## ##",
"+33 {{area_code_with_separator}} ## ## ##",
"0{{area_code_without_separator}}######",
"0{{area_code_with_separator}} ## ## ##",
)
# https://fr.wikipedia.org/wiki/Liste_des_indicatif... | Provider |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 144653,
"end": 148565
} | class ____(multi_rv_generic):
r"""An Orthogonal matrix (O(N)) random variable.
Return a random orthogonal matrix, drawn from the O(N) Haar
distribution (the only uniform distribution on O(N)).
The `dim` keyword specifies the dimension N.
Methods
-------
rvs(dim=None, size=1, random_state=... | ortho_group_gen |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver2.py | {
"start": 249,
"end": 472
} | class ____(Iterator[_T], Protocol):
pass
def decorator1(func: Callable[..., Iterator[_T]]) -> Callable[..., ProtoA[_T]]: ...
@decorator1
def func1() -> Iterator[str]:
yield ""
a = func1()
b: ProtoA[str] = a
| ProtoA |
python | faif__python-patterns | patterns/structural/bridge.py | {
"start": 216,
"end": 386
} | class ____:
def draw_circle(self, x: int, y: int, radius: float) -> None:
print(f"API1.circle at {x}:{y} radius {radius}")
# ConcreteImplementor 2/2
| DrawingAPI1 |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_alloy_db.py | {
"start": 1735,
"end": 2048
} | class ____:
def test_class_attributes(self):
assert AlloyDBClusterLink.key == EXPECTED_ALLOY_DB_CLUSTER_LINK_KEY
assert AlloyDBClusterLink.name == EXPECTED_ALLOY_DB_CLUSTER_LINK_NAME
assert AlloyDBClusterLink.format_str == EXPECTED_ALLOY_DB_CLUSTER_LINK_FORMAT_STR
| TestAlloyDBClusterLink |
python | kubernetes-client__python | kubernetes/base/config/kube_config.py | {
"start": 7009,
"end": 23659
} | class ____(object):
def __init__(self, config_dict, active_context=None,
get_google_credentials=None,
config_base_path="",
config_persister=None,
temp_file_path=None):
if config_dict is None:
raise ConfigException(
... | KubeConfigLoader |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 4610,
"end": 5635
} | class ____(greentest.TestCase):
link_method = None
def link(self, p, listener=None):
getattr(p, self.link_method)(listener)
def set_links(self, p):
event = AsyncResult()
self.link(p, event)
queue = Queue(1)
self.link(p, queue.put)
callback_flag = ['initia... | LinksTestCase |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 61447,
"end": 62047
} | class ____(object):
def __init__(self, name, parent):
self.name = name
self.parent = parent
def __call__(self, *args, **kwargs):
m = self.create_mock()
return m(*args, **kwargs)
def create_mock(self):
entry = self.name
parent = self.parent
m = parent... | MagicProxy |
python | tensorflow__tensorflow | tensorflow/python/keras/initializers/initializers_v2.py | {
"start": 7469,
"end": 9665
} | class ____(Initializer):
"""Initializer that generates tensors with a uniform distribution.
Also available via the shortcut function
`tf.keras.initializers.random_uniform`.
Examples:
>>> # Standalone usage:
>>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.)
>>> values = initial... | RandomUniform |
python | google__flatbuffers | tests/MyGame/Example/NestedUnion/NestedUnionTest.py | {
"start": 3365,
"end": 5390
} | class ____(object):
# NestedUnionTestT
def __init__(
self,
name = None,
dataType = 0,
data = None,
id = 0,
):
self.name = name # type: Optional[str]
self.dataType = dataType # type: int
self.data = data # type: Union[None, 'MyGame.Example.N... | NestedUnionTestT |
python | huggingface__transformers | src/transformers/models/hiera/modeling_hiera.py | {
"start": 7525,
"end": 11711
} | class ____(nn.Module):
"""
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
"""
def __init__(self, config, is_mae: bool = Fal... | HieraPatchEmbeddings |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 273130,
"end": 273222
} | class ____(Protocol):
def __call__(self, obj: Any, /) -> str: ...
| _SchemaForObjectCallable |
python | matplotlib__matplotlib | lib/matplotlib/backends/registry.py | {
"start": 245,
"end": 15480
} | class ____:
"""
Registry of backends available within Matplotlib.
This is the single source of truth for available backends.
All use of ``BackendRegistry`` should be via the singleton instance
``backend_registry`` which can be imported from ``matplotlib.backends``.
Each backend has a name, a ... | BackendRegistry |
python | ApeWorX__ape | tests/functional/test_coverage.py | {
"start": 5358,
"end": 8720
} | class ____:
@pytest.fixture
def pytest_config(self, mocker):
return mocker.MagicMock()
@pytest.fixture
def config_wrapper(self, pytest_config):
return ConfigWrapper(pytest_config)
@pytest.fixture
def tracker(self, pytest_config, project):
return CoverageTracker(pytest_c... | TestCoverageTracker |
python | numba__numba | numba/tests/test_numpy_support.py | {
"start": 356,
"end": 5380
} | class ____(TestCase):
def test_number_types(self):
"""
Test from_dtype() and as_dtype() with the various scalar number types.
"""
f = numpy_support.from_dtype
def check(typechar, numba_type):
# Only native ordering and alignment is supported
dtype = ... | TestFromDtype |
python | numba__numba | numba/tests/npyufunc/test_parallel_ufunc_issues.py | {
"start": 2556,
"end": 4387
} | class ____(unittest.TestCase):
_numba_parallel_test_ = False
@skip_if_freethreading
def test_gil_reacquire_deadlock(self):
"""
Testing similar issue to #1998 due to GIL reacquiring for Gufunc
"""
# make a ctypes callback that requires the GIL
proto = ctypes.CFUNCTYP... | TestParGUfuncIssues |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 3696,
"end": 3752
} | class ____:
pass
NoModule.__module__ = None
| NoModule |
python | getsentry__sentry | tests/sentry/api/test_utils.py | {
"start": 1036,
"end": 4048
} | class ____(unittest.TestCase):
def test_timeframe(self) -> None:
start, end = get_date_range_from_params({"timeframe": "14h"})
assert end - datetime.timedelta(hours=14) == start
start, end = get_date_range_from_params({"timeframe": "14d"})
assert end - datetime.timedelta(days=14) ==... | GetDateRangeFromParamsTest |
python | numba__numba | numba/testing/main.py | {
"start": 23362,
"end": 24338
} | class ____(object):
"""
A minimal, picklable TestResult-alike object.
"""
__slots__ = (
'failures', 'errors', 'skipped', 'expectedFailures',
'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun',
'test_id', 'resource_info')
def fixup_case(self, case):
"""
... | _MinimalResult |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 13566,
"end": 13659
} | class ____(OpcodeWithArg):
_FLAGS = HAS_NAME | HAS_ARGUMENT
__slots__ = ()
| STORE_ANNOTATION |
python | google__jax | jax/_src/core.py | {
"start": 59118,
"end": 59179
} | class ____(NamedTuple):
val: int
@dataclass(frozen=True)
| DBIdx |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/connections.py | {
"start": 2222,
"end": 2399
} | class ____(BaseModel):
"""Connection Collection serializer for responses."""
connections: Iterable[ConnectionResponse]
total_entries: int
| ConnectionCollectionResponse |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py | {
"start": 50762,
"end": 54298
} | class ____(GKEOperatorMixin, KubernetesDeleteJobOperator):
"""
Delete a Kubernetes job 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.
The **minimum** required to define a clust... | GKEDeleteJobOperator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/lambdas.py | {
"start": 1794,
"end": 4941
} | class ____(Options):
enable_tracking = True
track_closure_variables = True
track_on: Optional[object] = None
global_track_bound_values = True
track_bound_values = True
lambda_cache: Optional[_LambdaCacheType] = None
def lambda_stmt(
lmb: _StmtLambdaType,
enable_tracking: bool = True,
... | LambdaOptions |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 893,
"end": 1771
} | class ____(TestToken):
def test_match(self):
lines = ['### heading 3\n']
arg = 'heading 3'
self._test_match(block_token.Heading, lines, arg, level=3)
def test_children_with_enclosing_hashes(self):
lines = ['# heading 3 ##### \n']
arg = 'heading 3'
self._test_mat... | TestAtxHeading |
python | bokeh__bokeh | setup.py | {
"start": 6129,
"end": 6297
} | class ____(build): # type: ignore
def run(self) -> None:
check_tags()
build_or_install_bokehjs(self.distribution.packages)
super().run()
| Build |
python | getsentry__sentry | src/sentry/api/serializers/models/organization_member/response.py | {
"start": 1490,
"end": 1622
} | class ____(TypedDict):
teamSlug: str
role: str | None
@extend_schema_serializer(exclude_fields=["role", "roleName"])
| _TeamRole |
python | PyCQA__pylint | tests/functional/ext/no_self_use/no_self_use.py | {
"start": 2227,
"end": 2302
} | class ____(A):
def get_memo(self, obj):
return super().get(obj)
| B |
python | getsentry__sentry | src/sentry/models/organization.py | {
"start": 3368,
"end": 5396
} | class ____(BaseManager["Organization"]):
def get_for_user_ids(self, user_ids: Collection[int]) -> BaseQuerySet[Organization]:
"""Returns the QuerySet of all organizations that a set of Users have access to."""
return self.filter(
status=OrganizationStatus.ACTIVE,
member_set__... | OrganizationManager |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py | {
"start": 257,
"end": 353
} | class ____(GQLResult):
artifact: Optional[FetchArtifactManifestArtifact]
| FetchArtifactManifest |
python | sqlalchemy__sqlalchemy | test/orm/test_joins.py | {
"start": 67103,
"end": 74618
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
__dialect__ = "default"
run_setup_mappers = "once"
@classmethod
def define_tables(cls, metadata):
Table("table1", metadata, Column("id", Integer, primary_key=True))
Table(
"table2",
metadata,
Column... | JoinFromSelectableTest |
python | walkccc__LeetCode | solutions/3078. Match Alphanumerical Pattern in Matrix I/3078.py | {
"start": 0,
"end": 857
} | class ____:
def findPattern(
self,
board: list[list[int]],
pattern: list[str],
) -> list[int]:
def isMatch(x: int, y: int) -> bool:
digitToLetter = {}
letterToDigit = {}
for i, row in enumerate(pattern):
for j, c in enumerate(row):
digit = board[i + x][j + y... | Solution |
python | allegroai__clearml | clearml/utilities/io_manager.py | {
"start": 25,
"end": 1244
} | class ____(object):
def __init__(self) -> None:
self.threads_io = {}
def add_io_to_thread(self, thread_id: int, io_object: Any) -> None:
if thread_id in self.threads_io:
self.threads_io[thread_id].add(id(io_object))
else:
self.threads_io[thread_id] = {id(io_objec... | IOCallsManager |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 21831,
"end": 22558
} | class ____(nn.Module):
def __init__(self, config, dim, num_heads, window_size):
super().__init__()
self.self = SwinSelfAttention(config, dim, num_heads, window_size)
self.output = SwinSelfOutput(config, dim)
def forward(
self,
hidden_states: torch.Tensor,
attenti... | SwinAttention |
python | kamyu104__LeetCode-Solutions | Python/minimum-remove-to-make-valid-parentheses.py | {
"start": 29,
"end": 700
} | class ____(object):
def minRemoveToMakeValid(self, s):
"""
:type s: str
:rtype: str
"""
result = list(s)
count = 0
for i, v in enumerate(result):
if v == '(':
count += 1
elif v == ')':
if count:
... | Solution |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_training.py | {
"start": 36122,
"end": 38050
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return min(4, torch.get_device_module(device_type).device_count())
@skip_if_lt_x_gpu(2)
def test_train_parity_with_shared_params(self):
self.run_subtests(
{
"reshard_after_forward": [False, True],
... | TestFullyShardSharedParams |
python | streamlit__streamlit | lib/streamlit/runtime/state/session_state.py | {
"start": 2074,
"end": 2216
} | class ____:
"""A widget value that's serialized to a protobuf. Immutable."""
value: WidgetStateProto
@dataclass(frozen=True)
| Serialized |
python | ray-project__ray | python/ray/tune/examples/tf_mnist_example.py | {
"start": 795,
"end": 1212
} | class ____(Model):
def __init__(self, hiddens=128):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation="relu")
self.flatten = Flatten()
self.d1 = Dense(hiddens, activation="relu")
self.d2 = Dense(10, activation="softmax")
def call(self, x):
x =... | MyModel |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 1220,
"end": 3091
} | class ____(TestCase):
def test_simple(self):
def gn(x, y):
return torch.mul(x, y)
def fn(x, y):
return nested_compile_region(gn)(x, y)
x = torch.randn(8, requires_grad=True)
y = torch.randn(8, requires_grad=True)
ref = gn(x, y)
x_clone = x.d... | TestInvokeSubgraph |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 9752,
"end": 10885
} | class ____:
@declared_attr
def __table_args__(cls): # noqa: N805
return (
CheckConstraint(
"name ~* '^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$'::text",
name="%s_valid_name" % cls.__tablename__,
),
CheckConstraint(
"link... | OrganizationMixin |
python | getsentry__sentry | src/sentry/profiles/task.py | {
"start": 41450,
"end": 44766
} | class ____(TypedDict):
project_id: int
use_case: str
@metrics.wraps("process_profile.track_outcome")
def _track_duration_outcome(
profile: Profile,
project: Project,
) -> None:
duration_ms = _calculate_profile_duration_ms(profile)
if duration_ms <= 0:
return
track_outcome(
... | _ProjectKeyKwargs |
python | openai__gym | tests/envs/test_compatibility.py | {
"start": 812,
"end": 3885
} | class ____(gym.Env):
"""Legacy env that implicitly implements the old API as a protocol."""
observation_space = Discrete(1)
action_space = Discrete(1)
metadata = {"render.modes": ["human", "rgb_array"]}
def __init__(self):
pass
def reset(self): # type: ignore
return 0 # type... | LegacyEnvImplicit |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 41827,
"end": 45722
} | class ____(Marker):
''' Render scatter markers selected from a predefined list of designs.
Use ``Scatter`` to draw any of Bokeh's built-in marker types:
``asterisk``, ``circle``, ``circle_cross``, ``circle_dot``, ``circle_x``,
``circle_y``, ``cross``, ``dash``, ``diamond``, ``diamond_cross``,
``dia... | Scatter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_line05.py | {
"start": 315,
"end": 1367
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_line05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.