language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/convnextv2/modeling_convnextv2.py | {
"start": 9327,
"end": 10678
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.stages = nn.ModuleList()
drop_path_rates = [
x.tolist()
for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").split(config.depths)
]
prev_chs = con... | ConvNextV2Encoder |
python | django__django | tests/postgres_tests/test_indexes.py | {
"start": 8611,
"end": 32967
} | class ____(PostgreSQLTestCase):
get_opclass_query = """
SELECT opcname, c.relname FROM pg_opclass AS oc
JOIN pg_index as i on oc.oid = ANY(i.indclass)
JOIN pg_class as c on c.oid = i.indexrelid
WHERE c.relname = %s
"""
def get_constraints(self, table):
"""
Ge... | SchemaTests |
python | huggingface__transformers | src/transformers/models/deberta/modeling_deberta.py | {
"start": 21455,
"end": 24835
} | class ____(nn.Module):
"""Modified BertEncoder with relative position bias support"""
def __init__(self, config):
super().__init__()
self.layer = nn.ModuleList([DebertaLayer(config) for _ in range(config.num_hidden_layers)])
self.relative_attention = getattr(config, "relative_attention"... | DebertaEncoder |
python | huggingface__transformers | src/transformers/models/olmo2/modeling_olmo2.py | {
"start": 19052,
"end": 22150
} | class ____(Olmo2PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Olmo2Mo... | Olmo2ForCausalLM |
python | lepture__authlib | authlib/jose/rfc7518/jwe_encs.py | {
"start": 716,
"end": 3215
} | class ____(JWEEncAlgorithm):
# The IV used is a 128-bit value generated randomly or
# pseudo-randomly for use in the cipher.
IV_SIZE = 128
def __init__(self, key_size, hash_type):
self.name = f"A{key_size}CBC-HS{hash_type}"
tpl = "AES_{}_CBC_HMAC_SHA_{} authenticated encryption algorith... | CBCHS2EncAlgorithm |
python | ray-project__ray | rllib/policy/tests/test_policy.py | {
"start": 356,
"end": 2351
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_policy_get_and_set_state(self):
config = (
PPOConfig()
.environment("CartPole-v1")
.a... | TestPolicy |
python | conda__conda | conda/deprecations.py | {
"start": 807,
"end": 16473
} | class ____:
_version: str | None
_version_tuple: tuple[int, ...] | None
_version_object: Version | None
def __init__(self: Self, version: str) -> None:
"""Factory to create a deprecation handle for the specified version.
:param version: The version to compare against when checking depr... | DeprecationHandler |
python | run-llama__llama_index | llama-index-core/tests/memory/test_chat_summary_memory_buffer.py | {
"start": 2014,
"end": 15430
} | class ____(MockLLM):
_i: int = PrivateAttr()
_responses: List[ChatMessage] = PrivateAttr()
_role_counts: dict = PrivateAttr()
def __init__(self, responses: List[ChatMessage], max_tokens: int = 512) -> None:
super().__init__(max_tokens=max_tokens)
self._i = 0 # call counter, determines ... | MockSummarizerLLM |
python | neetcode-gh__leetcode | python/0605-can-place-flowers.py | {
"start": 1119,
"end": 1478
} | class ____:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# Solution with O(n) space complexity
f = [0] + flowerbed + [0]
for i in range(1, len(f) - 1): # skip first & last
if f[i - 1] == 0 and f[i] == 0 and f[i + 1] == 0:
f[i] = 1
... | Solution3 |
python | walkccc__LeetCode | solutions/599. Minimum Index Sum of Two Lists/599.py | {
"start": 0,
"end": 514
} | class ____:
def findRestaurant(self, list1: list[str], list2: list[str]) -> list[str]:
ans = []
restaurantToIndex = {restaurant: i for i,
restaurant in enumerate(list1)}
minSum = math.inf
for i, restaurant in enumerate(list2):
if restaurant in restaurantToIndex:
... | Solution |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-lindorm/llama_index/vector_stores/lindorm/base.py | {
"start": 27744,
"end": 32943
} | class ____(BasePydanticVectorStore):
"""
Lindorm vector store.
Args:
client (LindormVectorClient): Vector index client to use.
for data insertion/querying.
Examples:
`pip install llama-index`
`pip install opensearch-py`
`pip install llama-index-vector-stores... | LindormVectorStore |
python | neetcode-gh__leetcode | python/1700-number-of-students-unable-to-eat-lunch.py | {
"start": 0,
"end": 513
} | class ____:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
num_of_students_back_in_line = 0
while num_of_students_back_in_line != len(students):
curr_student = students.pop(0)
if curr_student == sandwiches[0]:
sandwiches.pop(0)
... | Solution |
python | redis__redis-py | tests/test_asyncio/test_multidb/test_config.py | {
"start": 734,
"end": 5288
} | class ____:
def test_default_config(self):
db_configs = [
DatabaseConfig(
client_kwargs={"host": "host1", "port": "port1"}, weight=1.0
),
DatabaseConfig(
client_kwargs={"host": "host2", "port": "port2"}, weight=0.9
),
... | TestMultiDbConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator1.py | {
"start": 336,
"end": 416
} | class ____:
def shouldContinue(self):
global s
return s
| ClassB |
python | cython__cython | Cython/Compiler/Code.py | {
"start": 36538,
"end": 47062
} | class ____:
# return_label string function return point label
# error_label string error catch point label
# error_without_exception boolean Can go to the error label without an exception (e.g. __next__ can return NULL)
# continue_label string loop continue point l... | FunctionState |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 24803,
"end": 25210
} | class ____(Constant):
# inherited class for all numeric constant node types
__slots__ = ()
def validate(self):
if self.value < SizeLimits.MIN_INT256:
raise OverflowException("Value is below lower bound for all numeric types", self)
if self.value > SizeLimits.MAX_UINT256:
... | Num |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataflow.py | {
"start": 9276,
"end": 23468
} | class ____(DataflowJobTerminalStateHelper):
"""
Interface for communication with Google Cloud Dataflow API.
Does not use Apache Beam API.
:param dataflow: Discovery resource
:param project_number: The Google Cloud Project ID.
:param location: Job location.
:param poll_sleep: The status ref... | _DataflowJobsController |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass12.py | {
"start": 305,
"end": 375
} | class ____(Base):
x: ClassVar[int] = 1
z: int
@dataclass
| Special |
python | ray-project__ray | doc/source/serve/doc_code/model_composition/streaming_example.py | {
"start": 231,
"end": 384
} | class ____:
def __call__(self, limit: int) -> Generator[int, None, None]:
for i in range(limit):
yield i
@serve.deployment
| Streamer |
python | anthropics__anthropic-sdk-python | src/anthropic/_response.py | {
"start": 10601,
"end": 13963
} | class ____(BaseAPIResponse[R]):
@property
def request_id(self) -> str | None:
return self.http_response.headers.get("request-id") # type: ignore[no-any-return]
@overload
def parse(self, *, to: type[_T]) -> _T: ...
@overload
def parse(self) -> R: ...
def parse(self, *, to: type[_T... | APIResponse |
python | scikit-learn__scikit-learn | sklearn/cluster/_feature_agglomeration.py | {
"start": 465,
"end": 2439
} | class ____(TransformerMixin):
"""
A class for feature agglomeration via the transform interface.
"""
def transform(self, X):
"""
Transform a new matrix using the built clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features) or \
... | AgglomerationTransform |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 237,
"end": 2423
} | class ____:
__slots__ = 'start_mark', 'end_mark', 'comment'
def __init__(self, start_mark=None, end_mark=None, comment=CommentCheck):
# type: (Any, Any, Any) -> None
self.start_mark = start_mark
self.end_mark = end_mark
# assert comment is not CommentCheck
if comment is ... | Event |
python | pytorch__pytorch | torch/_dynamo/variables/lists.py | {
"start": 42160,
"end": 43407
} | class ____(BaseListVariable):
def python_type(self) -> type[tuple]: # type: ignore[type-arg]
return tuple
def __repr__(self) -> str:
return f"{self.__class__.__name__}(length={len(self.items)})"
def debug_repr(self) -> str:
return self.debug_repr_helper("(", ")")
def reconstr... | TupleVariable |
python | dagster-io__dagster | python_modules/libraries/dagster-census/dagster_census/types.py | {
"start": 73,
"end": 698
} | class ____(
NamedTuple(
"_CensusOutput",
[
("sync_run", Mapping[str, Any]),
("source", Mapping[str, Any]),
("destination", Mapping[str, Any]),
],
)
):
"""Contains recorded information about the state of a Census sync after a sync completes.
Ar... | CensusOutput |
python | davidhalter__parso | parso/python/tree.py | {
"start": 12577,
"end": 12654
} | class ____(PythonBaseNode):
type = 'decorator'
__slots__ = ()
| Decorator |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 2217,
"end": 2366
} | class ____(Property):
@property
def close(self):
pass
@close.setter
def close(self, attr):
return attr
| PropertySetter |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 19084,
"end": 19303
} | class ____(BaseModel):
max_message_queue_size: int = Field(..., description="")
tick_period_ms: int = Field(..., description="")
bootstrap_timeout_sec: int = Field(..., description="")
| ConsensusConfigTelemetry |
python | apache__airflow | airflow-core/src/airflow/triggers/testing.py | {
"start": 1224,
"end": 1707
} | class ____(BaseTrigger):
"""
A trigger that always errors immediately.
Should only be used for testing.
"""
def serialize(self) -> tuple[str, dict[str, Any]]:
return ("airflow.triggers.testing.FailureTrigger", {})
async def run(self):
# Python needs at least one "yield" keywor... | FailureTrigger |
python | apache__airflow | airflow-core/tests/unit/core/test_impersonation_tests.py | {
"start": 7202,
"end": 8181
} | class ____(BaseImpersonationTest):
@classmethod
def setup_class(cls):
cls.dagbag = cls.get_dagbag(TEST_DAG_FOLDER)
def test_impersonation(self):
"""
Tests that impersonating a unix user works
"""
self.run_dag("test_impersonation", "test_impersonated_user")
def t... | TestImpersonation |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 19417,
"end": 20295
} | class ____(Operation):
def call(self, x):
return backend.nn.hard_tanh(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["keras.ops.hard_tanh", "keras.ops.nn.hard_tanh"])
def hard_tanh(x):
"""Applies the HardTanh function element-wise.
It i... | HardTanh |
python | django-crispy-forms__django-crispy-forms | tests/forms.py | {
"start": 2682,
"end": 2812
} | class ____(models.Model):
email = models.CharField(max_length=20)
password = models.CharField(max_length=20)
| CrispyTestModel |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_5408.py | {
"start": 642,
"end": 727
} | class ____(_Child):
def patch(cls):
MyClass.sub_class.inner_class = cls
| Child |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_sagemaker_processing.py | {
"start": 3580,
"end": 15256
} | class ____:
def setup_method(self):
self.processing_config_kwargs = dict(
task_id="test_sagemaker_operator",
wait_for_completion=False,
check_interval=5,
)
self.defer_processing_config_kwargs = dict(
task_id="test_sagemaker_operator", wait_for... | TestSageMakerProcessingOperator |
python | pypa__pip | tests/functional/test_install_user.py | {
"start": 1079,
"end": 12214
} | class ____:
@pytest.mark.network
def test_reset_env_system_site_packages_usersite(
self, script: PipTestEnvironment
) -> None:
"""
Check user site works as expected.
"""
script.pip("install", "--user", "INITools==0.2")
result = script.run(
"python"... | Tests_UserSite |
python | django__django | django/db/models/functions/comparison.py | {
"start": 4990,
"end": 5709
} | class ____(Func):
"""
Return the maximum expression.
If any expression is null the return value is database-specific:
On PostgreSQL, the maximum not-null expression is returned.
On MySQL, Oracle, and SQLite, if any expression is null, null is returned.
"""
function = "GREATEST"
def __... | Greatest |
python | wandb__wandb | wandb/old/summary.py | {
"start": 12136,
"end": 13843
} | class ____(Summary):
def __init__(self, run, client, summary=None):
super().__init__(run, summary=summary)
self._run = run
self._client = client
self._started = time.time()
def __delitem__(self, key):
if key not in self._json_dict:
raise KeyError(key)
... | HTTPSummary |
python | scipy__scipy | scipy/odr/_models.py | {
"start": 4599,
"end": 6045
} | class ____(Model):
r"""
Exponential model
This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}`
Examples
--------
We can calculate orthogonal distance regression with an exponential model:
>>> from scipy import odr
>>> import numpy as np
>>> x = np.linspace(0.0, 5.0)
>>> ... | _ExponentialModel |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 11375,
"end": 12116
} | class ____(BaseConfig):
config_path: str = config_path
configured_catalog_path: Optional[str] = configured_catalog_path
future_state: Optional[FutureStateConfig] = Field(description="Configuration for the future state.")
timeout_seconds: int = timeout_seconds
deployment_mode: Optional[str] = deploym... | IncrementalConfig |
python | cython__cython | Demos/benchmarks/bm_richards_cclass.py | {
"start": 7866,
"end": 10267
} | class ____(object):
def run(self, iterations: cython.long):
i: cython.long
for i in range(iterations):
taskWorkArea.holdCount = 0
taskWorkArea.qpktCount = 0
IdleTask(I_IDLE, 1, 10000, TaskState().running(), IdleTaskRec())
wkq = Packet(None, 0, K_WO... | Richards |
python | explosion__spaCy | spacy/lang/ja/__init__.py | {
"start": 7309,
"end": 7550
} | class ____(BaseDefaults):
config = load_config_from_str(DEFAULT_CONFIG)
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
writing_system = {"direction": "ltr", "has_case": False, "has_letters": False}
| JapaneseDefaults |
python | getsentry__sentry | tests/snuba/search/test_backend.py | {
"start": 11342,
"end": 98282
} | class ____(EventsDatasetTestSetup):
def test_query(self) -> None:
results = self.make_query(search_filter_query="foo")
assert set(results) == {self.group1}
results = self.make_query(search_filter_query="bar")
assert set(results) == {self.group2}
def test_query_multi_project(sel... | EventsSnubaSearchTestCases |
python | getsentry__sentry | src/sentry/seer/fetch_issues/by_function_name.py | {
"start": 1077,
"end": 9538
} | class ____(TypedDict):
group_id: int
event_id: str
title: str
def _simple_function_name_conditions(function_names: list[str], stack_frame_idx: int) -> Condition:
return Condition(
Function(
"arrayElement",
(Column("exception_frames.function"), stack_frame_idx),
... | IssueFromSnuba |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 55290,
"end": 62272
} | class ____(DetrPreTrainedModel):
def __init__(self, config: DetrConfig):
super().__init__(config)
# DETR encoder-decoder model
self.model = DetrModel(config)
# Object detection heads
self.class_labels_classifier = nn.Linear(
config.d_model, config.num_labels + 1... | DetrForObjectDetection |
python | huggingface__transformers | src/transformers/models/aria/modular_aria.py | {
"start": 55646,
"end": 60519
} | class ____(LlavaModel):
def __init__(self, config: AriaConfig):
super().__init__(config)
self.multi_modal_projector = AriaProjector(config)
def _create_patch_attention_mask(self, pixel_mask):
if pixel_mask is None:
return None
patches_subgrid = pixel_mask.unfold(
... | AriaModel |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/fs/s3.py | {
"start": 1327,
"end": 4818
} | class ____(Exception):
"""Raises when unable to sign a S3 request."""
def get_fs(conn_id: str | None, storage_options: dict[str, str] | None = None) -> AbstractFileSystem:
try:
from s3fs import S3FileSystem
except ImportError:
raise ImportError(
"Airflow FS S3 protocol requires... | SignError |
python | django__django | tests/admin_views/tests.py | {
"start": 149818,
"end": 161216
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.deleteuser = User.objects.create_user(
username="deleteuser", password="secret", is_staff... | AdminViewDeletedObjectsTest |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 36788,
"end": 36938
} | class ____(str, Enum):
UPSCALING = "UPSCALING"
DOWNSCALING = "DOWNSCALING"
STABLE = "STABLE"
@PublicAPI(stability="alpha")
| AutoscalingStatus |
python | kamyu104__LeetCode-Solutions | Python/pascals-triangle-ii.py | {
"start": 1111,
"end": 1370
} | class ____(object):
# @return a list of integers
def getRow(self, rowIndex):
result = [1]
for i in range(1, rowIndex + 1):
result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1]
return result
| Solution2 |
python | huggingface__transformers | src/transformers/models/dia/modeling_dia.py | {
"start": 18225,
"end": 19542
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: DiaEncoderConfig, layer_idx: int):
super().__init__()
self.pre_sa_norm = DiaRMSNorm(config.hidden_size, eps=config.norm_eps)
self.self_attention = DiaSelfAttention(config, layer_idx, is_causal=False)
self.post_sa_norm... | DiaEncoderLayer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/app/test_app01.py | {
"start": 333,
"end": 2222
} | class ____(unittest.TestCase):
"""
Test assembling a complete App file.
"""
def test_assemble_xml_file(self):
"""Test writing an App file."""
self.maxDiff = None
fh = StringIO()
app = App()
app._set_filehandle(fh)
app._add_part_name("Sheet1")
a... | TestAssembleApp |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/Parameter.py | {
"start": 36218,
"end": 36490
} | class ____(object):
def __init__(self, enterFn, exitFn):
self.enterFn = enterFn
self.exitFn = exitFn
def __enter__(self):
self.enterFn()
def __exit__(self, exc_type, exc_value, tb):
self.exitFn()
| SignalBlocker |
python | walkccc__LeetCode | solutions/2237. Count Positions on Street With Required Brightness/2237.py | {
"start": 0,
"end": 453
} | class ____:
def meetRequirement(
self,
n: int,
lights: list[list[int]],
requirement: list[int],
) -> int:
ans = 0
currBrightness = 0
change = [0] * (n + 1)
for position, rg in lights:
change[max(0, position - rg)] += 1
change[min(n, position + rg + 1)] -= 1
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/patreon/views.py | {
"start": 326,
"end": 2335
} | class ____(OAuth2Adapter):
provider_id = PROVIDER_ID
access_token_url = "https://www.patreon.com/api/oauth2/token" # nosec
authorize_url = "https://www.patreon.com/oauth2/authorize"
profile_url = "{0}/{1}".format(
API_URL,
(
"identity?include=memberships&fields%5Buser%5D=ema... | PatreonOAuth2Adapter |
python | urllib3__urllib3 | test/with_dummyserver/test_proxy_poolmanager.py | {
"start": 27215,
"end": 28048
} | class ____(IPv6HypercornDummyProxyTestCase):
@classmethod
def setup_class(cls) -> None:
super().setup_class()
cls.http_url = f"http://{cls.http_host}:{int(cls.http_port)}"
cls.http_url_alt = f"http://{cls.http_host_alt}:{int(cls.http_port)}"
cls.https_url = f"https://{cls.https_h... | TestIPv6HTTPProxyManager |
python | keras-team__keras | keras/src/dtype_policies/dtype_policy_test.py | {
"start": 27855,
"end": 29372
} | class ____(test_case.TestCase):
"""Test error handling in GPTQConfig."""
def test_invalid_weight_bits(self):
with self.assertRaisesRegex(ValueError, "Unsupported weight_bits"):
GPTQConfig(
dataset=None,
tokenizer=None,
weight_bits=5,
... | GPTQConfigErrorHandlingTest |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 14761,
"end": 63183
} | class ____(variables.Variable, core.Tensor):
"""A python variable from an existing handle."""
# TODO(wangpeng): Deprecate `constraint` when callers no long pass it in.
def __init__( # pylint: disable=super-init-not-called
self,
trainable=None,
shape=None,
dtype=None,
handle=None,
... | BaseResourceVariable |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 25277,
"end": 44859
} | class ____(PyrexType):
is_memoryviewslice = 1
default_value = "{ 0, 0, { 0 }, { 0 }, { 0 } }"
has_attributes = 1
needs_refcounting = 1 # Ideally this would be true and reference counting for
# memoryview and pyobject code could be generated in the same way.
# However, memoryviews are ... | MemoryViewSliceType |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 31308,
"end": 32252
} | class ____(AsyncHTTPTestCase):
def get_app(self):
class ChunkedWithContentLength(RequestHandler):
def get(self):
# Add an invalid Transfer-Encoding to the response
self.set_header("Transfer-Encoding", "chunked")
self.write("Hello world")
r... | ChunkedWithContentLengthTest |
python | kamyu104__LeetCode-Solutions | Python/distribute-elements-into-two-arrays-ii.py | {
"start": 89,
"end": 711
} | class ____(object):
def resultArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
sl1, sl2 = SortedList([nums[0]]), SortedList([nums[1]])
a, b = [nums[0]], [nums[1]]
for i in xrange(2, len(nums)):
cnt1 = len(sl1)-sl1.bisect_right(num... | Solution |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 10107,
"end": 13001
} | class ____(ModelOutput):
r"""
logits (`torch.FloatTensor` of shape `(batch_size, num_patches, num_queries)`):
Classification logits (including no-object) for all queries.
image_embeds (`torch.FloatTensor` of shape `(batch_size, patch_size, patch_size, output_dim`):
Pooled output of [`Owlv2Vi... | Owlv2ImageGuidedObjectDetectionOutput |
python | numba__numba | numba/cuda/tests/cudapy/test_math.py | {
"start": 3365,
"end": 27615
} | class ____(CUDATestCase):
def unary_template_float16(self, func, npfunc, start=0, stop=1):
self.unary_template(func, npfunc, np.float16, np.float16, start, stop)
def unary_template_float32(self, func, npfunc, start=0, stop=1):
self.unary_template(func, npfunc, np.float32, np.float32, start, sto... | TestCudaMath |
python | pytorch__pytorch | test/test_proxy_tensor.py | {
"start": 29785,
"end": 29871
} | class ____(TestGenericProxyTensor):
tracing_mode = "fake"
| TestGenericProxyTensorFake |
python | huggingface__transformers | src/transformers/models/qwen2_moe/modular_qwen2_moe.py | {
"start": 2123,
"end": 2735
} | class ____(GemmaMLP):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.Li... | Qwen2MoeMLP |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modular_falcon_mamba.py | {
"start": 25556,
"end": 25779
} | class ____(MambaRMSNorm):
def forward(self, hidden_states):
return self.weight.to(hidden_states.device) * rms_forward(
hidden_states, variance_epsilon=self.variance_epsilon
)
| FalconMambaRMSNorm |
python | doocs__leetcode | solution/0400-0499/0405.Convert a Number to Hexadecimal/Solution.py | {
"start": 0,
"end": 311
} | class ____:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars = '0123456789abcdef'
s = []
for i in range(7, -1, -1):
x = (num >> (4 * i)) & 0xF
if s or x != 0:
s.append(chars[x])
return ''.join(s)
| Solution |
python | dagster-io__dagster | examples/docs_projects/project_ask_ai_dagster/src/project_ask_ai_dagster/defs/io_managers.py | {
"start": 111,
"end": 1322
} | class ____(dg.IOManager):
def __init__(self, base_dir):
self.base_dir = base_dir
os.makedirs(base_dir, exist_ok=True)
def handle_output(self, context, obj):
# Convert documents to simple dicts
file_path = os.path.join(self.base_dir, f"{context.asset_key.path[-1]}.json")
... | DocumentIOManager |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 137092,
"end": 137499
} | 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(SecurityAdvisoryOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
s... | SecurityAdvisoryOrder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/mro3.py | {
"start": 285,
"end": 357
} | class ____(DerivableObject, SubclassableObject):
pass
| InheritingObject |
python | ray-project__ray | doc/source/train/doc_code/metric_logging.py | {
"start": 3148,
"end": 3705
} | class ____(ray.train.UserCallback):
def after_report(
self,
run_context,
metrics: List[Dict[str, Any]],
checkpoint: Optional[ray.train.Checkpoint],
):
rank_0_metrics = metrics[0]
print(rank_0_metrics)
# Ex: Write metrics to a file...
trainer = ray.train.... | CustomMetricsCallback |
python | pytorch__pytorch | torch/_dynamo/variables/torch_function.py | {
"start": 8367,
"end": 11615
} | class ____:
def __init__(self, py_stack: Iterable[Any]) -> None:
# This is annoyingly complicated because of how the torch function subclass + mode C API was designed
# There are two exposed C knobs here as contexts: torch._C.DisableTorchFunction and torch._C.DisableTorchFunctionSubclass
# T... | SymbolicTorchFunctionState |
python | getsentry__sentry | tests/sentry/middleware/test_ratelimit_middleware.py | {
"start": 1104,
"end": 10603
} | class ____(TestCase, BaseTestCase):
middleware = RatelimitMiddleware(lambda request: sentinel.response)
@cached_property
def factory(self):
return RequestFactory()
class TestEndpoint(Endpoint):
enforce_rate_limit = True
def get(self):
raise NotImplementedError
... | RatelimitMiddlewareTest |
python | tensorflow__tensorflow | tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py | {
"start": 10031,
"end": 35543
} | class ____(base_delegate.DelegatingTrackableMixin,
optimizer_v2.OptimizerV2):
"""An optimizer that applies loss scaling to prevent numeric underflow.
Loss scaling is a technique to prevent numeric underflow in intermediate
gradients when float16 is used. To prevent underflow, the loss is... | LossScaleOptimizer |
python | psf__black | tests/data/cases/dummy_implementations.py | {
"start": 1485,
"end": 1575
} | class ____:
def f(self):
...
def f2(self):
print(10)
| ClassE |
python | gevent__gevent | src/gevent/tests/test__hub.py | {
"start": 12343,
"end": 13126
} | class ____(unittest.TestCase):
def test_implemensts_ILoop(self):
from gevent.testing import verify
from gevent._interfaces import ILoop
loop = get_hub().loop
verify.verifyObject(ILoop, loop)
def test_callback_implements_ICallback(self):
from gevent.testing import veri... | TestLoopInterface |
python | dagster-io__dagster | examples/docs_projects/project_dspy/config.py | {
"start": 248,
"end": 5375
} | class ____(BaseSettings):
"""Project settings with environment variable support."""
model_config = SettingsConfigDict(
env_file=".env", env_file_encoding="utf-8", case_sensitive=False, extra="ignore"
)
# Google Gemini Configuration
gemini_api_key: str = Field(default="", env="GEMINI_API_KE... | Settings |
python | spyder-ide__spyder | spyder/widgets/collectionseditor.py | {
"start": 75533,
"end": 77230
} | class ____(CollectionsDelegate):
"""CollectionsEditor Item Delegate"""
def __init__(self, parent=None, namespacebrowser=None):
CollectionsDelegate.__init__(self, parent, namespacebrowser)
def get_value(self, index):
if index.isValid():
source_index = index.model().mapToSource(i... | RemoteCollectionsDelegate |
python | eventlet__eventlet | tests/pools_test.py | {
"start": 5712,
"end": 6104
} | class ____(TestCase):
mode = 'static'
def setUp(self):
self.pool = IntPool(min_size=3, max_size=3)
def test_something(self):
self.assertEqual(len(self.pool.free_items), 3)
# Cover the clause in get where we get from the free list instead of creating
# an item on get
... | TestIntPool2 |
python | great-expectations__great_expectations | docs/sphinx_api_docs_source/public_api_report.py | {
"start": 3155,
"end": 3886
} | class ____:
"""File contents as a string and file path.
Args:
filepath: Absolute path to the file.
contents: String of the file contents.
"""
def __init__(self, filepath: pathlib.Path, contents: str):
self.filepath = filepath
self.contents = contents
@classmethod
... | FileContents |
python | apache__avro | lang/py/avro/schema.py | {
"start": 4971,
"end": 5639
} | class ____(collections.abc.Hashable):
"""A mixin that defines equality as equal if the json deserializations are equal."""
fingerprint: Callable[..., bytes]
def __eq__(self, that: object) -> bool:
try:
that_obj = json.loads(str(that))
except json.decoder.JSONDecodeError:
... | EqualByJsonMixin |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py | {
"start": 2992,
"end": 5396
} | class ____(nn.Module):
"""Relative positional encoding module."""
def __init__(self, config):
super().__init__()
self.max_len = config.max_source_positions
self.d_model = config.hidden_size
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, self.max_len))
def... | Wav2Vec2BertRelPositionalEmbedding |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 97253,
"end": 102666
} | class ____(_QueryEntity):
"""mapper/class/AliasedClass entity"""
__slots__ = (
"expr",
"mapper",
"entity_zero",
"is_aliased_class",
"path",
"_extra_entities",
"_label_name",
"_with_polymorphic_mappers",
"selectable",
"_polymorphic_... | _MapperEntity |
python | huggingface__transformers | src/transformers/models/lfm2/modular_lfm2.py | {
"start": 2879,
"end": 8467
} | class ____:
"""
Attention and conv cache for Lfm2.
It stores the Key and Value states as a list of tensors, one for each layer.
Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`.
Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`.
"""
# Override @propert... | Lfm2HybridConvCache |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 83997,
"end": 85206
} | class ____(Response):
"""
Response of tasks.add_or_update_model endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_model"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
... | AddOrUpdateModelResponse |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 60235,
"end": 66912
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# Buffers to be lazily initialized later
# self.default_frames
# self.group_idx
# self.atom_mask
# self.lit_positions
self.layer_norm_s = LayerNorm(config.sequ... | EsmFoldStructureModule |
python | celery__celery | t/integration/tasks.py | {
"start": 12181,
"end": 12241
} | class ____(BaseModel):
x: int
y: int
| AddParameterModel |
python | keon__algorithms | algorithms/tree/b_tree.py | {
"start": 1032,
"end": 9572
} | class ____:
""" Class of BTree """
def __init__(self, t_val=2):
self.min_numbers_of_keys = t_val - 1
self.max_number_of_keys = 2 * t_val - 1
self.root = Node()
def _split_child(self, parent: Node, child_index: int):
new_right_child = Node()
half_max = self.max_numb... | BTree |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/custom_job.py | {
"start": 9856,
"end": 36914
} | class ____(CustomTrainingJobBaseOperator):
"""
Create Custom Container Training job.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param display_name: Required. Th... | CreateCustomContainerTrainingJobOperator |
python | walkccc__LeetCode | solutions/2278. Percentage of Letter in String/2278.py | {
"start": 0,
"end": 117
} | class ____:
def percentageLetter(self, s: str, letter: str) -> int:
return 100 * s.count(letter) // len(s)
| Solution |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 108157,
"end": 108306
} | class ____(_pkg_config_info):
section = 'gdk_x11_2'
append_config_exe = 'gdk-x11-2.0'
version_macro_name = 'GDK_X11_VERSION'
| gdk_x11_2_info |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 684,
"end": 743
} | class ____(Event):
pass
NEED_DATA = NeedData()
| NeedData |
python | pennersr__django-allauth | allauth/socialaccount/providers/bitly/provider.py | {
"start": 217,
"end": 436
} | class ____(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("profile_url")
def get_avatar_url(self):
return self.account.extra_data.get("profile_image")
| BitlyAccount |
python | vyperlang__vyper | tests/evm_backends/abi_contract.py | {
"start": 605,
"end": 783
} | class ____:
"""Represents a parsed log entry from a contract."""
address: ChecksumAddress
args: tuple
event: str
topics: list[bytes]
raw_data: bytes
| ABILog |
python | keon__algorithms | tests/test_matrix.py | {
"start": 7501,
"end": 7842
} | class ____(unittest.TestCase):
"""[summary]
Test for the file rotate_image.py
Arguments:
unittest {[type]} -- [description]
"""
def test_rotate_image(self):
self.assertEqual(rotate_image.rotate(
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
[[7, 4, 1], [8, 5, 2], [9, ... | TestRotateImage |
python | etianen__django-reversion | reversion/admin.py | {
"start": 1218,
"end": 13397
} | class ____(admin.ModelAdmin):
object_history_template = "reversion/object_history.html"
change_list_template = "reversion/change_list.html"
revision_form_template = None
recover_list_template = None
recover_form_template = None
history_latest_first = False
def reversion_register(self,... | VersionAdmin |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_users.py | {
"start": 136,
"end": 2174
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-users"
def setUp(self) -> None:
self.owner_user = self.create_user("foo@localhost", username="foo")
self.user_2 = self.create_user("bar@localhost", username="bar")
self.user_3 = self.create_user("unrelated@localhost", userna... | OrganizationMemberListTest |
python | django__django | tests/inspectdb/models.py | {
"start": 4241,
"end": 4725
} | class ____(models.Model):
field1 = models.IntegerField()
field2 = models.CharField(max_length=10)
from_field = models.IntegerField(db_column="from")
non_unique = models.IntegerField(db_column="non__unique_column")
non_unique_0 = models.IntegerField(db_column="non_unique__column")
class Meta:
... | UniqueTogether |
python | arrow-py__arrow | arrow/locales.py | {
"start": 103878,
"end": 105378
} | class ____(Locale):
names = ["lv", "lv-lv"]
past = "pirms {0}"
future = "pēc {0}"
and_word = "un"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "tagad",
"second": "sekundes",
"seconds": "{0} sekundēm",
"minute": "minūtes",... | LatvianLocale |
python | ray-project__ray | python/ray/tune/experimental/output.py | {
"start": 24809,
"end": 27752
} | class ____(ProgressReporter):
_heartbeat_threshold = AirVerbosity.DEFAULT
_wrap_headers = False
_intermediate_result_verbosity = AirVerbosity.VERBOSE
_start_end_verbosity = AirVerbosity.DEFAULT
_addressing_tmpl = "Trial {}"
def __init__(
self,
verbosity: AirVerbosity,
nu... | TuneReporterBase |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 1208,
"end": 1342
} | class ____:
"""Represents the details of a DAG."""
id: str | None = None
team_name: str | None = None
@dataclass
| DagDetails |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple14.py | {
"start": 1186,
"end": 2104
} | class ____:
@classmethod
def method1(cls, *shape: *Ts) -> tuple[*Ts]: ...
def func1(target: Callable[[*Ts], int]) -> tuple[*Ts]: ...
def func2(a: int, b: str, /) -> int: ...
def func3(action: Callable[[int, str], int]):
v1 = func1(func2)
reveal_type(v1, expected_text="tuple[int, str]")
v2 = f... | ClassA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.