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 | getsentry__sentry | src/sentry/issues/endpoints/project_codeowners_index.py | {
"start": 865,
"end": 3974
} | class ____(ProjectCodeOwnersBase):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, project: Project) -> Response:
"""
Retrieve the list of CODEOWNERS configurations for a proj... | ProjectCodeOwnersEndpoint |
python | ray-project__ray | python/ray/train/v2/_internal/execution/training_report.py | {
"start": 122,
"end": 552
} | class ____:
"""A specification for validation."""
def __init__(
self,
validate_fn: Callable[["Checkpoint", Optional[Dict]], Dict],
validate_config: Dict,
):
self.validate_fn = validate_fn
self.validate_config = validate_config
def __repr__(self) -> str:
... | _ValidationSpec |
python | kubernetes-client__python | kubernetes/client/models/v1_namespace.py | {
"start": 383,
"end": 7166
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Namespace |
python | fluentpython__example-code | attic/dicts/test_transformdict.py | {
"start": 7288,
"end": 9317
} | class ____(TransformDictTestBase,
mapping_tests.BasicTestMappingProtocol):
TransformDict = TransformDict
type2test = partial(TransformDict, str.lower)
def check_shallow_copy(self, copy_func):
d = self.TransformDict(str_lower, {'Foo': []})
e = copy_func(d)
... | TransformDictMappingTests |
python | doocs__leetcode | solution/1000-1099/1087.Brace Expansion/Solution.py | {
"start": 0,
"end": 849
} | class ____:
def expand(self, s: str) -> List[str]:
def convert(s):
if not s:
return
if s[0] == '{':
j = s.find('}')
items.append(s[1:j].split(','))
convert(s[j + 1 :])
else:
j = s.find('{')
... | Solution |
python | ansible__ansible | lib/ansible/plugins/test/files.py | {
"start": 803,
"end": 1407
} | class ____(object):
""" Ansible file jinja2 tests """
def tests(self):
return {
# file testing
'directory': isdir,
'is_dir': isdir,
'file': isfile,
'is_file': isfile,
'link': islink,
'is_link': islink,
'exis... | TestModule |
python | graphql-python__graphene | graphene/types/uuid.py | {
"start": 181,
"end": 1021
} | class ____(Scalar):
"""
Leverages the internal Python implementation of UUID (uuid.UUID) to provide native UUID objects
in fields, resolvers and input.
"""
@staticmethod
def serialize(uuid):
if isinstance(uuid, str):
uuid = _UUID(uuid)
assert isinstance(uuid, _UUID)... | UUID |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/branch.py | {
"start": 778,
"end": 15777
} | class ____(RunnableSerializable[Input, Output]):
"""`Runnable` that selects which branch to run based on a condition.
The `Runnable` is initialized with a list of `(condition, Runnable)` pairs and
a default branch.
When operating on an input, the first condition that evaluates to True is
selected,... | RunnableBranch |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 34454,
"end": 35059
} | class ____:
params = [get_benchmark_shapes("TimeDropDuplicatesSeries")]
param_names = ["shape"]
def setup(self, shape):
rows = shape[0]
self.series = IMPL.Series(
np.tile(
IMPL.Index([f"i-{i}" for i in range(rows // 10)], dtype=object).values,
10,... | TimeDropDuplicatesSeries |
python | pandas-dev__pandas | setup.py | {
"start": 8577,
"end": 8869
} | class ____(build_ext):
"""
Custom command subclassed from Cython.Distutils.build_ext
to compile pyx->c, and stop there. All this does is override the
C-compile method build_extension() with a no-op.
"""
def build_extension(self, ext) -> None:
pass
| CythonCommand |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/tests/test_helpers/test_execution/test_run_steps.py | {
"start": 14807,
"end": 17726
} | class ____:
def test_init(self):
options = RunStepOptions()
assert options.fail_fast is True
assert options.concurrency == 10
assert options.skip_steps == []
assert options.step_params == {}
options = RunStepOptions(fail_fast=False, concurrency=1, skip_steps=["step1"... | TestRunStepOptions |
python | gevent__gevent | src/gevent/tests/test__refcount.py | {
"start": 2386,
"end": 3457
} | class ____(object):
listening = False
client_data = None
server_port = None
def __init__(self, raise_on_timeout):
self.raise_on_timeout = raise_on_timeout
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.server_port = support.bind_port(self.... | Server |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/global_shuffle_test.py | {
"start": 7243,
"end": 8617
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
checkpoint_test_base.default_test_combinations(),
combinations.combine(
d... | GlobalShuffleCheckpointTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/document.py | {
"start": 2022,
"end": 2307
} | class ____:
def __init__(self) -> None:
#: List of lines for the Document text.
self.lines: _ImmutableLineList | None = None
#: List of index positions, pointing to the start of all the lines.
self.line_indexes: list[int] | None = None
| _DocumentCache |
python | sympy__sympy | sympy/functions/special/hyper.py | {
"start": 30711,
"end": 31139
} | class ____(HyperRep):
""" Represent -z*hyper([1, 1], [2], z) == log(1 - z). """
@classmethod
def _expr_small(cls, x):
return log(1 - x)
@classmethod
def _expr_small_minus(cls, x):
return log(1 + x)
@classmethod
def _expr_big(cls, x, n):
return log(x - 1) + (2*n - 1)... | HyperRep_log1 |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 35087,
"end": 39124
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self-attention layers. Each layer is a
[`GroupViTEncoderLayer`].
Args:
config: GroupViTTextConfig
"""
def __init__(self, config: GroupViTTextConfig):
super().__init__()
self.config =... | GroupViTTextEncoder |
python | allegroai__clearml | clearml/router/route.py | {
"start": 117,
"end": 3888
} | class ____:
def __init__(
self,
target_url: str,
request_callback: Optional[Callable[[Any, Dict[str, Any]], Any]] = None,
response_callback: Optional[Callable[[Any, Any, Dict[str, Any]], Any]] = None,
session: Optional[Any] = None,
error_callback: Optional[Callable[[A... | Route |
python | pytorch__pytorch | test/inductor/test_mps_basic.py | {
"start": 4475,
"end": 8627
} | class ____(TestCase):
def check_model(self, m, inp, dynamic_shapes=None):
res2 = m(*inp)
ep = torch.export.export(m, inp, dynamic_shapes=dynamic_shapes)
path = torch._inductor.aoti_compile_and_package(ep)
m = torch._inductor.aoti_load_package(path)
res = m(*inp)
asser... | MPSBasicTestsAOTI |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/testpkg-edgedata/script.py | {
"start": 55,
"end": 1384
} | class ____:
import toplevel_class_existing
import toplevel_class_nonexisting
if a == b:
import toplevel_conditional_existing
import toplevel_conditional_nonexisting
try:
import toplevel_conditional_import_existing
import toplevel_conditional_import_nonexisting
except:
i... | MyClass |
python | getsentry__sentry | tests/sentry/grouping/seer_similarity/test_training_mode.py | {
"start": 416,
"end": 7494
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.event = save_new_event({"message": "Dogs are great!"}, self.project)
self.variants = self.event.get_grouping_variants()
# save_new_event already creates a grouphash, so retrieve it
self.grouphash = GroupHash.... | MaybeSendSeerForNewModelTrainingTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/defs.py | {
"start": 1780,
"end": 10783
} | class ____(DgClickGroup):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._commands_defined = False
def get_command(self, ctx: click.Context, cmd_name: str) -> Optional[click.Command]:
if not self._commands_defined and cmd_name not in HARDCODED_COMMANDS:
... | ScaffoldDefsGroup |
python | openai__openai-python | tests/api_resources/beta/threads/test_messages.py | {
"start": 12498,
"end": 25287
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_create(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
... | TestAsyncMessages |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 110489,
"end": 112806
} | class ____(_ColumnEntity):
entity_zero = None
mapper = None
supports_single_entity = False
__slots__ = (
"expr",
"column",
"_label_name",
"entity_zero_or_selectable",
"_extra_entities",
)
def __init__(
self,
compile_state,
column,... | _RawColumnEntity |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 27465,
"end": 27555
} | class ____(TestKill):
def _start_greenlet(self, g):
g.start()
| TestKillAfterStart |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_percent_diff_less_than_or_equal_to_threshold.py | {
"start": 964,
"end": 7743
} | class ____(
DataProfilerProfileMetricProvider
):
metric_name = (
"data_profiler.profile_numeric_columns_percent_diff_less_than_or_equal_to_threshold"
)
value_keys = (
"profile_path",
"limit_check_report_keys",
"numerical_diff_statistics",
)
@metric_value(engine=... | DataProfilerProfileNumericColumnsPercentDiffLessThanOrEqualToThreshold |
python | getsentry__sentry | src/sentry/rules/history/backends/postgres.py | {
"start": 801,
"end": 1341
} | class ____(TypedDict):
group: int
count: int
last_triggered: datetime
event_id: str
def convert_results(results: Sequence[_Result]) -> Sequence[RuleGroupHistory]:
group_lookup = {g.id: g for g in Group.objects.filter(id__in=[r["group"] for r in results])}
return [
RuleGroupHistory(grou... | _Result |
python | pola-rs__polars | py-polars/tests/unit/io/database/test_read.py | {
"start": 3598,
"end": 3921
} | class ____(NamedTuple):
"""Clarify read test params."""
read_method: Literal["read_database", "read_database_uri"]
connect_using: Any
expected_dtypes: SchemaDefinition
expected_dates: list[date | str]
schema_overrides: SchemaDict | None = None
batch_size: int | None = None
| DatabaseReadTestParams |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 30575,
"end": 32373
} | class ____(forms.ModelForm):
"""Webhook form."""
project = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = WebHook
fields = ["project", "url", "events", "payload", "secret"]
widgets = {
"events": forms.CheckboxSelectMultiple,
}
... | WebHookForm |
python | facebook__pyre-check | scripts/explore_pysa_models.py | {
"start": 24124,
"end": 43130
} | class ____(NamedTuple):
condition_kind: ConditionKind
caller: str
caller_port: str
callee: Optional[str]
callee_port: Optional[str]
taint_kind: str
distance: Optional[int] # None for subtraces.
location: SourceLocationWithFilename
shared_local_features: List[Dict[str, str]]
loca... | TaintFrame |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_hash_returned.py | {
"start": 507,
"end": 568
} | class ____:
"""Hash through the metaclass."""
| ThirdGoodHash |
python | falconry__falcon | falcon/testing/client.py | {
"start": 12149,
"end": 36279
} | class ____(_ResultBase):
"""Encapsulates the streamed result of an ASGI request.
Args:
body_chunks (list): A list of body chunks. This list may be
appended to after a result object has been instantiated.
status (str): An HTTP status string, including status code and
reas... | StreamedResult |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 12983,
"end": 14532
} | class ____(DatabricksBaseTask[jobs.RunJobTask]):
@property
def task_type(self) -> str:
return "run_job"
@property
def task_config_metadata(self) -> Mapping[str, Any]:
task_config_metadata = {}
job_config = self.task_config["run_job_task"]
task_config_metadata["job_id"] =... | DatabricksJobTask |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/snap/snap.py | {
"start": 6136,
"end": 7731
} | class ____(PartitionsSnap, IHaveNew):
partition_keys: Sequence[str]
def __new__(cls, partition_keys: Sequence[str]):
# for back compat reasons we allow str as a Sequence[str] here
if not isinstance(partition_keys, str):
check.sequence_param(
partition_keys,
... | StaticPartitionsSnap |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-notion/components.py | {
"start": 1384,
"end": 2311
} | class ____(RecordTransformation):
"""
Transforms the nested 'properties' object within a Notion Page/Database record into a more
normalized form. In Notion's API response, 'properties' is a dictionary where each key
represents the name of a property and its value contains various metadata and the proper... | NotionPropertiesTransformation |
python | doocs__leetcode | solution/2400-2499/2410.Maximum Matching of Players With Trainers/Solution.py | {
"start": 0,
"end": 385
} | class ____:
def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
players.sort()
trainers.sort()
j, n = 0, len(trainers)
for i, p in enumerate(players):
while j < n and trainers[j] < p:
j += 1
if j == n:
... | Solution |
python | pytorch__pytorch | torch/_dynamo/variables/base.py | {
"start": 7845,
"end": 8066
} | class ____(NotImplementedError):
vt: "VariableTracker"
def __init__(self, vt: "VariableTracker") -> None:
super().__init__(f"{vt} is not a constant")
self.vt = vt
| AsPythonConstantNotImplementedError |
python | joblib__joblib | joblib/compressor.py | {
"start": 19088,
"end": 19281
} | class ____(CompressorWrapper):
def __init__(self):
CompressorWrapper.__init__(
self, obj=BinaryGzipFile, prefix=_GZIP_PREFIX, extension=".gz"
)
| GzipCompressorWrapper |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 37739,
"end": 37868
} | class ____(EnvironmentVariableMixin, CreateView):
success_message = _("Environment variable created")
| EnvironmentVariableCreate |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC501_google.py | {
"start": 54,
"end": 5088
} | class ____(Exception):
...
_some_error = Exception
# OK
def calculate_speed(distance: float, time: float) -> float:
"""Calculate speed as distance divided by time.
Args:
distance: Distance traveled.
time: Time spent traveling.
Returns:
Speed as distance divided by time.
... | FasterThanLightError |
python | huggingface__transformers | src/transformers/models/swinv2/modeling_swinv2.py | {
"start": 5690,
"end": 8634
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if con... | Swinv2ImageClassifierOutput |
python | django__django | tests/auth_tests/test_management.py | {
"start": 3587,
"end": 3878
} | class ____(TestCase):
@mock_inputs({"username": "alice"})
def test_input_not_found(self):
with self.assertRaisesMessage(
ValueError, "Mock input for 'Email address: ' not found."
):
call_command("createsuperuser", stdin=MockTTY())
| MockInputTests |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 8280,
"end": 8396
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
href: str
@dataclasses.dataclass(frozen=True)
| CodeDescription |
python | huggingface__transformers | src/transformers/models/seed_oss/modular_seed_oss.py | {
"start": 1520,
"end": 2381
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
... | SeedOssMLP |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 354955,
"end": 355305
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("message", "octicon")
message = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="message")
octicon = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_... | HovercardContext |
python | bokeh__bokeh | tests/unit/bokeh/test_objects.py | {
"start": 10951,
"end": 15983
} | class ____(TestContainerMutation):
def test_whether_included_in_props_with_values(self) -> None:
obj = HasListProp()
assert 'foo' not in obj.properties_with_values(include_defaults=False)
assert 'foo' in obj.properties_with_values(include_defaults=True)
# simply reading the property... | TestListMutation |
python | rapidsai__cudf | python/cudf/cudf/core/udf/masked_typing.py | {
"start": 12159,
"end": 12627
} | class ____(AbstractTemplate):
"""
Typing for `Masked is cudf.NA`
"""
def generic(self, args, kws):
if isinstance(args[0], MaskedType) and isinstance(args[1], NAType):
return nb_signature(types.boolean, args[0], na_type)
elif isinstance(args[1], MaskedType) and isinstance(arg... | MaskedScalarIsNull |
python | dask__dask | dask/dataframe/dask_expr/_categorical.py | {
"start": 549,
"end": 4716
} | class ____(Accessor):
"""
Accessor object for categorical properties of the Series values.
Examples
--------
>>> s.cat.categories # doctest: +SKIP
Notes
-----
Attributes that depend only on metadata are eager
* categories
* ordered
Attributes depending on the entire data... | CategoricalAccessor |
python | fastapi__sqlmodel | docs_src/tutorial/automatic_id_none_refresh/tutorial002.py | {
"start": 92,
"end": 2438
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
... | Hero |
python | python__mypy | mypy/copytype.py | {
"start": 880,
"end": 4480
} | class ____(TypeVisitor[ProperType]):
def visit_unbound_type(self, t: UnboundType) -> ProperType:
return t
def visit_any(self, t: AnyType) -> ProperType:
return self.copy_common(t, AnyType(t.type_of_any, t.source_any, t.missing_import_name))
def visit_none_type(self, t: NoneType) -> ProperT... | TypeShallowCopier |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/test_dataloaders.py | {
"start": 1950,
"end": 2255
} | class ____(BoringModel):
def val_dataloader(self):
return [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64), batch_size=8)]
def validation_step(self, batch, batch_idx, dataloader_idx):
return super().validation_step(batch, batch_idx)
| MultiValDataLoaderBoringModel |
python | langchain-ai__langchain | libs/standard-tests/langchain_tests/integration_tests/chat_models.py | {
"start": 2250,
"end": 2657
} | class ____(BaseCallbackHandler):
options: list[dict | None]
def __init__(self) -> None:
super().__init__()
self.options = []
@override
def on_chat_model_start(
self,
serialized: Any,
messages: Any,
*,
options: dict[str, Any] | None = None,
... | _TestCallbackHandler |
python | dagster-io__dagster | python_modules/libraries/dagster-snowflake-pyspark/dagster_snowflake_pyspark/snowflake_pyspark_type_handler.py | {
"start": 7514,
"end": 11157
} | class ____(SnowflakeIOManager):
"""An I/O manager definition that reads inputs from and writes PySpark DataFrames to Snowflake. When
using the SnowflakePySparkIOManager, any inputs and outputs without type annotations will be loaded
as PySpark DataFrames.
Returns:
IOManagerDefinition
Examp... | SnowflakePySparkIOManager |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 1409,
"end": 1517
} | class ____(ShowFieldTypeAndContent, PolymorphicModel):
field1 = models.CharField(max_length=10)
| TestModelA |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/unit_tests/test_spec_processing.py | {
"start": 405,
"end": 6139
} | class ____(BaseModel):
asset_attributes: Sequence[AssetPostProcessorModel] = []
defs = dg.Definitions(
assets=[
dg.AssetSpec("a", group_name="g1"),
dg.AssetSpec("b", group_name="g2"),
dg.AssetSpec("c", group_name="g2", tags={"tag": "val"}),
],
)
def test_replace_attributes() -> N... | M |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 41273,
"end": 45550
} | class ____(Operation):
def __init__(
self,
strides=1,
padding="valid",
data_format=None,
dilation_rate=1,
*,
name=None,
):
super().__init__(name=name)
self.strides = strides
self.padding = padding.lower()
self.data_format = ... | SeparableConv |
python | walkccc__LeetCode | solutions/3555. Smallest Subarray to Sort in Every Sliding Window/3555.py | {
"start": 0,
"end": 404
} | class ____:
def minSubarraySort(self, nums: list[int], k):
ans = []
for i in range(len(nums) - k + 1):
window = nums[i:i+k]
sortedWindow = sorted(window)
l = 0
r = k - 1
while l < k and window[l] == sortedWindow[l]:
l += 1
while r >= 0 and window[r] == sortedWindow... | Solution |
python | astropy__astropy | astropy/utils/iers/tests/test_iers.py | {
"start": 8857,
"end": 21634
} | class ____:
def setup_class(self):
"""Set up useful data for the tests."""
self.N = 40
self.ame = 30.0
self.iers_a_file_1 = get_pkg_data_filename(
os.path.join("data", "finals2000A-2016-02-30-test")
)
self.iers_a_file_2 = get_pkg_data_filename(
... | TestIERS_Auto |
python | aio-libs__aiohttp | aiohttp/payload.py | {
"start": 1108,
"end": 1505
} | class ____(str, enum.Enum):
normal = "normal"
try_first = "try_first"
try_last = "try_last"
def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload":
return PAYLOAD_REGISTRY.get(data, *args, **kwargs)
def register_payload(
factory: type["Payload"], type: Any, *, order: Order = Order.no... | Order |
python | huggingface__transformers | src/transformers/models/openai/modeling_openai.py | {
"start": 11683,
"end": 17050
} | class ____(OpenAIGPTPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.tokens_embed = nn.Embedding(config.vocab_size, config.n_embd)
self.positions_embed = nn.Embedding(config.n_positions, config.n_embd)
self.drop = nn.Dropout(config.embd_pdrop)
self... | OpenAIGPTModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/root.py | {
"start": 426,
"end": 1696
} | class ____(ConfigurableClass):
def __init__(self, base_dir: str, inst_data: Optional[ConfigurableClassData] = None):
self._base_dir = base_dir
self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)
@property
def inst_data(self) -> Optional[ConfigurableClassDat... | LocalArtifactStorage |
python | facelessuser__soupsieve | tests/test_level2/test_first_child.py | {
"start": 55,
"end": 738
} | class ____(util.TestCase):
"""Test first child selector."""
def test_first_child(self):
"""Test first child."""
self.assert_selector(
"""
<div id="div">
<p id="0">Some text <span id="1"> in a paragraph</span>.</p>
<a id="2" href="http://google.co... | TestFirstChild |
python | spack__spack | .github/workflows/bin/format-rst.py | {
"start": 1992,
"end": 2257
} | class ____:
def __init__(self, path: str, line: int, message: str) -> None:
self.path = path
self.line = line
self.message = message
def __str__(self) -> str:
return _warning(f"{self.path}:{self.line}: {self.message}")
| Warning |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 49556,
"end": 66059
} | class ____(QueryTest, AssertsCompiledSQL):
"""test sql.Comparator implementation for MapperProperties"""
__dialect__ = "default"
def _test(self, clause, expected, entity=None, checkparams=None):
dialect = default.DefaultDialect()
if entity is not None:
# specify a lead entity, ... | OperatorTest |
python | charliermarsh__ruff | crates/ty_completion_eval/truth/object-attr-instance-methods/main.py | {
"start": 0,
"end": 330
} | class ____:
def __init__(self): pass
def lion(self): pass
def tiger(self): pass
def bear(self): pass
def chicken(self): pass
def turkey(self): pass
def wasp(self): pass
def rabbit(self): pass
def squirrel(self): pass
quux = Quux()
quux.tur<CURSOR: turkey>
quux = Quux()
quux.be<CURS... | Quux |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py | {
"start": 1794,
"end": 2336
} | class ____(BaseEvent):
"""Event fired when attachment processing starts."""
page_id: str = Field(description="ID of the parent page")
attachment_id: str = Field(description="ID of the attachment")
attachment_name: str = Field(description="Name of the attachment")
attachment_type: str = Field(descri... | SNOWKBAttachmentProcessingStartEvent |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/dataframes.py | {
"start": 10705,
"end": 11015
} | class ____(Capture):
def __init__(self, left, right, ctx) -> None:
self.ctx = ctx
self.left = left
self.right = right
def __str__(self) -> str:
return f"{self.left} - {self.right}"
def execute(self):
return get_val(self.left) - get_val(self.right)
| CaptureSub |
python | ansible__ansible | test/units/mock/custom_types.py | {
"start": 66,
"end": 498
} | class ____(c.Mapping):
"""Minimally functional Mapping implementation for testing."""
def __init__(self, data: dict) -> None:
self._data = data
def __getitem__(self, __key):
return self._data[__key]
def __len__(self):
return len(self._data)
def __iter__(self):
retu... | CustomMapping |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 94489,
"end": 98081
} | class ____(APITestCase):
def setUp(self):
super().setUp()
self.login_as(self.user)
self.dashboard = Dashboard.objects.create(
title="Dashboard 1",
created_by_id=self.user.id,
organization=self.organization,
)
self.anon_users_query: _QueryDi... | OrganizationDashboardWidgetTestCase |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/image_ops/extract_volume_patches_grad_test.py | {
"start": 1248,
"end": 3771
} | class ____(test.TestCase, parameterized.TestCase):
"""Gradient-checking for ExtractVolumePatches op."""
@parameterized.parameters([
{
'in_shape': [2, 5, 5, 5, 3],
'ksizes': [1, 1, 1, 1, 1],
'strides': [1, 2, 3, 4, 1],
},
{
'in_shape': [2, 7, 7, 7, 3],
... | ExtractVolumePatchesGradTest |
python | doocs__leetcode | solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/Solution.py | {
"start": 0,
"end": 407
} | class ____:
def maxLength(self, arr: List[str]) -> int:
s = [0]
for t in arr:
x = 0
for b in map(lambda c: ord(c) - 97, t):
if x >> b & 1:
x = 0
break
x |= 1 << b
if x:
s.exten... | Solution |
python | buildout__buildout | src/zc/buildout/_package_index.py | {
"start": 12896,
"end": 13437
} | class ____:
"""
A null content checker that defines the interface for checking content
"""
def feed(self, block):
"""
Feed a block of data to the hash.
"""
return
def is_valid(self):
"""
Check the hash. Return False if validation fails.
"""
... | ContentChecker |
python | protocolbuffers__protobuf | python/google/protobuf/service_reflection.py | {
"start": 3359,
"end": 8119
} | class ____(object):
"""This class constructs a protocol service class using a service descriptor.
Given a service descriptor, this class constructs a class that represents
the specified service descriptor. One service builder instance constructs
exactly one service class. That means all instances of that clas... | _ServiceBuilder |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 19084,
"end": 19286
} | class ____(PrefectBaseModel):
"""Filter by `Log.flow_run_id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of flow run IDs to include"
)
| LogFilterFlowRunId |
python | great-expectations__great_expectations | great_expectations/data_context/store/checkpoint_store.py | {
"start": 860,
"end": 4538
} | class ____(Store):
_key_class = StringKey
def __init__(
self,
store_backend: dict | None = None,
runtime_environment: dict | None = None,
store_name: str = "no_store_name",
) -> None:
store_backend_class = self._determine_store_backend_class(store_backend)
if... | CheckpointStore |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 1838,
"end": 2936
} | class ____(TestCase):
"""Tests for ``tail()``"""
def test_iterator_greater(self):
"""Length of iterator is greater than requested tail"""
self.assertEqual(list(mi.tail(3, iter('ABCDEFG'))), list('EFG'))
def test_iterator_equal(self):
"""Length of iterator is equal to the requested ... | TailTests |
python | django__django | django/db/models/lookups.py | {
"start": 15850,
"end": 16530
} | class ____:
underflow_exception = EmptyResultSet
overflow_exception = EmptyResultSet
def process_rhs(self, compiler, connection):
rhs = self.rhs
if isinstance(rhs, int):
field_internal_type = self.lhs.output_field.get_internal_type()
min_value, max_value = connection... | IntegerFieldOverflow |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_at_time.py | {
"start": 269,
"end": 5521
} | class ____:
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
def test_localized_at_time(self, tzstr, frame_or_series):
tz = timezones.maybe_get_tz(tzstr)
rng = date_range("4/16/2012", "5/1/2012", freq="h")
ts = frame_or_series(
np.random.default_rng(2... | TestAtTime |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_trace.py | {
"start": 1341,
"end": 8373
} | class ____(TestCase):
"""Test serialization of columnar uptime data to span format."""
def setUp(self) -> None:
super().setUp()
self.project_slugs = {1: "test-project", 2: "another-project"}
self.snuba_params = mock.MagicMock(spec=SnubaParams)
self.snuba_params.project_ids = [1]... | TestSerializeColumnarUptimeItem |
python | pytorch__pytorch | test/inductor/test_debug_trace.py | {
"start": 6921,
"end": 7977
} | class ____:
var_ranges = {p0: 256}
index0 = p0
def body(self, ops):
get_index = self.get_index('index0')
load = ops.load('arg0_1', get_index)
constant = ops.constant(1.0, torch.float32)
add = ops.add(load, constant)
get_index_1 = self.get_index('index0')
store... | op0_loop_body |
python | huggingface__transformers | src/transformers/models/chameleon/modeling_chameleon.py | {
"start": 1723,
"end": 2552
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
ChameleonRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
in... | ChameleonRMSNorm |
python | ApeWorX__ape | src/ape_ethereum/_converters.py | {
"start": 538,
"end": 1203
} | class ____(ConverterAPI):
"""Converts units like `1 ether` to 1e18 wei."""
def is_convertible(self, value: str) -> bool:
if not isinstance(value, str):
return False
elif " " not in value or len(value.split(" ")) > 2:
return False
val, unit = value.split(" ")
... | WeiConversions |
python | google__jax | tests/hijax_test.py | {
"start": 5397,
"end": 5528
} | class ____:
elts: tuple
def __repr__(self):
return 'Tup{' + ','.join(map(repr, self.elts)) + '}'
@dataclass(frozen=True)
| HiTup |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/partition.py | {
"start": 309,
"end": 1213
} | class ____(Generic[T_cov]):
"""A Partition represents a single slice of the entire set of a job's possible work. It consists
of a value, which is an object that represents that partition, and an optional name, which is
used to label the partition in a human-readable way.
Args:
value (Any): The ... | Partition |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_delete_event.py | {
"start": 233,
"end": 549
} | class ____(BaseModel):
item_id: str
"""The ID of the item to delete."""
type: Literal["conversation.item.delete"]
"""The event type, must be `conversation.item.delete`."""
event_id: Optional[str] = None
"""Optional client-generated ID used to identify this event."""
| ConversationItemDeleteEvent |
python | pytorch__pytorch | test/distributed/tensor/test_placement_types.py | {
"start": 398,
"end": 3201
} | class ____(TestCase):
def test_type_identification(self):
shard = Shard(3)
strided_shard = _StridedShard(dim=3, split_factor=7)
partial_sum = Partial("sum")
partial_max = Partial("max")
replicate = Replicate()
ident_tests = (
(shard, True, False, False),
... | PlacementTypesTestCase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pytest_style/PT023.py | {
"start": 793,
"end": 874
} | class ____:
@pytest.mark.foo()
def test_something():
pass
| TestClass |
python | streamlit__streamlit | lib/streamlit/external/langchain/streamlit_callback_handler.py | {
"start": 4570,
"end": 10021
} | class ____:
"""Encapsulates the Streamlit UI for a single LLM 'thought' during a LangChain Agent
run. Each tool usage gets its own thought; and runs also generally having a
concluding thought where the Agent determines that it has an answer to the prompt.
Each thought gets its own expander UI.
"""
... | LLMThought |
python | aio-libs__aiohttp | tests/test_web_exceptions.py | {
"start": 11572,
"end": 14213
} | class ____:
def test_ctor(self) -> None:
exc = web.HTTPUnavailableForLegalReasons(
link="http://warning.or.kr/",
headers={"X-Custom": "value"},
reason="Zaprescheno",
text="text",
content_type="custom",
)
assert exc.link == URL("http... | TestHTTPUnavailableForLegalReasons |
python | django__django | tests/expressions_window/tests.py | {
"start": 1031,
"end": 79437
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
classification = Classification.objects.create()
Employee.objects.bulk_create(
[
Employee(
name=e[0],
salary=e[1],
department=e[2],
... | WindowFunctionTests |
python | mwaskom__seaborn | tests/_core/test_properties.py | {
"start": 1402,
"end": 1883
} | class ____(DataFixtures):
def test_bad_scale_arg_str(self, num_vector):
err = "Unknown magic arg for x scale: 'xxx'."
with pytest.raises(ValueError, match=err):
Coordinate("x").infer_scale("xxx", num_vector)
def test_bad_scale_arg_type(self, cat_vector):
err = "Magic arg ... | TestCoordinate |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B019.py | {
"start": 1989,
"end": 2148
} | class ____(enum.Enum):
ONE = enum.auto()
TWO = enum.auto()
@functools.cache
def bar(self, arg: str) -> str:
return f"{self} - {arg}"
| Foo |
python | huggingface__transformers | tests/models/clipseg/test_modeling_clipseg.py | {
"start": 4535,
"end": 7280
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as CLIPSeg does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (CLIPSegVisionModel,) if is_torch_available() else ()
test_resize_e... | CLIPSegVisionModelTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/overrides.py | {
"start": 3763,
"end": 3946
} | class ____(TooManyOverrides):
def return_source(self):
return _test_source()
def call_too_many_overrides(t: TooManyOverrides):
t.return_source()
| TooManyOverridesChild3 |
python | wandb__wandb | wandb/vendor/pygments/lexers/business.py | {
"start": 24074,
"end": 25361
} | class ____(RegexLexer):
"""
Lexer for `GoodData-CL
<http://github.com/gooddata/GoodData-CL/raw/master/cli/src/main/resources/\
com/gooddata/processor/COMMANDS.txt>`_
script files.
.. versionadded:: 1.4
"""
name = 'GoodData-CL'
aliases = ['gooddata-cl']
filenames = ['*.gdc']
mim... | GoodDataCLLexer |
python | altair-viz__altair | altair/expr/core.py | {
"start": 6629,
"end": 7269
} | class ____(OperatorMixin, SchemaBase):
"""
Expression.
Base object for enabling build-up of Javascript expressions using
a Python syntax. Calling ``repr(obj)`` will return a Javascript
representation of the object and the operations it encodes.
"""
_schema = {"type": "string"}
def to_... | Expression |
python | numba__numba | numba/core/options.py | {
"start": 1830,
"end": 2999
} | class ____:
"""Defines how user-level target options are mapped to the target flags.
"""
nopython = _mapping("enable_pyobject", operator.not_)
forceobj = _mapping("force_pyobject")
looplift = _mapping("enable_looplift")
_nrt = _mapping("nrt")
debug = _mapping("debuginfo")
boundscheck = _... | DefaultOptions |
python | scipy__scipy | benchmarks/benchmarks/interpolate.py | {
"start": 16770,
"end": 17093
} | class ____(Benchmark):
def setup(self):
self.z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, num=1000))
self.pts = np.linspace(-1, 1, num=1000)
def time_AAA(self):
r = interpolate.AAA(self.z, np.tan(np.pi*self.z/2))
r(self.pts)
r.poles()
r.residues()
r.root... | AAA |
python | ansible__ansible | test/integration/targets/ansible-doc/filter_plugins/other.py | {
"start": 228,
"end": 484
} | class ____(object):
""" Ansible core jinja2 filters """
def filters(self):
return {
'donothing': donothing,
'nodocs': donothing,
'split': donothing,
'b64decode': donothing,
}
| FilterModule |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 1652,
"end": 1869
} | class ____(NamedTuple("NT1", [("y", int), ("x", int)])):
def method(self, v: tuple[int, int]):
cls = type(self)
v = super().__new__(cls, *v)
return type(self)(self.y + v.y, self.x + v.x)
| ClassH |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 7332,
"end": 7446
} | class ____(AirflowException):
"""Raise when a file type is not supported."""
| AirflowUnsupportedFileTypeException |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.