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 | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 9279,
"end": 20807
} | class ____(graphene.ObjectType):
id = graphene.NonNull(graphene.String)
key = graphene.NonNull(GrapheneAssetKey)
assetMaterializations = graphene.Field(
non_null_list(GrapheneMaterializationEvent),
partitions=graphene.List(graphene.NonNull(graphene.String)),
beforeTimestampMillis=gra... | GrapheneAsset |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 34259,
"end": 37087
} | class ____:
"""
Float for use in a :class:`.FloatContainer`.
Except for the `content` parameter, all other options are optional.
:param content: :class:`.Container` instance.
:param width: :class:`.Dimension` or callable which returns a :class:`.Dimension`.
:param height: :class:`.Dimension` o... | Float |
python | django__django | django/contrib/flatpages/templatetags/flatpages.py | {
"start": 207,
"end": 3552
} | class ____(template.Node):
def __init__(self, context_name, starts_with=None, user=None):
self.context_name = context_name
if starts_with:
self.starts_with = template.Variable(starts_with)
else:
self.starts_with = None
if user:
self.user = template... | FlatpageNode |
python | ray-project__ray | python/ray/_private/ray_logging/logging_config.py | {
"start": 397,
"end": 649
} | class ____(ABC):
@abstractmethod
def get_supported_encodings(self) -> Set[str]:
raise NotImplementedError
@abstractmethod
def configure(self, logging_config: "LoggingConfig"):
raise NotImplementedError
| LoggingConfigurator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 295,
"end": 328
} | class ____:
pass
@final
| ParentC |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/assets.py | {
"start": 4074,
"end": 4237
} | class ____(BaseModel):
"""Asset event collection response."""
asset_events: Iterable[AssetEventResponse]
total_entries: int
| AssetEventCollectionResponse |
python | PyCQA__pylint | tests/functional/a/attribute_defined_outside_init_py38.py | {
"start": 55,
"end": 165
} | class ____(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.i = 42
| AsyncioTestCase |
python | ray-project__ray | doc/source/serve/doc_code/grpc_proxy/grpc_guide.py | {
"start": 7108,
"end": 9609
} | class ____:
def __init__(self):
self.preprocess = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.2... | DataPreprocessor |
python | python-pillow__Pillow | src/PIL/DdsImagePlugin.py | {
"start": 1258,
"end": 1417
} | class ____(IntFlag):
ALPHAPIXELS = 0x1
ALPHA = 0x2
FOURCC = 0x4
PALETTEINDEXED8 = 0x20
RGB = 0x40
LUMINANCE = 0x20000
# dxgiformat.h
| DDPF |
python | aimacode__aima-python | csp.py | {
"start": 28186,
"end": 33598
} | class ____(CSP):
"""
A Sudoku problem.
The box grid is a 3x3 array of boxes, each a 3x3 array of cells.
Each cell holds a digit in 1..9. In each box, all digits are
different; the same for each row and column as a 9x9 grid.
>>> e = Sudoku(easy1)
>>> e.display(e.infer_assignment())
. . 3 ... | Sudoku |
python | realpython__materials | python-first-steps/classes.py | {
"start": 0,
"end": 214
} | class ____:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof! Woof!"
fido = Dog("Fido", 3)
print(fido.name, fido.age)
print(fido.bark())
| Dog |
python | pytorch__pytorch | test/quantization/core/test_quantized_op.py | {
"start": 1659,
"end": 6877
} | class ____(NamedTuple):
binary_attr : str = "none"
alpha : float = 1.0
unary_attr : str = "none"
scalars : list = []
algorithm : str = ""
# Make sure we won't have overflows from vpmaddubsw instruction used in FBGEMM.
# On the current Intel x86 architecture, we need to utilize vpmaddubsw instructio... | PointwisePostOp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-gcs/source_gcs/cursor.py | {
"start": 246,
"end": 3166
} | class ____(DefaultFileBasedCursor):
@staticmethod
def get_file_uri(file: GCSUploadableRemoteFile) -> str:
file_uri = file.displayed_uri if file.displayed_uri else file.uri
return file_uri.split("?")[0]
def add_file(self, file: GCSUploadableRemoteFile) -> None:
uri = self.get_file_ur... | Cursor |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/tests/test_generate.py | {
"start": 395,
"end": 1821
} | class ____:
@pytest.fixture()
def processed_schema(self):
sys.path.append(str(TEST_DIR / ".." / "scripts"))
from generate import preprocess_fn # noqa
path = TEST_DIR / "mock_schema.yaml"
with open(path, "r") as f:
mock_schema = yaml.safe_load(f)
processed_s... | TestPreprocessFn |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_imei.py | {
"start": 1842,
"end": 4527
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid IMEI (International Mobile Equipment Identity)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"a... | ExpectColumnValuesToBeValidImei |
python | huggingface__transformers | src/transformers/models/deberta/tokenization_deberta.py | {
"start": 1036,
"end": 8211
} | class ____(TokenizersBackend):
"""
Construct a "fast" DeBERTa tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
Byte-Pair-Encoding.
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently w... | DebertaTokenizer |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_cache_implementation.py | {
"start": 1857,
"end": 1950
} | class ____(GenericCache):
def new_entry(self, key, value):
return value
| ValueScored |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 52002,
"end": 56832
} | class ____(_TestNormBase):
# Define the part for 2d arrays separately, so we can subclass this
# and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
array = np.array
def test_matrix_empty(self):
assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
def test_matrix_r... | _TestNorm2D |
python | realpython__materials | python-namedtuple/typed_namedtuple_time.py | {
"start": 632,
"end": 997
} | class ____(NamedTuple):
x: int
y: int
z: int
namedtuple_time = average_time(PointNamedTuple(x=1, y=2, z=3), time_structure)
typed_namedtuple_time = average_time(
PointTypedNamedTuple(x=1, y=2, z=3), time_structure
)
print(f"namedtuple: {namedtuple_time:.2f} ns")
print(f"typing.NamedTuple: {typ... | PointTypedNamedTuple |
python | keras-team__keras | benchmarks/layer_benchmark/base_benchmark.py | {
"start": 3044,
"end": 9434
} | class ____:
def __init__(
self,
layer_name,
init_args,
input_shape,
flat_call_inputs=True,
jit_compile=True,
keras_layer=None,
tf_keras_layer=None,
):
self.layer_name = layer_name
_keras_layer_class = getattr(keras.layers, layer_nam... | LayerBenchmark |
python | scikit-learn__scikit-learn | sklearn/tree/_export.py | {
"start": 1736,
"end": 6214
} | class ____:
def __repr__(self):
return '"tree.dot"'
SENTINEL = Sentinel()
@validate_params(
{
"decision_tree": [DecisionTreeClassifier, DecisionTreeRegressor],
"max_depth": [Interval(Integral, 0, None, closed="left"), None],
"feature_names": ["array-like", None],
"cla... | Sentinel |
python | davidhalter__parso | conftest.py | {
"start": 1696,
"end": 2675
} | class ____:
"""
Static Analysis cases lie in the static_analysis folder.
The tests also start with `#!`, like the goto_definition tests.
"""
def __init__(self, path):
self.path = path
self.name = os.path.basename(path)
match = re.search(r'python([\d.]+)\.py', self.name)
... | NormalizerIssueCase |
python | boto__boto3 | tests/integration/test_s3.py | {
"start": 9351,
"end": 26474
} | class ____(unittest.TestCase):
"""Tests for the high level boto3.s3.transfer module."""
def setUp(self):
self.region = _DEFAULT_REGION
self.bucket_name = _SHARED_BUCKET
clear_out_bucket(self.bucket_name, self.region)
self.session = boto3.session.Session(region_name=self.region)
... | TestS3Transfers |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/test_trainer.py | {
"start": 61523,
"end": 62337
} | class ____(BoringModel):
def validation_step(self, batch, batch_idx):
loss = self.step(batch)
self.log("x", loss)
@RunIf(skip_windows=True)
def test_fit_test_synchronization(tmp_path):
"""Test that the trainer synchronizes processes before returning control back to the caller."""
model = T... | TestDummyModelForCheckpoint |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 18396,
"end": 20719
} | class ____(nn.Module):
def __init__(self, config: ClvpConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.self_attn = ClvpSelfAttention(config)
self.mlp = ClvpEncoderMLP(config)
self.input_rmsnorm = ClvpRMSNorm(self.embed_dim, ep... | ClvpEncoderLayer |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core_tests/utils_tests/test_naming.py | {
"start": 60,
"end": 2999
} | class ____:
"""Test the snakecase function, particularly around handling of uppercase sequences."""
@pytest.mark.parametrize(
"input_str,expected",
[
# Basic cases
("SimpleComponent", "simple_component"),
("Component", "component"),
("MyComponent"... | TestSnakecase |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/loader.py | {
"start": 702,
"end": 1276
} | class ____(Reader, Scanner, Parser, Composer, BaseConstructor, VersionedResolver):
def __init__(self, stream, version=None, preserve_quotes=None):
# type: (StreamTextType, Optional[VersionType], Optional[bool]) -> None
self.comment_handling = None
Reader.__init__(self, stream, loader=self)
... | BaseLoader |
python | tensorflow__tensorflow | tensorflow/python/saved_model/builder_impl.py | {
"start": 2164,
"end": 21379
} | class ____(object):
"""Builds the `SavedModel` protocol buffer and saves variables and assets.
The `SavedModelBuilder` class provides the functionality to build a
`SavedModel` protocol buffer. Specifically, this allows multiple meta
graphs to be saved as part of a single language-neutral `SavedModel`,
while ... | _SavedModelBuilder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/spanner.py | {
"start": 2010,
"end": 19711
} | class ____(GoogleBaseHook, DbApiHook):
"""
Hook for Google Cloud Spanner APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
conn_name_attr = "gcp_conn_id"
default_conn_name = "google_cloud_spanner_default"
conn_t... | SpannerHook |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 29209,
"end": 30364
} | class ____:
param_names = ["parallel"]
params = [[True, False]]
def setup(self, parallel):
N = 10**3
data = DataFrame(
{0: [str(i) for i in range(100)] * N, 1: list(range(100)) * N},
columns=[0, 1],
)
self.parallel = parallel
self.grouper = da... | TransformEngine |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 1078,
"end": 1312
} | class ____(BaseModel):
"""
Asset alias serializer for responses.
"""
id: Annotated[int, Field(title="Id")]
name: Annotated[str, Field(title="Name")]
group: Annotated[str, Field(title="Group")]
| AssetAliasResponse |
python | great-expectations__great_expectations | great_expectations/expectations/row_conditions.py | {
"start": 11176,
"end": 11740
} | class ____(Condition):
"""Represents an AND condition composed of multiple conditions."""
type: Literal["and"] = Field(default="and")
conditions: List[Condition]
@validator("conditions", pre=True, each_item=True)
def _deserialize_condition(cls, v):
"""Deserialize each condition in the list... | AndCondition |
python | streamlit__streamlit | lib/streamlit/elements/pyplot.py | {
"start": 1261,
"end": 8438
} | class ____:
@gather_metrics("pyplot")
def pyplot(
self,
fig: Figure | None = None,
clear_figure: bool | None = None,
*,
width: Width = "stretch",
use_container_width: bool | None = None,
**kwargs: Any,
) -> DeltaGenerator:
"""Display a matplotl... | PyplotMixin |
python | kamyu104__LeetCode-Solutions | Python/sum-of-digit-differences-of-all-pairs.py | {
"start": 54,
"end": 515
} | class ____(object):
def sumDigitDifferences(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
base, l = 1, 0
while base <= nums[0]:
base *= 10
l += 1
cnts = [[0]*10 for _ in xrange(l)]
for x in nums:
for i in xr... | Solution |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 121694,
"end": 123594
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "postgresql"
@testing.combinations(
(postgresql.BIT(), "BIT(1)"),
(postgresql.BIT(5), "BIT(5)"),
(postgresql.BIT(varying=True), "BIT VARYING"),
(postgresql.BIT(5, varying=True), "BIT VARYING(5)"),
)
def tes... | SpecialTypesCompileTest |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 9254,
"end": 9475
} | class ____(GQLResult):
total_count: int = Field(alias="totalCount")
page_info: PageInfoFragment = Field(alias="pageInfo")
edges: List[VersionedArtifactConnectionFragmentEdges]
| VersionedArtifactConnectionFragment |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 120824,
"end": 121227
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(ProjectV2FieldOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgq... | ProjectV2FieldOrder |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 7383,
"end": 7533
} | class ____(TorchDynamoException):
def __init__(self) -> None:
self.real_stack = torch._guards.TracingContext.extract_stack()
| StepUnsupported |
python | pexpect__pexpect | tests/test_timeout_pattern.py | {
"start": 1101,
"end": 3792
} | class ____(PexpectTestCase.PexpectTestCase):
def test_matches_exp_timeout (self):
'''This tests that we can raise and catch TIMEOUT.
'''
try:
raise pexpect.TIMEOUT("TIMEOUT match test")
except pexpect.TIMEOUT:
pass
#print "Correctly caught TIMEOUT ... | Exp_TimeoutTestCase |
python | django__django | tests/admin_views/models.py | {
"start": 10788,
"end": 10919
} | class ____(models.Model):
owner = models.ForeignKey(Collector, models.CASCADE)
name = models.CharField(max_length=100)
| Widget |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 25436,
"end": 26488
} | class ____(AdminTestMixin, TestCase):
"""
If a custom field is declared with no attribute the field will be present
but with an empty string.
"""
class _BookResource(ModelResource):
author_email = Field(column_name="Author Email")
class Meta:
model = Book
def setUp... | DeclaredFieldWithNoAttributeExportTest |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qcat_test.py | {
"start": 715,
"end": 1951
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, L, dim, contig, dtype):
f_input = (torch.rand(M, N, K) - 0.5) * 256
self.qf = nnq.QFunctional()
scale = 1.0
zero_point = 0
self.qf.scale = scale
self.qf.zero_point = zero_point
assert contig in ... | QCatBenchmark |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_radar03.py | {
"start": 315,
"end": 1366
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_radar03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | django__django | tests/cache/tests.py | {
"start": 84992,
"end": 86561
} | class ____(SimpleTestCase):
path = "/cache/test/"
factory = RequestFactory()
def tearDown(self):
cache.clear()
def _set_cache(self, request, msg):
return UpdateCacheMiddleware(lambda req: HttpResponse(msg))(request)
def test_head_caches_correctly(self):
test_content = "tes... | CacheHEADTest |
python | walkccc__LeetCode | solutions/3457. Eat Pizzas!/3457.py | {
"start": 0,
"end": 259
} | class ____:
def maxWeight(self, pizzas: list[int]) -> int:
eat = len(pizzas) // 4
odd = math.ceil(eat / 2)
even = eat - odd
pizzas.sort(reverse=True)
return (sum(pizzas[:odd]) +
sum(pizzas[odd + 1:odd + 1 + even * 2:2]))
| Solution |
python | scikit-learn__scikit-learn | sklearn/decomposition/_nmf.py | {
"start": 42285,
"end": 57946
} | class ____(_BaseNMF):
"""Non-Negative Matrix Factorization (NMF).
Find two non-negative matrices, i.e. matrices with all non-negative elements, (W, H)
whose product approximates the non-negative matrix X. This factorization can be used
for example for dimensionality reduction, source separation or topi... | NMF |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v2_utils_test.py | {
"start": 1194,
"end": 3546
} | class ____(parameterized.TestCase, test.TestCase):
@parameterized.parameters(tpu_embedding_v2_utils.Adagrad,
tpu_embedding_v2_utils.Adam,
tpu_embedding_v2_utils.FTRL)
def test_grad_clip_with_accumulation_off(self, optimizer):
with self.assertRaisesRegex(V... | TPUEmbeddingOptimizerTest |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 7612,
"end": 9311
} | class ____:
variable: VarInfo
path: tuple[str | object, ...]
# A sentinel indicating a subscript access
SUBSCRIPT_ACCESS: ClassVar[Any] = object()
# custom __reduce__ and _produce implementations to work around
# a pickle bug.
# see https://github.com/python/cpython/issues/124937#issuecomm... | VarAccess |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 37386,
"end": 40857
} | class ____(SchemaLoader):
"""
Custom schema loader for HubSpot custom object streams.
This class generates a JSON schema based on the properties defined in the manifest.
These properties are injected into the parameters by the HttpComponentsResolver used within the DynamicDeclarativeStream.
"""
... | HubspotCustomObjectsSchemaLoader |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 110086,
"end": 111416
} | class ____(Normalize):
"""
The symmetrical logarithmic scale is logarithmic in both the
positive and negative directions from the origin.
Since the values close to zero tend toward infinity, there is a
need to have a range around zero that is linear. The parameter
*linthresh* allows the user t... | SymLogNorm |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_serialization_micro.py | {
"start": 9905,
"end": 15654
} | class ____:
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
@pytest.fixture(scope='module', name='fs_model_serializer')
def fs_model_serializer_fixture... | FieldsSetModel |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 5184,
"end": 5367
} | class ____(BaseOp):
val: Scalar = Field(alias="$lte")
@override
def __invert__(self) -> Gt:
"""Implements `~Lte(a) -> Gt(a)`."""
return Gt(val=self.val)
| Lte |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_type_check.py | {
"start": 9674,
"end": 9916
} | class ____(TestCase):
def test_generic(self):
vals = isneginf(np.array((-1.0, 0, 1)) / 0.0)
assert_(vals[0] == 1)
assert_(vals[1] == 0)
assert_(vals[2] == 0)
# @xfail #(reason="not implemented")
| TestIsneginf |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 271905,
"end": 272181
} | class ____(VegaLiteSchema):
"""ConditionalValueDefstringExprRef schema wrapper."""
_schema = {"$ref": "#/definitions/ConditionalValueDef<(string|ExprRef)>"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ConditionalValueDefstringExprRef |
python | scrapy__scrapy | tests/test_downloadermiddleware_httpauth.py | {
"start": 1808,
"end": 2477
} | class ____:
def setup_method(self):
self.mw = HttpAuthMiddleware()
spider = AnyDomainSpider("foo")
self.mw.spider_opened(spider)
def teardown_method(self):
del self.mw
def test_auth(self):
req = Request("http://example.com/")
assert self.mw.process_request(r... | TestHttpAuthAnyMiddleware |
python | python-markdown__markdown | markdown/extensions/meta.py | {
"start": 1364,
"end": 2600
} | class ____(Preprocessor):
""" Get Meta-Data. """
def run(self, lines: list[str]) -> list[str]:
""" Parse Meta-Data and store in Markdown.Meta. """
meta: dict[str, Any] = {}
key = None
if lines and BEGIN_RE.match(lines[0]):
lines.pop(0)
while lines:
... | MetaPreprocessor |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 898,
"end": 3040
} | class ____(WeaviateBaseError):
def __init__(self, message: str, response: Union[httpx.Response, AioRpcError, Call]):
"""Is raised in case the status code returned from Weaviate is not handled in the client implementation and suggests an error.
Custom code can act on the attributes:
- status... | UnexpectedStatusCodeError |
python | python__mypy | mypy/semanal_typeargs.py | {
"start": 1246,
"end": 13156
} | class ____(MixedTraverserVisitor):
def __init__(
self,
errors: Errors,
options: Options,
is_typeshed_file: bool,
named_type: Callable[[str, list[Type]], Instance],
) -> None:
super().__init__()
self.errors = errors
self.options = options
se... | TypeArgumentAnalyzer |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/openai_functions.py | {
"start": 9949,
"end": 10597
} | class ____(PydanticOutputFunctionsParser):
"""Parse an output as an attribute of a Pydantic object."""
attr_name: str
"""The name of the attribute to return."""
@override
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
"""Parse the result of an LLM call t... | PydanticAttrOutputFunctionsParser |
python | google__jax | jax/_src/custom_derivatives.py | {
"start": 22931,
"end": 35183
} | class ____(Generic[ReturnValue]):
"""Set up a JAX-transformable function for a custom VJP rule definition.
This class is meant to be used as a function decorator. Instances are
callables that behave similarly to the underlying function to which the
decorator was applied, except when a reverse-mode differentiat... | custom_vjp |
python | pypa__warehouse | warehouse/accounts/forms.py | {
"start": 21861,
"end": 23043
} | class ____(wtforms.Form):
username_or_email = wtforms.StringField(
validators=[
wtforms.validators.InputRequired(),
PreventNullBytesValidator(),
]
)
def validate_username_or_email(self, field):
"""
Check if the input is structurally correct, i.e. eith... | RequestPasswordResetForm |
python | huggingface__transformers | src/transformers/models/sam2/image_processing_sam2_fast.py | {
"start": 14970,
"end": 30227
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"height": 1024, "width": 1024}
mask_size = {"height": 256, "width": 256}
do_resize = True
do_rescale = True
do_normalize = True
do_co... | Sam2ImageProcessorFast |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 14555,
"end": 14713
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("SIZE",)
| LanguageOrderField |
python | pydata__xarray | xarray/core/variable.py | {
"start": 2604,
"end": 12116
} | class ____(ValueError):
"""Error class used when we can't safely guess a dimension name."""
# inherits from ValueError for backward compatibility
# TODO: move this to an xarray.exceptions module?
def as_variable(
obj: T_DuckArray | Any, name=None, auto_convert: bool = True
) -> Variable | IndexVariab... | MissingDimensionsError |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/cluster_resolver.py | {
"start": 15984,
"end": 23829
} | class ____(ClusterResolver):
"""Performs a union on underlying ClusterResolvers.
This class performs a union given two or more existing ClusterResolvers. It
merges the underlying ClusterResolvers, and returns one unified ClusterSpec
when cluster_spec is called. The details of the merge function is
documented... | UnionClusterResolver |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/organizationmemberinvite.py | {
"start": 7043,
"end": 7307
} | class ____(serializers.Serializer):
trigger_regenerate_token = serializers.BooleanField(
required=False,
default=False,
help_text="Whether or not to regenerate the token for this invitation",
)
| OrganizationMemberReinviteRequestValidator |
python | ray-project__ray | python/ray/dashboard/subprocesses/tests/utils.py | {
"start": 5822,
"end": 6495
} | class ____(BaseTestModule):
@routes.get("/test1")
async def test(self, req: aiohttp.web.Request) -> aiohttp.web.Response:
return aiohttp.web.Response(text="Hello from TestModule1")
@routes.get("/redirect_between_modules")
async def redirect_between_modules(
self, req: aiohttp.web.Reques... | TestModule1 |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_build.py | {
"start": 45027,
"end": 49082
} | class ____:
"""
Processes build configurations to add additional functionality to support the use of operators.
The following improvements are made:
* It is required to provide the source and only one type can be given,
* It is possible to provide the source as the URL address instead dict.
:p... | BuildProcessor |
python | lepture__authlib | authlib/common/errors.py | {
"start": 1615,
"end": 1667
} | class ____(AuthlibBaseError):
pass
| ContinueIteration |
python | openai__openai-python | src/openai/types/beta/chatkit/chatkit_thread_user_message_item.py | {
"start": 1069,
"end": 1395
} | class ____(BaseModel):
model: Optional[str] = None
"""Model name that generated the response.
Defaults to null when using the session default.
"""
tool_choice: Optional[InferenceOptionsToolChoice] = None
"""Preferred tool to invoke. Defaults to null when ChatKit should auto-select."""
| InferenceOptions |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 44186,
"end": 48530
} | class ____(StationaryKernelMixin, GenericKernelMixin, Kernel):
"""White kernel.
The main use-case of this kernel is as part of a sum-kernel where it
explains the noise of the signal as independently and identically
normally-distributed. The parameter noise_level equals the variance of this
noise.
... | WhiteKernel |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 347890,
"end": 349407
} | class ____(ExprNode):
# A starred expression like "*a"
#
# This is only allowed in sequence assignment or construction such as
#
# a, *b = (1,2,3,4) => a = 1 ; b = [2,3,4]
#
# and will be special cased during type analysis (or generate an error
# if it's found at unexpect... | StarredUnpackingNode |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 27860,
"end": 27928
} | class ____(PallasCallTest):
INTERPRET = True
| PallasCallInterpretTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_dataplex.py | {
"start": 6433,
"end": 7474
} | class ____:
@pytest.mark.db_test
def test_get_link(self, create_task_instance_of_operator, session, mock_supervisor_comms):
expected_url = DATAPLEX_LAKE_LINK
link = DataplexLakeLink()
ti = create_task_instance_of_operator(
DataplexCreateLakeOperator,
dag_id="test_... | TestDataplexLakeLink |
python | numba__numba | numba/core/typing/listdecl.py | {
"start": 2808,
"end": 3179
} | class ____(AbstractTemplate):
def generic(self, args, kws):
if len(args) == 2:
a, b = args
if isinstance(a, types.List) and isinstance(b, types.List):
unified = self.context.unify_pairs(a, b)
if unified is not None:
return signatur... | AddList |
python | TheAlgorithms__Python | data_structures/binary_tree/avl_tree.py | {
"start": 6977,
"end": 9702
} | class ____:
"""
An AVL tree doctest
Examples:
>>> t = AVLtree()
>>> t.insert(4)
insert:4
>>> print(str(t).replace(" \\n","\\n"))
4
*************************************
>>> t.insert(2)
insert:2
>>> print(str(t).replace(" \\n","\\n").replace(" \\n","\\n"))
4
2 ... | AVLtree |
python | tensorflow__tensorflow | tensorflow/python/keras/callbacks.py | {
"start": 21810,
"end": 32875
} | class ____:
"""Abstract base class used to build new callbacks.
Callbacks can be passed to keras methods such as `fit`, `evaluate`, and
`predict` in order to hook into the various stages of the model training and
inference lifecycle.
To create a custom callback, subclass `keras.callbacks.Callback` and overr... | Callback |
python | plotly__plotly.py | plotly/graph_objs/layout/annotation/_hoverlabel.py | {
"start": 235,
"end": 5099
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.annotation"
_path_str = "layout.annotation.hoverlabel"
_valid_props = {"bgcolor", "bordercolor", "font"}
@property
def bgcolor(self):
"""
Sets the background color of the hover label. By default uses
the annota... | Hoverlabel |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 86404,
"end": 86782
} | class ____(BaseModel, extra="forbid"):
points: List["PointStruct"] = Field(..., description="")
shard_key: Optional["ShardKeySelector"] = Field(default=None, description="")
update_filter: Optional["Filter"] = Field(
default=None,
description="If specified, only points that match this filter... | PointsList |
python | spack__spack | lib/spack/spack/error.py | {
"start": 5103,
"end": 5476
} | class ____(SpackError):
"""Raised when something goes wrong during install or uninstall.
The error can be annotated with a ``pkg`` attribute to allow the
caller to get the package for which the exception was raised.
"""
def __init__(self, message, long_msg=None, pkg=None):
super().__init__... | InstallError |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/int.py | {
"start": 15898,
"end": 20982
} | class ____(BaseInt[np.dtypes.Int16DType, np.int16], HasEndianness):
"""
A Zarr data type for arrays containing 16-bit signed integers.
Wraps the [`np.dtypes.Int16DType`][numpy.dtypes.Int16DType] data type. Scalars for this data type are instances of
[`np.int16`][numpy.int16].
Attributes
------... | Int16 |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 98439,
"end": 98931
} | class ____(CType):
#
# PEP-539 "Py_tss_t" type
#
declaration_value = "Py_tss_NEEDS_INIT"
def __repr__(self):
return "<Py_tss_t>"
def declaration_code(self, entity_code,
for_display=0, dll_linkage=None, pyrex=0):
if pyrex or for_display:
b... | CPyTSSTType |
python | cython__cython | Cython/Compiler/Errors.py | {
"start": 2757,
"end": 2973
} | class ____(Exception):
# Throw this to stop the compilation immediately.
def __init__(self, message):
self.message_only = message
Exception.__init__(self, "Abort error: %s" % message)
| AbortError |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-galaxia/llama_index/retrievers/galaxia/base.py | {
"start": 2880,
"end": 4939
} | class ____(BaseRetriever):
"""
Galaxia knowledge retriever.
before using the API create your knowledge base here:
beta.cloud.smabbler.com/
learn more here:
https://smabbler.gitbook.io/smabbler/api-rag/smabblers-api-rag
Args:
api_url : url of galaxia API, e.g. "https://beta.api.sma... | GalaxiaRetriever |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 6385,
"end": 6530
} | class ____(_PathValueError):
code = 'path.not_exists'
msg_template = 'file or directory at path "{path}" does not exist'
| PathNotExistsError |
python | getsentry__sentry | src/sentry/integrations/base.py | {
"start": 2005,
"end": 2192
} | class ____(NamedTuple):
description: str # A markdown description of the feature
featureGate: IntegrationFeatures # A IntegrationFeature that gates this feature
| FeatureDescription |
python | allegroai__clearml | clearml/backend_api/services/v2_20/auth.py | {
"start": 13416,
"end": 15207
} | class ____(Response):
"""
Response of auth.edit_user endpoint.
:param updated: Number of users updated (0 or 1)
:type updated: float
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "auth"
_action = "edit_user"
_version = "2.20"
_schema = {
... | EditUserResponse |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 32504,
"end": 33963
} | class ____(TestCase):
"""Tests for ``spy()``"""
def test_basic(self):
original_iterable = iter('abcdefg')
head, new_iterable = mi.spy(original_iterable)
self.assertEqual(head, ['a'])
self.assertEqual(
list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']
)
... | SpyTests |
python | py-pdf__pypdf | pypdf/_encryption.py | {
"start": 2058,
"end": 4351
} | class ____:
def __init__(
self,
stm_crypt: CryptBase,
str_crypt: CryptBase,
ef_crypt: CryptBase,
) -> None:
self.stm_crypt = stm_crypt
self.str_crypt = str_crypt
self.ef_crypt = ef_crypt
def encrypt_object(self, obj: PdfObject) -> PdfObject:
i... | CryptFilter |
python | donnemartin__interactive-coding-challenges | online_judges/utopian_tree/test_utopian_tree.py | {
"start": 18,
"end": 478
} | class ____(unittest.TestCase):
def test_utopian_tree(self):
solution = Solution()
self.assertEqual(solution.calc_utopian_tree_height(0), 1)
self.assertEqual(solution.calc_utopian_tree_height(1), 2)
self.assertEqual(solution.calc_utopian_tree_height(4), 7)
print('Success: tes... | TestUtopianTree |
python | davidhalter__jedi | jedi/inference/analysis.py | {
"start": 2271,
"end": 7763
} | class ____(Error):
pass
def add(node_context, error_name, node, message=None, typ=Error, payload=None):
exception = CODES[error_name][1]
if _check_for_exception_catch(node_context, node, exception, payload):
return
# TODO this path is probably not right
module_context = node_context.get_r... | Warning |
python | google__pytype | pytype/tests/test_paramspec.py | {
"start": 174,
"end": 7468
} | class ____(test_base.BaseTest):
"""Tests for ParamSpec."""
def test_basic(self):
ty = self.Infer("""
from typing import ParamSpec
P = ParamSpec("P")
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import ParamSpec
P = ParamSpec("P")
""",
)
def test... | ParamSpecTest |
python | pytorch__pytorch | torch/_higher_order_ops/_invoke_quant.py | {
"start": 826,
"end": 1770
} | class ____:
"""
Invoke a quantization function that will be preserved as a single operator. Preservation
as a single operator aids in pattern matching and custom lowerings.
The operation appears as:
torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme)
Args:
codegen_l... | InvokeQuant |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 517073,
"end": 517946
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "labels")
field = sgqlc.types.Field(
sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field"
)
labels = sgqlc.types.Field(
Label... | ProjectV2ItemFieldLabelValue |
python | pandas-dev__pandas | pandas/tests/indexing/test_scalar.py | {
"start": 2115,
"end": 8504
} | class ____:
# at and iat tests that don't need Base class
def test_float_index_at_iat(self):
ser = Series([1, 2, 3], index=[0.1, 0.2, 0.3])
for el, item in ser.items():
assert ser.at[el] == item
for i in range(len(ser)):
assert ser.iat[i] == i + 1
def test_a... | TestAtAndiAT |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 28833,
"end": 35625
} | class ____(Conv):
"""3D convolution layer (e.g. spatial convolution over volumes).
This layer creates a convolution kernel that is convolved
with the layer input to produce a tensor of
outputs. If `use_bias` is True,
a bias vector is created and added to the outputs. Finally, if
`activation` is not `None`,... | Conv3D |
python | django__django | tests/postgres_tests/models.py | {
"start": 2888,
"end": 3112
} | class ____(models.Model):
id = models.BigAutoField(primary_key=True)
# Scene/Character/Line models are used to test full text search. They're
# populated with content from Monty Python and the Holy Grail.
| BigAutoFieldModel |
python | walkccc__LeetCode | solutions/3062. Winner of the Linked List Game/3062.py | {
"start": 0,
"end": 342
} | class ____:
def gameResult(self, head: ListNode | None) -> str:
even = 0
odd = 0
while head:
if head.val > head.next.val:
even += 1
elif head.val < head.next.val:
odd += 1
head = head.next.next
if even > odd:
return 'Even'
if even < odd:
return 'Odd'... | Solution |
python | MongoEngine__mongoengine | tests/fields/test_url_field.py | {
"start": 83,
"end": 1823
} | class ____(MongoDBTestCase):
def test_validation(self):
"""Ensure that URLFields validate urls properly."""
class Link(Document):
url = URLField()
link = Link()
link.url = "google"
with pytest.raises(ValidationError):
link.validate()
link.ur... | TestURLField |
python | getsentry__sentry | tests/sentry/integrations/github/test_webhooks.py | {
"start": 26837,
"end": 39435
} | class ____(APITestCase):
def setUp(self) -> None:
self.url = "/extensions/github/webhook/"
self.secret = "b3002c3e321d4b7880360d397db2ccfd"
options.set("github-app.webhook-secret", self.secret)
def _create_integration_and_send_pull_request_opened_event(self):
future_expires = da... | PullRequestEventWebhook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.