language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry | src/sentry/integrations/discord/integration.py | {
"start": 3071,
"end": 4958
} | class ____(IntegrationInstallation, IntegrationNotificationClient):
def get_client(self) -> DiscordClient:
return DiscordClient()
def send_notification(
self, target: IntegrationNotificationTarget, payload: DiscordRenderable
) -> None:
client = self.get_client()
try:
... | DiscordIntegration |
python | numpy__numpy | numpy/_core/tests/test_defchararray.py | {
"start": 28803,
"end": 30683
} | class ____:
def test_mod(self):
A = np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']], dtype='S')
tgt = [[b'123 abc ', b'123'],
[b'12312345', b'123MixedCase'],
[b'123123 \t 345 \0 ', b'123UPPER']]
... | TestMethodsScalarValues |
python | huggingface__transformers | src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | {
"start": 2667,
"end": 8342
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.token_type_embeddings = nn... | XLMRobertaXLEmbeddings |
python | facelessuser__pymdown-extensions | pymdownx/details.py | {
"start": 1259,
"end": 6341
} | class ____(BlockProcessor):
"""Details block processor."""
START = re.compile(
r'(?:^|\n)\?{3}(\+)? ?(?:([\w\-]+(?: +[\w\-]+)*?)?(?: +"(.*?)")|([\w\-]+(?: +[\w\-]+)*?)) *(?:\n|$)'
)
COMPRESS_SPACES = re.compile(r' {2,}')
def __init__(self, parser):
"""Initialization."""
su... | DetailsProcessor |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 377,
"end": 4842
} | class ____(TestCase):
def test_get_iterable_objects_with_none(self):
self.assertEqual([], SearchField.get_iterable_objects(None))
def test_get_iterable_objects_with_single_non_iterable_object(self):
obj = object()
expected = [obj]
self.assertEqual(expected, SearchField.get_iter... | SearchFieldTestCase |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_json_parseable.py | {
"start": 414,
"end": 1196
} | class ____(ColumnMapMetricProvider):
condition_metric_name = "column_values.json_parseable"
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
def is_json(val):
try:
json.loads(val)
return True
except E... | ColumnValuesJsonParseable |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/cloud_memorystore.py | {
"start": 1740,
"end": 21736
} | class ____(GoogleBaseHook):
"""
Hook for Google Cloud Memorystore APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Opt... | CloudMemorystoreHook |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/legacy_resources.py | {
"start": 1353,
"end": 9687
} | class ____(ConfigurableResource):
request_max_retries: int = Field(
default=3,
description=(
"The maximum number of times requests to the Airbyte API should be retried "
"before failing."
),
)
request_retry_delay: float = Field(
default=0.25,
d... | BaseAirbyteResource |
python | coleifer__peewee | tests/transactions.py | {
"start": 384,
"end": 875
} | class ____(ModelTestCase):
requires = [Register]
def assertRegister(self, vals):
query = Register.select().order_by(Register.value)
self.assertEqual([register.value for register in query], vals)
def _save(self, *vals):
Register.insert([{Register.value: val} for val in vals]).execut... | BaseTransactionTestCase |
python | ray-project__ray | python/ray/train/xgboost/xgboost_trainer.py | {
"start": 2872,
"end": 13184
} | class ____(SimpleXGBoostTrainer):
"""A Trainer for distributed data-parallel XGBoost training.
Example
-------
.. testcode::
:skipif: True
import xgboost
import ray.data
import ray.train
from ray.train.xgboost import RayTrainReportCallback, XGBoostTrainer
... | XGBoostTrainer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 319431,
"end": 320176
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UnmarkIssueAsDuplicate"""
__schema__ = github_schema
__field_names__ = ("duplicate_id", "canonical_id", "client_mutation_id")
duplicate_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="duplicateId")
"""ID of the issue or pu... | UnmarkIssueAsDuplicateInput |
python | conda__conda | conda/core/package_cache_data.py | {
"start": 2551,
"end": 3116
} | class ____(type):
"""This metaclass does basic caching of PackageCache instance objects."""
def __call__(cls, pkgs_dir: str | os.PathLike | Path):
if isinstance(pkgs_dir, PackageCacheData):
return pkgs_dir
elif (pkgs_dir := str(pkgs_dir)) in PackageCacheData._cache_:
ret... | PackageCacheType |
python | walkccc__LeetCode | solutions/2321. Maximum Score Of Spliced Array/2321.py | {
"start": 0,
"end": 526
} | class ____:
def maximumsSplicedArray(self, nums1: list[int], nums2: list[int]) -> int:
def kadane(nums1: list[int], nums2: list[int]) -> int:
"""
Returns the maximum gain of swapping some numbers in `nums1` with some
numbers in `nums2`.
"""
gain = 0
maxGain = 0
for num1,... | Solution |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/10_A3C/A3C_discrete_action.py | {
"start": 802,
"end": 4413
} | class ____(object):
def __init__(self, scope, globalAC=None):
if scope == GLOBAL_NET_SCOPE: # get global network
with tf.variable_scope(scope):
self.s = tf.placeholder(tf.float32, [None, N_S], 'S')
self.a_params, self.c_params = self._build_net(scope)[-2:]
... | ACNet |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/definitions_component/__init__.py | {
"start": 514,
"end": 891
} | class ____(Component, Model, Resolvable):
"""An arbitrary set of Dagster definitions."""
path: Optional[str]
def build_defs(self, context: ComponentLoadContext) -> Definitions:
component = PythonFileComponent(
Path(self.path) if self.path else context.path, components={}
)
... | DefinitionsComponent |
python | getsentry__sentry | tests/snuba/tsdb/test_tsdb_backend.py | {
"start": 31968,
"end": 33965
} | class ____(TestCase):
def setUp(self) -> None:
self.db = SnubaTSDB()
def run_test(self, end, interval, jitter, expected_start, expected_end):
start = end - interval
rollup, rollup_series = self.db.get_optimal_rollup_series(start, end)
series = self.db._add_jitter_to_series(rollu... | AddJitterToSeriesTest |
python | getsentry__sentry | src/sentry/migrations/0985_add_timestamp_to_grouphash_table.py | {
"start": 184,
"end": 1899
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | keras-team__keras | keras/src/constraints/constraints.py | {
"start": 5292,
"end": 7422
} | class ____(Constraint):
"""MinMaxNorm weight constraint.
Constrains the weights incident to each hidden unit
to have the norm between a lower bound and an upper bound.
Args:
min_value: the minimum norm for the incoming weights.
max_value: the maximum norm for the incoming weights.
... | MinMaxNorm |
python | walkccc__LeetCode | solutions/2492. Minimum Score of a Path Between Two Cities/2492.py | {
"start": 0,
"end": 507
} | class ____:
def minScore(self, n: int, roads: list[list[int]]) -> int:
ans = math.inf
graph = [[] for _ in range(n + 1)] # graph[u] := [(v, distance)]
q = collections.deque([1])
seen = {1}
for u, v, distance in roads:
graph[u].append((v, distance))
graph[v].append((u, distance))
... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py | {
"start": 4376,
"end": 6796
} | class ____(AwsBaseSensor[EmrServerlessHook]):
"""
Poll the state of the job run until it reaches a terminal state; fails if the job run fails.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:EmrServerlessJobSensor`
:param applic... | EmrServerlessJobSensor |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 9377,
"end": 9520
} | class ____(_TestDCTIIIBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 5
self.type = 3
| TestDCTIIIFloat |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 18882,
"end": 28846
} | class ____(_CollectionOperations):
collection_class = set
def test_set_operations(self):
Parent, Child = self.classes.Parent, self.classes.Child
self.session = fixture_session()
p1 = Parent("P1")
self.assert_(not p1._children)
self.assert_(not p1.children)
ch... | SetTest |
python | huggingface__transformers | tests/models/sam/test_modeling_sam.py | {
"start": 1370,
"end": 5448
} | class ____:
def __init__(
self,
parent,
hidden_size=36,
intermediate_size=72,
projection_dim=62,
output_channels=32,
num_hidden_layers=2,
num_attention_heads=4,
num_channels=3,
image_size=24,
patch_size=2,
hidden_act="ge... | SamVisionModelTester |
python | ipython__ipython | IPython/core/display.py | {
"start": 14928,
"end": 15032
} | class ____(TextDisplayObject):
def _repr_latex_(self):
return self._data_and_metadata()
| Latex |
python | astropy__astropy | astropy/io/ascii/fixedwidth.py | {
"start": 15339,
"end": 15483
} | class ____(FixedWidthSplitter):
"""Splitter for fixed width tables splitting on ``' '``."""
delimiter = " "
| FixedWidthTwoLineDataSplitter |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py | {
"start": 30237,
"end": 34829
} | class ____(googletest.Benchmark):
# Configurations to test. See `run_benchmark` for config param docs.
CONFIGS = [
{'shape': [10, 10]},
{'shape': [10, 1000]},
{'shape': [1000, 10]},
{'shape': [1000, 10], 'fill': [1, 0.95]}, # Mostly full.
{'shape': [1000, 10], 'fill': [1, 0.05]}, #... | RaggedToDenseBenchmark |
python | neetcode-gh__leetcode | python/0901-online-stock-span.py | {
"start": 0,
"end": 333
} | class ____:
def __init__(self):
self.stack = [] # pair: (price, span)
def next(self, price: int) -> int:
span = 1
while self.stack and self.stack[-1][0] <= price:
span += self.stack[-1][1]
self.stack.pop()
self.stack.append((price, span))
return ... | StockSpanner |
python | getsentry__sentry | tests/acceptance/test_link_team.py | {
"start": 464,
"end": 4196
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=self.user)
self.team = self.create_team(organization=self.org, name="Team One")
self.create_m... | SlackLinkTeamTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-commcare/source_commcare/source.py | {
"start": 10408,
"end": 12951
} | class ____(AbstractSource):
def check_connection(self, logger, config) -> Tuple[bool, any]:
if "api_key" not in config:
return False, None
return True, None
def base_schema(self):
return {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": ... | SourceCommcare |
python | facebook__pyre-check | client/dataclasses_json_extensions.py | {
"start": 989,
"end": 1271
} | class ____(DataclassJsonMixinWithCachedSchema):
dataclass_json_config: Mapping[str, object] = dataclasses_json.config(
letter_case=dataclasses_json.LetterCase.SNAKE,
undefined=dataclasses_json.Undefined.EXCLUDE,
)["dataclasses_json"]
| SnakeCaseAndExcludeJsonMixin |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 10164,
"end": 10300
} | class ____(PrefectException):
"""
Raised when attempting to call Task.map with all static arguments
"""
| MappingMissingIterable |
python | astropy__astropy | astropy/time/formats.py | {
"start": 79580,
"end": 80169
} | class ____(TimeDeltaFormat, TimeNumeric):
_check_finite = False
def set_jds(self, val1, val2):
self._check_scale(self._scale) # Validate scale.
self.jd1, self.jd2 = day_frac(val1, val2, divisor=1.0 / self.unit)
def to_value(self, **kwargs):
# Note that 1/unit is always exactly rep... | TimeDeltaNumeric |
python | conda__conda | conda/plugins/types.py | {
"start": 2779,
"end": 6090
} | class ____(CondaPlugin):
"""
Return type to use when defining a conda virtual package plugin hook.
For details on how this is used, see
:meth:`~conda.plugins.hookspec.CondaSpecs.conda_virtual_packages`.
.. note::
The ``version`` and ``build`` parameters can be provided in two ways:
... | CondaVirtualPackage |
python | doocs__leetcode | lcof2/剑指 Offer II 018. 有效的回文/Solution.py | {
"start": 0,
"end": 378
} | class ____:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return Fals... | Solution |
python | walkccc__LeetCode | solutions/3343. Count Number of Balanced Permutations/3343.py | {
"start": 0,
"end": 1143
} | class ____:
def countBalancedPermutations(self, num: str) -> int:
nums = list(map(int, num))
summ = sum(nums)
if summ % 2 == 1:
return 0
nums.sort(reverse=True)
@functools.lru_cache(None)
def dp(even: int, odd: int, evenBalance: int) -> int:
"""
Returns the number of permut... | Solution |
python | ray-project__ray | rllib/policy/tf_mixins.py | {
"start": 7339,
"end": 9804
} | class ____:
"""Assign the `update_target` method to the policy.
The function is called every `target_network_update_freq` steps by the
master learner.
"""
def __init__(self):
model_vars = self.model.trainable_variables()
target_model_vars = self.target_model.trainable_variables()
... | TargetNetworkMixin |
python | pypa__warehouse | tests/common/db/packaging.py | {
"start": 2332,
"end": 3638
} | class ____(WarehouseFactory):
class Meta:
model = File
release = factory.SubFactory(ReleaseFactory)
python_version = "source"
# TODO: Replace when factory_boy supports `unique`.
# See https://github.com/FactoryBoy/factory_boy/pull/997
filename = factory.Sequence(lambda _: fake.unique.... | FileFactory |
python | numba__numba | numba/cuda/cudamath.py | {
"start": 3512,
"end": 3788
} | class ____(ConcreteTemplate):
cases = [
signature(types.boolean, types.int64),
signature(types.boolean, types.uint64),
signature(types.boolean, types.float32),
signature(types.boolean, types.float64),
]
@infer_global(math.modf)
| Math_isnan |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/meta_metric_provider.py | {
"start": 550,
"end": 3256
} | class ____(MetaMetricProvider):
"""
Goals:
Instantiation of a deprecated class should raise a warning;
Subclassing of a deprecated class should raise a warning;
Support isinstance and issubclass checks.
"""
# TODO: <Alex>All logging/warning directives should be placed into a com... | DeprecatedMetaMetricProvider |
python | apache__airflow | providers/google/tests/unit/google/suite/sensors/test_drive.py | {
"start": 1283,
"end": 2197
} | class ____:
@mock.patch("airflow.providers.google.suite.sensors.drive.GoogleDriveHook")
def test_should_pass_argument_to_hook(self, mock_hook):
task = GoogleDriveFileExistenceSensor(
task_id="task-id",
folder_id=TEST_FOLDER_ID,
file_name=TEST_FILE_NAME,
dr... | TestGoogleDriveFileSensor |
python | weaviate__weaviate-python-client | weaviate/collections/aggregations/base_executor.py | {
"start": 1513,
"end": 21672
} | class ____(Generic[ConnectionType]):
def __init__(
self,
connection: ConnectionType,
name: str,
consistency_level: Optional[ConsistencyLevel],
tenant: Optional[str],
validate_arguments: bool,
) -> None:
self._connection = connection
self._name = na... | _BaseExecutor |
python | pypa__installer | src/installer/exceptions.py | {
"start": 41,
"end": 134
} | class ____(Exception):
"""All exceptions raised from this package's code."""
| InstallerError |
python | kamyu104__LeetCode-Solutions | Python/reward-top-k-students.py | {
"start": 139,
"end": 1912
} | class ____(object):
def topStudents(self, positive_feedback, negative_feedback, report, student_id, k):
"""
:type positive_feedback: List[str]
:type negative_feedback: List[str]
:type report: List[str]
:type student_id: List[int]
:type k: int
:rtype: List[int]... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/simple/simple_auth_manager.py | {
"start": 2159,
"end": 2934
} | class ____(namedtuple("SimpleAuthManagerRole", "name order"), Enum):
"""
List of pre-defined roles in simple auth manager.
The first attribute defines the name that references this role in the config.
The second attribute defines the order between roles. The role with order X means it grants access to
... | SimpleAuthManagerRole |
python | huggingface__transformers | examples/modular-transformers/configuration_my_new_model2.py | {
"start": 724,
"end": 5345
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configur... | MyNewModel2Config |
python | redis__redis-py | tests/test_asyncio/test_search.py | {
"start": 1535,
"end": 4206
} | class ____:
@pytest_asyncio.fixture()
async def decoded_r(self, create_redis, stack_url):
return await create_redis(decode_responses=True, url=stack_url)
@staticmethod
async def waitForIndex(env, idx, timeout=None):
delay = 0.1
while True:
try:
res = ... | AsyncSearchTestsBase |
python | kubernetes-client__python | kubernetes/client/models/v1_validation.py | {
"start": 383,
"end": 15762
} | 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... | V1Validation |
python | getsentry__sentry | tests/acceptance/test_replay_list.py | {
"start": 338,
"end": 7039
} | class ____(ReplaysAcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band 1")
sel... | ReplayListTest |
python | ApeWorX__ape | src/ape/api/accounts.py | {
"start": 1335,
"end": 25693
} | class ____(BaseInterfaceModel, BaseAddress):
"""
An API class representing an account.
"""
def __dir__(self) -> list[str]:
"""
Display methods to IPython on ``a.[TAB]`` tab completion.
Returns:
list[str]: Method names that IPython uses for tab completion.
""... | AccountAPI |
python | walkccc__LeetCode | solutions/40. Combination Sum II/40.py | {
"start": 0,
"end": 583
} | class ____:
def combinationSum2(self, candidates: list[int],
target: int) -> list[list[int]]:
ans = []
def dfs(s: int, target: int, path: list[int]) -> None:
if target < 0:
return
if target == 0:
ans.append(path.copy())
return
for i in range(s,... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/types.py | {
"start": 3674,
"end": 4136
} | class ____:
"""Represents the data of a dbt Cloud workspace, given a project and environment."""
project_id: int
environment_id: int
# The ID of the ad hoc dbt Cloud job created by Dagster.
# This job is used to parse the dbt Cloud project.
# This job is also used to kick off cli invocation if ... | DbtCloudWorkspaceData |
python | walkccc__LeetCode | solutions/1722. Minimize Hamming Distance After Swap Operations/1722.py | {
"start": 514,
"end": 1181
} | class ____:
def minimumHammingDistance(
self,
source: list[int],
target: list[int],
allowedSwaps: list[list[int]],
) -> int:
n = len(source)
ans = 0
uf = UnionFind(n)
groupIdToCount = [collections.Counter() for _ in range(n)]
for a, b in allowedSwaps:
uf.unionByRan... | Solution |
python | walkccc__LeetCode | solutions/552. Student Attendance Record II/552.py | {
"start": 0,
"end": 750
} | class ____:
def checkRecord(self, n: int) -> int:
MOD = 1_000_000_007
# dp[i][j] := the length so far with i A's and the last letters are j L's
dp = [[0] * 3 for _ in range(2)]
dp[0][0] = 1
for _ in range(n):
prev = [A[:] for A in dp]
# Append a P.
dp[0][0] = (prev[0][0] + prev... | Solution |
python | pytorch__pytorch | test/dynamo/test_exceptions.py | {
"start": 920,
"end": 27316
} | class ____(torch._dynamo.test_case.TestCase):
def test_exception(self):
def fn(x):
x = torch.cos(x)
try:
x = torch.sin(x)
raise NotImplementedError
except Exception:
x = torch.sigmoid(x)
return x
x = to... | ExceptionTests |
python | google__pytype | pytype/abstract/_singletons.py | {
"start": 7948,
"end": 9038
} | class ____(Singleton):
"""An empty value.
These values represent items extracted from empty containers. Because of false
positives in flagging containers as empty (consider:
x = []
def initialize():
populate(x)
def f():
iterate(x)
), we treat these values as placeholders that we can do ... | Empty |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 16762,
"end": 17486
} | class ____:
"""Table 58 – Entries in a Graphics State Parameter Dictionary"""
TYPE = "/Type" # name, optional
LW = "/LW" # number, optional
LC = "/LC" # integer, optional
LJ = "/LJ" # integer, optional
ML = "/ML" # number, optional
D = "/D" # array, optional
RI = "/RI" # name, op... | GraphicsStateParameters |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 16804,
"end": 17108
} | class ____(RequestHandler):
def initialize(self, test):
self.test = test
@gen.coroutine
def get(self):
self.test.on_handler_waiting()
yield self.test.cleanup_event.wait()
def on_connection_close(self):
self.test.on_connection_close()
| ConnectionCloseHandler |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 9480,
"end": 10828
} | class ____(nn.Module):
"""2D Image to Patch Embeddings"""
def __init__(self, config):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
num_channels, hidden_size = config.num_channels, config.hidden_size
image_size = image_size if isinstance(image... | UdopPatchEmbeddings |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 16440,
"end": 18382
} | class ____:
def test_set_module(self):
assert_equal(np.sum.__module__, 'numpy')
assert_equal(np.char.equal.__module__, 'numpy.char')
assert_equal(np.fft.fft.__module__, 'numpy.fft')
assert_equal(np.linalg.solve.__module__, 'numpy.linalg')
def test_inspect_sum(self):
sig... | TestNumPyFunctions |
python | bokeh__bokeh | src/bokeh/models/annotations/dimensional.py | {
"start": 1733,
"end": 2383
} | class ____(Model):
""" A base class for models defining units of measurement.
"""
# explicit __init__ to support Init signatures
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
ticks = Required(List(Float), help="""
Preferred values to choose from in non-exact mod... | Dimensional |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 4516,
"end": 4671
} | class ____(_Test_random):
def setup_method(self):
super().setup_method()
self.x = np.random.randn(self.m)+10
@KDTreeTest
| _Test_random_far |
python | huggingface__transformers | tests/deepspeed/test_alst_ulysses_sp.py | {
"start": 1121,
"end": 7450
} | class ____(TestCasePlus):
"""Test Trainer with ALST/Ulysses sequence parallelism enabled via accelerate's ParallelismConfig."""
@require_torch_multi_accelerator
@require_accelerate
@slow
def test_sp_equivalence(self):
"""Test that ALST/Ulysses sequence parallelism produces the same losses a... | TestTrainerALSTUlyssesSP |
python | numba__llvmlite | llvmlite/tests/test_binding.py | {
"start": 24691,
"end": 29817
} | class ____(BaseTest):
"""
Test miscellaneous functions in llvm.binding.
"""
def test_parse_assembly(self):
self.module(asm_sum)
def test_parse_assembly_error(self):
with self.assertRaises(RuntimeError) as cm:
self.module(asm_parse_error)
s = str(cm.exception)
... | TestMisc |
python | tensorflow__tensorflow | tensorflow/python/saved_model/load.py | {
"start": 7157,
"end": 50120
} | class ____(object):
"""Helper class to load an object-based SavedModel."""
def __init__(self, object_graph_proto, saved_model_proto, export_dir,
ckpt_options, save_options, filters):
meta_graph = saved_model_proto.meta_graphs[0]
self._asset_file_def = meta_graph.asset_file_def
self._oper... | Loader |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_serializers.py | {
"start": 40678,
"end": 58006
} | class ____(TestAlertRuleSerializerBase):
def mock_conversations_info(self, channel):
return mock_slack_response(
"conversations_info",
body={"ok": True, "channel": channel},
req_args={"channel": channel},
)
def patch_msg_schedule_response(self, channel_id, re... | TestAlertRuleTriggerActionSerializer |
python | anthropics__anthropic-sdk-python | src/anthropic/_client.py | {
"start": 18861,
"end": 19815
} | class ____:
_client: Anthropic
def __init__(self, client: Anthropic) -> None:
self._client = client
@cached_property
def completions(self) -> completions.CompletionsWithRawResponse:
from .resources.completions import CompletionsWithRawResponse
return CompletionsWithRawResponse... | AnthropicWithRawResponse |
python | huggingface__transformers | src/transformers/cli/serve.py | {
"start": 11574,
"end": 78507
} | class ____:
# Defining a class to help with internal state but in practice it's just a method to call
# TODO: refactor into a proper module with helpers + 1 main method
def __init__(
self,
continuous_batching: Annotated[
bool, typer.Option(help="Whether to use continuous batching... | Serve |
python | great-expectations__great_expectations | great_expectations/expectations/legacy_row_conditions.py | {
"start": 2142,
"end": 2770
} | class ____(enum.Enum):
"""Type of condition or parser to be used to interpret a RowCondition
Note that many of these are forward looking and are not yet implemented.
In the future this enum can be used internally
instead of strings for the condition_parser user input.
"""
GE = "ge" # GE inter... | RowConditionParserType |
python | django__django | tests/db_functions/math/test_cos.py | {
"start": 268,
"end": 2270
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_cos=Cos("normal")).first()
self.assertIsNone(obj.null_cos)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6"))
obj = ... | CosTests |
python | huggingface__transformers | src/transformers/models/llava_next_video/modeling_llava_next_video.py | {
"start": 6759,
"end": 7740
} | class ____(nn.Module):
def __init__(self, config: LlavaNextVideoConfig):
super().__init__()
# We have hidden_size * the number of vision feature layers
num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
self.linear_1 = nn.Line... | LlavaNextVideoMultiModalProjector |
python | PyCQA__pylint | tests/functional/t/too/too_many_ancestors.py | {
"start": 292,
"end": 385
} | class ____(Aaaa, Bbbb, Cccc, Dddd, Eeee, Ffff, Gggg, Hhhh): # [too-many-ancestors]
pass
| Iiii |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-tplcentral/source_tplcentral/streams.py | {
"start": 3445,
"end": 4715
} | class ____(TplcentralStream, ABC):
state_checkpoint_interval = 100
cursor_field = "_cursor"
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
current = current_stream_state.get(self.cursor_field, "")
latest =... | IncrementalTplcentralStream |
python | joke2k__faker | faker/providers/person/fr_CH/__init__.py | {
"start": 44,
"end": 6954
} | class ____(PersonProvider):
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{l... | Provider |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Robot_arm/DPPO.py | {
"start": 4554,
"end": 8028
} | class ____(object):
def __init__(self, wid):
self.wid = wid
self.env = ArmEnv(mode=MODE[n_model])
self.ppo = GLOBAL_PPO
def work(self):
global GLOBAL_EP, GLOBAL_RUNNING_R, GLOBAL_UPDATE_COUNTER
while not COORD.should_stop():
s = self.env.reset()
e... | Worker |
python | getsentry__sentry | src/sudo/middleware.py | {
"start": 459,
"end": 2470
} | class ____(MiddlewareMixin):
"""
Middleware that contributes ``request.is_sudo()`` and sets the required
cookie for sudo mode to work correctly.
"""
def has_sudo_privileges(self, request: HttpRequest) -> bool:
# Override me to alter behavior
return has_sudo_privileges(request)
... | SudoMiddleware |
python | facebook__pyre-check | tools/upgrade/commands/consolidate_nested_configurations.py | {
"start": 1189,
"end": 5278
} | class ____(ErrorSuppressingCommand):
def __init__(
self,
command_arguments: CommandArguments,
*,
repository: Repository,
subdirectory: Optional[str],
) -> None:
super().__init__(command_arguments, repository)
self._subdirectory: Final[Optional[str]] = subd... | ConsolidateNestedConfigurations |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/tests/test_core.py | {
"start": 73003,
"end": 78555
} | class ____(BaseTest):
# Override from BaseTest!
# Used so that this is not part of the mandatory high strictness test suite yet
MANDATORY_FOR_TEST_STRICTNESS_LEVELS = []
@pytest.fixture(name="operational_certification_test")
async def operational_certification_test_fixture(self, is_connector_certif... | TestConnectorAttributes |
python | wandb__wandb | wandb/vendor/pygments/filters/__init__.py | {
"start": 6019,
"end": 9314
} | class ____(Filter):
"""Convert tabs, newlines and/or spaces to visible characters.
Options accepted:
`spaces` : string or bool
If this is a one-character string, spaces will be replaces by this string.
If it is another true value, spaces will be replaced by ``·`` (unicode
MIDDLE DOT). I... | VisibleWhitespaceFilter |
python | realpython__materials | python-flask-example-heroku/config.py | {
"start": 229,
"end": 302
} | class ____(Config):
DEBUG = True
DEVELOPMENT = True
| DevelopmentConfig |
python | google__jax | jax/experimental/_private_mm/mini_dime.py | {
"start": 2377,
"end": 3736
} | class ____(tuple[jax.Device, ...]):
def __new__(cls, *args):
return super().__new__(cls, sorted(set(args), key=lambda d: d.id))
@cached_property
def ranks(self):
return OrderedDict((d, idx) for idx, d in enumerate(self))
@property
def leader(self):
return self[0]
@cach... | UniqueDevices |
python | crytic__slither | slither/detectors/statements/tautological_compare.py | {
"start": 306,
"end": 2249
} | class ____(AbstractDetector):
"""
Same variable comparison detector
"""
ARGUMENT = "tautological-compare"
HELP = "Comparing a variable to itself always returns true or false, depending on comparison"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.HIGH
WIKI =... | TautologicalCompare |
python | tensorflow__tensorflow | tensorflow/python/eager/monitoring.py | {
"start": 7854,
"end": 8666
} | class ____(Metric):
"""A stateful class for updating a gauge-like integer metric.
This class encapsulates a set of integer values (or a single value for a
label-less metric). Each value is identified by a tuple of labels. The class
allows the user to set each value.
"""
__slots__ = []
def __init__(self... | IntGauge |
python | crytic__slither | slither/tools/mutator/mutators/CR.py | {
"start": 214,
"end": 1457
} | class ____(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "CR"
HELP = "Comment Replacement"
def _mutate(self) -> Dict:
result: Dict = {}
for ( # pylint: disable=too-many-nested-blocks
function
) in self.contract.functions_and_modifiers_declared:
... | CR |
python | pytorch__pytorch | torch/utils/data/datapipes/_decorator.py | {
"start": 1980,
"end": 2347
} | class ____:
prev: bool
def __init__(self) -> None:
global _determinism
self.prev = _determinism
_determinism = True
def __enter__(self) -> None:
pass
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
global _determinism
_determi... | guaranteed_datapipes_determinism |
python | python-jsonschema__jsonschema | jsonschema/protocols.py | {
"start": 1360,
"end": 7198
} | class ____(Protocol):
"""
The protocol to which all validator classes adhere.
Arguments:
schema:
The schema that the validator object will validate with.
It is assumed to be valid, and providing
an invalid schema can lead to undefined behavior. See
... | Validator |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/early_stopping.py | {
"start": 1133,
"end": 1341
} | class ____(Enum):
"""Enum for early stopping reasons."""
NOT_STOPPED = 0
STOPPING_THRESHOLD = 1
DIVERGENCE_THRESHOLD = 2
PATIENCE_EXHAUSTED = 3
NON_FINITE_METRIC = 4
| EarlyStoppingReason |
python | django__django | tests/admin_scripts/tests.py | {
"start": 115353,
"end": 121092
} | class ____(AdminScriptTestCase):
def test_invalid_name(self):
"""startapp validates that app name is a valid Python identifier."""
for bad_name in ("7testproject", "../testproject"):
with self.subTest(app_name=bad_name):
args = ["startapp", bad_name]
testp... | StartApp |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 203332,
"end": 203444
} | class ____(
_DateTimeMultiRangeTests, _MultiRangeTypeCompilation
):
pass
| DateTimeMultiRangeCompilationTest |
python | Farama-Foundation__Gymnasium | tests/envs/mujoco/test_mujoco_custom_env.py | {
"start": 291,
"end": 4040
} | class ____(MujocoEnv, utils.EzPickle):
"""
A simple mujoco env to test third party mujoco env, using the `Gymnasium.MujocoEnv` environment API.
"""
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
"rgbd_tuple",
],
}
... | PointEnv |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 28252,
"end": 39379
} | class ____(Request):
"""
Create a new model not associated with a task
:param uri: URI for the model
:type uri: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined tags list
:type tags:... | CreateRequest |
python | pytorch__pytorch | torch/_subclasses/meta_utils.py | {
"start": 18782,
"end": 19305
} | class ____:
id: MetaStorageId
size: int
# NB: this is only populated with copy_data True, it is not directly
# serializable in JSON, you want to do something special here anyway
data: Optional[torch.UntypedStorage]
def as_json(self, describer_id: _DescriberId) -> dict[str, object]:
retu... | MetaStorageDesc |
python | Pylons__pyramid | tests/test_csrf.py | {
"start": 7758,
"end": 9436
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
# set up CSRF
self.config.set_default_csrf_options(require_csrf=False)
def _callFUT(self, *args, **kwargs):
from pyramid.csrf import check_csrf_token
return check_csrf_token(*args, **kwargs)
... | Test_check_csrf_token |
python | google__pytype | pytype/tests/test_unions.py | {
"start": 2318,
"end": 6201
} | class ____(test_base.BaseTest):
"""Tests for the A | B | ... type union syntax."""
def test_basic(self):
ty = self.Infer("""
x: int | str
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Union
x: Union[int, str]
""",
)
def test_chained(self):
t... | UnionOrTest |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 16588,
"end": 26159
} | class ____:
def test_example1a(self):
# Example data from Scholz & Stephens (1987), originally
# published in Lehmann (1995, Nonparametrics, Statistical
# Methods Based on Ranks, p. 309)
# Pass a mixture of lists and arrays
t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0... | TestAndersonKSamp |
python | streamlit__streamlit | lib/streamlit/web/server/upload_file_request_handler.py | {
"start": 1105,
"end": 5822
} | class ____(tornado.web.RequestHandler):
"""Implements the POST /upload_file endpoint."""
def initialize(
self,
file_mgr: MemoryUploadedFileManager,
is_active_session: Callable[[str], bool],
) -> None:
"""
Parameters
----------
file_mgr : UploadedFileM... | UploadFileRequestHandler |
python | tensorflow__tensorflow | tensorflow/python/trackable/resource.py | {
"start": 1196,
"end": 2427
} | class ____:
"""An object that tracks a list of resources."""
__slots__ = ["_resources"]
def __init__(self):
self._resources = []
@property
def resources(self):
return self._resources
def add_resource(self, resource):
self._resources.append(resource)
@tf_contextlib.contextmanager
def resour... | ResourceTracker |
python | Textualize__textual | docs/examples/tutorial/stopwatch.py | {
"start": 1468,
"end": 2306
} | class ____(HorizontalGroup):
"""A stopwatch widget."""
def on_button_pressed(self, event: Button.Pressed) -> None:
"""Event handler called when a button is pressed."""
button_id = event.button.id
time_display = self.query_one(TimeDisplay)
if button_id == "start":
tim... | Stopwatch |
python | tensorflow__tensorflow | tensorflow/python/grappler/item_test.py | {
"start": 1361,
"end": 4737
} | class ____(test.TestCase):
def testInvalidItem(self):
with ops.Graph().as_default() as g:
a = constant_op.constant(10)
b = constant_op.constant(20)
c = a + b # pylint: disable=unused-variable
mg = meta_graph.create_meta_graph_def(graph=g)
# The train op isn't specified: this should ... | ItemTest |
python | explosion__spaCy | spacy/lang/ja/__init__.py | {
"start": 1105,
"end": 7309
} | class ____(DummyTokenizer):
def __init__(self, vocab: Vocab, split_mode: Optional[str] = None) -> None:
self.vocab = vocab
self.split_mode = split_mode
self.tokenizer = try_sudachi_import(self.split_mode)
# if we're using split mode A we don't need subtokens
self.need_subtoke... | JapaneseTokenizer |
python | walkccc__LeetCode | solutions/709. To Lower Case/709.py | {
"start": 0,
"end": 134
} | class ____:
def toLowerCase(self, str: str) -> str:
return ''.join(chr(ord(c) + 32) if 'A' <= c <= 'Z' else c for c in str)
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.