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 | walkccc__LeetCode | solutions/2502. Design Memory Allocator/2502.py | {
"start": 0,
"end": 716
} | class ____:
def __init__(self, n: int):
self.memory = [0] * n
self.mIDToIndices = [[] for _ in range(1001)]
def allocate(self, size: int, mID: int) -> int:
consecutiveFree = 0
for i, m in enumerate(self.memory):
consecutiveFree = consecutiveFree + 1 if m == 0 else 0
if consecutiveFree =... | Allocator |
python | has2k1__plotnine | plotnine/stats/stat_pointdensity.py | {
"start": 292,
"end": 2368
} | class ____(stat):
"""
Compute density estimation for each point
{usage}
Parameters
----------
{common_parameters}
package : Literal["statsmodels", "scipy", "sklearn"], default="statsmodels"
Package whose kernel density estimation to use.
kde_params : dict, default=None
... | stat_pointdensity |
python | ipython__ipython | IPython/core/magics/script.py | {
"start": 2380,
"end": 2443
} | class ____(Exception):
pass
@magics_class
| RaiseAfterInterrupt |
python | matplotlib__matplotlib | lib/matplotlib/backend_tools.py | {
"start": 26783,
"end": 28986
} | class ____(ZoomPanBase):
"""Pan Axes with left mouse, zoom with right."""
default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
description = 'Pan axes with left mouse, zoom with right'
image = 'mpl-data/images/move'
cursor = cursors.MOVE
radio_group = 'default'
def __init__(s... | ToolPan |
python | apache__airflow | providers/oracle/src/airflow/providers/oracle/transfers/oracle_to_oracle.py | {
"start": 1097,
"end": 3631
} | class ____(BaseOperator):
"""
Moves data from Oracle to Oracle.
:param oracle_destination_conn_id: destination Oracle connection.
:param destination_table: destination table to insert rows.
:param oracle_source_conn_id: :ref:`Source Oracle connection <howto/connection:oracle>`.
:param source_sq... | OracleToOracleOperator |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 59197,
"end": 62700
} | class ____(MegatronBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = MegatronBertModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize w... | MegatronBertForQuestionAnswering |
python | kamyu104__LeetCode-Solutions | Python/largest-magic-square.py | {
"start": 55,
"end": 1487
} | class ____(object):
def largestMagicSquare(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def get_sum(prefix, a, b):
return prefix[b+1]-prefix[a]
def check(grid, prefix_row, prefix_col, l, i, j):
diag, anti_diag = 0, 0
... | Solution |
python | scikit-image__scikit-image | src/skimage/_shared/utils.py | {
"start": 16007,
"end": 16210
} | class ____(AttributeError):
"""Error from use of failed estimation instance
This error arises from attempts to use an instance of
:class:`FailedEstimation`.
"""
| FailedEstimationAccessError |
python | vyperlang__vyper | tests/evm_backends/abi_contract.py | {
"start": 10236,
"end": 12639
} | class ____:
"""A contract that has been deployed to the blockchain and created via an ABI."""
@property
def address(self) -> HexAddress:
assert self._address is not None
return self._address
def __init__(
self,
env: "BaseEnv",
name: str,
abi: dict,
... | ABIContract |
python | kamyu104__LeetCode-Solutions | Python/palindrome-pairs.py | {
"start": 4074,
"end": 4443
} | class ____(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
res = []
trie = TrieNode()
for i in xrange(len(words)):
trie.insert(words[i], i)
for i in xrange(len(words)):
trie.fin... | Solution_MLE |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/runs.py | {
"start": 4749,
"end": 4937
} | class ____(graphene.Union):
class Meta:
types = (GrapheneRunIds, GrapheneInvalidPipelineRunsFilterError, GraphenePythonError)
name = "RunIdsOrError"
| GrapheneRunIdsOrError |
python | django__django | tests/lookup/test_decimalfield.py | {
"start": 107,
"end": 1467
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.p1 = Product.objects.create(name="Product1", qty_target=10)
Stock.objects.create(product=cls.p1, qty_available=5)
Stock.objects.create(product=cls.p1, qty_available=6)
cls.p2 = Product.objects.create(name="Product2", ... | DecimalFieldLookupTests |
python | ansible__ansible | lib/ansible/_internal/_ssh/_ssh_agent.py | {
"start": 16395,
"end": 17687
} | class ____(Msg):
keys: list[PublicKeyMsg]
def __iter__(self) -> t.Iterator[PublicKeyMsg]:
yield from self.keys
def __len__(self) -> int:
return len(self.keys)
@classmethod
def from_blob(cls, blob: memoryview | bytes) -> t.Self: ...
@classmethod
def consume_from_blob(cls, ... | PublicKeyMsgList |
python | scipy__scipy | scipy/optimize/tests/test_minimize_constrained.py | {
"start": 3070,
"end": 4267
} | class ____:
"""Problem 15.4 from Nocedal and Wright
The following optimization problem:
minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
Subject to: x[0]**2 + x[1]**2 - 1 = 0
"""
def __init__(self, degrees=60, constr_jac=None, constr_hess=None):
rads = degrees/180*np.pi
self.x... | MaratosGradInFunc |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 50993,
"end": 51162
} | class ____(skipIf):
def __init__(self, dep, reason):
super().__init__(dep, reason, device_type="hpu")
# Skips a test on XLA if the condition is true.
| skipHPUIf |
python | sqlalchemy__sqlalchemy | test/ext/test_automap.py | {
"start": 1168,
"end": 11653
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
FixtureTest.define_tables(metadata)
def test_relationship_o2m_default(self):
Base = automap_base(metadata=self.tables_test_metadata)
Base.prepare()
User = Base.classes.users
Address = Ba... | AutomapTest |
python | bokeh__bokeh | src/bokeh/command/subcommands/file_output.py | {
"start": 1708,
"end": 7297
} | class ____(Subcommand):
''' Abstract subcommand to output applications as some type of file.
'''
# subtype must set this instance attribute to file extension
extension: str
@classmethod
def files_arg(cls, output_type_name: str) -> Arg:
''' Returns a positional arg for ``files`` to spe... | FileOutputSubcommand |
python | huggingface__transformers | src/transformers/models/exaone4/modular_exaone4.py | {
"start": 14348,
"end": 14483
} | class ____(LlamaPreTrainedModel):
config_class = Exaone4Config
_no_split_modules = ["Exaone4DecoderLayer"]
| Exaone4PreTrainedModel |
python | doocs__leetcode | solution/1900-1999/1991.Find the Middle Index in Array/Solution.py | {
"start": 0,
"end": 240
} | class ____:
def findMiddleIndex(self, nums: List[int]) -> int:
l, r = 0, sum(nums)
for i, x in enumerate(nums):
r -= x
if l == r:
return i
l += x
return -1
| Solution |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_global_variable.py | {
"start": 377,
"end": 1003
} | class ____:
...
hello = "hello"
world: str = "world"
def g():
foo.append(1)
def h():
_test_sink(Baz)
_test_sink(_test_source())
def returns_any() -> typing.Any:
return {"hello": Baz()}
typed_global_dict: typing.Dict[str, Baz] = returns_any()
untyped_global_dict = returns_any()
typed_global... | Baz |
python | kamyu104__LeetCode-Solutions | Python/minimum-add-to-make-parentheses-valid.py | {
"start": 29,
"end": 341
} | class ____(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
add, bal, = 0, 0
for c in S:
bal += 1 if c == '(' else -1
if bal == -1:
add += 1
bal += 1
return add + bal
| Solution |
python | doocs__leetcode | solution/2500-2599/2552.Count Increasing Quadruplets/Solution.py | {
"start": 0,
"end": 811
} | class ____:
def countQuadruplets(self, nums: List[int]) -> int:
n = len(nums)
f = [[0] * n for _ in range(n)]
g = [[0] * n for _ in range(n)]
for j in range(1, n - 2):
cnt = sum(nums[l] > nums[j] for l in range(j + 1, n))
for k in range(j + 1, n - 1):
... | Solution |
python | pytorch__pytorch | torch/sparse/semi_structured.py | {
"start": 16031,
"end": 22196
} | class ____(SparseSemiStructuredTensor):
"""
This class implements semi-structured sparsity for the CUTLASS backend.
In this implementation, the specified elements and metadata are stored separately,
in packed and meta respectively.
When _FORCE_CUTLASS is set, or when cuSPARSELt is not available, ... | SparseSemiStructuredTensorCUTLASS |
python | spack__spack | lib/spack/spack/install_test.py | {
"start": 42222,
"end": 42471
} | class ____(spack.error.SpackError):
"""Raised when one or more tests in a suite have failed."""
def __init__(self, num_failures):
msg = "%d test(s) in the suite failed.\n" % num_failures
super().__init__(msg)
| TestSuiteFailure |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-people-that-can-be-caught-in-tag.py | {
"start": 631,
"end": 1223
} | class ____(object):
def catchMaximumAmountofPeople(self, team, dist):
"""
:type team: List[int]
:type dist: int
:rtype: int
"""
result = j = 0
for i in xrange(len(team)):
if not team[i]:
continue
while j < i-dist:
... | Solution2 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py | {
"start": 4133,
"end": 4165
} | class ____(TD_A1, TD_A2): ...
| TD_A |
python | PrefectHQ__prefect | src/prefect/client/schemas/responses.py | {
"start": 2176,
"end": 2852
} | class ____(PrefectBaseModel):
"""Details associated with a WAIT state transition."""
type: Literal["wait_details"] = Field(
default="wait_details",
description=(
"The type of state transition detail. Used to ensure pydantic does not"
" coerce into a different type."
... | StateWaitDetails |
python | sanic-org__sanic | sanic/compat.py | {
"start": 855,
"end": 2741
} | class ____(StrEnum):
"""Base class for string enums that are case insensitive."""
def _generate_next_value_(name, start, count, last_values):
return name.upper()
def __eq__(self, value: object) -> bool:
value = str(value).upper()
return super().__eq__(value)
def __hash__(self)... | UpperStrEnum |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 13209,
"end": 18754
} | class ____(IHaveNew):
name: str
job_name: Optional[str]
op_selection: Optional[Sequence[str]]
mode: Optional[str]
min_interval: Optional[int]
description: Optional[str]
target_dict: Mapping[str, TargetSnap]
metadata: Optional[SensorMetadataSnap]
default_status: Optional[DefaultSensor... | SensorSnap |
python | mlflow__mlflow | mlflow/metrics/genai/prompts/v1.py | {
"start": 4394,
"end": 7960
} | class ____:
definition = (
"Answer similarity is evaluated on the degree of semantic similarity of the provided "
"output to the provided targets, which is the ground truth. Scores can be assigned based "
"on the gradual similarity in meaning and description to the provided targets, where a ... | AnswerSimilarityMetric |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 1888,
"end": 1969
} | class ____(NormalModelA):
field2 = models.CharField(max_length=10)
| NormalModelB |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 8374,
"end": 8506
} | class ____(TestCase, jtu.CudaArchSpecificTest):
def setUp(self):
self.skip_unless_sm90a()
super().setUp()
| Sm90ATestCase |
python | Textualize__textual | src/textual/widgets/_tabs.py | {
"start": 5490,
"end": 27054
} | class ____(Widget, can_focus=True):
"""A row of tabs."""
DEFAULT_CSS = """
Tabs {
width: 100%;
height: 2;
&:focus {
.underline--bar {
background: $foreground 30%;
}
& .-active {
text-style: $block-cursor-text-style;... | Tabs |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/auth.py | {
"start": 213,
"end": 1432
} | class ____(Oauth2Authenticator):
def _prepare_refresh_token_params(self) -> Dict[str, str]:
return {
"refresh_token": self.get_refresh_token(),
"client_id": self.get_client_id(),
"client_secret": self.get_client_secret(),
"grant_type": "refresh_token",
... | ZohoOauth2Authenticator |
python | charliermarsh__ruff | crates/ruff_python_ast/generate.py | {
"start": 855,
"end": 2219
} | class ____:
name: str
accepts_sequence: bool = False
# Map of AST node types to their corresponding visitor information.
# Only visitors that are different from the default `visit_*` method are included.
# These visitors either have a different name or accept a sequence of items.
type_to_visitor_function: dic... | VisitorInfo |
python | getsentry__sentry | src/sentry/migrations/0925_backfill_open_periods.py | {
"start": 1168,
"end": 6988
} | class ____:
UNRESOLVED = 0
RESOLVED = 1
# end copy
def get_open_periods_for_group(
apps: StateApps,
group_id: int,
status: int,
project_id: int,
first_seen: datetime,
activities: list[Any],
GroupOpenPeriod: Any,
) -> list[Any]:
# No activities means the group has been open si... | GroupStatus |
python | tensorflow__tensorflow | tensorflow/compiler/tests/matrix_triangular_solve_op_test.py | {
"start": 1308,
"end": 7375
} | class ____(xla_test.XLATestCase):
# MatrixTriangularSolve defined for float64, float32, complex64, complex128
# (https://www.tensorflow.org/api_docs/python/tf/matrix_triangular_solve)
@property
def float_types(self):
return set(super(MatrixTriangularSolveOpTest,
self).float_types).int... | MatrixTriangularSolveOpTest |
python | matplotlib__matplotlib | galleries/examples/units/basic_units.py | {
"start": 8170,
"end": 9979
} | class ____:
def addition_rule(self, units):
for unit_1, unit_2 in itertools.pairwise(units):
if unit_1 != unit_2:
return NotImplemented
return units[0]
def multiplication_rule(self, units):
non_null = [u for u in units if u]
if len(non_null) > 1:
... | UnitResolver |
python | django__django | tests/lookup/models.py | {
"start": 2035,
"end": 2174
} | class ____(models.Model):
name = models.CharField(max_length=100)
games = models.ManyToManyField(Game, related_name="players")
| Player |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver_test.py | {
"start": 2034,
"end": 3025
} | class ____(object):
def __init__(self, tpu_map):
self._tpu_map = tpu_map
def get(self, name):
return MockRequestClass(name, self._tpu_map)
def mock_request_compute_metadata(*args, **kwargs):
del kwargs # Unused.
if args[0] == 'project/project-id':
return 'test-project'
elif args[0] == 'instan... | MockNodeClass |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/pandas_filesystem_csv.py | {
"start": 649,
"end": 1898
} | class ____(DataSourceTestConfig):
# see options: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
read_options: dict[str, Any] = field(default_factory=dict)
# see options: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html
write_options: dict[str, Any] = field(def... | PandasFilesystemCsvDatasourceTestConfig |
python | networkx__networkx | networkx/algorithms/planarity.py | {
"start": 5159,
"end": 5997
} | class ____:
"""Represents a set of return edges.
All return edges in an interval induce a same constraint on the contained
edges, which means that all edges must either have a left orientation or
all edges must have a right orientation.
"""
def __init__(self, low=None, high=None):
self... | Interval |
python | kamyu104__LeetCode-Solutions | Python/sum-of-beautiful-subsequences.py | {
"start": 1171,
"end": 2093
} | class ____(object):
def totalBeauty(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def count(arr):
for i, x in enumerate(sorted(arr)): # coordinate compression
val_to_idx[x] = i
bit = BIT(len(arr))
for x in arr:
... | Solution |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_index.py | {
"start": 3645,
"end": 7790
} | class ____(unittest.TestCase):
def test_ivfflat_cpu_coarse(self):
res = faiss.StandardGpuResources()
d = 128
nb = 5000
nq = 100
nlist = 10
nprobe = 3
q = faiss.IndexFlatL2(d)
idx_cpu = faiss.IndexIVFFlat(q, d, nlist)
rs = np.random.RandomStat... | TestIVFPluggableCoarseQuantizer |
python | kamyu104__LeetCode-Solutions | Python/maximum-product-of-three-numbers.py | {
"start": 29,
"end": 741
} | class ____(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
min1, min2 = float("inf"), float("inf")
max1, max2, max3 = float("-inf"), float("-inf"), float("-inf")
for n in nums:
if n <= min1:
min2 ... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 197194,
"end": 197556
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("assignable", "client_mutation_id")
assignable = sgqlc.types.Field("Assignable", graphql_name="assignable")
client_mutation_id = sgqlc.types.Field(String, graphql_name="client... | AddAssigneesToAssignablePayload |
python | pytorch__pytorch | torch/distributed/fsdp/_trace_utils.py | {
"start": 2296,
"end": 3814
} | class ____:
"""
This represents the execution order information from the forward pass.
Attributes:
curr_module (nn.Module): Current module being traced.
module_forward_order (List[nn.Module]): The modules in (pre-)forward
order, i.e. the order in which their ``forward()`` method... | _ExecutionInfo |
python | apache__thrift | lib/py/src/transport/TTwisted.py | {
"start": 1186,
"end": 1560
} | class ____(TTransport.TTransportBase):
def __init__(self):
self.__wbuf = BytesIO()
def write(self, buf):
self.__wbuf.write(buf)
def flush(self):
msg = self.__wbuf.getvalue()
self.__wbuf = BytesIO()
return self.sendMessage(msg)
def sendMessage(self, message):
... | TMessageSenderTransport |
python | huggingface__transformers | tests/models/internvl/test_modeling_internvl.py | {
"start": 1547,
"end": 6236
} | class ____:
def __init__(
self,
parent,
batch_size=3,
seq_length=7,
image_seq_length=64,
vision_feature_layer=-1,
ignore_index=-100,
image_token_id=1,
num_channels=3,
image_size=64,
model_type="internvl",
is_training=Tru... | InternVLVisionText2TextModelTester |
python | getsentry__sentry | src/sentry/models/files/fileblobindex.py | {
"start": 276,
"end": 637
} | class ____(AbstractFileBlobIndex):
__relocation_scope__ = RelocationScope.Excluded
file = FlexibleForeignKey("sentry.File")
blob = FlexibleForeignKey("sentry.FileBlob", on_delete=models.PROTECT)
class Meta:
app_label = "sentry"
db_table = "sentry_fileblobindex"
unique_together ... | FileBlobIndex |
python | instagram__MonkeyType | tests/test_typing.py | {
"start": 20175,
"end": 24855
} | class ____:
@pytest.mark.parametrize(
'value, expected_type',
[
(1, int),
('foo', str),
(Dummy, Type[Dummy]),
(1.1, float),
((), typing_Tuple[()]),
(('a', 1, True), typing_Tuple[str, int, bool]),
(set(), Set[Any]),
... | TestGetType |
python | spyder-ide__spyder | spyder/plugins/appearance/widgets.py | {
"start": 570,
"end": 9150
} | class ____(QDialog):
"""A color scheme editor dialog."""
def __init__(self, parent=None, stack=None):
super().__init__(parent)
self.parent = parent
self.stack = stack
self.order = [] # Uses scheme names
# Needed for self.get_edited_color_scheme()
self.widgets... | SchemeEditor |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/triggers/test_await_message.py | {
"start": 1365,
"end": 1490
} | class ____:
def __init__(*args, **kwargs):
pass
def error(*args, **kwargs):
return False
| MockedMessage |
python | agronholm__apscheduler | src/apscheduler/datastores/mongodb.py | {
"start": 2949,
"end": 3710
} | class ____(Generic[T]):
cursor: Cursor[T]
def __aiter__(self) -> AsyncIterator[T]:
return self
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await to_thread.run_sync(self.cursor.close)
def __next__(self) -> T... | AsyncCursor |
python | has2k1__plotnine | plotnine/coords/coord_trans.py | {
"start": 630,
"end": 4750
} | class ____(coord):
"""
Transformed cartesian coordinate system
Parameters
----------
x : str | trans
Name of transform or `trans` class to transform the x axis
y : str | trans
Name of transform or `trans` class to transform the y axis
xlim : tuple[float, float]
Limit... | coord_trans |
python | pytorch__pytorch | torch/_inductor/remote_cache.py | {
"start": 11046,
"end": 11102
} | class ____(RedisRemoteCache):
pass
| RemoteAutotuneCache |
python | ray-project__ray | doc/source/ray-core/doc_code/pattern_async_actor.py | {
"start": 1079,
"end": 2049
} | class ____:
def __init__(self, task_store):
self.task_store = task_store
self.num_executed_tasks = 0
async def run(self):
while True:
# Here we use await instead of ray.get() to
# wait for the next task and it will yield
# the control while waiting.
... | AsyncTaskExecutor |
python | jazzband__django-waffle | waffle/tests/test_management.py | {
"start": 7643,
"end": 9177
} | class ____(TestCase):
def test_create(self):
""" The command should create a new sample. """
name = 'test'
percent = 20
call_command('waffle_sample', name, str(percent), create=True)
sample = get_waffle_sample_model().objects.get(name=name)
self.assertEqual(sample.pe... | WaffleSampleManagementCommandTests |
python | boto__boto3 | tests/unit/dynamodb/test_transform.py | {
"start": 12722,
"end": 13619
} | class ____(BaseTransformAttributeValueTest):
def test_handler(self):
input_params = {
'Structure': {
'TransformMe': self.python_value,
'LeaveAlone': 'unchanged',
}
}
input_shape = {
'Structure': {
'type': 'st... | TestTransformAttributeValueInput |
python | chardet__chardet | chardet/enums.py | {
"start": 873,
"end": 1028
} | class ____:
"""
This enum represents the different states a state machine can be in.
"""
START = 0
ERROR = 1
ITS_ME = 2
| MachineState |
python | redis__redis-py | redis/commands/core.py | {
"start": 245527,
"end": 249848
} | class ____:
"""
Redis Function commands
"""
def function_load(
self, code: str, replace: Optional[bool] = False
) -> Union[Awaitable[str], str]:
"""
Load a library to Redis.
:param code: the source code (must start with
Shebang statement that provides a metad... | FunctionCommands |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1210127,
"end": 1212577
} | class ____(sgqlc.types.Type, Node):
"""A repository's open source license"""
__schema__ = github_schema
__field_names__ = (
"body",
"conditions",
"description",
"featured",
"hidden",
"implementation",
"key",
"limitations",
"name",
... | License |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 13324,
"end": 13444
} | class ____(OpcodeWithArg): # Stores local variable number
_FLAGS = HAS_LOCAL | HAS_ARGUMENT
__slots__ = ()
| STORE_FAST |
python | pytorch__pytorch | torch/nn/modules/linear.py | {
"start": 8881,
"end": 12326
} | class ____(LazyModuleMixin, Linear):
r"""A :class:`torch.nn.Linear` module where `in_features` is inferred.
In this module, the `weight` and `bias` are of :class:`torch.nn.UninitializedParameter`
class. They will be initialized after the first call to ``forward`` is done and the
module will become a re... | LazyLinear |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 8253,
"end": 9462
} | class ____:
"""mixin to easily allow tests of both sparray and spmatrix"""
bsr_container = bsr_matrix
coo_container = coo_matrix
csc_container = csc_matrix
csr_container = csr_matrix
dia_container = dia_matrix
dok_container = dok_matrix
lil_container = lil_matrix
asdense = staticmeth... | _MatrixMixin |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 47876,
"end": 50284
} | class ____(_DOF_estimator_geom):
"""
The 'smoothest' approximation, df is computed through global minimization
of the bending energy:
E(f) = integral[(d2z/dx2 + d2z/dy2 + 2 d2z/dxdy)**2 dA]
"""
def __init__(self, Interpolator):
self._eccs = Interpolator._eccs
super().__init__(I... | _DOF_estimator_min_E |
python | tensorflow__tensorflow | tensorflow/python/keras/keras_parameterized.py | {
"start": 1226,
"end": 17664
} | class ____(test.TestCase, parameterized.TestCase):
def tearDown(self):
keras.backend.clear_session()
super(TestCase, self).tearDown()
def run_with_all_saved_model_formats(
test_or_class=None,
exclude_formats=None):
"""Execute the decorated test with all Keras saved model formats).
This decorat... | TestCase |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/implementation/utils.py | {
"start": 21752,
"end": 23192
} | class ____(
NamedTuple(
"_ExecutionParams",
[
("selector", JobSubsetSelector),
("run_config", Mapping[str, object]),
("mode", Optional[str]),
("execution_metadata", "ExecutionMetadata"),
("step_keys", Optional[Sequence[str]]),
],
... | ExecutionParams |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 6217,
"end": 6314
} | class ____(InitializationTestMixin):
item_class = NameDataClass
| TestInitializationFromDataClass |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 12445,
"end": 12586
} | class ____(_TestIDCTBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 5
self.type = 4
| TestIDCTIVFloat |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_meta.py | {
"start": 2446,
"end": 2777
} | class ____(nn.Module):
def __init__(self, device: torch.device):
super().__init__()
self.lin1 = MyLinear(2, 2, bias=False, device=device)
self.lin2 = MyLinear(2, 2, bias=False, device=device)
self.buf_mod = MyBuffer(device)
def forward(self, x):
return self.lin2(self.lin... | MyModel |
python | Textualize__textual | docs/examples/styles/display.py | {
"start": 65,
"end": 325
} | class ____(App):
CSS_PATH = "display.tcss"
def compose(self):
yield Static("Widget 1")
yield Static("Widget 2", classes="remove")
yield Static("Widget 3")
if __name__ == "__main__":
app = DisplayApp()
app.run()
| DisplayApp |
python | kamyu104__LeetCode-Solutions | Python/design-a-todo-list.py | {
"start": 388,
"end": 2231
} | class ____(object):
def __init__(self):
self.__tasks = []
self.__user_task_ids = collections.defaultdict(SortedList)
def addTask(self, userId, taskDescription, dueDate, tags):
"""
:type userId: int
:type taskDescription: str
:type dueDate: int
:type tags... | TodoList |
python | astropy__astropy | astropy/wcs/wcs.py | {
"start": 9058,
"end": 141876
} | class ____(FITSWCSAPIMixin, WCSBase):
"""WCS objects perform standard WCS transformations, and correct for
`SIP`_ and `distortion paper`_ table-lookup transformations, based
on the WCS keywords and supplementary data read from a FITS file.
See also: https://docs.astropy.org/en/stable/wcs/
Paramete... | WCS |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/transform_reward.py | {
"start": 1817,
"end": 3540
} | class ____(TransformReward[ObsType, ActType], gym.utils.RecordConstructorArgs):
"""Clips the rewards for an environment between an upper and lower bound.
A vector version of the wrapper exists :class:`gymnasium.wrappers.vector.ClipReward`.
Example:
>>> import gymnasium as gym
>>> from gymn... | ClipReward |
python | zarr-developers__zarr-python | tests/test_store/test_wrapper.py | {
"start": 759,
"end": 4566
} | class ____(StoreTests[WrapperStore[Any], Buffer]):
store_cls = WrapperStore
buffer_cls = CPUBuffer
async def get(self, store: WrapperStore[LocalStore], key: str) -> Buffer:
return self.buffer_cls.from_bytes((store._store.root / key).read_bytes())
async def set(self, store: WrapperStore[LocalSt... | TestWrapperStore |
python | kamyu104__LeetCode-Solutions | Python/magic-squares-in-grid.py | {
"start": 34,
"end": 1158
} | class ____(object):
def numMagicSquaresInside(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def magic(grid, r, c):
expect = k * (k**2+1) // 2
nums = set()
min_num = float("inf")
sum_diag, sum_anti = 0, 0
... | Solution |
python | ray-project__ray | rllib/policy/tests/test_timesteps.py | {
"start": 199,
"end": 1878
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_timesteps(self):
"""Test whether PG can be built with both frameworks."""
config = (
ppo.PPOConfig()
.api... | TestTimeSteps |
python | huggingface__transformers | src/transformers/models/diffllama/modeling_diffllama.py | {
"start": 3149,
"end": 8619
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: DiffLlamaConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
se... | DiffLlamaRotaryEmbedding |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_query.py | {
"start": 42674,
"end": 43736
} | class ____(fixtures.TestBase):
__only_on__ = "postgresql"
__backend__ = True
def test_tuple_containment(self, connection):
for test, exp in [
([("a", "b")], True),
([("a", "c")], False),
([("f", "q"), ("a", "b")], True),
([("f", "q"), ("a", "c")], Fal... | TupleTest |
python | pypa__warehouse | tests/unit/utils/test_paginate.py | {
"start": 1314,
"end": 1592
} | class ____:
def __init__(self, fake):
self.fake = fake
self.range = slice(None)
def __getitem__(self, range):
self.range = range
return self
def execute(self):
return FakeResult(self.fake[self.range], len(self.fake))
| FakeQuery |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 8087,
"end": 9617
} | class ____:
"""Define how the BM25 query's token matching should be performed."""
def __init__(self) -> None:
raise TypeError("BM25Operator cannot be instantiated. Use the static methods to create.")
@staticmethod
def or_(minimum_match: int) -> BM25OperatorOptions:
"""Use the 'Or' oper... | BM25OperatorFactory |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/base.py | {
"start": 24310,
"end": 25958
} | class ____(_MappedAnnotationBase[_T_co]):
"""Represent the ORM mapped attribute type for a "dynamic" relationship.
The :class:`_orm.DynamicMapped` type annotation may be used in an
:ref:`Annotated Declarative Table <orm_declarative_mapped_column>` mapping
to indicate that the ``lazy="dynamic"`` loader ... | DynamicMapped |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchaudio_models.py | {
"start": 4844,
"end": 6003
} | class ____(nn.Module):
def __init__(self, seq_module):
"""
Adds padding to the output of the module based on the given lengths. This is to ensure that the
results of the model do not change when batch sizes change during inference.
Input needs to be in the shape of (BxCxDxT)
... | MaskConv |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/general_tests/grpc_tests/state_versions/sample_state_backed_component.py | {
"start": 315,
"end": 1207
} | class ____(StateBackedComponent, dg.Model, dg.Resolvable):
def build_defs_from_state(
self, context: dg.ComponentLoadContext, state_path: Optional[Path]
) -> dg.Definitions:
assert state_path is not None
with open(state_path) as f:
state = f.read()
assert state == "hi... | SampleStateBackedComponent |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramNames1.py | {
"start": 114,
"end": 1598
} | class ____:
# This should generate an error or warning if the setting
# is enabled because __new__ is expected to take cls.
def __new__(blah):
return super().__new__(blah)
# This should generate an error or warning if the setting
# is enabled because it's missing a "self" parameter.
def... | Class1 |
python | numba__numba | numba/tests/test_np_randomgen.py | {
"start": 53649,
"end": 54301
} | class ____(TestCase, SerialMixin):
def test_randomgen_caching(self):
nb_rng = np.random.default_rng(1)
np_rng = np.random.default_rng(1)
numba_func = numba.njit(lambda x: x.random(10), cache=True)
self.assertPreciseEqual(np_rng.random(10), numba_func(nb_rng))
# Run the funct... | TestGeneratorCaching |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 14968,
"end": 15114
} | class ____(InventoryConfig, NetworkConfig):
"""Configuration for network hosts using inventory."""
@dataclasses.dataclass
| NetworkInventoryConfig |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 44085,
"end": 45960
} | class ____(TestCase):
def setUp(self):
self.patterns = [
path('excluded-cbv/', ExcludedAPIView.as_view()),
path('excluded-fbv/', excluded_fbv),
path('included-fbv/', included_fbv),
]
def test_schema_generator_excludes_correctly(self):
"""Schema should... | SchemaGenerationExclusionTests |
python | great-expectations__great_expectations | great_expectations/execution_engine/execution_engine.py | {
"start": 2114,
"end": 2298
} | class ____(ValueError):
def __init__(self, condition: Condition):
super().__init__(f"Invalid condition type: {type(condition)}")
@dataclass(frozen=True)
| InvalidConditionError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external.py | {
"start": 32230,
"end": 37079
} | class ____:
def __init__(self, schedule_snap: ScheduleSnap, handle: RepositoryHandle):
self._schedule_snap = check.inst_param(schedule_snap, "schedule_snap", ScheduleSnap)
self._handle = InstigatorHandle(
self._schedule_snap.name,
check.inst_param(handle, "handle", Repository... | RemoteSchedule |
python | neetcode-gh__leetcode | python/0523-continuous-subarray-sum.py | {
"start": 157,
"end": 581
} | class ____:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
hashmap = {}
hashmap[0]=-1
summ=0
for i,j in enumerate(nums):
summ+=j
if summ%k in hashmap.keys():
if i-hashmap[summ%k]>=2:
return True
... | Solution |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/util.py | {
"start": 10235,
"end": 11799
} | class ____(str):
"""
A string that compares equal to another string regardless of case,
unless it is quoted.
"""
def __init__(self, string: str):
# TODO: check if string is already a CaseInsensitiveString?
self._original = string
self._folded = (
string.casefold(... | CaseInsensitiveString |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/encoders.py | {
"start": 7468,
"end": 8684
} | class ____(nn.Module):
def __init__(
self, height: int, width: int, initial_channels: int, output_size: int
):
super().__init__()
self.h_size = output_size
conv_1_hw = conv_output_shape((height, width), 8, 4)
conv_2_hw = conv_output_shape(conv_1_hw, 4, 2)
conv_3_h... | NatureVisualEncoder |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 398389,
"end": 399201
} | class ____(Request):
"""
Gets task information
:param task: Task ID
:type task: str
"""
_service = "tasks"
_action = "get_by_id"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task ID", "type": "string"}},
"required"... | GetByIdRequest |
python | pennersr__django-allauth | allauth/socialaccount/providers/yahoo/views.py | {
"start": 181,
"end": 995
} | class ____(OAuth2Adapter):
provider_id = "yahoo"
access_token_url = "https://api.login.yahoo.com/oauth2/get_token" # nosec
authorize_url = "https://api.login.yahoo.com/oauth2/request_auth"
profile_url = "https://api.login.yahoo.com/openid/v1/userinfo"
def complete_login(self, request, app, token, ... | YahooOAuth2Adapter |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 83085,
"end": 83412
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = FunctionalConv2d()
def forward(self, x):
x = self.conv1(x)
return x
def get_example_inputs(self) -> tuple[Any, ...]:
return self.conv1.get_example_inputs()
| SingleLayerFunctionalConvModel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_generative_model.py | {
"start": 15004,
"end": 16970
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("generative_model.GenerativeModelHook"))
def test_execute(self, mock_hook):
model_name = "gemini-1.5-pro-002"
system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new ... | TestVertexAICreateCachedContentOperator |
python | encode__django-rest-framework | tests/test_api_client.py | {
"start": 4041,
"end": 4652
} | class ____(APIView):
def get(self, request):
return Response({
'method': request.method,
'query_params': _get_query_params(request)
})
def post(self, request):
if request.content_type:
content_type = request.content_type.split(';')[0]
else:
... | ListView |
python | pytorch__pytorch | test/test_cpp_extensions_aot.py | {
"start": 15881,
"end": 16596
} | class ____(common.TestCase):
def test_torch_library(self):
import torch_test_cpp_extension.torch_library # noqa: F401
def f(a: bool, b: bool):
return torch.ops.torch_library.logical_and(a, b)
self.assertTrue(f(True, True))
self.assertFalse(f(True, False))
self.... | TestTorchLibrary |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.