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/dagster/_core/execution/resources_init.py | {
"start": 12150,
"end": 19689
} | class ____:
"""Utility class to wrap the untyped resource object emitted from the user-supplied
resource function. Used for distinguishing from the framework-yielded events in an
`EventGenerationManager`-wrapped event stream.
"""
def __init__(self, obj: Any, duration: str, is_generator: bool):
... | InitializedResource |
python | pytorch__pytorch | test/distributed/nn/jit/test_instantiator.py | {
"start": 408,
"end": 564
} | class ____:
def forward(
self, tensor: Tensor, number: int, word: str = "default"
) -> tuple[Tensor, int, str]:
pass
| MyModuleInterface |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 1139,
"end": 1242
} | class ____(forms.Form):
def __repr__(self):
return f"{self.data!r}\n{self.errors!r}"
| ReprForm |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/extra/_array_helpers.py | {
"start": 9855,
"end": 18482
} | class ____(NamedTuple):
input_shapes: tuple[Shape, ...]
result_shape: Shape
def _hypothesis_parse_gufunc_signature(signature):
# Disable all_checks to better match the Numpy version, for testing
if not re.match(_SIGNATURE, signature):
if re.match(_SIGNATURE_MULTIPLE_OUTPUT, signature):
... | _GUfuncSig |
python | wandb__wandb | wandb/automations/_filters/expressions.py | {
"start": 4164,
"end": 5921
} | class ____(CompatBaseModel, SupportsBitwiseLogicalOps):
"""A MongoDB filter expression on a specific field."""
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
field: str
op: Union[Op, Dict[str, Any]]
def __repr__(self) -> str:
return f"{nameof(type(self))}({self.fie... | FilterExpr |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 3260,
"end": 3370
} | class ____(vLLMEmbeddingResponse):
model_config = ConfigDict(arbitrary_types_allowed=True)
| EmbeddingResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overload5.py | {
"start": 871,
"end": 1248
} | class ____(BBase, Protocol):
@final
@overload
def method1(self, x: int) -> int: ...
@final
@overload
# This should generate an error.
def method1(self, x: str) -> str: ...
@override
@overload
def method2(self, x: int) -> int: ...
@override
@overload
# This should g... | B |
python | google__pytype | pytype/errors/errors_test.py | {
"start": 6509,
"end": 11741
} | class ____(unittest.TestCase):
@errors._error_name(_TEST_ERROR)
def test_error(self):
errorlog = make_errorlog()
op = test_utils.FakeOpcode("foo.py", 123, 123, 0, 0, "foo")
errorlog.error(op.to_stack(), f"unknown attribute {'xyz'}")
self.assertEqual(len(errorlog), 1)
e = list(errorlog)[0] # it... | ErrorLogTest |
python | pandas-dev__pandas | asv_bench/benchmarks/reshape.py | {
"start": 684,
"end": 1120
} | class ____:
def setup(self):
N = 10000
index = date_range("1/1/2000", periods=N, freq="h")
data = {
"value": np.random.randn(N * 50),
"variable": np.arange(50).repeat(N),
"date": np.tile(index.values, 50),
}
self.df = DataFrame(data)
d... | Pivot |
python | tiangolo__fastapi | tests/test_get_request_body.py | {
"start": 120,
"end": 3744
} | class ____(BaseModel):
name: str
description: str = None # type: ignore
price: float
@app.get("/product")
async def create_item(product: Product):
return product
client = TestClient(app)
def test_get_with_body():
body = {"name": "Foo", "description": "Some description", "price": 5.5}
resp... | Product |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 1450,
"end": 1533
} | class ____: # [single-string-used-for-slots]
__slots__ = deque.__name__
| EighthBad |
python | doocs__leetcode | solution/2000-2099/2032.Two Out of Three/Solution.py | {
"start": 0,
"end": 265
} | class ____:
def twoOutOfThree(
self, nums1: List[int], nums2: List[int], nums3: List[int]
) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1]
| Solution |
python | TheAlgorithms__Python | data_structures/linked_list/singly_linked_list.py | {
"start": 745,
"end": 16035
} | class ____:
def __init__(self):
"""
Create and initialize LinkedList class instance.
>>> linked_list = LinkedList()
>>> linked_list.head is None
True
"""
self.head = None
def __iter__(self) -> Iterator[Any]:
"""
This function is intended f... | LinkedList |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 1708,
"end": 2198
} | class ____(BaseTimeGroupBy):
param_names = ["shape", "ngroups", "groupby_ncols"]
params = [
get_benchmark_shapes("TimeGroupByMultiColumn"),
GROUPBY_NGROUPS,
[6],
]
def time_groupby_agg_quan(self, *args, **kwargs):
execute(self.df.groupby(by=self.groupby_columns).agg("qua... | TimeGroupByMultiColumn |
python | tensorflow__tensorflow | tensorflow/lite/python/lite.py | {
"start": 92335,
"end": 104710
} | class ____(TFLiteConverterBase):
"""Converter subclass to share functionality between V1 converters."""
def __init__(self, experimental_debug_info_func):
"""Constructor for TFLiteConverter.
Args:
experimental_debug_info_func: An experimental function to retrieve the
graph debug info for a se... | TFLiteConverterBaseV1 |
python | allegroai__clearml | clearml/backend_interface/datasets/hyper_dataset.py | {
"start": 405,
"end": 513
} | class ____(_SaveFramesRequest):
def validate(self, schema=None):
pass
| _SaveFramesRequestNoValidate |
python | kubernetes-client__python | kubernetes/client/models/v1_scale_io_volume_source.py | {
"start": 383,
"end": 12779
} | 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... | V1ScaleIOVolumeSource |
python | chroma-core__chroma | chromadb/telemetry/product/events.py | {
"start": 2568,
"end": 4242
} | class ____(ProductTelemetryEvent):
max_batch_size: ClassVar[int] = 300
batch_size: int
collection_uuid: str
update_amount: int
with_embeddings: int
with_metadata: int
with_documents: int
with_uris: int
def __init__(
self,
collection_uuid: str,
update_amount: ... | CollectionUpdateEvent |
python | wandb__wandb | wandb/sdk/artifacts/exceptions.py | {
"start": 1903,
"end": 2015
} | class ____(errors.Error):
"""Raised when wait() timeout occurs before process is finished."""
| WaitTimeoutError |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 2786,
"end": 3675
} | class ____(dict):
"""
plotly.graph_objs.AngularAxis is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.layout.AngularAxis
- plotly.graph_objs.layout.polar.AngularAxis
"""
def __init__(self, *args, **kwargs):
"""
... | AngularAxis |
python | viewflow__viewflow | viewflow/apps.py | {
"start": 302,
"end": 482
} | class ____(AppConfig):
"""Default application config."""
name = "viewflow"
label = "viewflow_base" # allow to user 'viewflow' label for 'viewflow.workflow'
| ViewflowConfig |
python | plotly__plotly.py | plotly/graph_objs/box/unselected/_marker.py | {
"start": 233,
"end": 4030
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "box.unselected"
_path_str = "box.unselected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exists.
... | Marker |
python | streamlit__streamlit | lib/tests/streamlit/runtime/forward_msg_cache_test.py | {
"start": 971,
"end": 3933
} | class ____(unittest.TestCase):
def test_msg_hash(self):
"""Test that ForwardMsg hash generation works as expected"""
with patch_config_options({"global.minCachedMessageSize": 0}):
msg1 = create_dataframe_msg([1, 2, 3])
msg2 = create_dataframe_msg([1, 2, 3])
popula... | ForwardMsgCacheTest |
python | ray-project__ray | python/ray/train/v2/api/exceptions.py | {
"start": 409,
"end": 1153
} | class ____(TrainingFailedError):
"""Exception raised from the worker group during training.
Args:
error_message: A human-readable error message describing the training worker failures.
worker_failures: A mapping from worker rank to the exception that
occurred on that worker during t... | WorkerGroupError |
python | Textualize__textual | tests/workers/test_work_decorator.py | {
"start": 266,
"end": 2561
} | class ____(App):
worker: Worker
def __init__(self) -> None:
super().__init__()
self.states: list[WorkerState] = []
@work
async def async_work(self) -> str:
await asyncio.sleep(0.1)
return "foo"
@work(thread=True)
async def async_thread_work(self) -> str:
... | WorkApp |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 15375,
"end": 16056
} | class ____(TestCase):
def test_ip_address_validation(self):
class IPAddressFieldModel(models.Model):
address = models.GenericIPAddressField()
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = IPAddressFieldModel
fields = '... | TestGenericIPAddressFieldValidation |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 25547,
"end": 31042
} | class ____(BertPreTrainedModel):
_no_split_modules = ["BertEmbeddings", "BertLayer"]
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
... | BertModel |
python | Farama-Foundation__Gymnasium | gymnasium/core.py | {
"start": 24708,
"end": 26706
} | class ____(Wrapper[WrapperObsType, ActType, ObsType, ActType]):
"""Modify observations from :meth:`Env.reset` and :meth:`Env.step` using :meth:`observation` function.
If you would like to apply a function to only the observation before
passing it to the learning code, you can simply inherit from :class:`Ob... | ObservationWrapper |
python | numpy__numpy | tools/swig/test/testSuperTensor.py | {
"start": 12039,
"end": 12356
} | class ____(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "schar"
self.typeCode = "b"
#self.result = int(self.result)
######################################################################
| scharTestCase |
python | facebook__pyre-check | tools/generate_taint_models/annotated_function_generator.py | {
"start": 1245,
"end": 1662
} | class ____(ast.NodeVisitor):
def __init__(self) -> None:
self.found_functions: Dict[
DecoratorAnnotationSpecification, List[FunctionDefinition]
] = defaultdict(list)
@abstractmethod
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
pass
@abstract... | FunctionVisitor |
python | HypothesisWorks__hypothesis | hypothesis-python/examples/test_basic.py | {
"start": 484,
"end": 1155
} | class ____:
def __init__(self, price: float) -> None:
self.price: float = price
def get_discount_price(self, discount_percentage: float):
return self.price * (discount_percentage / 100)
# The @given decorator generates examples for us!
@given(
price=st.floats(min_value=0, allow_nan=False,... | Product |
python | wandb__wandb | wandb/filesync/step_checksum.py | {
"start": 992,
"end": 1183
} | class ____(NamedTuple):
callback: Optional[step_upload.OnRequestFinishFn]
Event = Union[
RequestUpload, RequestStoreManifestFiles, RequestCommitArtifact, RequestFinish
]
| RequestFinish |
python | gevent__gevent | src/greentest/3.14/test__interpreters.py | {
"start": 2324,
"end": 3743
} | class ____(unittest.TestCase):
def test_default_shareables(self):
shareables = [
# singletons
None,
# builtin objects
b'spam',
'spam',
10,
-10,
True,
False,
... | IsShareableTests |
python | huggingface__transformers | tests/models/phi/test_modeling_phi.py | {
"start": 1171,
"end": 1732
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = PhiModelTester
# TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79292/workflows/fa2ba644-8953-44a6-8f67-ccd69ca6a476/jobs/1012905
def is_pipeline_test_to_skip(
self,
pi... | PhiModelTest |
python | falconry__falcon | falcon/constants.py | {
"start": 5684,
"end": 5827
} | class ____(Enum):
"""Enum representing the two possible WebSocket payload types."""
TEXT = auto()
BINARY = auto()
| WebSocketPayloadType |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 143459,
"end": 143652
} | class ____(BaseModel):
operation_id: Optional[int] = Field(default=None, description="Sequential number of the operation")
status: "UpdateStatus" = Field(..., description="")
| UpdateResult |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 3622,
"end": 5599
} | class ____(BadParameter):
"""Raised if click required an option or argument but it was not
provided when invoking the script.
.. versionadded:: 4.0
:param param_type: a string that indicates the type of the parameter.
The default is to inherit the parameter type from
... | MissingParameter |
python | scikit-learn__scikit-learn | sklearn/ensemble/tests/test_bagging.py | {
"start": 24387,
"end": 38647
} | class ____(BaseEstimator):
"""Fake estimator rejecting sample_weight"""
def fit(self, X, y):
"""Record values passed during fit"""
self.X_ = X
self.y_ = y
def predict(self, X):
pass
@pytest.mark.parametrize("bagging_class", [BaggingRegressor, BaggingClassifier])
@pytest.m... | EstimatorRejectingSampleWeight |
python | tensorflow__tensorflow | tensorflow/python/training/optimizer.py | {
"start": 8882,
"end": 56167
} | class ____(
# Optimizers inherit from Trackable rather than AutoTrackable
# since they do most of their dependency management themselves (slot
# variables are special-cased, and non-slot variables are keyed to graphs).
trackable.Trackable):
"""Base class for optimizers.
This class defines the API t... | Optimizer |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 18665,
"end": 20455
} | class ____(Div):
"""
Base class used for `Tab` and `AccordionGroup`, represents a basic
container concept.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
css_class : str, optional
CSS classes to be applied to... | Container |
python | crytic__slither | slither/slithir/operations/operation.py | {
"start": 781,
"end": 1745
} | class ____(Context, AbstractOperation):
def __init__(self) -> None:
super().__init__()
self._node: Optional["Node"] = None
self._expression: Optional[Expression] = None
def set_node(self, node: "Node") -> None:
self._node = node
@property
def node(self) -> "Node":
... | Operation |
python | mwaskom__seaborn | tests/_core/test_moves.py | {
"start": 10268,
"end": 11391
} | class ____(MoveFixtures):
@pytest.mark.parametrize("orient", ["x", "y"])
def test_default_no_groups(self, df, orient):
other = {"x": "y", "y": "x"}[orient]
gb = GroupBy(["null"])
res = Norm()(df, gb, orient, {})
assert res[other].max() == pytest.approx(1)
@pytest.mark.para... | TestNorm |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 112639,
"end": 113072
} | class ____(Dataset):
def __len__(self):
return 4
def __getitem__(self, ndx):
return {
"a_tensor": torch.empty(4, 2).fill_(ndx),
"another_dict": {"a_number": ndx},
}
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting ne... | DictDataset |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 5137,
"end": 7002
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def name(self):
raise NotImplementedError()
@name.setter
def name(self, value):
raise NotImplementedError()
@property
def names(self):
raise NotImplementedError()
@property
... | Sheet |
python | getsentry__sentry | src/sentry/grouping/fingerprinting/parser.py | {
"start": 1577,
"end": 5221
} | class ____(NodeVisitor[list[FingerprintRule]]):
visit_empty = lambda *a: None
unwrapped_exceptions = (InvalidFingerprintingConfig,)
# a note on the typing of `children`
# these are actually lists of sub-lists of the various types
# so instead typed as tuples so unpacking works
def visit_commen... | FingerprintingVisitor |
python | walkccc__LeetCode | solutions/2331. Evaluate Boolean Binary Tree/2331.py | {
"start": 0,
"end": 303
} | class ____:
def evaluateTree(self, root: TreeNode | None) -> bool:
if root.val < 2:
return root.val
if root.val == 2: # OR
return self.evaluateTree(root.left) or self.evaluateTree(root.right)
# AND
return self.evaluateTree(root.left) and self.evaluateTree(root.right)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/dynamic_ragged_shape_test.py | {
"start": 126111,
"end": 169861
} | class ____(parameterized.TestCase):
def assertRowPartitionSpecEqual(self,
a: RowPartitionSpec,
b: RowPartitionSpec,
msg='') -> None:
self.assertEqual(a.nrows, b.nrows, msg)
self.assertEqual(a.nvals, b.nvals,... | DynamicRaggedShapeSpecTest |
python | gevent__gevent | src/gevent/tests/test__issue600.py | {
"start": 469,
"end": 1386
} | class ____(greentest.TestCase):
__timeout__ = greentest.LARGE_TIMEOUT
@greentest.skipOnLibuvOnPyPyOnWin("hangs")
def test_invoke(self):
# Run a subprocess through Popen to make sure
# libev is handling SIGCHLD. This could *probably* be simplified to use
# just hub.loop.install_sigc... | TestIssue600 |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 877,
"end": 1274
} | class ____(resource.Resource):
"""
L{ForeverTakingResource} is a resource which never finishes responding
to requests.
"""
def __init__(self, write=False):
resource.Resource.__init__(self)
self._write = write
def render(self, request):
if self._write:
reques... | ForeverTakingResource |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 73965,
"end": 75465
} | class ____(EditTool, Drag, Tap):
''' *toolbar icon*: |freehand_draw_icon|
Allows freehand drawing of ``Patches`` and ``MultiLine`` glyphs. The glyph
to draw may be defined via the ``renderers`` property.
The tool will modify the columns on the data source corresponding to the
``xs`` and ``ys`` val... | FreehandDrawTool |
python | airbytehq__airbyte | airbyte-integrations/bases/base-normalization/normalization/transform_config/transform.py | {
"start": 251,
"end": 15848
} | class ____:
def run(self, args):
inputs = self.parse(args)
original_config = self.read_json_config(inputs["config"])
integration_type = inputs["integration_type"]
transformed_config = self.transform(integration_type, original_config)
self.write_yaml_config(inputs["output_path... | TransformConfig |
python | walkccc__LeetCode | solutions/953. Verifying an Alien Dictionary/953.py | {
"start": 0,
"end": 245
} | class ____:
def isAlienSorted(self, words: list[str], order: str) -> bool:
dict = {c: i for i, c in enumerate(order)}
words = [[dict[c] for c in word] for word in words]
return all(w1 <= w2 for w1, w2 in zip(words, words[1:]))
| Solution |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 32626,
"end": 39399
} | class ____(BrosPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.config = config
self.num_labels = config.num_labels
self.n_relations = config.n_relations
self.backbone_hidden_size = config.hidden... | BrosSpadeEEForTokenClassification |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/python/reverse_level_traversal.py | {
"start": 132,
"end": 1462
} | class ____:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to print reverse level order traversal
def reverseLevelOrder(root):
h = height(root)
for i in reversed(range(1, h+1)):
pri... | Node |
python | Netflix__metaflow | test/cmd/develop/test_stub_generator.py | {
"start": 468,
"end": 20299
} | class ____:
"""Test suite for StubGenerator functionality"""
def setup_method(self):
"""Set up test environment"""
self.temp_dir = tempfile.mkdtemp()
self.generator = StubGenerator(self.temp_dir, include_generated_for=False)
# Reset internal state
self.generator._reset()... | TestStubGenerator |
python | sympy__sympy | sympy/logic/algorithms/dpll2.py | {
"start": 21195,
"end": 21497
} | class ____:
"""
Represents a single level in the DPLL algorithm, and contains
enough information for a sound backtracking procedure.
"""
def __init__(self, decision, flipped=False):
self.decision = decision
self.var_settings = set()
self.flipped = flipped
| Level |
python | pytorch__pytorch | torch/cuda/jiterator.py | {
"start": 141,
"end": 1457
} | class ____:
def __init__(self, code_string: str):
optional_ws = r"\s*"
required_ws = r"\s+"
template_params = r"(?P<template_params>\<.+\>)"
return_type = r"(?P<return_type>\w+)"
function_name = r"(?P<function_name>\w+)"
function_params = r"(?P<function_params>\(.+\))... | _CodeParser |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 876176,
"end": 882546
} | class ____(LatLongDef, Position2Def):
"""
DatumDef schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
a... | DatumDef |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 7341,
"end": 76103
} | class ____(StateManager):
"""Manages the state of DenseFeatures and LinearLayer.
Some `FeatureColumn`s create variables or resources to assist their
computation. The `StateManager` is responsible for creating and storing these
objects since `FeatureColumn`s are supposed to be stateless configuration
only.
... | _StateManagerImpl |
python | google__pytype | pytype/overlays/metaclass.py | {
"start": 428,
"end": 1475
} | class ____(abstract.BaseValue):
"""AddMetaclass instance (constructed by AddMetaclass.call())."""
def __init__(self, meta, ctx, module):
super().__init__("AddMetaclassInstance", ctx)
self.meta = meta
self.module = module
def call(self, node, func, args, alias_map=None):
del func, alias_map # un... | AddMetaclassInstance |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 5250,
"end": 5310
} | class ____(TestRss2Feed):
language = "de"
| TestLanguageFeed |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_compiler.py | {
"start": 1741,
"end": 63625
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "oracle"
@testing.fixture
def legacy_oracle_limitoffset(self):
self.__dialect__ = oracle.OracleDialect(enable_offset_fetch=False)
yield
del self.__dialect__
def test_true_false(self):
self.assert_compile(s... | CompileTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 114674,
"end": 115471
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"repository_id",
"base",
"head",
"commit_message",
"author_email",
"client_mutation_id",
)
repository_id = sgqlc.types.Field(... | MergeBranchInput |
python | getsentry__sentry | src/sentry/monitors/processing_errors/errors.py | {
"start": 4014,
"end": 4265
} | class ____(TypedDict):
"""
The monitor has too many environments associated with it already, can't add
another
"""
type: Literal[ProcessingErrorType.MONITOR_ENVIRONMENT_LIMIT_EXCEEDED]
reason: str
| MonitorEnvironmentLimitExceeded |
python | huggingface__transformers | src/transformers/models/donut/modeling_donut_swin.py | {
"start": 15441,
"end": 16011
} | class ____(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:... | DonutSwinDropPath |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_vml01.py | {
"start": 391,
"end": 2627
} | class ____(unittest.TestCase):
"""
Test assembling a complete Vml file.
"""
def test_assemble_xml_file(self):
"""Test writing a vml with no cell data."""
self.maxDiff = None
fh = StringIO()
vml = Vml()
vml._set_filehandle(fh)
comment = CommentType(1, 1... | TestAssembleVml |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_text_editor_code_execution_str_replace_result_block.py | {
"start": 259,
"end": 580
} | class ____(BaseModel):
lines: Optional[List[str]] = None
new_lines: Optional[int] = None
new_start: Optional[int] = None
old_lines: Optional[int] = None
old_start: Optional[int] = None
type: Literal["text_editor_code_execution_str_replace_result"]
| BetaTextEditorCodeExecutionStrReplaceResultBlock |
python | pytorch__pytorch | test/test_testing.py | {
"start": 99204,
"end": 101486
} | class ____(TestCase):
def test_sample_input(self) -> None:
a, b, c, d, e = (object() for _ in range(5))
# Construction with natural syntax
s = SampleInput(a, b, c, d=d, e=e)
assert s.input is a
assert s.args == (b, c)
assert s.kwargs == dict(d=d, e=e)
# Cons... | TestOpInfos |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 76760,
"end": 77135
} | class ____(DQLDMLClauseElement):
"""Handle a type keyword in a SQL statement.
Used by the ``Case`` statement.
"""
__visit_name__ = "typeclause"
_traverse_internals: _TraverseInternalsType = [
("type", InternalTraversal.dp_type)
]
type: TypeEngine[Any]
def __init__(self, type... | TypeClause |
python | apache__airflow | providers/dbt/cloud/src/airflow/providers/dbt/cloud/hooks/dbt.py | {
"start": 3455,
"end": 3588
} | class ____(TypedDict):
"""Type class for the ``job_run_info`` dictionary."""
account_id: int | None
run_id: int
| JobRunInfo |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_diag.py | {
"start": 1464,
"end": 14511
} | class ____(linear_operator.LinearOperator):
"""`LinearOperator` acting like a [batch] square diagonal matrix.
This operator acts like a [batch] diagonal matrix `A` with shape
`[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a
batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, ... | LinearOperatorDiag |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver45.py | {
"start": 387,
"end": 560
} | class ____(TypedDict):
a: int
def test2():
a: TD1
b: TD1
a, b = ({"a": 1}, {"a": 2})
def test3():
a: Literal[1]
b: Literal[2]
a, b = (1, 2)
| TD1 |
python | joke2k__faker | faker/providers/ssn/en_IE/__init__.py | {
"start": 42,
"end": 459
} | class ____(BaseProvider):
"""
A Faker provider for the Irish VAT IDs
"""
vat_id_formats = (
"IE#?#####?",
"IE#######?",
"IE#######??",
)
def vat_id(self) -> str:
"""
http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
:return: a random Iri... | Provider |
python | pyca__cryptography | tests/x509/test_ocsp.py | {
"start": 40448,
"end": 43296
} | class ____:
def test_init(self):
with pytest.raises(TypeError):
x509.SignedCertificateTimestamps(
[object()] # type: ignore[list-item]
)
def test_repr(self):
assert repr(x509.SignedCertificateTimestamps([])) == (
"<SignedCertificateTimestamps... | TestSignedCertificateTimestampsExtension |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/traceback.py | {
"start": 8412,
"end": 35198
} | class ____:
"""A Console renderable that renders a traceback.
Args:
trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
the last exception.
width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
c... | Traceback |
python | django__django | django/utils/regex_helper.py | {
"start": 904,
"end": 12772
} | class ____(list):
"""Represent a non-capturing group in the pattern string."""
def normalize(pattern):
r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following:
(1) For any repeating sections, keeps the minimum number of occurre... | NonCapture |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/scoped_resources_builder.py | {
"start": 845,
"end": 1392
} | class ____:
"""This class functions as a "tag" that we can use to type the namedtuple returned by
ScopedResourcesBuilder.build(). The way that we create the namedtuple returned by build() is
incompatible with type annotations on its own due to its dynamic attributes, so this tag class
provides a workaro... | Resources |
python | fluentpython__example-code-2e | 24-class-metaprog/bulkfood/model_v7.py | {
"start": 1695,
"end": 1804
} | class ____(metaclass=EntityMeta): # <3>
"""Business entity with validated fields"""
# end::MODEL_V7[]
| Entity |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/adaboost.py | {
"start": 761,
"end": 5633
} | class ____():
"""Boosting method that uses a number of weak classifiers in
ensemble to make a strong classifier. This implementation uses decision
stumps, which is a one level Decision Tree.
Parameters:
-----------
n_clf: int
The number of weak classifiers that will be used.
"""
... | Adaboost |
python | tensorflow__tensorflow | tensorflow/examples/speech_commands/train_test.py | {
"start": 1401,
"end": 4393
} | class ____(test.TestCase):
def _getWavData(self):
with self.cached_session():
sample_data = tf.zeros([32000, 2])
wav_encoder = tf.audio.encode_wav(sample_data, 16000)
wav_data = self.evaluate(wav_encoder)
return wav_data
def _saveTestWavFile(self, filename, wav_data):
with open(filen... | TrainTest |
python | pypa__pip | src/pip/_vendor/urllib3/packages/six.py | {
"start": 19169,
"end": 34665
} | class ____(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
__path__ = [] # mark as package
parse = _importer._get_module("moves.urllib_parse")
error = _importer._get_module("moves.urllib_error")
request = _importer._get_module("moves.urllib_reque... | Module_six_moves_urllib |
python | GoogleCloudPlatform__python-docs-samples | compute/autoscaler/demo/frontend.py | {
"start": 2887,
"end": 3514
} | class ____(BaseHTTPServer.BaseHTTPRequestHandler):
"""Request handler for Demo http server."""
def do_GET(self):
"""Handle an HTTP GET request."""
mapping = {
"/": lambda: (200, "OK"), # Return HTTP 200 response.
"/service": CpuBurner().handle_http_request,
}
... | DemoRequestHandler |
python | ansible__ansible | test/lib/ansible_test/_internal/ci/local.py | {
"start": 6690,
"end": 8120
} | class ____(metaclass=abc.ABCMeta):
"""Base class for authenticators."""
@staticmethod
def list() -> list[type[Authenticator]]:
"""List all authenticators in priority order."""
return sorted((sc for sc in get_subclasses(Authenticator) if not inspect.isabstract(sc)), key=lambda obj: obj.prior... | Authenticator |
python | pytorch__pytorch | torch/backends/_coreml/preprocess.py | {
"start": 894,
"end": 985
} | class ____:
CPU = "cpuOnly"
CPUAndGPU = "cpuAndGPU"
ALL = "all"
| CoreMLComputeUnit |
python | ray-project__ray | doc/source/ray-overview/examples/e2e-xgboost/dist_xgboost/serve.py | {
"start": 468,
"end": 3730
} | class ____:
def __init__(self, loader):
# pass in loader function from the outer context to
# make it easier to mock during testing
self.preprocessor, self.model = loader()
@serve.batch(max_batch_size=16, batch_wait_timeout_s=0.1)
async def predict_batch(self, input_data: list[dict]... | XGBoostModel |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 1071,
"end": 5244
} | class ____(fixtures.MappedTest):
"""A self-referential mapper with an additional list of child objects."""
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"c1", Integer, primary_key=True, test_needs_autoincrement=True... | SelfReferentialTest |
python | google__jax | jax/_src/traceback_util.py | {
"start": 4721,
"end": 4991
} | class ____(Exception): pass
_simplified_tb_msg = ("For simplicity, JAX has removed its internal frames from the "
"traceback of the following exception. Set "
"JAX_TRACEBACK_FILTERING=off to include these.")
| UnfilteredStackTrace |
python | public-apis__public-apis | scripts/tests/test_validate_links.py | {
"start": 281,
"end": 462
} | class ____():
def __init__(self, code: int, headers: dict, text: str) -> None:
self.status_code = code
self.headers = headers
self.text = text
| FakeResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-us-census/components.py | {
"start": 881,
"end": 4069
} | class ____(RecordExtractor):
"""
Parses the response from the us census website.
The US Census provides data in an atypical format,
which motivated the creation of this source rather
than using a generic http source.
* Data are represented in a two-dimensional array
* Square brackets [ ] h... | USCensusRecordExtractor |
python | django-haystack__django-haystack | haystack/query.py | {
"start": 22411,
"end": 23711
} | class ____(SearchQuerySet):
"""
A ``SearchQuerySet`` which returns a list of field values as tuples, exactly
like Django's ``ValuesListQuerySet``.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._flat = False
self._fields = []
# Remov... | ValuesListSearchQuerySet |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_slug.py | {
"start": 891,
"end": 3595
} | class ____(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.pip = Project.objects.get(slug="pip")
def test_saving(self):
version = Version.objects.create(
verbose_name="1.0",
project=self.pip,
)
self.assertEqual(version.slug, "1.0")
... | VersionSlugFieldTests |
python | kamyu104__LeetCode-Solutions | Python/select-k-disjoint-special-substrings.py | {
"start": 1358,
"end": 2614
} | class ____(object):
def maxSubstringLength(self, s, k):
"""
:type s: str
:type k: int
:rtype: bool
"""
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda interval: interval[1])
result, right = 0, float("-inf")
for l, ... | Solution2 |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 4588,
"end": 5759
} | class ____:
def setup(self):
index = Index([f"i-{i}" for i in range(1000)], dtype=object)
columns = Index([f"i-{i}" for i in range(30)], dtype=object)
with warnings.catch_warnings(record=True):
self.df = DataFrame(np.random.randn(1000, 30), index=index, columns=columns)
s... | DataFrameStringIndexing |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 14172,
"end": 14237
} | class ____(scale_color_cmap_d):
pass
@alias
| scale_color_ordinal |
python | sympy__sympy | sympy/core/kind.py | {
"start": 1379,
"end": 1694
} | class ____(type):
"""
Metaclass for ``Kind``.
Assigns empty ``dict`` as class attribute ``_inst`` for every class,
in order to endow singleton-like behavior.
"""
def __new__(cls, clsname, bases, dct):
dct['_inst'] = {}
return super().__new__(cls, clsname, bases, dct)
| KindMeta |
python | scipy__scipy | scipy/special/tests/test_orthogonal.py | {
"start": 9998,
"end": 10971
} | class ____:
def test_call(self):
poly = []
for n in range(5):
poly.extend([x.strip() for x in
(f"""
orth.jacobi({n},0.3,0.9)
orth.sh_jacobi({n},0.3,0.9)
orth.genlaguerre({n},0.3)
orth.laguerre({n})
... | TestCall |
python | modin-project__modin | modin/config/envvars.py | {
"start": 35312,
"end": 36458
} | class ____(EnvironmentVariable, type=int):
"""
Minimum number of rows in a single pandas partition split.
Once a partition for a pandas dataframe has more than this many elements,
Modin adds another partition.
"""
varname = "MODIN_MIN_ROW_PARTITION_SIZE"
default = 32
@classmethod
... | MinRowPartitionSize |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_slack.py | {
"start": 453,
"end": 3371
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.integration, self.org_integration = self.create_provider_integration_for(
provider="slack",
organization=self.organization,
user=self.user,
name="slack",
metadata={"domain_... | TestSlackActionValidator |
python | huggingface__transformers | tests/models/bit/test_image_processing_bit.py | {
"start": 3252,
"end": 5142
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = BitImageProcessor if is_vision_available() else None
fast_image_processing_class = BitImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = B... | BitImageProcessingTest |
python | google__pytype | pytype/tests/test_typeguard.py | {
"start": 789,
"end": 2417
} | class ____(test_base.BaseTest):
"""Tests for misuse of typing.TypeGuard."""
def test_bool_subclass(self):
# While PEP 647 says that TypeGuard is not a subtype of bool
# (https://peps.python.org/pep-0647/#typeguard-type), mypy treats it as
# such, and typeshed has the same expectation. For example, insp... | MisuseTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.