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 | facebook__pyre-check | stubs/integration_test/fixture_source/integration_test/overrides.py | {
"start": 303,
"end": 547
} | class ____(Iterable[T]):
def __iter__(self):
return source()
def issue_with_direct_call_of_subclass(mi: MyIterable[int]):
eval(mi.__iter__())
def no_issue_with_iterable_call(mi: Iterable[int]):
eval(mi.__iter__())
| MyIterable |
python | django__django | tests/admin_views/test_history_view.py | {
"start": 1894,
"end": 4541
} | class ____(AdminSeleniumTestCase):
available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps
def setUp(self):
self.superuser = User.objects.create_superuser(
username="super",
password="secret",
email="super@example.com",
)
for i in rang... | SeleniumTests |
python | openai__openai-python | src/openai/types/fine_tuning/reinforcement_hyperparameters.py | {
"start": 240,
"end": 1426
} | class ____(BaseModel):
batch_size: Union[Literal["auto"], int, None] = None
"""Number of examples in each batch.
A larger batch size means that model parameters are updated less frequently, but
with lower variance.
"""
compute_multiplier: Union[Literal["auto"], float, None] = None
"""
... | ReinforcementHyperparameters |
python | kamyu104__LeetCode-Solutions | Python/count-connected-components-in-lcm-graph.py | {
"start": 781,
"end": 1522
} | class ____(object):
def countComponents(self, nums, threshold):
"""
:type nums: List[int]
:type threshold: int
:rtype: int
"""
uf = UnionFind(threshold)
lookup = [-1]*threshold
result = len(nums)
for x in nums:
if x-1 >= threshold:
... | Solution |
python | python__mypy | mypyc/ir/func_ir.py | {
"start": 8024,
"end": 15944
} | class ____:
"""Intermediate representation of a function with contextual information.
Unlike FuncDecl, this includes the IR of the body (basic blocks).
"""
def __init__(
self,
decl: FuncDecl,
arg_regs: list[Register],
blocks: list[BasicBlock],
line: int = -1,
... | FuncIR |
python | openai__openai-python | src/openai/types/audio/transcription_text_delta_event.py | {
"start": 249,
"end": 564
} | class ____(BaseModel):
token: Optional[str] = None
"""The token that was used to generate the log probability."""
bytes: Optional[List[int]] = None
"""The bytes that were used to generate the log probability."""
logprob: Optional[float] = None
"""The log probability of the token."""
| Logprob |
python | apache__airflow | airflow-core/tests/unit/utils/test_file.py | {
"start": 3366,
"end": 11412
} | class ____:
@pytest.fixture
def test_dir(self, tmp_path):
# create test tree with symlinks
source = os.path.join(tmp_path, "folder")
target = os.path.join(tmp_path, "symlink")
py_file = os.path.join(source, "hello_world.py")
ignore_file = os.path.join(tmp_path, ".airflowi... | TestListPyFilesPath |
python | tensorflow__tensorflow | tensorflow/python/distribute/remote_mirrored_strategy_eager_test.py | {
"start": 1574,
"end": 2348
} | class ____(
multi_worker_test_base.SingleWorkerTestBaseEager,
strategy_test_lib.RemoteSingleWorkerMirroredStrategyBase):
def _get_num_gpus(self):
return len(get_gpus())
def testNumReplicasInSync(self, distribution):
self._testNumReplicasInSync(distribution)
def testMinimizeLoss(self, distributi... | RemoteSingleWorkerMirroredStrategyEager |
python | lazyprogrammer__machine_learning_examples | rl2/atari/dqn_tf.py | {
"start": 1024,
"end": 1793
} | class ____:
def __init__(self):
with tf.variable_scope("image_transformer"):
self.input_state = tf.placeholder(shape=[210, 160, 3], dtype=tf.uint8)
self.output = tf.image.rgb_to_grayscale(self.input_state)
self.output = tf.image.crop_to_bounding_box(self.output, 34, 0, 160, 160)
self.outpu... | ImageTransformer |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_matmul_op_test.py | {
"start": 4688,
"end": 6790
} | class ____(test.TestCase):
def _testGradients(self, tr_a, tr_b, sp_a, sp_b, a_dtype, b_dtype, delta,
name):
with self.cached_session():
a = constant_op.constant(
RandMatrix(
3, 2, tr_a, round_bfloat=True), dtype=dtypes.float32)
b = constant_op.constant(
... | MatMulGradientTest |
python | sqlalchemy__sqlalchemy | test/orm/test_transaction.py | {
"start": 48080,
"end": 55564
} | class ____(_LocalFixture):
__sparse_driver_backend__ = True
@testing.requires.savepoints
def test_savepoint_rollback(self):
User = self.classes.User
s = fixture_session()
u1 = User(name="ed")
u2 = User(name="jack")
s.add_all([u1, u2])
nt1 = s.begin_nested()
... | SavepointTest |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_bytes.py | {
"start": 3168,
"end": 5515
} | class ____(BaseTestZDType):
test_cls = VariableLengthBytes
valid_dtype = (np.dtype("|O"),)
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.float64),
np.dtype("|U10"),
)
valid_json_v2 = ({"name": "|O", "object_codec_id": "vlen-bytes"},)
valid_json_v3 = ("variable_length_b... | TestVariableLengthBytes |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_engine.py | {
"start": 1059,
"end": 13854
} | class ____(fixtures.TestBase):
def test_pyodbc_connect_dsn_trusted(self):
dialect = pyodbc.dialect()
u = url.make_url("mssql+pyodbc://mydsn")
connection = dialect.create_connect_args(u)
eq_((("dsn=mydsn;Trusted_Connection=Yes",), {}), connection)
def test_pyodbc_connect_old_styl... | ParseConnectTest |
python | getsentry__sentry | tests/sentry/flags/endpoints/test_logs.py | {
"start": 198,
"end": 13192
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-flag-logs"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.url = reverse(self.endpoint, args=(self.organization.id,))
@property
def features(self) -> dict[str, bool]:
return {}
... | OrganizationFlagLogIndexEndpointTestCase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 2930,
"end": 3038
} | class ____(Contra_TA[Contra_TA[Contra_TA[T_co]]]): ...
Ts = TypeVarTuple("Ts")
| ContraToContraToContra_WithTA |
python | huggingface__transformers | src/transformers/models/aimv2/modular_aimv2.py | {
"start": 13235,
"end": 13280
} | class ____(LlamaRMSNorm):
pass
| Aimv2RMSNorm |
python | realpython__materials | python-absolute-value/sample_code.py | {
"start": 95,
"end": 313
} | class ____:
def __init__(self, *coordinates):
self.coordinates = coordinates
def __abs__(self):
origin = [0] * len(self.coordinates)
return math.dist(origin, self.coordinates)
| VectorBound |
python | rapidsai__cudf | python/cudf/cudf/core/udf/masked_typing.py | {
"start": 13028,
"end": 13529
} | class ____(AbstractTemplate):
"""
Typing for float(Masked)
returns the result of calling "float" on the input
TODO: retains the validity of the input rather than
raising as in float(pd.NA)
"""
def generic(self, args, kws):
if isinstance(args[0], MaskedType):
# following ... | MaskedScalarFloatCast |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/cholesky_op_test.py | {
"start": 8136,
"end": 11928
} | class ____(test.TestCase):
_backprop_block_size = 16
def getShapes(self, shapeList):
return ((elem, int(np.floor(1.2 * elem))) for elem in shapeList)
@test_util.run_in_graph_and_eager_modes(use_gpu=True)
def testSmallMatrices(self):
np.random.seed(0)
shapes = self.getShapes([1, 2, 10])
self.ru... | CholeskyGradTest |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/llm_checker/base.py | {
"start": 2194,
"end": 6786
} | class ____(Chain):
"""Chain for question-answering with self-verification.
Example:
```python
from langchain_openai import OpenAI
from langchain_classic.chains import LLMCheckerChain
model = OpenAI(temperature=0.7)
checker_chain = LLMCheckerChain.from_llm(model)
... | LLMCheckerChain |
python | openai__openai-python | src/openai/types/realtime/realtime_transcription_session_audio_input_turn_detection_param.py | {
"start": 2314,
"end": 3320
} | class ____(TypedDict, total=False):
type: Required[Literal["semantic_vad"]]
"""Type of turn detection, `semantic_vad` to turn on Semantic VAD."""
create_response: bool
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
eagerness: Literal["low", "m... | SemanticVad |
python | getsentry__sentry | src/sentry/hybridcloud/services/organizationmember_mapping/impl.py | {
"start": 818,
"end": 4369
} | class ____(OrganizationMemberMappingService):
def upsert_mapping(
self,
*,
organization_id: int,
organizationmember_id: int,
mapping: RpcOrganizationMemberMappingUpdate,
) -> RpcOrganizationMemberMapping:
def apply_update(orm_mapping: OrganizationMemberMapping) ->... | DatabaseBackedOrganizationMemberMappingService |
python | kamyu104__LeetCode-Solutions | Python/find-all-good-indices.py | {
"start": 42,
"end": 592
} | class ____(object):
def goodIndices(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
left = [1]*len(nums)
for i in xrange(1, len(nums)-1):
if nums[i] <= nums[i-1]:
left[i] = left[i-1]+1
right = [1... | Solution |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py | {
"start": 85128,
"end": 90251
} | class ____:
edges = [
(1, 3),
(3, 2),
(3, 4),
(4, 9),
(4, 5),
(3, 9),
(5, 8),
(5, 7),
(8, 7),
(7, 6),
]
mapped = {
0: "x",
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
6: "f",
... | TestDiGraphTinoutUpdating |
python | wireservice__csvkit | csvkit/grep.py | {
"start": 78,
"end": 4344
} | class ____:
r"""
Given any row iterator, only return rows which pass the filter.
If 'header' is False, then all rows must pass the filter; by default, the first row will be passed
through untested.
The value of patterns may be either a sequence or a dictionary. Items in the sequence and values in ... | FilteringCSVReader |
python | getsentry__sentry | src/sentry/api/endpoints/source_map_debug_blue_thunder_edition.py | {
"start": 3167,
"end": 3370
} | class ____(TypedDict):
debug_id_process: SourceMapDebugIdProcessResult
release_process: SourceMapReleaseProcessResult | None
scraping_process: SourceMapScrapingProcessResult
| SourceMapDebugFrame |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 1555,
"end": 1652
} | class ____(ClassF[T]):
def __init__(self, val: T) -> None:
super().__init__(val)
| ClassG |
python | sympy__sympy | sympy/physics/quantum/spin.py | {
"start": 13414,
"end": 21415
} | class ____(UnitaryOperator):
"""Wigner D operator in terms of Euler angles.
Defines the rotation operator in terms of the Euler angles defined by
the z-y-z convention for a passive transformation. That is the coordinate
axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
thi... | Rotation |
python | doocs__leetcode | solution/0900-0999/0952.Largest Component Size by Common Factor/Solution.py | {
"start": 320,
"end": 698
} | class ____:
def largestComponentSize(self, nums: List[int]) -> int:
uf = UnionFind(max(nums) + 1)
for v in nums:
i = 2
while i <= v // i:
if v % i == 0:
uf.union(v, i)
uf.union(v, v // i)
i += 1
r... | Solution |
python | django__django | tests/serializers/models/data.py | {
"start": 4634,
"end": 4729
} | class ____(models.Model):
data = models.CharField(max_length=30, primary_key=True)
| CharPKData |
python | protocolbuffers__protobuf | upb/cmake/staleness_test_lib.py | {
"start": 2111,
"end": 6136
} | class ____(object):
"""Represents the configuration for a single staleness test target."""
def __init__(self, file_list):
# Duplicate to avoid modifying our arguments.
file_list = list(file_list)
# The file list contains a few other bits of information at the end.
# This is packed by the code in b... | Config |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_geometry_to_be_of_type.py | {
"start": 1684,
"end": 7528
} | class ____(ColumnMapExpectation):
"""Expect values in a column to belong to one of the specified geometry types.
Args:
column (str): \
The column name.
geom_types_list (str): \
List of shapely geometry types to match against. \
e.g: Point, Polygon, LineString... | ExpectColumnValuesGeometryToBeOfType |
python | PrefectHQ__prefect | src/prefect/utilities/pydantic.py | {
"start": 6889,
"end": 13132
} | class ____(Generic[M]):
"""
A utility for creating a Pydantic model in several steps.
Fields may be set at initialization, via attribute assignment, or at finalization
when the concrete model is returned.
Pydantic validation does not occur until finalization.
Each field can only be set once a... | PartialModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-tplcentral/source_tplcentral/streams.py | {
"start": 6735,
"end": 8163
} | class ____(IncrementalTplcentralStream):
# https://api.3plcentral.com/rels/inventory/inventory
upstream_primary_key = "ReceiveItemId"
upstream_cursor_field = "ReceivedDate"
collection_field = "ResourceList"
page_size = 1000
def path(self, **kwargs) -> str:
return "inventory"
def re... | Inventory |
python | kamyu104__LeetCode-Solutions | Python/maximum-energy-boost-from-two-drinks.py | {
"start": 34,
"end": 410
} | class ____(object):
def maxEnergyBoost(self, energyDrinkA, energyDrinkB):
"""
:type energyDrinkA: List[int]
:type energyDrinkB: List[int]
:rtype: int
"""
dp = [0]*2
for i in xrange(len(energyDrinkA)):
dp = [max(dp[0]+energyDrinkA[i], dp[1]), max(dp... | Solution |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 38727,
"end": 39589
} | class ____(IntegralTransform):
"""
Base class for sine and cosine transforms.
Specify cls._kern.
"""
def a(self):
raise NotImplementedError(
"Class %s must implement a(self) but does not" % self.__class__)
def b(self):
raise NotImplementedError(
"Class %... | SineCosineTypeTransform |
python | nryoung__algorithms | tests/test_sorting.py | {
"start": 3052,
"end": 3673
} | class ____(SortingAlgorithmTestCase):
"""
Tests Quick sort in place version on a small range from 0-9
also tests partition function included in quick sort
"""
def test_quicksort_in_place(self):
self.output = quick_sort_in_place.sort(
self.input, 0,
len(self.input)-1
... | TestQuickSortInPlace |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 5364,
"end": 5811
} | class ____(CtrlNode):
"""Removes anomalous spikes from data, replacing with nearby values"""
nodeName = 'DenoiseFilter'
uiTemplate = [
('radius', 'intSpin', {'value': 2, 'min': 0, 'max': 1000000}),
('threshold', 'doubleSpin', {'value': 4.0, 'min': 0, 'max': 1000})
]
def processD... | Denoise |
python | streamlit__streamlit | lib/streamlit/elements/widgets/button.py | {
"start": 3191,
"end": 54744
} | class ____:
@gather_metrics("button")
def button(
self,
label: str,
key: Key | None = None,
help: str | None = None,
on_click: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwargs: WidgetKwargs | None = None,
*, # keyword-only argu... | ButtonMixin |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/backfills.py | {
"start": 1074,
"end": 1388
} | class ____(StrictBaseModel):
"""Object used for create backfill request."""
dag_id: str
from_date: datetime
to_date: datetime
run_backwards: bool = False
dag_run_conf: dict = {}
reprocess_behavior: ReprocessBehavior = ReprocessBehavior.NONE
max_active_runs: int = 10
| BackfillPostBody |
python | weaviate__weaviate-python-client | mock_tests/conftest.py | {
"start": 9347,
"end": 11719
} | class ____(weaviate_pb2_grpc.WeaviateServicer):
search_count = 0
tenants_count = 0
def Search(
self, request: search_get_pb2.SearchRequest, context: grpc.ServicerContext
) -> search_get_pb2.SearchReply:
if self.search_count == 0:
self.search_count += 1
context.se... | MockRetriesWeaviateService |
python | tornadoweb__tornado | tornado/template.py | {
"start": 19267,
"end": 19917
} | class ____(_Node):
def __init__(self, template: Template, body: "_ChunkList") -> None:
self.template = template
self.body = body
self.line = 0
def generate(self, writer: "_CodeWriter") -> None:
writer.write_line("def _tt_execute():", self.line)
with writer.indent():
... | _File |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 16419,
"end": 16762
} | class ____:
"""
Page 84, PDF 1.4 reference.
Page 115, PDF 2.0 reference.
"""
SINGLE_PAGE = "/SinglePage"
ONE_COLUMN = "/OneColumn"
TWO_COLUMN_LEFT = "/TwoColumnLeft"
TWO_COLUMN_RIGHT = "/TwoColumnRight"
TWO_PAGE_LEFT = "/TwoPageLeft" # (PDF 1.5)
TWO_PAGE_RIGHT = "/TwoPageRight"... | PageLayouts |
python | doocs__leetcode | solution/3100-3199/3106.Lexicographically Smallest String After Operations With Constraint/Solution.py | {
"start": 0,
"end": 427
} | class ____:
def getSmallestString(self, s: str, k: int) -> str:
cs = list(s)
for i, c1 in enumerate(s):
for c2 in ascii_lowercase:
if c2 >= c1:
break
d = min(ord(c1) - ord(c2), 26 - ord(c1) + ord(c2))
if d <= k:
... | Solution |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 28701,
"end": 29206
} | class ____(CompositeTransform, BaseStretch):
"""
A combination of two stretches.
Parameters
----------
stretch_1 : :class:`astropy.visualization.BaseStretch`
The first stretch to apply.
stretch_2 : :class:`astropy.visualization.BaseStretch`
The second stretch to apply.
"""
... | CompositeStretch |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 22427,
"end": 22484
} | class ____(Interface):
pass
@implementer(IDummy)
| IDummy |
python | networkx__networkx | networkx/algorithms/tests/test_euler.py | {
"start": 3712,
"end": 4288
} | class ____:
def test_is_semieulerian(self):
# Test graphs with Eulerian paths but no cycles return True.
assert nx.is_semieulerian(nx.path_graph(4))
G = nx.path_graph(6, create_using=nx.DiGraph)
assert nx.is_semieulerian(G)
# Test graphs with Eulerian cycles return False.
... | TestIsSemiEulerian |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-build-sturdy-brick-wall.py | {
"start": 94,
"end": 1308
} | class ____(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
def backtracking(height, width, bricks, total, mask, lookup, patterns):
if mask in ... | Solution |
python | google__jax | tests/experimental_rnn_test.py | {
"start": 878,
"end": 9182
} | class ____(jtu.JaxTestCase):
@jtu.sample_product(
batch_size=[1, 4],
seq_len=[1, 4],
input_size=[1, 2],
hidden_size=[1, 6],
num_layers=[1, 4],
bidirectional=[True, False],
)
@jtu.run_on_devices("cuda", "rocm")
@jax.default_matmul_precision("float32")
def test_lstm(self, ba... | RnnTest |
python | keon__algorithms | tests/test_maths.py | {
"start": 15057,
"end": 16289
} | class ____(unittest.TestCase):
def test_k_three(self):
# Example which should give the answer 143
# which is the smallest possible x that
# solves the system of equations
num = [3, 7, 10]
rem = [2, 3, 3]
self.assertEqual(chinese_remainder_theorem.
... | TestChineseRemainderSolver |
python | huggingface__transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | {
"start": 23127,
"end": 27343
} | class ____(nn.Module):
def __init__(
self,
config,
n_bins,
n_attractors=16,
min_depth=1e-3,
max_depth=10,
memory_efficient=False,
):
"""
Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)
... | ZoeDepthAttractorLayer |
python | celery__celery | t/unit/events/test_state.py | {
"start": 10427,
"end": 22261
} | class ____:
def test_repr(self):
assert repr(State())
def test_pickleable(self):
state = State()
r = ev_logical_clock_ordering(state)
r.play()
assert pickle.loads(pickle.dumps(state))
def test_task_logical_clock_ordering(self):
state = State()
r = e... | test_State |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 114739,
"end": 115530
} | class ____(BaseModel, extra="forbid"):
shard_key: Optional["ShardKeySelector"] = Field(
default=None,
description="Specify in which shards to look for the points, if not specified - look in all shards",
)
filter: Optional["Filter"] = Field(default=None, description="Look only for points whic... | SearchMatrixRequest |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 48062,
"end": 48314
} | class ____(VOTableSpecError):
"""
The table had only *x* fields defined, but the data itself has more
columns than that.
"""
message_template = "Data has more columns than are defined in the header ({})"
default_args = ("x",)
| E20 |
python | joke2k__faker | faker/providers/currency/el_GR/__init__.py | {
"start": 46,
"end": 5680
} | class ____(CurrencyProvider):
# Source https://el.wikipedia.org/wiki/Κατάλογος_νομισμάτων_των_χωρών_του_κόσμου
# Format: (code, name)
currencies = (
("AED", "Ντιρχάμ των Ηνωμένων Αραβικών Εμιράτων"),
("AFN", "Αφγάνι"),
("ALL", "Λεκ"),
("AMD", "Ντραμ"),
("AOA", "Κουάνζ... | Provider |
python | astropy__astropy | astropy/io/fits/hdu/compressed/_codecs.py | {
"start": 8694,
"end": 10423
} | class ____(Codec):
"""
The FITS PLIO1 compression and decompression algorithm.
The IRAF PLIO (pixel list) algorithm was developed to store integer-valued
image masks in a compressed form. Such masks often have large regions of
constant value hence are highly compressible. The compression algorithm
... | PLIO1 |
python | paramiko__paramiko | tests/agent.py | {
"start": 320,
"end": 469
} | class ____(AgentKey):
def __init__(self, name, blob):
self.name = name
self.blob = blob
self.inner_key = None
| _BareAgentKey |
python | doocs__leetcode | solution/2200-2299/2202.Maximize the Topmost Element After K Moves/Solution.py | {
"start": 0,
"end": 354
} | class ____:
def maximumTop(self, nums: List[int], k: int) -> int:
if k == 0:
return nums[0]
n = len(nums)
if n == 1:
if k % 2:
return -1
return nums[0]
ans = max(nums[: k - 1], default=-1)
if k < n:
ans = max(ans... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_tensor_shape_test.py | {
"start": 1251,
"end": 21585
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def assertShapeEq(self, x, y):
assert isinstance(x, RaggedTensorDynamicShape)
assert isinstance(y, RaggedTensorDynamicShape)
self.assertLen(x.partitioned_dim_sizes, len(y.partitioned_dim_sizes))
for x_dims, ... | RaggedTensorShapeTest |
python | sympy__sympy | sympy/series/fourier.py | {
"start": 3947,
"end": 12746
} | class ____(SeriesBase):
r"""Represents Fourier sine/cosine series.
Explanation
===========
This class only represents a fourier series.
No computation is performed.
For how to compute Fourier series, see the :func:`fourier_series`
docstring.
See Also
========
sympy.series.fo... | FourierSeries |
python | huggingface__transformers | src/transformers/trainer_callback.py | {
"start": 10340,
"end": 12795
} | class ____(ExportableState):
"""
A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some
switches in the training loop.
Args:
should_training_stop (`bool`, *optional*, defaults to `False`):
Whether or not the training should ... | TrainerControl |
python | kamyu104__LeetCode-Solutions | Python/subsequence-sum-after-capping-elements.py | {
"start": 89,
"end": 795
} | class ____(object):
def subsequenceSumAfterCapping(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[bool]
"""
result = [False]*len(nums)
nums.sort()
mask = (1<<(k+1))-1
dp = 1
i = 0
for x in xrange(1, len(nums... | Solution |
python | kamyu104__LeetCode-Solutions | Python/count-number-of-pairs-with-absolute-difference-k.py | {
"start": 50,
"end": 495
} | class ____(object):
def countKDifference(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
lookup = collections.defaultdict(int)
result = 0
for x in nums:
if x-k in lookup:
result += lookup[x-k]
... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/transfers/test_s3_to_gcs.py | {
"start": 2813,
"end": 11857
} | class ____:
def test_init(self):
"""Test S3ToGCSOperator instance is properly initialized."""
operator = S3ToGCSOperator(
task_id=TASK_ID,
bucket=S3_BUCKET,
prefix=S3_PREFIX,
delimiter=S3_DELIMITER,
gcp_conn_id=GCS_CONN_ID,
des... | TestS3ToGoogleCloudStorageOperator |
python | pypa__warehouse | tests/unit/tuf/test_tuf.py | {
"start": 129,
"end": 2560
} | class ____:
server = "rstuf.api"
task_id = "123456"
def test_get_task_state(self, monkeypatch):
state = "SUCCESS"
resp_json = {"data": {"state": state}}
resp = stub(
raise_for_status=(lambda *a: None), json=(lambda *a, **kw: resp_json)
)
get = call_recor... | TestTUF |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVar4.py | {
"start": 308,
"end": 1408
} | class ____(Generic[_T, _T_co, _T_contra]):
def func1(self, a: _T):
pass
# This should generate an error because covariant
# TypeVars are not allowed for input parameters.
def func2(self, a: _T_co):
def inner(b: _T_co) -> None:
pass
return inner
def func3(self, ... | ClassA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol8.py | {
"start": 140,
"end": 303
} | class ____(Protocol):
def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None: ...
def f(*args: Any, kwarg0: Any, kwarg1: Any) -> None: ...
p: P = f
| P |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/core.py | {
"start": 4765,
"end": 28274
} | class ____:
"""
Add an explicit input to a Hypothesis test, which Hypothesis will always
try before generating random inputs. This combines the randomized nature of
Hypothesis generation with a traditional parametrized test.
For example:
.. code-block:: python
@example("Hello world")
... | example |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/templater.py | {
"start": 1445,
"end": 1879
} | class ____(ResolveMixin):
"""
A wrapper for a value that should be rendered as-is, without applying jinja templating to its contents.
:param value: The value to be rendered without templating
"""
value: Any
def iter_references(self) -> Iterable[tuple[Operator, str]]:
return ()
de... | LiteralValue |
python | mlflow__mlflow | tests/transformers/test_transformers_llm_inference_utils.py | {
"start": 1362,
"end": 2476
} | class ____:
def __call__(self, text: str, **kwargs):
input_ids = list(map(int, text.split(" ")))
return {"input_ids": torch.tensor([input_ids])}
def decode(self, tensor, **kwargs):
if isinstance(tensor, torch.Tensor):
tensor = tensor.tolist()
return " ".join([str(x) ... | DummyTokenizer |
python | walkccc__LeetCode | solutions/3501. Maximize Active Section with Trade II/3501.py | {
"start": 696,
"end": 3641
} | class ____:
def maxActiveSectionsAfterTrade(
self,
s: str,
queries: list[list[int]]
) -> list[int]:
ones = s.count('1')
zeroGroups, zeroGroupIndex = self._getZeroGroups(s)
if not zeroGroups:
return [ones] * len(queries)
st = SparseTable(self._getZeroMergeLengths(zeroGroups))... | Solution |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/regression.py | {
"start": 418,
"end": 684
} | class ____():
""" Regularization for Ridge Regression """
def __init__(self, alpha):
self.alpha = alpha
def __call__(self, w):
return self.alpha * 0.5 * w.T.dot(w)
def grad(self, w):
return self.alpha * w
| l2_regularization |
python | openai__openai-python | src/openai/resources/models.py | {
"start": 9999,
"end": 10440
} | class ____:
def __init__(self, models: AsyncModels) -> None:
self._models = models
self.retrieve = _legacy_response.async_to_raw_response_wrapper(
models.retrieve,
)
self.list = _legacy_response.async_to_raw_response_wrapper(
models.list,
)
se... | AsyncModelsWithRawResponse |
python | ansible__ansible | lib/ansible/module_utils/facts/network/freebsd.py | {
"start": 1029,
"end": 1137
} | class ____(NetworkCollector):
_fact_class = FreeBSDNetwork
_platform = 'FreeBSD'
| FreeBSDNetworkCollector |
python | OmkarPathak__pygorithm | pygorithm/data_structures/graph.py | {
"start": 7566,
"end": 8836
} | class ____(Graph):
def topological_sort(self):
"""
function for sorting graph elements using topological sort
"""
# Marking all vertices as not visited
visited = [False] * self.count
# Stack for storing the vertex
stack = []
for vertex in range(self.c... | TopologicalSort |
python | joblib__joblib | joblib/externals/loky/backend/process.py | {
"start": 324,
"end": 1139
} | class ____(BaseProcess):
_start_method = "loky"
def __init__(
self,
group=None,
target=None,
name=None,
args=(),
kwargs={},
daemon=None,
init_main_module=False,
env=None,
):
super().__init__(
group=group,
... | LokyProcess |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 6409,
"end": 13288
} | class ____(nn.Module):
def __init__(self, config: Gemma3nAudioConfig):
super().__init__()
self.config = config
self.num_heads = self.config.conf_num_attention_heads
self.channels = self.config.hidden_size
self.head_dim = self.channels // self.num_heads
self.max_backw... | Gemma3nAudioRelativePositionEmbedding |
python | pypa__pip | src/pip/_vendor/dependency_groups/_implementation.py | {
"start": 1706,
"end": 8041
} | class ____:
"""
A resolver for Dependency Group data.
This class handles caching, name normalization, cycle detection, and other
parsing requirements. There are only two public methods for exploring the data:
``lookup()`` and ``resolve()``.
:param dependency_groups: A mapping, as provided via ... | DependencyGroupResolver |
python | PrefectHQ__prefect | src/integrations/prefect-azure/tests/conftest.py | {
"start": 6002,
"end": 6600
} | class ____(MagicMock):
def from_connection_string(connection_string):
return CosmosClientMock()
def get_client(self):
return CosmosClientMock(client="client")
def get_database_client(self, database):
return CosmosClientMock(database=database)
def get_container_client(self, con... | CosmosClientMock |
python | walkccc__LeetCode | solutions/139. Word Break/139.py | {
"start": 0,
"end": 366
} | class ____:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
wordSet = set(wordDict)
@functools.lru_cache(None)
def wordBreak(s: str) -> bool:
"""Returns True if s can be segmented."""
if s in wordSet:
return True
return any(s[:i] in wordSet and wordBreak(s[i:]) for i i... | Solution |
python | FactoryBoy__factory_boy | factory/builder.py | {
"start": 6584,
"end": 7841
} | class ____:
def __init__(self, builder, sequence, parent_step=None):
self.builder = builder
self.sequence = sequence
self.attributes = {}
self.parent_step = parent_step
self.stub = None
def resolve(self, declarations):
self.stub = Resolver(
declaratio... | BuildStep |
python | docker__docker-py | scripts/versions.py | {
"start": 232,
"end": 2186
} | class ____(namedtuple('_Version', 'major minor patch stage edition')):
@classmethod
def parse(cls, version):
edition = None
version = version.lstrip('v')
version, _, stage = version.partition('-')
if stage:
if not any(marker in stage for marker in STAGES):
... | Version |
python | django__django | tests/proxy_models/tests.py | {
"start": 863,
"end": 14438
} | class ____(TestCase):
def test_same_manager_queries(self):
"""
The MyPerson model should be generating the same database queries as
the Person model (when the same manager is used in each case).
"""
my_person_sql = (
MyPerson.other.all().query.get_compiler(DEFAULT... | ProxyModelTests |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/lexers/pygments.py | {
"start": 4070,
"end": 4517
} | class ____(Dict[Tuple[str, ...], str]):
"""
Cache that converts Pygments tokens into `prompt_toolkit` style objects.
``Token.A.B.C`` will be converted into:
``class:pygments,pygments.A,pygments.A.B,pygments.A.B.C``
"""
def __missing__(self, key: tuple[str, ...]) -> str:
result = "class... | _TokenCache |
python | scikit-learn__scikit-learn | sklearn/ensemble/_gb.py | {
"start": 13779,
"end": 43921
} | class ____(BaseEnsemble, metaclass=ABCMeta):
"""Abstract base class for Gradient Boosting."""
_parameter_constraints: dict = {
**DecisionTreeRegressor._parameter_constraints,
"learning_rate": [Interval(Real, 0.0, None, closed="left")],
"n_estimators": [Interval(Integral, 1, None, closed... | BaseGradientBoosting |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 15696,
"end": 16009
} | class ____(BaseModel):
"""
Serializer for Plugin FastAPI App responses.
"""
model_config = ConfigDict(
extra="allow",
)
app: Annotated[str, Field(title="App")]
url_prefix: Annotated[str, Field(title="Url Prefix")]
name: Annotated[str, Field(title="Name")]
| FastAPIAppResponse |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 79398,
"end": 85391
} | class ____:
gensym: Callable[[AbstractValue], Var]
constid_to_tracer: WeakValueDictionary[ConstId, DynamicJaxprTracer]
constvar_to_val: dict[Var, Constants]
tracing_eqns: list[Union[ReferenceType[TracingEqn], Callable[[], TracingEqn]]]
invars: list[Var]
effects: core.Effects
debug_info: core.DebugInfo
i... | JaxprStackFrame |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 7778,
"end": 8689
} | class ____(serializers.Serializer[Never]):
query = serializers.CharField(required=False, allow_null=True)
span = serializers.CharField(required=True, allow_null=False)
min_exclusive_time = serializers.FloatField(required=False)
max_exclusive_time = serializers.FloatField(required=False)
def validat... | SpanSerializer |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 15972,
"end": 16479
} | class ____:
param_names = ["shape", "tail_count"]
params = [
get_benchmark_shapes("TimeTail"),
[5, 0.8],
]
def setup(self, shape, tail_count):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
self.tail_count = (
int(tail_count * len(self.df.in... | TimeTail |
python | google__pytype | pytype/rewrite/abstract/internal.py | {
"start": 745,
"end": 1632
} | class ____(base.BaseValue):
"""Representation of a function kwarg dict."""
def __init__(
self,
ctx: base.ContextType,
constant: dict[str, _Var] | None = None,
indefinite: bool = False,
):
super().__init__(ctx)
constant = constant or {}
self._check_keys(constant)
self.const... | FunctionArgDict |
python | django__django | tests/forms_tests/tests/test_media.py | {
"start": 32502,
"end": 36502
} | class ____(SimpleTestCase):
"""Media handling when media are objects instead of raw strings."""
def test_construction(self):
m = Media(
css={
"all": (
CSS("path/to/css1", media="all"),
CSS("/path/to/css2", media="all"),
... | FormsMediaObjectTestCase |
python | huggingface__transformers | tests/models/deepseek_vl_hybrid/test_image_processing_deepseek_vl_hybrid.py | {
"start": 3740,
"end": 12878
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = DeepseekVLHybridImageProcessor if is_vision_available() else None
fast_image_processing_class = DeepseekVLHybridImageProcessorFast if is_torchvision_available() else None
# Copied from tests.models.vit.test_image_processing_v... | DeepseekVLHybridImageProcessingTest |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 36327,
"end": 38765
} | class ____(NestedType):
"""
Struct composite type.
Parameters
----------
fields
The fields that make up the struct. Can be either a sequence of Field
objects or a mapping of column names to data types.
Examples
--------
Initialize using a dictionary:
>>> dtype = pl... | Struct |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/comprehension7.py | {
"start": 216,
"end": 391
} | class ____:
var1 = [1, 2]
var2 = {x for x in var1}
# This should generate an error.
var3 = {var1[0] for x in var1}
var4 = {outer_var[0] for x in outer_var}
| A |
python | readthedocs__readthedocs.org | readthedocs/organizations/migrations/0015_remove_unused_indexes.py | {
"start": 150,
"end": 1201
} | class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("organizations", "0014_update_dj_simple_history"),
]
operations = [
migrations.AlterField(
model_name="historicalorganization",
name="extra_history_user_id",
field=models... | Migration |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 15219,
"end": 15330
} | class ____(SubscriptMixin, TestCase):
def _getFUT(self):
return queue.PriorityQueue
| TestPriorityQueue |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 1860,
"end": 3325
} | class ____(HasDescriptionCode, Exception):
"""Generic error class."""
def _message(self) -> str:
# rules:
#
# 1. single arg string will usually be a unicode
# object, but since __str__() must return unicode, check for
# bytestring just in case
#
# 2. for ... | SQLAlchemyError |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/comments.py | {
"start": 8560,
"end": 8870
} | class ____:
"""store tag information for roundtripping"""
__slots__ = ('value',)
attrib = tag_attrib
def __init__(self):
# type: () -> None
self.value = None
def __repr__(self):
# type: () -> Any
return '{0.__class__.__name__}({0.value!r})'.format(self)
| Tag |
python | encode__django-rest-framework | tests/test_utils.py | {
"start": 7922,
"end": 8515
} | class ____(TestCase):
def test_it_formats_correctly(self):
formatted = lazy_format('Does {} work? {answer}: %s', 'it', answer='Yes')
assert str(formatted) == 'Does it work? Yes: %s'
assert formatted % 'it does' == 'Does it work? Yes: it does'
def test_it_formats_lazily(self):
me... | LazyFormatTests |
python | google__pytype | pytype/rewrite/tests/test_basic.py | {
"start": 2049,
"end": 2709
} | class ____(RewriteTest):
"""Operator tests."""
def test_type_subscript(self):
self.Check("""
IntList = list[int]
def f(xs: IntList) -> list[str]:
return ["hello world"]
a = f([1, 2, 3])
assert_type(a, list)
""")
def test_binop(self):
self.Check("""
x = 1
y... | OperatorsTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.