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-python | sentry_sdk/tracing_utils.py | {
"start": 1483,
"end": 11670
} | class ____(Mapping): # type: ignore
def __init__(
self,
environ, # type: Mapping[str, str]
prefix="HTTP_", # type: str
):
# type: (...) -> None
self.environ = environ
self.prefix = prefix
def __getitem__(self, key):
# type: (str) -> Optional[Any]
... | EnvironHeaders |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/softsign_op_test.py | {
"start": 1110,
"end": 3064
} | class ____(test.TestCase):
def _npSoftsign(self, np_features):
return np_features / (1 + np.abs(np_features))
def _testSoftsign(self, np_features, atol, rtol, use_gpu=False):
np_softsign = self._npSoftsign(np_features)
with self.cached_session(use_gpu=use_gpu):
softsign = nn_ops.softsign(np_feat... | SoftsignTest |
python | Lightning-AI__lightning | src/lightning/pytorch/trainer/trainer.py | {
"start": 4189,
"end": 79058
} | class ____:
@_defaults_from_env_vars
def __init__(
self,
*,
accelerator: Union[str, Accelerator] = "auto",
strategy: Union[str, Strategy] = "auto",
devices: Union[list[int], str, int] = "auto",
num_nodes: int = 1,
precision: Optional[_PRECISION_INPUT] = No... | Trainer |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 7156,
"end": 7633
} | class ____:
def __init__(self, realtime: AsyncRealtime) -> None:
self._realtime = realtime
@cached_property
def sessions(self) -> AsyncSessionsWithRawResponse:
return AsyncSessionsWithRawResponse(self._realtime.sessions)
@cached_property
def transcription_sessions(self) -> AsyncTra... | AsyncRealtimeWithRawResponse |
python | pennersr__django-allauth | allauth/socialaccount/providers/angellist/provider.py | {
"start": 442,
"end": 930
} | class ____(OAuth2Provider):
id = "angellist"
name = "AngelList"
account_class = AngelListAccount
oauth2_adapter_class = AngelListOAuth2Adapter
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
return dict(
email=data.get("ema... | AngelListProvider |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 18314,
"end": 18610
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (
GrapheneMessageEvent,
GrapheneDisplayableEvent,
GrapheneStepEvent,
GrapheneMarkerEvent,
GrapheneErrorEvent,
)
name = "EngineEvent"
| GrapheneEngineEvent |
python | dagster-io__dagster | python_modules/libraries/dagster-twilio/dagster_twilio/resources.py | {
"start": 266,
"end": 1371
} | class ____(ConfigurableResource):
"""This resource is for connecting to Twilio."""
account_sid: str = Field(
description=(
"Twilio Account SID, created with yout Twilio account. This can be found on your Twilio"
" dashboard, see"
" https://www.twilio.com/blog/twilio-... | TwilioResource |
python | kamyu104__LeetCode-Solutions | Python/largest-perimeter-triangle.py | {
"start": 33,
"end": 329
} | class ____(object):
def largestPerimeter(self, A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
for i in reversed(xrange(len(A) - 2)):
if A[i] + A[i+1] > A[i+2]:
return A[i] + A[i+1] + A[i+2]
return 0
| Solution |
python | donnemartin__system-design-primer | solutions/object_oriented_design/online_chat/online_chat.py | {
"start": 2353,
"end": 2443
} | class ____(Enum):
UNREAD = 0
READ = 1
ACCEPTED = 2
REJECTED = 3
| RequestStatus |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_utils.py | {
"start": 6222,
"end": 9314
} | class ____(_CppPrinter):
def doprint(self, expr, *, simplify: bool = True, p=True):
# TODO: why are people passing strings to the printer here :think:
if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"):
expr = V.graph.sizevars.simplify(expr)
return supe... | CppPrinter |
python | astropy__astropy | astropy/units/tests/test_quantity_array_methods.py | {
"start": 2762,
"end": 5545
} | class ____:
"""Test different ndarray methods that alter the array shape
tests: reshape, squeeze, ravel, flatten, transpose, swapaxes
"""
def test_reshape(self):
q = np.arange(6.0) * u.m
q_reshape = q.reshape(3, 2)
assert isinstance(q_reshape, u.Quantity)
assert q_resha... | TestQuantityReshapeFuncs |
python | matplotlib__matplotlib | lib/matplotlib/streamplot.py | {
"start": 15947,
"end": 17794
} | class ____:
"""
Mask to keep track of discrete regions crossed by streamlines.
The resolution of this grid determines the approximate spacing between
trajectories. Streamlines are only allowed to pass through zeroed cells:
When a streamline enters a cell, that cell is set to 1, and no new
strea... | StreamMask |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_trace_item_attributes.py | {
"start": 701,
"end": 1636
} | class ____(APITestCase, SnubaTestCase):
feature_flags: dict[str, bool]
item_type: SupportedTraceItemType
viewname = "sentry-api-0-organization-trace-item-attributes"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def do_request(self, query=None, features=No... | OrganizationTraceItemAttributesEndpointTestBase |
python | Netflix__metaflow | metaflow/plugins/aws/batch/batch_client.py | {
"start": 24477,
"end": 25468
} | class ____(object):
def __init__(self, delta_in_secs=1, num_tries=20):
self.delta_in_secs = delta_in_secs
self.num_tries = num_tries
self._now = None
self._reset()
def _reset(self):
self._tries_left = self.num_tries
self._wait = self.delta_in_secs
def __call... | Throttle |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule_test.py | {
"start": 4595,
"end": 6237
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
schedules.PolynomialDecay(
initial_learning_rate=0.1,
decay_steps=100,
end_learning_rate=0.005,
power=1.0,
cycle=False,
... | LinearDecayTest |
python | huggingface__transformers | src/transformers/models/aria/modeling_aria.py | {
"start": 24530,
"end": 25343
} | class ____(PreTrainedModel):
config: AriaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["AriaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_... | AriaPreTrainedModel |
python | joblib__joblib | joblib/parallel.py | {
"start": 26711,
"end": 37786
} | class ____(object):
"""Callback to keep track of completed results and schedule the next tasks.
This callable is executed by the parent process whenever a worker process
has completed a batch of tasks.
It is used for progress reporting, to update estimate of the batch
processing duration and to sc... | BatchCompletionCallBack |
python | Pylons__pyramid | tests/test_config/test_assets.py | {
"start": 35891,
"end": 36063
} | class ____:
def __init__(self):
self.registered = []
def register_loader_type(self, typ, inst):
self.registered.append((typ, inst))
| DummyPkgResources |
python | django__django | tests/model_forms/models.py | {
"start": 10543,
"end": 10717
} | class ____(models.Model):
name = models.CharField(max_length=50)
def __iter__(self):
yield from range(5)
def __str__(self):
return self.name
| Color |
python | rq__rq | tests/test_callbacks.py | {
"start": 400,
"end": 4402
} | class ____(RQTestCase):
def test_enqueue_with_success_callback(self):
"""Test enqueue* methods with on_success"""
queue = Queue(connection=self.connection)
# Only functions and builtins are supported as callback
with self.assertRaises(ValueError):
queue.enqueue(say_hello... | QueueCallbackTestCase |
python | astropy__astropy | astropy/io/ascii/fastbasic.py | {
"start": 8443,
"end": 9243
} | class ____(FastBasic):
"""
A faster version of the ordinary :class:`Csv` writer that uses the
optimized C parsing engine. Note that this reader will append empty
field values to the end of any row with not enough columns, while
:class:`FastBasic` simply raises an error.
"""
_format_name = "... | FastCsv |
python | neetcode-gh__leetcode | python/0371-sum-of-two-integers.py | {
"start": 0,
"end": 537
} | class ____:
def getSum(self, a: int, b: int) -> int:
def add(a, b):
if not a or not b:
return a or b
return add(a ^ b, (a & b) << 1)
if a * b < 0: # assume a < 0, b > 0
if a > 0:
return self.getSum(b, a)
if add(~a, 1) ... | Solution |
python | pypa__warehouse | tests/unit/packaging/test_views.py | {
"start": 17114,
"end": 19631
} | class ____:
def test_get_render_form(self, pyramid_request):
project = pretend.stub()
form_obj = pretend.stub()
form_class = pretend.call_recorder(lambda d, **kw: form_obj)
result = views.submit_malware_observation(
project, pyramid_request, _form_class=form_class
... | TestProjectSubmitMalwareObservation |
python | django__django | django/contrib/gis/gdal/srs.py | {
"start": 11724,
"end": 12392
} | class ____(GDALBase):
"The coordinate system transformation object."
destructor = capi.destroy_ct
def __init__(self, source, target):
"Initialize on a source and target SpatialReference objects."
if not isinstance(source, SpatialReference) or not isinstance(
target, SpatialRefe... | CoordTransform |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/objects.py | {
"start": 2591,
"end": 5050
} | class ____(
NamedTuple(
"_StepFailureData",
[
("error", Optional[SerializableErrorInfo]),
("user_failure_data", Optional[UserFailureData]),
("error_source", ErrorSource),
],
)
):
def __new__(cls, error, user_failure_data, error_source=None):
... | StepFailureData |
python | huggingface__transformers | tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py | {
"start": 2349,
"end": 19314
} | class ____:
supports_sdpa = False
def get_encoder_decoder_model(self, config, decoder_config):
pass
def prepare_config_and_inputs(self):
pass
def get_pretrained_model_and_inputs(self):
pass
def check_encoder_decoder_model_from_pretrained_configs(
self, config, dec... | EncoderDecoderMixin |
python | ray-project__ray | python/ray/data/_internal/execution/operators/actor_pool_map_operator.py | {
"start": 24161,
"end": 26398
} | class ____:
"""An actor worker for MapOperator."""
def __init__(
self,
ctx: DataContext,
src_fn_name: str,
map_transformer: MapTransformer,
logical_actor_id: str,
actor_location_tracker: ray.actor.ActorHandle[ActorLocationTracker],
):
self.src_fn_name... | _MapWorker |
python | getsentry__sentry | src/sentry/models/groupinbox.py | {
"start": 4278,
"end": 4455
} | class ____(TypedDict):
until: str | None # datetime str
count: int | None
window: int | None
user_count: int | None
user_window: int | None
| InboxReasonDetails |
python | pytorch__pytorch | torch/_inductor/select_algorithm.py | {
"start": 95226,
"end": 97860
} | class ____(RuntimeError):
pass
@functools.cache
def get_num_workers() -> int:
if "TORCHINDUCTOR_COMPILE_THREADS" in os.environ:
return int(os.environ["TORCHINDUCTOR_COMPILE_THREADS"])
cpu_count = (
len(os.sched_getaffinity(0))
if hasattr(os, "sched_getaffinity")
else os.cp... | NoValidChoicesError |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-vertex/llama_index/llms/vertex/base.py | {
"start": 1652,
"end": 19162
} | class ____(FunctionCallingLLM):
"""
Vertext LLM.
Examples:
`pip install llama-index-llms-vertex`
```python
from llama_index.llms.vertex import Vertex
# Set up necessary variables
credentials = {
"project_id": "INSERT_PROJECT_ID",
"api_key": ... | Vertex |
python | pennersr__django-allauth | allauth/socialaccount/providers/vimeo/provider.py | {
"start": 262,
"end": 708
} | class ____(OAuthProvider):
id = "vimeo"
name = "Vimeo"
account_class = VimeoAccount
oauth_adapter_class = VimeoOAuthAdapter
def get_default_scope(self):
scope = []
return scope
def extract_uid(self, data):
return data["id"]
def extract_common_fields(self, data):
... | VimeoProvider |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/test_utils.py | {
"start": 3993,
"end": 9658
} | class ____:
@mock.patch(f"{MODULE}.PipelineRequest")
@mock.patch(f"{MODULE}.BearerTokenCredentialPolicy")
@mock.patch(f"{MODULE}.DefaultAzureCredential")
def test_signed_session(self, mock_default_azure_credential, mock_policy, mock_request):
mock_request.return_value.http_request.headers = {"Au... | TestAzureIdentityCredentialAdapter |
python | scrapy__scrapy | tests/test_utils_log.py | {
"start": 3398,
"end": 4771
} | class ____:
def test_redirect(self):
logger = logging.getLogger("test")
logger.setLevel(logging.WARNING)
old_stdout = sys.stdout
sys.stdout = StreamLogger(logger, logging.ERROR)
with LogCapture() as log:
print("test log msg")
log.check(("test", "ERROR", "... | TestStreamLogger |
python | kamyu104__LeetCode-Solutions | Python/find-the-child-who-has-the-ball-after-k-seconds.py | {
"start": 36,
"end": 290
} | class ____(object):
def numberOfChild(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
q, r = divmod(k, n-1)
return r if q&1 == 0 else (n-1)-r
# Time: O(1)
# Space: O(1)
# math
| Solution |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 86671,
"end": 96406
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_deprecated_v1
def testBasic(self):
g = ops.Graph()
with g.as_default():
# Creating unregistered ops with _apply_op() doesn't work with the C API
# TODO(skyewm): address this more consistently. Possible solutions are
# to use registe... | ControlDependenciesTest |
python | huggingface__transformers | src/transformers/pipelines/pt_utils.py | {
"start": 502,
"end": 6627
} | class ____(IterableDataset):
def __init__(self, loader, infer, params, loader_batch_size=None):
"""
Roughly equivalent to
```
for item in loader:
yield infer(item, **params)
```
Arguments:
loader (`torch.utils.data.DataLoader`... | PipelineIterator |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_common.py | {
"start": 331,
"end": 8600
} | class ____:
def test_validate_entrypoint(self):
r = validate_request_type({"entrypoint": "abc"}, JobSubmitRequest)
assert r.entrypoint == "abc"
with pytest.raises(TypeError, match="required positional argument"):
validate_request_type({}, JobSubmitRequest)
with pytest.r... | TestJobSubmitRequestValidation |
python | pydantic__pydantic | pydantic/warnings.py | {
"start": 3547,
"end": 3868
} | class ____(PydanticDeprecationWarning):
"""A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.12."""
def __init__(self, message: str, *args: object) -> None:
super().__init__(message, *args, since=(2, 12), expected_removal=(3, 0))
| PydanticDeprecatedSince212 |
python | numba__llvmlite | llvmlite/binding/value.py | {
"start": 13770,
"end": 13987
} | class ____(_ValueIterator):
kind = 'operand'
def _dispose(self):
self._capi.LLVMPY_DisposeOperandsIter(self)
def _next(self):
return ffi.lib.LLVMPY_OperandsIterNext(self)
| _OperandsIterator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_formula_results01.py | {
"start": 315,
"end": 1708
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("formula_results01.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workboo... | TestCompareXLSXFiles |
python | redis__redis-py | tests/test_encoding.py | {
"start": 2092,
"end": 2657
} | class ____:
def test_ignore(self, request):
r = _get_client(
redis.Redis,
request=request,
decode_responses=True,
encoding_errors="ignore",
)
r.set("a", b"foo\xff")
assert r.get("a") == "foo"
def test_replace(self, request):
... | TestEncodingErrors |
python | pypa__pipenv | pipenv/vendor/click/parser.py | {
"start": 4962,
"end": 6770
} | class ____:
def __init__(
self,
obj: "CoreOption",
opts: t.Sequence[str],
dest: t.Optional[str],
action: t.Optional[str] = None,
nargs: int = 1,
const: t.Optional[t.Any] = None,
):
self._short_opts = []
self._long_opts = []
self.pre... | Option |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-superlinked/llama_index/retrievers/superlinked/retriever.py | {
"start": 365,
"end": 4299
} | class ____(BaseRetriever):
"""
LlamaIndex retriever for Superlinked.
Provides an adapter that executes a Superlinked query and converts results
into LlamaIndex `TextNode` instances with scores.
"""
def __init__(
self,
*,
sl_client: App,
sl_query: QueryDescriptor... | SuperlinkedRetriever |
python | joke2k__faker | faker/providers/address/de_DE/__init__.py | {
"start": 47,
"end": 10331
} | class ____(AddressProvider):
city_formats = ("{{city_name}}",)
city_with_postcode_formats = ("{{postcode}} {{city}}",)
street_name_formats = (
"{{first_name}}-{{last_name}}-{{street_suffix_long}}",
"{{last_name}}{{street_suffix_short}}",
)
street_address_formats = ("{{street_name}}... | Provider |
python | wandb__wandb | wandb/sdk/data_types/object_3d.py | {
"start": 19043,
"end": 19178
} | class ____(_dtypes.Type):
name = "object3D-file"
types = [Object3D]
_dtypes.TypeRegistry.add(_Object3DFileType)
| _Object3DFileType |
python | walkccc__LeetCode | solutions/1632. Rank Transform of a Matrix/1632.py | {
"start": 0,
"end": 575
} | class ____:
def __init__(self):
self.id = {}
def union(self, u: int, v: int) -> None:
self.id.setdefault(u, u)
self.id.setdefault(v, v)
i = self._find(u)
j = self._find(v)
if i != j:
self.id[i] = j
def getGroupIdToValues(self) -> dict[int, list[int]]:
groupIdToValues = collecti... | UnionFind |
python | zarr-developers__zarr-python | src/zarr/errors.py | {
"start": 2268,
"end": 2442
} | class ____(BaseZarrError):
"""Raised when the Zarr metadata is invalid in some way"""
_msg = "Invalid value for '{}'. Expected '{}'. Got '{}'."
| MetadataValidationError |
python | ray-project__ray | python/ray/autoscaler/_private/spark/spark_job_server.py | {
"start": 278,
"end": 7271
} | class ____(BaseHTTPRequestHandler):
def setup(self) -> None:
super().setup()
self._handler_lock = threading.RLock()
self._created_node_id_set = set()
self._logger = logging.getLogger(__name__)
if "RAY_ON_SPARK_JOB_SERVER_VERBOSE" in os.environ:
self._logger.setLev... | SparkJobServerRequestHandler |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/client.py | {
"start": 8969,
"end": 41343
} | class ____:
def __init__(self, batch_api, core_api, logger, sleeper, timer):
self.batch_api = batch_api
self.core_api = core_api
self.logger = logger
self.sleeper = sleeper
self.timer = timer
@staticmethod
def production_client(batch_api_override=None, core_api_overr... | DagsterKubernetesClient |
python | apache__airflow | airflow-core/src/airflow/models/dagrun.py | {
"start": 90158,
"end": 93112
} | class ____(Base):
"""For storage of arbitrary notes concerning the dagrun instance."""
__tablename__ = "dag_run_note"
user_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
dag_run_id: Mapped[int] = mapped_column(Integer, primary_key=True, nullable=False)
content: Mapped[str | Non... | DagRunNote |
python | huggingface__transformers | tests/models/upernet/test_modeling_upernet.py | {
"start": 9408,
"end": 11135
} | class ____(unittest.TestCase):
def test_inference_swin_backbone(self):
processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny")
model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny").to(torch_device)
image = prepare_img()
inputs = ... | UperNetModelIntegrationTest |
python | walkccc__LeetCode | solutions/2239. Find Closest Number to Zero/2239.py | {
"start": 0,
"end": 132
} | class ____:
def findClosestNumber(self, nums: list[int]) -> int:
nums.sort(key=lambda x: (abs(x), -x))
return nums[0]
| Solution |
python | pytorch__pytorch | tools/testing/target_determination/heuristics/profiling.py | {
"start": 650,
"end": 1146
} | class ____(HeuristicInterface):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
def get_prediction_confidence(self, tests: list[str]) -> TestPrioritizations:
test_ratings = get_ratings_for_tests(
ADDITIONAL_CI_FILES_FOLDER / TD_HEURISTIC_PROFILING_FILE
... | Profiling |
python | mlflow__mlflow | tests/gateway/tools.py | {
"start": 4514,
"end": 7163
} | class ____:
# This test utility class is used to validate the internal functionality of the
# AI Gateway within-process so that the provider endpoints can be mocked,
# allowing a nearly end-to-end validation of the entire AI Gateway stack.
# NB: this implementation should only be used for integration te... | UvicornGateway |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops_v2_test.py | {
"start": 10796,
"end": 13716
} | class ____(InitializersTest):
@test_util.run_in_graph_and_eager_modes
def testTruncatedNormalDistribution(self):
shape = [100, 100]
expect_mean = 0.
expect_var = 1. / shape[0]
init = init_ops_v2.VarianceScaling(distribution="truncated_normal")
with test_util.use_gpu(), test.mock.patch.object(
... | VarianceScalingInitializerTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_set_row04.py | {
"start": 315,
"end": 1233
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_row03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_fil... | TestCompareXLSXFiles |
python | getsentry__sentry | tests/sentry/notifications/notification_action/metric_alert_registry/test_opsgenie_metric_alert_handler.py | {
"start": 920,
"end": 8035
} | class ____(MetricAlertHandlerBase):
def setUp(self) -> None:
self.create_models()
self.action = self.create_action(
type=Action.Type.OPSGENIE,
integration_id=1234567890,
config={"target_identifier": "team123", "target_type": ActionTarget.SPECIFIC},
dat... | TestOpsgenieMetricAlertHandler |
python | falconry__falcon | tests/test_app_initializers.py | {
"start": 83,
"end": 241
} | class ____:
def on_get(self, req, resp):
resp.media = {'foo': 'bar'}
def on_post(self, req, resp):
resp.media = req.media
| MediaResource |
python | scipy__scipy | scipy/special/tests/test_spherical_bessel.py | {
"start": 2662,
"end": 4700
} | class ____:
def test_spherical_yn_exact(self):
# https://dlmf.nist.gov/10.49.E5
# Note: exact expression is numerically stable only for small
# n or z >> n.
x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
assert_allclose(spherical_yn(2, x),
(1/x - 3/... | TestSphericalYn |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/stubs.py | {
"start": 544,
"end": 639
} | class ____(AIMessageChunk, _AnyIDMixin):
"""AIMessageChunk with any ID."""
| _AnyIdAIMessageChunk |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 32275,
"end": 33967
} | class ____(test.TestCase):
def _validateReverseSequence(
self, x, batch_axis, seq_axis, seq_lengths, truth, use_gpu=False
):
with self.cached_session(use_gpu=use_gpu):
ans = array_ops.reverse_sequence(
x, batch_axis=batch_axis, seq_axis=seq_axis, seq_lengths=seq_lengths
)
tf_a... | ReverseSequenceTest |
python | bokeh__bokeh | src/bokeh/document/events.py | {
"start": 6948,
"end": 8569
} | class ____(DocumentChangedEvent, Serializable):
''' A Base class for events that represent updating Bokeh Models and
their properties.
'''
kind: ClassVar[str]
_handlers: ClassVar[dict[str, type[DocumentPatchedEvent]]] = {}
def __init_subclass__(cls):
cls._handlers[cls.kind] = cls
... | DocumentPatchedEvent |
python | Textualize__textual | docs/examples/how-to/containers08.py | {
"start": 130,
"end": 275
} | class ____(Placeholder):
"""Example widget."""
DEFAULT_CSS = """
Box {
width: 16;
height: 5;
}
"""
| Box |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_natural_foreign_key.py | {
"start": 140,
"end": 308
} | class ____(resources.ModelResource):
class Meta:
model = Book
fields = ["name", "author"]
use_natural_foreign_keys = True
| BookUsingNaturalKeys |
python | lazyprogrammer__machine_learning_examples | rnn_class/srn_language.py | {
"start": 546,
"end": 7700
} | class ____:
def __init__(self, D, M, V):
self.D = D # dimensionality of word embedding
self.M = M # hidden layer size
self.V = V # vocabulary size
def fit(self, X, learning_rate=1., mu=0.99, reg=1.0, activation=T.tanh, epochs=500, show_fig=False):
N = len(X)
D = self.D
... | SimpleRNN |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 4214,
"end": 4970
} | class ____(nn.Module):
def __init__(self, config: ParakeetEncoderConfig):
super().__init__()
self.linear1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.attention_bias)
self.activation = ACT2FN[config.hidden_act]
self.linear2 = nn.Linear(config.intermediate_siz... | ParakeetEncoderFeedForward |
python | huggingface__transformers | src/transformers/models/cpmant/modeling_cpmant.py | {
"start": 10516,
"end": 11379
} | class ____(nn.Module):
def __init__(self, config: CpmAntConfig):
super().__init__()
self.layernorm_before_ffn = CpmAntLayerNorm(config)
self.ffn = CpmAntFeedForward(config)
if config.dropout_p:
self.dropout = torch.nn.Dropout(config.dropout_p)
else:
se... | CpmAntFFNBlock |
python | PyCQA__pylint | tests/functional/m/missing/missing_docstring_new_style.py | {
"start": 127,
"end": 234
} | class ____: # [missing-class-docstring]
pass
# pylint: disable=missing-class-docstring
| UndocumentedClass |
python | apache__airflow | airflow-core/src/airflow/models/serialized_dag.py | {
"start": 2398,
"end": 12099
} | class ____:
"""Resolver that resolves dag dependencies to include asset id and assets link to asset aliases."""
def __init__(self, dag_id_dependencies: Sequence[tuple[str, dict]], session: Session) -> None:
self.dag_id_dependencies = dag_id_dependencies
self.session = session
self.asse... | _DagDependenciesResolver |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 57911,
"end": 61871
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, seed=None):
super().__init__()
self.config = config
self.attention_type = config.attention_type
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = BigBi... | BigBirdLayer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_write_idmap.py | {
"start": 289,
"end": 741
} | class ____(unittest.TestCase):
"""
Test the Vml _write_idmap() method.
"""
def setUp(self):
self.fh = StringIO()
self.vml = Vml()
self.vml._set_filehandle(self.fh)
def test_write_idmap(self):
"""Test the _write_idmap() method"""
self.vml._write_idmap(1)
... | TestWriteOidmap |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 35485,
"end": 35763
} | class ____(BaseModel):
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional["ErrorResponseStatus"] = Field(default=None, description="")
result: Optional[Any] = Field(default=None, description="")
| ErrorResponse |
python | pandas-dev__pandas | pandas/io/sas/sasreader.py | {
"start": 663,
"end": 5447
} | class ____(Iterator["DataFrame"], ABC):
"""
Abstract class for XportReader and SAS7BDATReader.
"""
@abstractmethod
def read(self, nrows: int | None = None) -> DataFrame: ...
@abstractmethod
def close(self) -> None: ...
def __enter__(self) -> Self:
return self
def __exit__... | SASReader |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 179,
"end": 728
} | class ____(Exception):
"""
Exception mixin inherited by all exceptions of web3.py
This allows::
try:
some_call()
except Web3Exception:
# deal with web3 exception
except:
# deal with other exceptions
"""
user_message: str | None = None
... | Web3Exception |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/datafusion.py | {
"start": 21388,
"end": 25557
} | class ____(GoogleBaseAsyncHook):
"""Class to get asynchronous hook for DataFusion."""
sync_hook_class = DataFusionHook
scopes = ["https://www.googleapis.com/auth/cloud-platform"]
@staticmethod
def _base_url(instance_url: str, namespace: str) -> str:
return urljoin(f"{instance_url}/", f"v3/... | DataFusionAsyncHook |
python | numba__numba | numba/cuda/tests/cudadrv/test_cuda_driver.py | {
"start": 6873,
"end": 7663
} | class ____(CUDATestCase):
def test_device_get_uuid(self):
# A device UUID looks like:
#
# GPU-e6489c45-5b68-3b03-bab7-0e7c8e809643
#
# To test, we construct an RE that matches this form and verify that
# the returned UUID matches.
#
# Device UUIDs ... | TestDevice |
python | pytorch__pytorch | torch/ao/nn/intrinsic/qat/modules/conv_fused.py | {
"start": 17315,
"end": 18484
} | class ____(ConvBn1d):
r"""
A ConvBnReLU1d module is a module fused from Conv1d, BatchNorm1d and ReLU,
attached with FakeQuantize modules for weight,
used in quantization aware training.
We combined the interface of :class:`torch.nn.Conv1d` and
:class:`torch.nn.BatchNorm1d` and :class:`torch.nn.... | ConvBnReLU1d |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 24968,
"end": 27643
} | class ____:
def test_declared_field_disabling(self):
class Parent(serializers.Serializer):
f1 = serializers.CharField()
f2 = serializers.CharField()
class Child(Parent):
f1 = None
class Grandchild(Child):
pass
assert len(Parent._decl... | TestDeclaredFieldInheritance |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 188778,
"end": 191044
} | class ____(test_util.TensorFlowTestCase):
def _testValid(self, filename):
# Read some real GIFs
prefix = "tensorflow/core/lib/gif/testdata/"
WIDTH = 20
HEIGHT = 40
STRIDE = 5
shape = (12, HEIGHT, WIDTH, 3)
with self.cached_session():
gif0 = io_ops.read_file(prefix + filename)
... | GifTest |
python | matplotlib__matplotlib | galleries/examples/units/basic_units.py | {
"start": 1179,
"end": 1436
} | class ____:
def __init__(self, fn_name, obj):
self.fn_name = fn_name
self.target = obj.proxy_target
def __call__(self, *args):
fn = getattr(self.target, self.fn_name)
ret = fn(*args)
return ret
| PassThroughProxy |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py | {
"start": 3729,
"end": 3909
} | class ____(StrictBaseModel):
"""Schema for updating TaskInstance to a target state, excluding terminal and running states."""
state: IntermediateTIState
| TITargetStatePayload |
python | numba__numba | numba/cuda/simulator/cudadrv/devices.py | {
"start": 1691,
"end": 2689
} | class ____:
'''
This stub implements a device list containing a single GPU. It also
keeps track of the GPU status, i.e. whether the context is closed or not,
which may have been set by the user calling reset()
'''
def __init__(self):
self.lst = (FakeCUDAContext(0),)
self.closed =... | FakeDeviceList |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 39151,
"end": 40381
} | class ____(BaseModel, extra="forbid"):
"""
All possible payload filtering conditions
"""
key: str = Field(..., description="Payload key")
match: Optional["Match"] = Field(default=None, description="Check if point has field with a given value")
range: Optional["RangeInterface"] = Field(default=N... | FieldCondition |
python | numpy__numpy | numpy/polynomial/tests/test_printing.py | {
"start": 13592,
"end": 15003
} | class ____:
def test_polynomial_repr(self):
res = repr(poly.Polynomial([0, 1]))
tgt = (
"Polynomial([0., 1.], domain=[-1., 1.], window=[-1., 1.], "
"symbol='x')"
)
assert_equal(res, tgt)
def test_chebyshev_repr(self):
res = repr(poly.Chebyshev([... | TestRepr |
python | spyder-ide__spyder | spyder/plugins/completion/providers/snippets/provider.py | {
"start": 989,
"end": 2887
} | class ____(SpyderCompletionProvider):
COMPLETION_PROVIDER_NAME = 'snippets'
DEFAULT_ORDER = 3
CONF_DEFAULTS = [(lang, SNIPPETS[lang]) for lang in SNIPPETS]
CONF_VERSION = "0.1.0"
CONF_TABS = [SnippetsConfigTab]
def __init__(self, parent, config):
SpyderCompletionProvider.__init__(self, ... | SnippetsProvider |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_model.py | {
"start": 2105,
"end": 12438
} | class ____:
class_var: ClassVar[int] = 1
foo: int
bar: str
spam: bytes
frog: dataclasses.InitVar[int]
def test_dataclass():
schema = core_schema.call_schema(
core_schema.arguments_schema(
[
core_schema.arguments_parameter('foo', core_schema.int_schema()),
... | DataClass |
python | django__django | django/db/models/fetch_modes.py | {
"start": 235,
"end": 439
} | class ____(FetchMode):
__slots__ = ()
def fetch(self, fetcher, instance):
fetcher.fetch_one(instance)
def __reduce__(self):
return "FETCH_ONE"
FETCH_ONE = FetchOne()
| FetchOne |
python | django__django | django/contrib/humanize/apps.py | {
"start": 91,
"end": 194
} | class ____(AppConfig):
name = "django.contrib.humanize"
verbose_name = _("Humanize")
| HumanizeConfig |
python | getsentry__sentry | tests/snuba/api/serializers/test_group.py | {
"start": 20650,
"end": 22271
} | class ____(
APITestCase,
SnubaTestCase,
SearchIssueTestMixin,
):
def test_profiling_seen_stats(self) -> None:
proj = self.create_project()
environment = self.create_environment(project=proj)
first_group_fingerprint = f"{ProfileFileIOGroupType.type_id}-group1"
timestamp =... | ProfilingGroupSerializerSnubaTest |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/app.py | {
"start": 2233,
"end": 3186
} | class ____(JupyterApp):
description: str = "Show information about the currently running Spyder server."
def start(self):
"""Start the server list application."""
runtime_dir = Path(jupyter_runtime_dir())
# The runtime dir might not exist
if not runtime_dir.is_dir():
... | SpyderServerInfoApp |
python | sympy__sympy | sympy/printing/lambdarepr.py | {
"start": 7451,
"end": 8307
} | class ____(MpmathPrinter, LambdaPrinter):
"""Use ``lambda`` printer but print numbers as ``mpi`` intervals. """
def _print_Integer(self, expr):
return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr)
def _print_Rational(self, expr):
return "mpi('%s')" % super(PythonCodePri... | IntervalPrinter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol46.py | {
"start": 337,
"end": 504
} | class ____(Protocol[T_contra, T]):
def method1(self, value: T_contra) -> "ProtoA[T_contra, T]": ...
@classmethod
def method2(cls, value: T) -> T: ...
| ProtoA |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 561,
"end": 1071
} | class ____:
def __init__(self, val, config):
request_method = as_sorted_tuple(val)
if 'GET' in request_method and 'HEAD' not in request_method:
# GET implies HEAD too
request_method = as_sorted_tuple(request_method + ('HEAD',))
self.val = request_method
def text(... | RequestMethodPredicate |
python | TheAlgorithms__Python | data_structures/heap/binomial_heap.py | {
"start": 1268,
"end": 12247
} | class ____:
r"""
Min-oriented priority queue implemented with the Binomial Heap data
structure implemented with the BinomialHeap class. It supports:
- Insert element in a heap with n elements: Guaranteed logn, amoratized 1
- Merge (meld) heaps of size m and n: O(logn + logm)
- Delete... | BinomialHeap |
python | doocs__leetcode | solution/0900-0999/0989.Add to Array-Form of Integer/Solution.py | {
"start": 0,
"end": 295
} | class ____:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
ans = []
i = len(num) - 1
while i >= 0 or k:
k += 0 if i < 0 else num[i]
k, x = divmod(k, 10)
ans.append(x)
i -= 1
return ans[::-1]
| Solution |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/activation.py | {
"start": 9365,
"end": 11891
} | class ____(torch.nn.Module):
r"""This is the quantized equivalent of :class:`~torch.nn.PReLU`.
Args:
scale: quantization scale of the output tensor
zero_point: quantization zero point of the output tensor
num_parameters: number of parameters: 1, or the number of channels at input. Defau... | PReLU |
python | kamyu104__LeetCode-Solutions | Python/max-consecutive-ones-ii.py | {
"start": 29,
"end": 442
} | class ____(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result, prev, curr = 0, 0, 0
for n in nums:
if n == 0:
result = max(result, prev+curr+1)
prev, curr = curr, 0
... | Solution |
python | walkccc__LeetCode | solutions/3093. Longest Common Suffix Queries/3093.py | {
"start": 0,
"end": 155
} | class ____:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.isWord = False
self.length = math.inf
self.index = -1
| TrieNode |
python | donnemartin__system-design-primer | solutions/object_oriented_design/online_chat/online_chat.py | {
"start": 1788,
"end": 1904
} | class ____(Chat):
def add_user(self, user):
pass
def remove_user(self, user):
pass
| GroupChat |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/cli_tests/workspace_tests/pending_repo/pending_repo.py | {
"start": 214,
"end": 927
} | class ____(CacheableAssetsDefinition):
def compute_cacheable_data(self):
return [
AssetsDefinitionCacheableData(
keys_by_input_name={}, keys_by_output_name={"result": dg.AssetKey(self.unique_id)}
)
]
def build_definitions(self, data):
@dg.op
... | MyCacheableAssetsDefinition |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.