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/llama/modeling_llama.py | {
"start": 2725,
"end": 7491
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: LlamaConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.c... | LlamaRotaryEmbedding |
python | gevent__gevent | src/gevent/_fileobjectcommon.py | {
"start": 19872,
"end": 20276
} | class ____(FileObjectBase):
"""
FileObjectBlock()
A simple synchronous wrapper around a file object.
Adds no concurrency or gevent compatibility.
"""
def __init__(self, fobj, *args, **kwargs):
descriptor = OpenDescriptor(fobj, *args, **kwargs)
FileObjectBase.__init__(self, des... | FileObjectBlock |
python | matplotlib__matplotlib | galleries/examples/misc/demo_agg_filter.py | {
"start": 4507,
"end": 8768
} | class ____(Artist):
"""A simple container to filter multiple artists at once."""
def __init__(self, artist_list, filter):
super().__init__()
self._artist_list = artist_list
self._filter = filter
def draw(self, renderer):
renderer.start_rasterizing()
renderer.start_f... | FilteredArtistList |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_ticker.py | {
"start": 17357,
"end": 17669
} | class ____:
def test_set_params(self):
"""
Create null locator, and attempt to call set_params() on it.
Should not exception, and should raise a warning.
"""
loc = mticker.NullLocator()
with pytest.warns(UserWarning):
loc.set_params()
| TestNullLocator |
python | altair-viz__altair | altair/datasets/_constraints.py | {
"start": 863,
"end": 3341
} | class ____(Set[tuple[str, Any]]):
_requires: frozenset[tuple[str, Any]]
def __init__(self, kwds: frozenset[tuple[str, Any]], /) -> None:
object.__setattr__(self, "_requires", kwds)
@classmethod
def from_metadata(cls, meta: Metadata, /) -> MetaIs:
return cls(frozenset(meta.items()))
... | MetaIs |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 1608,
"end": 1700
} | class ____(viewsets.ModelViewSet):
queryset = None
serializer_class = None
| MockViewSet |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/sql/dml.py | {
"start": 446,
"end": 611
} | class ____(DeclarativeBase):
pass
user_table = Table(
"user",
MetaData(),
Column("id", Integer, primary_key=True),
Column("data", String),
)
| Base |
python | pytorch__pytorch | torch/utils/benchmark/op_fuzzers/binary.py | {
"start": 321,
"end": 4144
} | class ____(Fuzzer):
def __init__(self, seed, dtype=torch.float32, cuda=False) -> None:
super().__init__(
parameters=[
# Dimensionality of x and y. (e.g. 1D, 2D, or 3D.)
FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
# ... | BinaryOpFuzzer |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_schema_enforcement.py | {
"start": 1097,
"end": 2525
} | class ____:
@staticmethod
def predict(pdf, params=None):
return pdf
@pytest.fixture(scope="module")
def sample_params_basic():
return {
"str_param": "str_a",
"int_param": np.int32(1),
"bool_param": True,
"double_param": 1.0,
"float_param": np.float32(0.1),
... | TestModel |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 55530,
"end": 56104
} | class ____(ToFrameIndex):
_defaults = {"name": no_default, "index": None}
operation = M.to_series
_preserves_partitioning_information = True
def pd_split(df, p, random_state=None, shuffle=False):
p = list(p)
if shuffle:
if not isinstance(random_state, np.random.RandomState):
ra... | ToSeriesIndex |
python | MongoEngine__mongoengine | tests/queryset/test_visitor.py | {
"start": 196,
"end": 12600
} | class ____(unittest.TestCase):
def setUp(self):
connect(db="mongoenginetest")
class Person(Document):
name = StringField()
age = IntField()
meta = {"allow_inheritance": True}
Person.drop_collection()
self.Person = Person
def test_empty_q(sel... | TestQ |
python | spack__spack | var/spack/test_repos/spack_repo/duplicates_test/packages/virtual_build/package.py | {
"start": 216,
"end": 503
} | class ____(Package):
"""A package that has a pure build virtual dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/tdep-1.0.tar.gz"
version("1.0.0", md5="0123456789abcdef0123456789abcdef")
depends_on("pkgconfig", type="build")
| VirtualBuild |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/parse_single_example_op_test.py | {
"start": 3389,
"end": 31632
} | class ____(test.TestCase):
def _test(self, kwargs, expected_values=None, expected_err=None):
with self.cached_session() as sess:
if expected_err:
with self.assertRaisesWithPredicateMatch(expected_err[0],
expected_err[1]):
out = parsing_ops.... | ParseExampleTest |
python | walkccc__LeetCode | solutions/2682. Find the Losers of the Circular Game/2682.py | {
"start": 0,
"end": 374
} | class ____:
def circularGameLosers(self, n: int, k: int) -> list[int]:
seen = [False] * n
friendIndex = 0
turn = 1
while not seen[friendIndex]:
seen[friendIndex] = True
friendIndex += turn * k
friendIndex %= n
turn += 1
return [friendIndex + 1
for friendIndex ... | Solution |
python | scipy__scipy | scipy/stats/_qmc.py | {
"start": 38393,
"end": 44941
} | class ____(QMCEngine):
"""Halton sequence.
Pseudo-random number generator that generalize the Van der Corput sequence
for multiple dimensions. The Halton sequence uses the base-two Van der
Corput sequence for the first dimension, base-three for its second and
base-:math:`p` for its :math:`n`-dimens... | Halton |
python | spack__spack | lib/spack/spack/relocate_text.py | {
"start": 3726,
"end": 5070
} | class ____(PrefixReplacer):
"""This class applies prefix to prefix mappings for relocation
on text files.
Note that UTF-8 encoding is assumed."""
def __init__(self, prefix_to_prefix: Dict[bytes, bytes]):
"""
prefix_to_prefix (OrderedDict): OrderedDictionary where the keys are
... | TextFilePrefixReplacer |
python | getsentry__sentry | src/sentry/tasks/embeddings_grouping/utils.py | {
"start": 1896,
"end": 1966
} | class ____(TypedDict):
event_id: str
group_id: int
| GroupEventRow |
python | getsentry__sentry | tests/sentry/metrics/test_sentry_sdk.py | {
"start": 106,
"end": 5880
} | class ____:
@pytest.fixture
def backend(self):
return SentrySDKMetricsBackend(prefix="test.", experimental_sample_rate=1.0)
@mock.patch("sentry_sdk.metrics.count")
def test_incr(self, mock_count, backend):
with mock.patch.object(backend, "_should_send", return_value=True):
b... | TestSentrySDKMetricsBackend |
python | sympy__sympy | sympy/physics/quantum/operator.py | {
"start": 1187,
"end": 5712
} | class ____(QExpr):
"""Base class for non-commuting quantum operators.
An operator maps between quantum states [1]_. In quantum mechanics,
observables (including, but not limited to, measured physical values) are
represented as Hermitian operators [2]_.
Parameters
==========
args : tuple
... | Operator |
python | boto__boto3 | tests/functional/test_s3.py | {
"start": 4546,
"end": 8518
} | class ____(BaseTransferTest):
def setUp(self):
super().setUp()
self.copy_source = {'Bucket': 'foo', 'Key': 'bar'}
def stub_single_part_copy(self):
self.stub_head(expected_params=self.copy_source)
self.stub_copy_object()
def stub_multipart_copy(self, part_size, num_parts):
... | TestCopy |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/sensor_definition.py | {
"start": 24588,
"end": 50594
} | class ____(IHasInternalInit):
"""Define a sensor that initiates a set of runs based on some external state.
Args:
evaluation_fn (Callable[[SensorEvaluationContext]]): The core evaluation function for the
sensor, which is run at an interval to determine whether a run should be launched or
... | SensorDefinition |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 28758,
"end": 29925
} | class ____(Response):
"""
Response of queues.delete endpoint.
:param deleted: Number of queues deleted (0 or 1)
:type deleted: int
"""
_service = "queues"
_action = "delete"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"deleted": {
... | DeleteResponse |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_checks/asset_check_factories/schema_change_checks.py | {
"start": 6421,
"end": 7761
} | class ____(BaseModel):
added_columns: Sequence[TableColumn]
removed_columns: Sequence[TableColumn]
column_type_changes: Mapping[str, TypeChange]
@staticmethod
def from_table_schemas(
old_table_schema: TableSchema, new_table_schema: TableSchema
) -> "TableSchemaDiff":
old_columns... | TableSchemaDiff |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 27782,
"end": 28605
} | class ____(Exception):
"""
Exception is raised when trying to perform an operation on a closed HDFStore file.
``ClosedFileError`` is specific to operations on ``HDFStore`` objects. Once an
HDFStore is closed, its resources are no longer available, and any further attempt
to access data or perform f... | ClosedFileError |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 2598,
"end": 3866
} | class ____(str, Enum):
NOT_ANNOTATED = "NOT_ANNOTATED"
PARTIALLY_ANNOTATED = "PARTIALLY_ANNOTATED"
FULLY_ANNOTATED = "FULLY_ANNOTATED"
@staticmethod
def from_function_data(
is_non_static_method: bool,
is_return_annotated: bool,
parameters: Sequence[libcst.Param],
) -> "F... | FunctionAnnotationStatus |
python | python-poetry__poetry | tests/helpers.py | {
"start": 2769,
"end": 3684
} | class ____:
def __init__(self, root: Path | str, **__: Any) -> None:
self.path = str(root)
def head(self) -> bytes:
return MOCK_DEFAULT_GIT_REVISION.encode()
def mock_clone(
url: str,
*_: Any,
source_root: Path | None = None,
**__: Any,
) -> MockDulwichRepo:
# Checking sou... | MockDulwichRepo |
python | ApeWorX__ape | src/ape_node/provider.py | {
"start": 17492,
"end": 18131
} | class ____(ConnectionError):
def __init__(self):
super().__init__(
"No node found and 'ape-node' is unable to start one.\n"
"Things you can do:\n"
"\t1. Check your connection URL, if trying to connect remotely.\n"
"\t2. Install node software (geth), if trying ... | NodeSoftwareNotInstalledError |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/split.py | {
"start": 85,
"end": 946
} | class ____(App):
CSS = """
#split1 {
split: right;
width: 20;
}
#split2 {
split: bottom;
height: 10;
}
#split3 {
split: top;
height: 6;
}
#split4 {
split: left;
width: 30;
}
.scrollable {
height: 5;
... | SplitApp |
python | ray-project__ray | python/ray/tests/test_ray_event_export_task_events.py | {
"start": 67701,
"end": 76474
} | class ____:
def __init__(self):
pass
def task(self):
pass
actor = Actor.remote()
ray.kill(actor)
"""
def validate_events(events: json):
(
driver_script_job_id,
driver_task_id,
) = get_job_id_and_driver_script_task_id_from... | Actor |
python | ray-project__ray | python/ray/_private/custom_types.py | {
"start": 3227,
"end": 5027
} | class ____(Enum):
OBJECT_STORE = TensorTransport.Value("OBJECT_STORE")
NCCL = TensorTransport.Value("NCCL")
GLOO = TensorTransport.Value("GLOO")
NIXL = TensorTransport.Value("NIXL")
@classmethod
def from_str(cls, name: str) -> "TensorTransportEnum":
name = name.upper()
if name n... | TensorTransportEnum |
python | numpy__numpy | numpy/random/tests/test_smoke.py | {
"start": 28066,
"end": 28380
} | class ____(RNG):
@classmethod
def _create_rng(cls):
bit_generator = PCG64
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
| TestPCG64 |
python | rapidsai__cudf | python/dask_cudf/dask_cudf/_expr/groupby.py | {
"start": 13914,
"end": 15333
} | class ____(SingleAggregation):
@staticmethod
def groupby_chunk(arg):
return arg.agg(list)
@staticmethod
def groupby_aggregate(arg):
gb = arg.agg(list)
if gb.ndim > 1:
for col in gb.columns:
gb[col] = gb[col].list.concat()
return gb
... | ListAgg |
python | doocs__leetcode | solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/Solution.py | {
"start": 0,
"end": 239
} | class ____:
def maxScore(self, nums: List[int]) -> int:
nums.sort(reverse=True)
s = 0
for i, x in enumerate(nums):
s += x
if s <= 0:
return i
return len(nums)
| Solution |
python | automl__auto-sklearn | test/test_pipeline/components/classification/test_bernoulli_nb.py | {
"start": 170,
"end": 839
} | class ____(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris"] = 0.26
res["iris_n_calls"] = None
res["default_iris_iterative"] = 0.26
res["default_iris_proba"] = 1.1157508543538652
res["default_iris_sparse"] = 0.38
res["default_digits"] = 0.81238615664845... | BernoulliNBComponentTest |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/entrypoint.py | {
"start": 3354,
"end": 7100
} | class ____(logging.Formatter):
def __init__(self, fmt: str, json_fields: Mapping[str, str]):
super().__init__(fmt=fmt)
self.json_fields = dict(json_fields)
def format(self, record: logging.LogRecord) -> str:
log = super().format(record)
output = {
# Time format speci... | FluentbitJsonFormatter |
python | euske__pdfminer | pdfminer/psparser.py | {
"start": 1012,
"end": 1545
} | class ____(PSObject):
"""A class that represents a PostScript keyword.
PostScript keywords are a dozen of predefined words.
Commands and directives in PostScript are expressed by keywords.
They are also used to denote the content boundaries.
Note: Do not create an instance of PSKeyword directly.
... | PSKeyword |
python | ansible__ansible | test/units/mock/yaml_helper.py | {
"start": 115,
"end": 2067
} | class ____(object):
"""Mixin class to combine with a unittest.TestCase subclass."""
def _loader(self, stream):
"""Vault related tests will want to override this.
Vault cases should setup a AnsibleLoader that has the vault password."""
def _dump_stream(self, obj, stream, dumper=None):
... | YamlTestUtils |
python | jmcnamara__XlsxWriter | xlsxwriter/chart_doughnut.py | {
"start": 322,
"end": 2707
} | class ____(chart_pie.ChartPie):
"""
A class for writing the Excel XLSX Doughnut charts.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self)... | ChartDoughnut |
python | google__pytype | pytype/abstract/_singletons.py | {
"start": 9449,
"end": 10565
} | class ____(Singleton):
"""Representation of value we know nothing about.
Unlike "Unknowns", we don't treat these as solvable. We just put them
where values are needed, but make no effort to later try to map them
to named types. This helps conserve memory where creating and solving
hundreds of unknowns would ... | Unsolvable |
python | pallets__quart | src/quart/config.py | {
"start": 237,
"end": 1524
} | class ____(FlaskConfig):
def from_prefixed_env(
self, prefix: str = "QUART", *, loads: Callable[[str], Any] = json.loads
) -> bool:
"""Load any environment variables that start with the prefix.
The prefix (default ``QUART_``) is dropped from the env key
for the config key. Value... | Config |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/variables/variable_scope_test.py | {
"start": 77642,
"end": 80872
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testTwoThreadsDisjointScopeEntry(self):
def thread_fn(i, graph):
with graph.as_default():
with variable_scope.variable_scope("foo"):
if i == 0:
v = variable_scop... | VariableScopeMultithreadedTest |
python | getsentry__sentry | src/sentry/models/release_threshold/constants.py | {
"start": 1687,
"end": 3726
} | class ____:
OVER = 0
UNDER = 1
OVER_STR = "over"
UNDER_STR = "under"
@classmethod
def as_choices(cls): # choices for model column
return (
(cls.OVER_STR, cls.OVER),
(cls.UNDER_STR, cls.UNDER),
)
@classmethod
def as_str_choices(cls): # choices ... | TriggerType |
python | pypa__warehouse | tests/unit/packaging/test_services.py | {
"start": 32258,
"end": 35488
} | class ____:
def test_verify_service(self):
assert verifyClass(ISimpleStorage, GCSSimpleStorage)
def test_basic_init(self):
bucket = pretend.stub()
storage = GCSSimpleStorage(bucket)
assert storage.bucket is bucket
def test_create_service(self):
service = pretend.stu... | TestGCSSimpleStorage |
python | kamyu104__LeetCode-Solutions | Python/maximize-number-of-nice-divisors.py | {
"start": 66,
"end": 788
} | class ____(object):
def maxNiceDivisors(self, primeFactors):
"""
:type primeFactors: int
:rtype: int
"""
# given a1 + a2 + ... + ak <= n, find max of a1 * a2 * ... * ak
# => given a1 + a2 + ... + ak = n, find max of a1 * a2 * ... * ak
# => ai is either 3 or ... | Solution |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 3942,
"end": 4034
} | class ____(Parent):
def method(self):
print("Child")
super().method()
| Child |
python | kamyu104__LeetCode-Solutions | Python/all-divisions-with-the-highest-score-of-a-binary-array.py | {
"start": 42,
"end": 561
} | class ____(object):
def maxScoreIndices(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
mx = zeros = 0
total = sum(nums)
for i in xrange(len(nums)+1):
zeros += ((nums[i-1] if i else 0) == 0)
if zeros+(to... | Solution |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py | {
"start": 8981,
"end": 10010
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.embed_tokens = nn.Embedding(
config.vocab_size + (config.num_codebooks * config.codebook_vocab_size) + 1,
config.hidden_size,
padding_idx=config.audio_pad_token_id,
)
audio_... | KyutaiSpeechToTextEmbeddings |
python | getsentry__sentry | src/sentry/utils/sentry_apps/request_buffer.py | {
"start": 1106,
"end": 1468
} | class ____(TypedDict):
date: str
response_code: int
webhook_url: str
organization_id: int
event_type: str
error_id: NotRequired[str | None]
project_id: NotRequired[int | None]
request_body: NotRequired[str | None]
request_headers: NotRequired[Mapping[str, str] | None]
response_bo... | SentryAppRequest |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 2125,
"end": 11160
} | class ____(Interface):
"""Represents a WSGI response using the WebOb response interface.
Some attribute and method documentation of this interface references
:rfc:`2616`.
This interface is most famously implemented by
:class:`pyramid.response.Response` and the HTTP exception classes in
:mod:`py... | IResponse |
python | walkccc__LeetCode | solutions/1235. Maximum Profit in Job Scheduling/1235-2.py | {
"start": 0,
"end": 546
} | class ____:
def jobScheduling(
self,
startTime: list[int],
endTime: list[int],
profit: list[int],
) -> int:
# dp[i] := the maximum profit to schedule jobs[i..n)
dp = [0] * (len(startTime) + 1)
jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)])
for i in... | Solution |
python | jina-ai__jina | tests/integration/docarray_v2/test_issues.py | {
"start": 251,
"end": 295
} | class ____(BaseDoc):
value: str
| Nested2Doc |
python | tensorflow__tensorflow | tensorflow/python/keras/constraints.py | {
"start": 4491,
"end": 5583
} | class ____(Constraint):
"""Constrains the weights incident to each hidden unit to have unit norm.
Also available via the shortcut function `tf.keras.constraints.unit_norm`.
Args:
axis: integer, axis along which to calculate weight norms.
For instance, in a `Dense` layer the weight matrix
has sha... | UnitNorm |
python | pytorch__pytorch | torchgen/model.py | {
"start": 13279,
"end": 13344
} | class ____(Enum):
NoCheck = 0
ExactSame = 1
| DeviceCheckType |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 34654,
"end": 36774
} | class ____(TestCase):
body = b'abcde'
end = b'end'
content_length = str(len(body + end))
def application(self, env, start_response):
if env['PATH_INFO'] == '/explicit-content-length':
write = start_response('200 OK', [('Content-Type', 'text/plain'),
... | TestUseWrite |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/legacy_resources.py | {
"start": 9687,
"end": 24349
} | class ____(BaseAirbyteResource):
"""This resource allows users to programatically interface with the Airbyte REST API to launch
syncs and monitor their progress.
**Examples:**
.. code-block:: python
from dagster import job, EnvVar
from dagster_airbyte import AirbyteResource
m... | AirbyteResource |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py | {
"start": 2074,
"end": 4406
} | class ____(test_util.TensorFlowTestCase):
def _SparseTensor_5x6(self, dtype):
ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]])
val = np.array([0, 10, 13, 14, 32, 33])
shape = np.array([5, 6])
return sparse_tensor.SparseTensor(
constant_op.constant(ind, dtypes.int64),
c... | SparseToIndicatorTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 7971,
"end": 8770
} | class ____(BaseModel):
property_name: str
pointing_to: bool
def to_gql(self) -> str:
body = " ".join(
[
"pointingTo" if self.pointing_to else "",
]
)
return f"{self.property_name} {{ {body} }}"
def to_grpc(self) -> aggregate_pb2.Aggregate... | _MetricsReference |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 168265,
"end": 168994
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"enterprise_id",
"organization_id",
"organization_role",
"client_mutation_id",
)
enterprise_id = sgqlc.types.Field(
sgqlc.types.non_n... | UpdateEnterpriseOwnerOrganizationRoleInput |
python | astropy__astropy | astropy/table/groups.py | {
"start": 5339,
"end": 7356
} | class ____:
"""
A class to represent groups within a table of heterogeneous data.
- ``keys``: key values corresponding to each group
- ``indices``: index values in parent table or column corresponding to group boundaries
- ``aggregate()``: method to create new table by aggregating within grou... | BaseGroups |
python | sympy__sympy | sympy/printing/llvmjitcode.py | {
"start": 12423,
"end": 18001
} | class ____:
def __init__(self, ret_type):
self.ret_type = ret_type
self.arg_ctypes = []
# Input argument array element index
self.input_arg = 0
# For the case output value is referenced through a parameter rather
# than the return value
self.ret_arg = None
... | CodeSignature |
python | viewflow__viewflow | viewflow/workflow/token.py | {
"start": 133,
"end": 1893
} | class ____:
"""
Helper for tree-like flow token management.
We follow basic strategy for flow split/join
Flow starts with only one 'start' token,
- each split adds split_pk and path id to following task 'start/3_4',
and 'start/3_4/7_4' on one more split
- each join removes correspondin... | Token |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/unselected/_textfont.py | {
"start": 233,
"end": 2608
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.unselected"
_path_str = "scattersmith.unselected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of unselected points, applied only
when a selection exists.
... | Textfont |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 40571,
"end": 41364
} | class ____(BaseModel):
"""Represents a node in the deployment topology.
Each node represents a deployment and tracks which other deployments it calls.
"""
name: str = Field(description="The name of the deployment.")
app_name: str = Field(
description="The name of the application this deplo... | DeploymentNode |
python | TheAlgorithms__Python | machine_learning/self_organizing_map.py | {
"start": 73,
"end": 2077
} | class ____:
def get_winner(self, weights: list[list[float]], sample: list[int]) -> int:
"""
Compute the winning vector by Euclidean distance
>>> SelfOrganizingMap().get_winner([[1, 2, 3], [4, 5, 6]], [1, 2, 3])
1
"""
d0 = 0.0
d1 = 0.0
for i in range(l... | SelfOrganizingMap |
python | django__django | tests/get_object_or_404/tests.py | {
"start": 199,
"end": 4678
} | class ____(TestCase):
def test_get_object_or_404(self):
a1 = Author.objects.create(name="Brave Sir Robin")
a2 = Author.objects.create(name="Patsy")
# No Articles yet, so we should get an Http404 error.
with self.assertRaises(Http404):
get_object_or_404(Article, title="Fo... | GetObjectOr404Tests |
python | fsspec__filesystem_spec | fsspec/implementations/dbfs.py | {
"start": 13767,
"end": 16217
} | class ____(AbstractBufferedFile):
"""
Helper class for files referenced in the DatabricksFileSystem.
"""
DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size
def __init__(
self,
fs,
path,
mode="rb",
block_size="default",
autocommit=True,
... | DatabricksFile |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 94165,
"end": 95567
} | class ____:
def __enter__(self):
# Before starting CUDA test save currently active streams on all
# CUDA devices and set new non default streams to all CUDA devices
# to ensure CUDA tests do not use default stream by mistake.
beforeDevice = torch.cuda.current_device()
self.be... | CudaNonDefaultStream |
python | openai__openai-python | src/openai/types/beta/assistant_stream_event.py | {
"start": 3907,
"end": 4071
} | class ____(BaseModel):
data: RunStep
"""Represents a step in execution of a run."""
event: Literal["thread.run.step.in_progress"]
| ThreadRunStepInProgress |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 9138,
"end": 9428
} | class ____(models.Model):
related_field = models.ForeignKey(
ModelMethodSluggedTestModel, on_delete=models.CASCADE
)
slug = AutoSlugField(populate_from="related_field__get_readable_title")
class Meta:
app_label = "django_extensions"
| FKSluggedTestModelCallable |
python | wandb__wandb | wandb/vendor/pygments/lexers/haxe.py | {
"start": 504,
"end": 29156
} | class ____(ExtendedRegexLexer):
"""
For Haxe source code (http://haxe.org/).
.. versionadded:: 1.3
"""
name = 'Haxe'
aliases = ['hx', 'haxe', 'hxsl']
filenames = ['*.hx', '*.hxsl']
mimetypes = ['text/haxe', 'text/x-haxe', 'text/x-hx']
# keywords extracted from lexer.mll in the hax... | HaxeLexer |
python | mlflow__mlflow | mlflow/ag2/ag2_logger.py | {
"start": 2528,
"end": 12782
} | class ____(BaseLogger):
def __init__(self):
self._chat_state = ChatState()
def start(self) -> str:
return "session_id"
@_catch_exception
def log_new_agent(self, agent: ConversableAgent, init_args: dict[str, Any]) -> None:
"""
This handler is called whenever a new agent ... | MlflowAg2Logger |
python | great-expectations__great_expectations | great_expectations/data_context/data_context_variables.py | {
"start": 8546,
"end": 12632
} | class ____(DataContextVariables):
data_context: FileDataContext = None # type: ignore[assignment] # post_init ensures field always set
def __post_init__(self) -> None:
# Chetan - 20220607 - Although the above argument is not truly optional, we are
# required to use default values because the p... | FileDataContextVariables |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_rule.py | {
"start": 383,
"end": 6694
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1IngressRule |
python | getsentry__sentry | src/sentry/sentry_apps/utils/webhooks.py | {
"start": 1130,
"end": 2893
} | class ____(StrEnum):
@staticmethod
def map_sentry_app_webhook_events(
resource: str, action_type: type[SentryAppActionType]
) -> list[str]:
# Turn resource + action into webhook event e.g issue.created, issue.resolved, etc.
webhook_events = [
f"{resource}.{action.value}"... | SentryAppResourceType |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/container_instance.py | {
"start": 3701,
"end": 3810
} | class ____:
"""
The result of an `AzureContainerInstanceJob` run.
"""
| AzureContainerInstanceJobResult |
python | neetcode-gh__leetcode | python/0226-invert-binary-tree.py | {
"start": 192,
"end": 551
} | class ____:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# swap the children
root.left, root.right = root.right, root.left
# make 2 recursive calls
self.invertTree(root.left)
self.invertTr... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_ticker.py | {
"start": 55161,
"end": 55344
} | class ____:
def test_basic(self):
# test % style formatter
tmp_form = mticker.FormatStrFormatter('%05d')
assert '00002' == tmp_form(2)
| TestFormatStrFormatter |
python | huggingface__transformers | src/transformers/models/mobilenet_v1/image_processing_mobilenet_v1_fast.py | {
"start": 899,
"end": 1330
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
size = {"shortest_edge": 256}
default_to_square = False
crop_size = {"height": 224, "width": 224}
do_resize = True
do_center_crop = True
do... | MobileNetV1ImageProcessorFast |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/transformed_distribution.py | {
"start": 4400,
"end": 27605
} | class ____(distribution_lib.Distribution):
"""A Transformed Distribution.
A `TransformedDistribution` models `p(y)` given a base distribution `p(x)`,
and a deterministic, invertible, differentiable transform, `Y = g(X)`. The
transform is typically an instance of the `Bijector` class and the base
distribution... | TransformedDistribution |
python | allegroai__clearml | clearml/hyperdatasets/core.py | {
"start": 761,
"end": 22222
} | class ____(HyperDatasetManagement):
MAX_HASH_FETCH_BATCH_SIZE = 100
SOURCE_FIELDS = ["source", "preview_source", "mask_source"]
def __init__(
self,
project_name: str,
dataset_name: str,
version_name: str,
description: Optional[str] = None,
parent_ids: Optiona... | HyperDataset |
python | getlogbook__logbook | src/logbook/ticketing.py | {
"start": 1925,
"end": 3187
} | class ____:
"""Provides an abstract interface to various databases."""
def __init__(self, **options):
self.options = options
self.setup_backend()
def setup_backend(self):
"""Setup the database backend."""
raise NotImplementedError()
def record_ticket(self, record, data... | BackendBase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec43.py | {
"start": 202,
"end": 408
} | class ____(Protocol):
def __call__(self, __x: Callable[P, R]) -> Callable[P, R]: ...
def func1(deco: Decorator):
deco(lambda: None)()
deco(lambda x: x)(1)
deco(lambda x, y: x)(1, "")
| Decorator |
python | getsentry__sentry | tests/sentry/seer/test_seer_setup.py | {
"start": 306,
"end": 5512
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.organization = self.create_organization(name="test-org")
self.user = self.create_user()
self.feature_name = "seer_autofix_setup_acknowledged"
def test_returns_true_when_org_has_acknowledged(self):
"""Test return... | TestGetSeerOrgAcknowledgementForScanner |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_ignore_params.py | {
"start": 1090,
"end": 1309
} | class ____(nn.Module):
def __init__(self, dim: int) -> None:
super().__init__()
self.lin_c = nn.Linear(dim, dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.lin_c(x)
| C |
python | pytorch__pytorch | test/distributed/_shard/sharded_tensor/test_sharded_tensor.py | {
"start": 7872,
"end": 11448
} | class ____(ShardedTensorTestBase):
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_shard_tensor(self):
spec = ChunkShardingSpec(
dim=0,
placements=[
"rank:0/cuda:0",
"rank:1/cuda:1",
"rank:2/cuda:2... | TestShardTensor |
python | django__django | tests/serializers/models/natural.py | {
"start": 567,
"end": 1117
} | class ____(models.Model):
key = models.CharField(max_length=100, unique=True)
other_thing = models.ForeignKey(
"NaturalKeyThing", on_delete=models.CASCADE, null=True
)
other_things = models.ManyToManyField(
"NaturalKeyThing", related_name="thing_m2m_set"
)
class Manager(models.M... | NaturalKeyThing |
python | allegroai__clearml | examples/frameworks/pytorch/pytorch_matplotlib.py | {
"start": 10469,
"end": 12096
} | class ____(nn.Module):
def __init__(self, target_feature):
super(StyleLoss, self).__init__()
self.target = gram_matrix(target_feature).detach()
def forward(self, input):
G = gram_matrix(input)
self.loss = F.mse_loss(G, self.target)
return input
#######################... | StyleLoss |
python | numba__numba | numba/pycc/compiler.py | {
"start": 13204,
"end": 19452
} | class ____(_ModuleCompiler):
_ptr_fun = lambda ret, *args: ir.PointerType(ir.FunctionType(ret, args))
#: typedef int (*visitproc)(PyObject *, void *);
visitproc_ty = _ptr_fun(lt._int8,
lt._pyobject_head_p)
#: typedef int (*inquiry)(PyObject *);
inquiry_ty = _ptr_fun(lt... | ModuleCompiler |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_codeowners_auto_sync_failure_email.py | {
"start": 527,
"end": 1015
} | class ____(View):
def get(self, request: HttpRequest) -> HttpResponse:
org = Organization(id=1, slug="petal", name="Petal")
project = Project(id=1, slug="nodejs", name="Node.js", organization=org)
user = User(name="Nisanthan")
OrganizationMember(organization=org, user_id=user.id, rol... | DebugCodeOwnersAutoSyncFailureView |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol17.py | {
"start": 1850,
"end": 1952
} | class ____(Protocol[P, R]):
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ...
| Callback |
python | gevent__gevent | examples/psycopg2_pool.py | {
"start": 4133,
"end": 4945
} | class ____(AbstractDatabaseConnectionPool):
def __init__(self, *args, **kwargs):
self.connect = kwargs.pop('connect', connect)
maxsize = kwargs.pop('maxsize', None)
self.args = args
self.kwargs = kwargs
AbstractDatabaseConnectionPool.__init__(self, maxsize)
def create_c... | PostgresConnectionPool |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 30025,
"end": 31637
} | class ____(ASTExpression):
def __init__(self, cast: str, typ: ASTType, expr: ASTExpression) -> None:
assert cast in _id_explicit_cast
self.cast = cast
self.typ = typ
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTExplicitCast):
... | ASTExplicitCast |
python | pandas-dev__pandas | pandas/tests/series/methods/test_repeat.py | {
"start": 116,
"end": 1274
} | class ____:
def test_repeat(self):
ser = Series(np.random.default_rng(2).standard_normal(3), index=["a", "b", "c"])
reps = ser.repeat(5)
exp = Series(ser.values.repeat(5), index=ser.index.values.repeat(5))
tm.assert_series_equal(reps, exp)
to_rep = [2, 3, 4]
reps = ... | TestRepeat |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_join.py | {
"start": 7517,
"end": 14997
} | class ____:
@pytest.fixture
def index_large(self):
# large values used in TestUInt64Index where no compat needed with int64/float64
large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]
return Index(large, dtype=np.uint64)
def test_join_inner(self, index_large):
ot... | TestJoinUInt64Index |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 929,
"end": 1298
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
project = FlexibleForeignKey("sentry.Project", db_index=False, db_constraint=False)
incident = FlexibleForeignKey("sentry.Incident")
class Meta:
app_label = "sentry"
db_table = "sentry_incidentproject"
unique_to... | IncidentProject |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/mixins.py | {
"start": 10479,
"end": 16553
} | class ____:
def system_redirect(
self, request, final_project, version_slug, filename, is_external_version=False
):
"""
Return a redirect that is defined by RTD instead of the user.
This is normally used for `/` and `/page/*` redirects.
:param request: Request object.
... | ServeRedirectMixin |
python | bokeh__bokeh | tests/unit/bokeh/test_client_server.py | {
"start": 2456,
"end": 44203
} | class ____:
def test_minimal_connect_and_disconnect(self, ManagedServerLoop: MSL) -> None:
application = Application()
with ManagedServerLoop(application) as server:
# we don't have to start the server because it
# uses the same main loop as the client, so
# if we... | TestClientServer |
python | kamyu104__LeetCode-Solutions | Python/random-pick-with-blacklist.py | {
"start": 71,
"end": 737
} | class ____(object):
def __init__(self, N, blacklist):
"""
:type N: int
:type blacklist: List[int]
"""
self.__n = N-len(blacklist)
self.__lookup = {}
white = iter(set(range(self.__n, N))-set(blacklist))
for black in blacklist:
if black ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/insert-interval.py | {
"start": 29,
"end": 708
} | class ____(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
result = []
i = 0
while i < len(intervals) and newInterval[0] > intervals[i][1]:
res... | Solution |
python | django__django | tests/template_tests/filter_tests/test_date.py | {
"start": 2869,
"end": 3252
} | class ____(SimpleTestCase):
def test_date(self):
self.assertEqual(date(datetime(2005, 12, 29), "d F Y"), "29 December 2005")
def test_no_args(self):
self.assertEqual(date(""), "")
self.assertEqual(date(None), "")
def test_escape_characters(self):
self.assertEqual(date(datet... | FunctionTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.