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 | joke2k__faker | faker/providers/company/zh_TW/__init__.py | {
"start": 45,
"end": 2041
} | class ____(CompanyProvider):
formats = ("{{company_prefix}}{{company_suffix}}",)
company_prefixes = (
"品王餐飲",
"一統企業",
"品誠",
"台灣電信",
"Goagle",
"一統星巴克",
"台日積體電路",
"榮長航空",
"台灣印無品良",
"華中航空",
"台灣人銀行",
"國中鋼鐵",
"海鴻... | Provider |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 2251,
"end": 10079
} | class ____(object):
"""
A mixin defining constant operations, for use in constant-like classes.
"""
#
# Arithmetic APIs
#
@_binop('shl')
def shl(self, other):
"""
Left integer shift:
lhs << rhs
"""
@_binop('lshr')
def lshr(self, other):
... | _ConstOpMixin |
python | apache__airflow | helm-tests/tests/helm_tests/apiserver/test_ingress_apiserver.py | {
"start": 914,
"end": 9797
} | class ____:
"""Tests ingress API Server."""
def test_should_pass_validation_with_just_ingress_enabled_v1(self):
render_chart(
values={"ingress": {"apiServer": {"enabled": True}}, "airflowVersion": "3.0.0"},
show_only=["templates/api-server/api-server-ingress.yaml"],
) #... | TestIngressAPIServer |
python | ipython__ipython | IPython/utils/strdispatch.py | {
"start": 185,
"end": 1832
} | class ____:
"""Dispatch (lookup) a set of strings / regexps for match.
Example:
>>> dis = StrDispatch()
>>> dis.add_s('hei',34, priority = 4)
>>> dis.add_s('hei',123, priority = 2)
>>> dis.add_re('h.i', 686)
>>> print(list(dis.flat_matches('hei')))
[123, 34, 686]
"""
def __ini... | StrDispatch |
python | huggingface__transformers | src/transformers/models/sam/modeling_sam.py | {
"start": 14985,
"end": 17074
} | class ____(nn.Module):
def __init__(self, config: SamMaskDecoderConfig):
super().__init__()
self.config = config
self.num_hidden_layers = config.num_hidden_layers
self.layers = nn.ModuleList()
for i in range(self.num_hidden_layers):
self.layers.append(SamTwoWayA... | SamTwoWayTransformer |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 37343,
"end": 37694
} | class ____(Operator):
""" Decrement a lower index. """
def __init__(self, bi):
bi = sympify(bi)
if bi == 1:
raise ValueError('Cannot decrement unit lower index.')
self._poly = Poly(_x/(bi - 1) + 1, _x)
def __str__(self):
return '<Decrement lower %s.>' % (1/self.... | ShiftB |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore.py | {
"start": 17334,
"end": 18034
} | class ____(unittest.TestCase):
class MockSearcher(Searcher):
def __init__(self, data):
self.data = data
def save(self, path):
with open(path, "w") as f:
f.write(self.data)
def restore(self, path):
with open(path, "r") as f:
... | SearcherTest |
python | joke2k__faker | faker/providers/barcode/en_US/__init__.py | {
"start": 156,
"end": 11356
} | class ____(BarcodeProvider):
"""Implement barcode provider for ``en_US`` locale.
Sources:
- https://gs1.org/standards/id-keys/company-prefix
"""
local_prefixes = (
*product((0,), range(10)),
*product((1,), range(4)),
)
upc_e_base_pattern: Pattern = re.compile(r"^\d{6}$")
... | Provider |
python | kamyu104__LeetCode-Solutions | Python/count-pairs-with-xor-in-a-range.py | {
"start": 783,
"end": 1611
} | class ____(object):
def __init__(self):
self.__root = {}
def insert(self, num):
node = self.__root
for i in reversed(xrange(32)):
curr = (num>>i) & 1
if curr not in node:
node[curr] = {"_count":0}
node = node[curr]
... | Trie |
python | django__django | tests/signals/tests.py | {
"start": 17847,
"end": 17967
} | class ____:
param = 0
def __call__(self, **kwargs):
self.param += 1
return self.param
| SyncHandler |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/dropbox/tests.py | {
"start": 260,
"end": 1373
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = DropboxOAuth2Provider.id
def get_mocked_response(self):
payload = {
"account_id": "dbid:ASDFasd3ASdfasdFAsd1AS2ASDF1aS-DfAs",
"account_type": {".tag": "basic"},
"country": "US",
"disabled": False,
... | DropboxOAuth2Tests |
python | apache__airflow | dev/breeze/tests/test_ui_commands.py | {
"start": 6875,
"end": 7253
} | class ____:
def test_locale_key_set_with_keys(self):
lks = LocaleKeySet(locale="en", keys={"key1", "key2"})
assert lks.locale == "en"
assert lks.keys == {"key1", "key2"}
def test_locale_key_set_without_keys(self):
lks = LocaleKeySet(locale="de", keys=None)
assert lks.loc... | TestLocaleKeySet |
python | tensorflow__tensorflow | tensorflow/python/training/saving/saveable_object.py | {
"start": 2100,
"end": 3369
} | class ____:
"""Base class for saving and restoring saveable objects."""
def __init__(self, op, specs, name):
"""Creates a `SaveableObject` object.
Args:
op: the "producer" object that this class wraps; it produces a list of
tensors to save. E.g., a "Variable" object saving its backing tenso... | SaveableObject |
python | Netflix__metaflow | metaflow/datastore/datastore_set.py | {
"start": 345,
"end": 2317
} | class ____(object):
def __init__(
self,
flow_datastore,
run_id,
steps=None,
pathspecs=None,
prefetch_data_artifacts=None,
allow_not_done=False,
join_type=None,
orig_flow_datastore=None,
spin_artifacts=None,
):
self.task_data... | TaskDataStoreSet |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 37011,
"end": 37517
} | class ____(_TestBasicOps, __TestCase):
def setUp(self):
self.case = "unit set (number)"
self.values = [3]
self.set = set(self.values)
self.dup = set(self.values)
self.length = 1
self.repr = "{3}"
super().setUp()
def test_in(self):
self.a... | TestBasicOpsSingleton |
python | pydata__xarray | xarray/tests/test_tutorial.py | {
"start": 173,
"end": 835
} | class ____:
def test_download_from_github(self, tmp_path) -> None:
cache_dir = tmp_path / tutorial._default_cache_dir_name
ds = tutorial.load_dataset("tiny", cache_dir=cache_dir)
tiny = DataArray(range(5), name="tiny").to_dataset()
assert_identical(ds, tiny)
def test_download_fr... | TestLoadDataset |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/c10d_rendezvous_backend_test.py | {
"start": 2089,
"end": 10454
} | class ____(TestCase):
def setUp(self) -> None:
# For testing, the default parameters used are for tcp. If a test
# uses parameters for file store, we set the self._params to
# self._params_filestore.
port = get_free_port()
self._params = RendezvousParameters(
bac... | CreateBackendTest |
python | openai__openai-python | src/openai/types/beta/file_search_tool.py | {
"start": 626,
"end": 1555
} | class ____(BaseModel):
max_num_results: Optional[int] = None
"""The maximum number of results the file search tool should output.
The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number
should be between 1 and 50 inclusive.
Note that the file search tool may output fewer than ... | FileSearch |
python | getsentry__sentry | src/sentry/http.py | {
"start": 1131,
"end": 1399
} | class ____(Exception):
error_type = EventError.UNKNOWN_ERROR
def __init__(self, data=None):
if data is None:
data = {}
data.setdefault("type", self.error_type)
super().__init__(data["type"])
self.data = data
| BadSource |
python | pypa__hatch | src/hatch/config/model.py | {
"start": 557,
"end": 1144
} | class ____:
def __init__(self, config: dict, steps: tuple = ()):
self.raw_data = config
self.steps = steps
def parse_fields(self):
for attribute in self.__dict__:
_, prefix, name = attribute.partition("_field_")
if prefix:
parse_config(getattr(sel... | LazilyParsedConfig |
python | huggingface__transformers | src/transformers/models/donut/modeling_donut_swin.py | {
"start": 1545,
"end": 2593
} | class ____(ModelOutput):
r"""
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
... | DonutSwinEncoderOutput |
python | tensorflow__tensorflow | tensorflow/python/framework/versions_test.py | {
"start": 830,
"end": 1990
} | class ____(test.TestCase):
def testVersion(self):
self.assertEqual(type(versions.__version__), str)
self.assertEqual(type(versions.VERSION), str)
# This pattern will need to grow as we include alpha, builds, etc.
self.assertRegex(
versions.__version__, r'^\d+\.\d+\.(\d+(\-\w+)?(\+\w+)?|head)$... | VersionTest |
python | doocs__leetcode | solution/2700-2799/2762.Continuous Subarrays/Solution.py | {
"start": 0,
"end": 308
} | class ____:
def continuousSubarrays(self, nums: List[int]) -> int:
ans = i = 0
sl = SortedList()
for x in nums:
sl.add(x)
while sl[-1] - sl[0] > 2:
sl.remove(nums[i])
i += 1
ans += len(sl)
return ans
| Solution |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 162442,
"end": 163700
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.outer(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [1])
x2_shape = getattr(x2, "shape", [1])
if None in x1_shape:
x1_flatten_shape = None
else:
x... | Outer |
python | django__django | tests/invalid_models_tests/test_relative_fields.py | {
"start": 61487,
"end": 64797
} | class ____(SimpleTestCase):
def test_accessor_clash(self):
class Model(models.Model):
model_set = models.ForeignKey("Model", models.CASCADE)
self.assertEqual(
Model.check(),
[
Error(
"Reverse accessor 'Model.model_set' for "
... | SelfReferentialFKClashTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 66171,
"end": 66583
} | class ____(GenericFunction[_T]):
r"""Implement the ``ROLLUP`` grouping operation.
This function is used as part of the GROUP BY of a statement,
e.g. :meth:`_expression.Select.group_by`::
stmt = select(
func.sum(table.c.value), table.c.col_1, table.c.col_2
).group_by(func.rollup... | rollup |
python | PrefectHQ__prefect | tests/runtime/test_flow_run.py | {
"start": 20808,
"end": 22805
} | class ____:
@pytest.mark.parametrize("url_type", ["api_url", "ui_url"])
async def test_url_is_attribute(self, url_type: str):
assert url_type in dir(flow_run)
@pytest.mark.parametrize("url_type", ["api_url", "ui_url"])
async def test_url_is_none_when_id_not_set(self, url_type: str):
ass... | TestURL |
python | gevent__gevent | src/gevent/tests/test__server_pywsgi.py | {
"start": 2624,
"end": 2718
} | class ____(test__server.TestSSLSocketNotAllowed):
Settings = Settings
| TestSSLSocketNotAllowed |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1571680,
"end": 1572832
} | class ____(sgqlc.types.Type, Node):
"""An edit on user content"""
__schema__ = github_schema
__field_names__ = ("created_at", "deleted_at", "deleted_by", "diff", "edited_at", "editor", "updated_at")
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifi... | UserContentEdit |
python | pytorch__pytorch | test/lazy/test_generator.py | {
"start": 232,
"end": 3163
} | class ____(TestCase):
def test_generator(self):
"""
Test that generators are being inserted into the TorchScript
graph by setting different seeds before each call to
generate_tensor but the resulting tensor is the same
"""
def generate_tensor():
g1 = torc... | LazyGeneratorTest |
python | crytic__slither | slither/core/expressions/member_access.py | {
"start": 112,
"end": 872
} | class ____(Expression):
def __init__(self, member_name: str, member_type: str, expression: Expression) -> None:
# assert isinstance(member_type, Type)
# TODO member_type is not always a Type
assert isinstance(expression, Expression)
super().__init__()
self._type: Type = membe... | MemberAccess |
python | doocs__leetcode | solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/Solution.py | {
"start": 0,
"end": 181
} | class ____:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1))
| Solution |
python | astropy__astropy | astropy/table/bst.py | {
"start": 1921,
"end": 3452
} | class ____:
"""
An element in a binary search tree, containing
a key, data, and references to children nodes and
a parent node.
Parameters
----------
key : tuple
Node key
data : list or int
Node data
"""
__lt__ = lambda x, y: x.key < y.key
__le__ = lambda x,... | Node |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 8709,
"end": 10704
} | class ____(String):
"""A variable length Unicode string type.
The :class:`.Unicode` type is a :class:`.String` subclass that assumes
input and output strings that may contain non-ASCII characters, and for
some backends implies an underlying column type that is explicitly
supporting of non-ASCII dat... | Unicode |
python | encode__starlette | starlette/middleware/cors.py | {
"start": 454,
"end": 7527
} | class ____:
def __init__(
self,
app: ASGIApp,
allow_origins: Sequence[str] = (),
allow_methods: Sequence[str] = ("GET",),
allow_headers: Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: str | None = None,
allow_private_network: ... | CORSMiddleware |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_sentry.py | {
"start": 2138,
"end": 2322
} | class ____:
pass
def is_configured(obj):
from airflow.sdk.execution_time.sentry.configured import ConfiguredSentry
return isinstance(obj, ConfiguredSentry)
| CustomTransport |
python | huggingface__transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | {
"start": 35983,
"end": 38460
} | class ____(nn.Module):
def __init__(self, config):
"""ViT-like transformer block
Args:
config (`ZoeDepthConfig`):
Model configuration class defining the model architecture.
"""
super().__init__()
in_channels = config.bottleneck_features
... | ZoeDepthPatchTransformerEncoder |
python | pytorch__pytorch | torch/distributed/checkpoint/examples/stateful_example.py | {
"start": 565,
"end": 2817
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
torch.manual_seed(0)
self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU())
self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU())
self.net3 = nn.Linear(32, 64)
self.net4 = nn.Sequential(nn.R... | Model |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_container_instance.py | {
"start": 5573,
"end": 6902
} | class ____:
@patch("airflow.providers.microsoft.azure.hooks.container_instance.ContainerInstanceManagementClient")
@patch("azure.common.credentials.ServicePrincipalCredentials")
@patch("airflow.providers.microsoft.azure.hooks.container_instance.get_sync_default_azure_credential")
def test_get_conn_fallb... | TestAzureContainerInstanceHookWithoutSetupCredential |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_typed_mapping.py | {
"start": 6772,
"end": 38819
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
@testing.combinations(
"default", "insert_default", argnames="use_paramname"
)
@testing.combinations(True, False, argnames="use_none")
def test_col_defaults(self, use_paramname, use_none, decl_base):
... | MappedColumnTest |
python | conda__conda | conda/exceptions.py | {
"start": 32430,
"end": 32947
} | class ____(CondaError, ValueError):
def __init__(self, packages_with_cycles: Iterable[PackageRecord], **kwargs):
from .models.records import PackageRecord
packages_with_cycles = tuple(
PackageRecord.from_objects(p) for p in packages_with_cycles
)
message = f"Cyclic depen... | CyclicalDependencyError |
python | huggingface__transformers | tests/models/clvp/test_modeling_clvp.py | {
"start": 10428,
"end": 12218
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (ClvpModel, ClvpForCausalLM) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": ClvpModelForConditionalGeneration} if is_torch_available() else {}
def setUp(self):
... | ClvpDecoderTest |
python | ray-project__ray | doc/source/ray-core/doc_code/direct_transport_gloo.py | {
"start": 1240,
"end": 1928
} | class ____:
@ray.method(tensor_transport="gloo")
def random_tensor(self):
return torch.randn(1000, 1000)
def sum(self, tensor: torch.Tensor):
return torch.sum(tensor)
sender, receiver = MyActor.remote(), MyActor.remote()
group = create_collective_group([sender, receiver], backend="torch_g... | MyActor |
python | conda__conda | conda/exceptions.py | {
"start": 42173,
"end": 42305
} | class ____(CondaError):
def __init__(self, msg: str, *args, **kwargs):
super().__init__(msg, *args, **kwargs)
| SpecNotFound |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/vultr.py | {
"start": 725,
"end": 1489
} | class ____(CloudEnvironment):
"""Updates integration test environment after delegation. Will setup the config file as parameter."""
def get_environment_config(self) -> CloudEnvironmentConfig:
"""Return environment configuration for use in the test environment after delegation."""
parser = confi... | VultrCloudEnvironment |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 2353,
"end": 2873
} | class ____(ModelOutput):
r"""
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
Pixel reconstruction logits.
"""
logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[... | ViTMAEDecoderOutput |
python | Netflix__metaflow | metaflow/user_configs/config_parameters.py | {
"start": 1283,
"end": 7728
} | class ____(collections.abc.Mapping, dict):
"""
ConfigValue is a thin wrapper around an arbitrarily nested dictionary-like
configuration object. It allows you to access elements of this nested structure
using either a "." notation or a [] notation. As an example, if your configuration
object is:
... | ConfigValue |
python | openai__gym | gym/error.py | {
"start": 942,
"end": 1106
} | class ____(Error):
"""Raised when the user requests an env from the registry with an older version number than the latest env with the same name."""
| DeprecatedEnv |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/workers/container_instance.py | {
"start": 14106,
"end": 18895
} | class ____(BaseVariables):
"""
Variables for an Azure Container Instance flow run.
"""
image: str = Field(
default_factory=get_prefect_image_name,
description=(
"The image to use for the Prefect container in the task. This value "
"defaults to a Prefect base imag... | AzureContainerVariables |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/attention.py | {
"start": 4023,
"end": 6984
} | class ____(torch.nn.Module):
"""
A module used to embed entities before passing them to a self-attention block.
Used in conjunction with ResidualSelfAttention to encode information about a self
and additional entities. Can also concatenate self to entities for ego-centric self-
attention. Inspired b... | EntityEmbedding |
python | getsentry__sentry | src/sentry/codecov/enums.py | {
"start": 464,
"end": 615
} | class ____(Enum):
INTERVAL_30_DAY = "INTERVAL_30_DAY"
INTERVAL_7_DAY = "INTERVAL_7_DAY"
INTERVAL_1_DAY = "INTERVAL_1_DAY"
| MeasurementInterval |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1250866,
"end": 1251666
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData):
"""Audit log entry for a org.enable_saml event."""
__schema__ = github_schema
__field_names__ = ("digest_method_url", "issuer_url", "signature_method_url", "single_sign_on_url")
digest_method_url = sgqlc.types.Field(URI, graphq... | OrgEnableSamlAuditEntry |
python | prabhupant__python-ds | data_structures/bst/dfs_recursion.py | {
"start": 0,
"end": 615
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Depth First Search
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
... | Node |
python | doocs__leetcode | solution/2200-2299/2288.Apply Discount to Prices/Solution.py | {
"start": 0,
"end": 302
} | class ____:
def discountPrices(self, sentence: str, discount: int) -> str:
ans = []
for w in sentence.split():
if w[0] == '$' and w[1:].isdigit():
w = f'${int(w[1:]) * (1 - discount / 100):.2f}'
ans.append(w)
return ' '.join(ans)
| Solution |
python | google__python-fire | fire/decorators_test.py | {
"start": 2045,
"end": 5582
} | class ____(testutils.BaseTestCase):
def testSetParseFnsNamedArgs(self):
self.assertEqual(core.Fire(NoDefaults, command=['double', '2']), 4)
self.assertEqual(core.Fire(NoDefaults, command=['triple', '4']), 12.0)
def testSetParseFnsPositionalArgs(self):
self.assertEqual(core.Fire(NoDefaults, command=['q... | FireDecoratorsTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/collections.py | {
"start": 14268,
"end": 47821
} | class ____:
"""Bridges between the ORM and arbitrary Python collections.
Proxies base-level collection operations (append, remove, iterate)
to the underlying Python collection, and emits add/remove events for
entities entering or leaving the collection.
The ORM uses :class:`.CollectionAdapter` exc... | CollectionAdapter |
python | huggingface__transformers | src/transformers/models/florence2/modular_florence2.py | {
"start": 44262,
"end": 44318
} | class ____(BeitDropPath):
pass
| Florence2VisionDropPath |
python | doocs__leetcode | solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/Solution.py | {
"start": 0,
"end": 192
} | class ____:
def minStartValue(self, nums: List[int]) -> int:
s, t = 0, inf
for num in nums:
s += num
t = min(t, s)
return max(1, 1 - t)
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 60233,
"end": 61064
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"path",
"location",
"annotation_level",
"message",
"title",
"raw_details",
)
path = sgqlc.types.Field(sgqlc.types.non_null(St... | CheckAnnotationData |
python | numba__numba | numba/cuda/tests/cudapy/test_array_args.py | {
"start": 193,
"end": 4991
} | class ____(CUDATestCase):
def test_array_ary(self):
@cuda.jit('double(double[:],int64)', device=True, inline=True)
def device_function(a, c):
return a[c]
@cuda.jit('void(double[:],double[:])')
def kernel(x, y):
i = cuda.grid(1)
y[i] = device_func... | TestCudaArrayArg |
python | getsentry__sentry | src/sentry/migrations/1007_cleanup_failed_safe_deletes.py | {
"start": 207,
"end": 1933
} | 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 | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py | {
"start": 4980,
"end": 6712
} | class ____(AwsBaseOperator[DmsHook]):
"""
Deletes AWS DMS replication task.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DmsDeleteTaskOperator`
:param replication_task_arn: Replication task ARN
:param aws_conn_id: The... | DmsDeleteTaskOperator |
python | sqlalchemy__sqlalchemy | test/orm/test_instrumentation.py | {
"start": 11583,
"end": 12145
} | class ____(fixtures.ORMTest):
"""Check that Events.load is not hit in regular attributes operations."""
def test_basic(self):
import pickle
global A
class A:
pass
def canary(instance):
assert False
try:
instrumentation.register_cla... | OnLoadTest |
python | numpy__numpy | benchmarks/benchmarks/bench_reduce.py | {
"start": 2682,
"end": 2834
} | class ____(Benchmark):
def setup(self):
self.d = np.ones(100, dtype=np.float32)
def time_small(self):
np.sum(self.d)
| SmallReduction |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_compiler.py | {
"start": 59023,
"end": 65020
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = mysql.dialect()
match_table = table(
"user",
column("firstname", String),
column("lastname", String),
)
@testing.combinations(
(
lambda title: title.match("somstr", mysql_boolean_mode=False),
... | MatchExpressionTest |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/session_debug_testlib.py | {
"start": 60881,
"end": 64715
} | class ____(test_util.TensorFlowTestCase):
"""Test for debugging concurrent Session.run() calls."""
def _get_concurrent_debug_urls(self):
"""Abstract method to generate debug URLs for concurrent debugged runs."""
raise NotImplementedError(
"_get_concurrent_debug_urls is not implemented in the base t... | DebugConcurrentRunCallsTest |
python | OmkarPathak__pygorithm | tests/test_geometry.py | {
"start": 62026,
"end": 95476
} | class ____(unittest.TestCase):
"""
It is suggested that you follow along these tests with the images
at imgs/test_geometry/test_extrapolated_intersection. All image
references will be relative to that folder and will be referencing
the .py file, whereas the actual images are in the out/
folde... | TestExtrapolatedIntersection |
python | numpy__numpy | numpy/_core/tests/test_function_base.py | {
"start": 4115,
"end": 10531
} | class ____:
def test_basic(self):
y = geomspace(1, 1e6)
assert_(len(y) == 50)
y = geomspace(1, 1e6, num=100)
assert_(y[-1] == 10 ** 6)
y = geomspace(1, 1e6, endpoint=False)
assert_(y[-1] < 10 ** 6)
y = geomspace(1, 1e6, num=7)
assert_array_equal(y, [1... | TestGeomspace |
python | ultrajson__ultrajson | tests/fuzz.py | {
"start": 653,
"end": 1987
} | class ____:
"""A random JSON serialisable object generator."""
def __init__(self, seed=None):
self._randomizer = random.Random(seed)
self._shrink = 1
def key(self):
key_types = [self.int, self.float, self.string, self.null, self.bool]
return self._randomizer.choice(key_type... | FuzzGenerator |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 113533,
"end": 141610
} | class ____(CType):
# return_type CType
# args [CFuncTypeArg]
# has_varargs boolean
# exception_value CFuncType.ExceptionValue or Node (for except+)
# exception_check boolean True if PyErr_Occurred check needed
# calling_convention string Function calling conven... | CFuncType |
python | getsentry__sentry | src/sentry/snuba/metrics/datasource.py | {
"start": 19205,
"end": 38219
} | class ____:
"""Fields and values to filter queries when exceeding the Snuba query limit.
Snuba imposes a limit on the number of rows that can be queried and
returned. This limit can be exceeded when grouping metrics by one or more
tags. In this case, we take the first groups returned by Snuba and filte... | GroupLimitFilters |
python | getsentry__sentry | src/sentry/notifications/notification_action/action_validation.py | {
"start": 3954,
"end": 4402
} | class ____(BaseActionValidatorHandler):
notify_action_form = IntegrationNotifyServiceForm
def generate_action_form_data(self) -> dict[str, Any]:
return {
"integration": self.validated_data["integration_id"],
}
def update_action_data(self, cleaned_data: dict[str, Any]) -> dict[s... | TicketingActionValidatorHandler |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/aot_autograd_result.py | {
"start": 21469,
"end": 25018
} | class ____(
GenericAOTAutogradResult[
BundledCompiledForward[TOutputCode], BundledCompiledBackward[TOutputCode]
],
Generic[TOutputCode],
):
"""
Generic AOTAutogradResult where we bundle the entire OutputCode directly
(rather than looking it up via FxGraphCache).
This works with any ... | BundledAOTAutogradResult |
python | tensorflow__tensorflow | tensorflow/python/data/ops/snapshot_op.py | {
"start": 2279,
"end": 4707
} | class ____(dataset_ops.UnaryUnchangedStructureDataset):
"""A dataset that allows saving and re-use of already processed data."""
def __init__(self,
input_dataset,
path,
shard_func,
compression=None,
reader_func=None,
pending_... | _SnapshotDataset |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_function.py | {
"start": 791,
"end": 2192
} | class ____(threading.local):
"""A context object holding state about the TPU computation being built."""
def __init__(self):
"""Creates a new TpuContext."""
self._number_of_shards = None
@property
def number_of_shards(self):
return self._number_of_shards
def set_number_of_shards(self, number_of... | TpuContext |
python | ray-project__ray | python/ray/train/tests/test_predictor.py | {
"start": 1068,
"end": 1542
} | class ____(DummyPreprocessor):
def _transform_numpy(
self, np_data: Union[np.ndarray, Dict[str, np.ndarray]]
) -> Union[np.ndarray, Dict[str, np.ndarray]]:
self.inputs.append(np_data)
assert isinstance(np_data, np.ndarray)
rst = np_data * self.multiplier
self.outputs.appe... | DummyWithNumpyPreprocessor |
python | wandb__wandb | wandb/apis/importers/wandb.py | {
"start": 50195,
"end": 54547
} | class ____:
entity: str = ""
project: str = ""
run_id: str = RUN_DUMMY_PLACEHOLDER
id: str = RUN_DUMMY_PLACEHOLDER
display_name: str = RUN_DUMMY_PLACEHOLDER
notes: str = ""
url: str = ""
group: str = ""
created_at: str = "2000-01-01"
user: _DummyUser = field(default_factory=_Dumm... | _DummyRun |
python | python-openxml__python-docx | src/docx/parts/hdrftr.py | {
"start": 1008,
"end": 1709
} | class ____(StoryPart):
"""Definition of a section header."""
@classmethod
def new(cls, package: Package):
"""Return newly created header part."""
partname = package.next_partname("/word/header%d.xml")
content_type = CT.WML_HEADER
element = parse_xml(cls._default_header_xml()... | HeaderPart |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/manifest_resolver.py | {
"start": 143,
"end": 6639
} | class ____:
"""
An incoming manifest can contain references to values previously defined.
This parser will dereference these values to produce a complete ConnectionDefinition.
References can be defined using a #/<arg> string.
```
key: 1234
reference: "#/key"
```
will produce the fol... | ManifestReferenceResolver |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/gcs_upload.py | {
"start": 1453,
"end": 1600
} | class ____:
metadata_uploaded: bool
metadata_file_path: str
uploaded_files: List[UploadedFile]
@dataclass(frozen=True)
| MetadataUploadInfo |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/remote_explorer.py | {
"start": 1907,
"end": 2062
} | class ____:
CopyPaste = "remote_copy_paste_section"
Extras = "remote_extras_section"
New = "remote_new_section"
| RemoteExplorerContextMenuSections |
python | apache__airflow | airflow-core/tests/unit/utils/test_sqlalchemy.py | {
"start": 7994,
"end": 13750
} | class ____:
@pytest.mark.parametrize(
("input", "expected"),
[
("anything", "anything"),
(
{"pod_override": TEST_POD},
{
"pod_override": {
"__var": {"spec": {"containers": [{"name": "base"}]}},
... | TestExecutorConfigType |
python | ray-project__ray | doc/source/serve/doc_code/batching_guide.py | {
"start": 494,
"end": 1183
} | class ____:
@serve.batch(max_batch_size=8, batch_wait_timeout_s=0.1)
async def __call__(self, multiple_samples: List[int]) -> List[int]:
# Use numpy's vectorized computation to efficiently process a batch.
return np.array(multiple_samples) * 2
handle: DeploymentHandle = serve.run(Model.bind())... | Model |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/private.py | {
"start": 4514,
"end": 4842
} | class ____(
PrivateViewMixin,
UpdateChangeReasonPostView,
OrganizationView,
AsyncDeleteViewWithMessage,
):
http_method_names = ["post"]
success_message = _("Organization queued for deletion")
def get_success_url(self):
return reverse_lazy("organization_list")
# Owners views
| DeleteOrganization |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/definition/cacheable_assets_definition.py | {
"start": 9074,
"end": 10537
} | class ____(CacheableAssetsDefinition):
"""Wraps an instance of CacheableAssetsDefinition, applying transformed_assets_def to the
generated AssetsDefinition objects. This lets e.g. users define resources on
the cacheable assets at repo creation time which are not actually bound until
the assets themselve... | WrappedCacheableAssetsDefinition |
python | scikit-learn__scikit-learn | sklearn/_loss/loss.py | {
"start": 31565,
"end": 34014
} | class ____(BaseLoss):
"""Half Binomial deviance loss with logit link, for binary classification.
This is also know as binary cross entropy, log-loss and logistic loss.
Domain:
y_true in [0, 1], i.e. regression on the unit interval
y_pred in (0, 1), i.e. boundaries excluded
Link:
y_pred = ... | HalfBinomialLoss |
python | marshmallow-code__marshmallow | src/marshmallow/constants.py | {
"start": 115,
"end": 415
} | class ____:
def __bool__(self):
return False
def __copy__(self):
return self
def __deepcopy__(self, _):
return self
def __repr__(self):
return "<marshmallow.missing>"
def __len__(self):
return 0
missing: typing.Final = _Missing()
| _Missing |
python | tiangolo__fastapi | scripts/contributors.py | {
"start": 3648,
"end": 8771
} | class ____(BaseModel):
contributors: Counter[str]
translation_reviewers: Counter[str]
translators: Counter[str]
authors: dict[str, Author]
def get_contributors(pr_nodes: list[PullRequestNode]) -> ContributorsResults:
contributors = Counter[str]()
translation_reviewers = Counter[str]()
tran... | ContributorsResults |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 8707,
"end": 8786
} | class ____(Opcode):
_FLAGS = HAS_JUNKNOWN | NO_NEXT
__slots__ = ()
| BREAK_LOOP |
python | huggingface__transformers | tests/models/got_ocr2/test_modeling_got_ocr2.py | {
"start": 5497,
"end": 11092
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@slow
def test_small_model_integration_test_got_ocr_stop_strings(self):
model_id = "stepfun-ai/... | GotOcr2IntegrationTest |
python | getsentry__sentry | tests/sentry/sentry_apps/api/parsers/test_image.py | {
"start": 201,
"end": 1054
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.schema: dict[str, Any] = {
"type": "image",
"url": "https://example.com/image.gif",
"alt": "example video",
}
def test_valid_schema(self) -> None:
validate_component(self.schema)
@inval... | TestImageSchemaValidation |
python | huggingface__transformers | src/transformers/models/xmod/modeling_xmod.py | {
"start": 15310,
"end": 17065
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = XmodCrossAttention if is_cross_attention else XmodSelfAttention
self.self = attention_class(... | XmodAttention |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/progress/tqdm_progress.py | {
"start": 1217,
"end": 2175
} | class ____(_tqdm):
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Custom tqdm progressbar where we append 0 to floating points/strings to prevent the progress bar from
flickering."""
# this just to make the make docs happy, otherwise it pulls docs which has some issues...
... | Tqdm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 540707,
"end": 541159
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateProjectV2"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_v2")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mut... | CreateProjectV2Payload |
python | getsentry__sentry | src/sentry/integrations/services/integration/service.py | {
"start": 841,
"end": 10028
} | class ____(RpcService):
key = "integration"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.integrations.services.integration.impl import DatabaseBackedIntegrationService
return DatabaseBackedIntegrationService()
@rpc_method
... | IntegrationService |
python | getsentry__sentry | tests/acceptance/test_performance_landing.py | {
"start": 493,
"end": 2914
} | class ____(AcceptanceTestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(
organization=self.org, name="Mariachi Band", members=[self.user]
)
self.p... | PerformanceLandingTest |
python | nedbat__coveragepy | coverage/cmdline.py | {
"start": 12628,
"end": 21651
} | class ____(CoverageOptionParser):
"""Parse one of the new-style commands for coverage.py."""
def __init__(
self,
action: str,
options: list[optparse.Option],
description: str,
usage: str | None = None,
):
"""Create an OptionParser for a coverage.py command.
... | CmdOptionParser |
python | pytorch__pytorch | torch/_inductor/cpu_vec_isa.py | {
"start": 6664,
"end": 8469
} | class ____(VecISA):
_bit_width = 512
_macro = ["CPU_CAPABILITY_AVX512"]
_arch_flags = (
"-mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma"
if not _IS_WINDOWS
else "/arch:AVX512"
) # TODO: use cflags
_dtype_nelements = {torch.float: 16, torch.bfloat16: 32, torch.float16: 32}
... | VecAVX512 |
python | huggingface__transformers | src/transformers/models/grounding_dino/configuration_grounding_dino.py | {
"start": 906,
"end": 14778
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GroundingDinoModel`]. It is used to instantiate a
Grounding DINO model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a ... | GroundingDinoConfig |
python | pandas-dev__pandas | pandas/tests/arrays/sparse/test_libsparse.py | {
"start": 11877,
"end": 14671
} | class ____:
def test_block_internal(self):
idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="block")
assert isinstance(idx, BlockIndex)
assert idx.npoints == 2
tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32))
tm.assert_numpy_array_equal(i... | TestBlockIndex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.