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/wav2vec2/modeling_wav2vec2.py | {
"start": 2201,
"end": 10874
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `sample_negative_indices` are passed, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
paper](https://huggingface.co/papers/2006.11477).
... | Wav2Vec2ForPreTrainingOutput |
python | cython__cython | Cython/Compiler/MemoryView.py | {
"start": 14665,
"end": 15550
} | class ____(SliceIter):
def start_loops(self):
code = self.code
code.begin_block()
type_decl = self.slice_type.dtype.empty_declaration_code()
total_size = ' * '.join("%s.shape[%d]" % (self.slice_result, i)
for i in range(self.ndim))
code.putln... | ContigSliceIter |
python | crytic__slither | slither/tools/properties/properties/properties.py | {
"start": 54,
"end": 170
} | class ____(Enum):
CODE_QUALITY = 1
LOW_SEVERITY = 2
MEDIUM_SEVERITY = 3
HIGH_SEVERITY = 4
| PropertyType |
python | PrefectHQ__prefect | tests/cli/test_flow_run.py | {
"start": 28866,
"end": 31061
} | class ____:
@pytest.mark.parametrize("sigterm_handling", ["reschedule", None])
async def test_flow_run_execute_sigterm_handling(
self,
monkeypatch: pytest.MonkeyPatch,
prefect_client: PrefectClient,
sigterm_handling: str | None,
):
if sigterm_handling is not None:
... | TestSignalHandling |
python | Lightning-AI__lightning | examples/fabric/image_classifier/train_torch.py | {
"start": 1040,
"end": 5608
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear... | Net |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 23291,
"end": 24085
} | class ____(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.L... | Glm4vMoeTextMLP |
python | ansible__ansible | test/units/module_utils/common/test_dict_transformations.py | {
"start": 1478,
"end": 1710
} | class ____:
def test_camel_to_snake_and_back(self):
for (k, v) in EXPECTED_REVERSIBLE.items():
assert _snake_to_camel(_camel_to_snake(k, reversible=True), capitalize_first=True) == k
| TestCaseCamelToSnakeAndBack |
python | Netflix__metaflow | metaflow/_vendor/click/_compat.py | {
"start": 1519,
"end": 2672
} | class ____(io.TextIOWrapper):
def __init__(
self,
stream,
encoding,
errors,
force_readable=False,
force_writable=False,
**extra
):
self._stream = stream = _FixupStream(stream, force_readable, force_writable)
io.TextIOWrapper.__init__(self, ... | _NonClosingTextIOWrapper |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_utilities.py | {
"start": 641,
"end": 1197
} | class ____(Mock):
call_count = 0
def __init__(self, succeeded=False, *args, **kwargs):
super().__init__()
self.log_uri = "test_uri"
self._succeeded = succeeded
def is_running(self):
MockExecution.call_count += 1
if self.call_count > 2:
return False
... | MockExecution |
python | yandexdataschool__Practical_RL | week04_approx_rl/dqn/logger.py | {
"start": 102,
"end": 2615
} | class ____:
def __init__(self, use_tensorboard=True, log_dir='runs'):
"""
Initializes the Logger.
:param use_tensorboard: If True, logs will be sent to TensorBoard.
:param log_dir: Directory where TensorBoard logs are saved.
"""
self.use_tensorboard = use_tensorboard... | Logger |
python | openai__openai-python | src/openai/types/chat/chat_completion_named_tool_choice_custom_param.py | {
"start": 361,
"end": 565
} | class ____(TypedDict, total=False):
custom: Required[Custom]
type: Required[Literal["custom"]]
"""For custom tool calling, the type is always `custom`."""
| ChatCompletionNamedToolChoiceCustomParam |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/parsing_ops_test.py | {
"start": 42272,
"end": 51985
} | class ____(test.TestCase):
def _test(self, kwargs, expected_values=None, expected_err=None):
if expected_err:
with self.assertRaisesWithPredicateMatch(expected_err[0],
expected_err[1]):
self.evaluate(parsing_ops.parse_single_example(**kwargs))
else... | ParseSingleExampleTest |
python | django__django | tests/generic_relations/models.py | {
"start": 3823,
"end": 3933
} | class ____(ConcreteRelatedModel):
class Meta:
proxy = True
# To test fix for #7551
| ProxyRelatedModel |
python | sympy__sympy | sympy/core/logic.py | {
"start": 8939,
"end": 9653
} | class ____(AndOr_Base):
op_x_notx = False
def _eval_propagate_not(self):
# !(a&b&c ...) == !a | !b | !c ...
return Or(*[Not(a) for a in self.args])
# (a|b|...) & c == (a&c) | (b&c) | ...
def expand(self):
# first locate Or
for i, arg in enumerate(self.args):
... | And |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 39335,
"end": 40069
} | class ____(test_lib.TestCase):
def test(self):
np.random.seed(1) # Make it reproducible.
x = np.random.randn(3, 4).astype(np.float32)
y = np.maximum(x, 0.0)
z = self.evaluate(nn_ops.relu(constant_op.constant(x)))
self.assertAllEqual(y, z)
@test_util.disable_xla(
"This test relies on un... | ReluTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 97165,
"end": 97657
} | class ____(sgqlc.types.Enum):
"""Represents the individual results of a search.
Enumeration Choices:
* `DISCUSSION`: Returns matching discussions in repositories.
* `ISSUE`: Returns results matching issues in repositories.
* `REPOSITORY`: Returns results matching repositories.
* `USER`: Return... | SearchType |
python | numpy__numpy | numpy/exceptions.py | {
"start": 5644,
"end": 7709
} | class ____(TypeError):
"""Multiple DTypes could not be converted to a common one.
This exception derives from ``TypeError`` and is raised whenever dtypes
cannot be converted to a single common one. This can be because they
are of a different category/class or incompatible instances of the same
one... | DTypePromotionError |
python | ansible__ansible | lib/ansible/module_utils/facts/system/selinux.py | {
"start": 1027,
"end": 3227
} | class ____(BaseFactCollector):
name = 'selinux'
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
facts_dict = {}
selinux_facts = {}
# If selinux library is missing, only set the status and selinux_python_present since
# there is no... | SelinuxFactCollector |
python | oauthlib__oauthlib | tests/oauth2/rfc6749/test_server.py | {
"start": 8948,
"end": 15975
} | class ____(TestCase):
def setUp(self):
self.expires_in = 1800
def set_user(request):
request.user = mock.MagicMock()
request.client = mock.MagicMock()
request.client.client_id = 'mocked_client_id'
return True
self.mock_validator = mock.Magic... | SignedTokenEndpointTest |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 21721,
"end": 22942
} | class ____(django_test.TestCase):
def test_undeclared_fields(self):
class WithDefaultValueFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.WithDefaultValue
class Params:
with_bar = factory.Trait(
foo='bar',
... | DjangoParamsTestCase |
python | tiangolo__fastapi | tests/test_response_model_as_return_annotation.py | {
"start": 397,
"end": 442
} | class ____(User):
password_hash: str
| DBUser |
python | openai__openai-python | src/openai/types/responses/tool_choice_mcp_param.py | {
"start": 246,
"end": 540
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""The label of the MCP server to use."""
type: Required[Literal["mcp"]]
"""For MCP tools, the type is always `mcp`."""
name: Optional[str]
"""The name of the tool to call on the server."""
| ToolChoiceMcpParam |
python | sqlalchemy__sqlalchemy | test/orm/test_froms.py | {
"start": 114010,
"end": 116742
} | class ____(QueryTest):
run_setup_mappers = None
def test_double_same_mappers_explicit_alias(self):
"""test aliasing of joins with a custom join condition"""
(
addresses,
items,
order_items,
orders,
Item,
User,
... | CustomJoinTest |
python | RaRe-Technologies__gensim | gensim/similarities/termsim.py | {
"start": 3073,
"end": 15423
} | class ____(TermSimilarityIndex):
"""
Computes cosine similarities between word embeddings and retrieves most
similar terms for a given term.
Notes
-----
By fitting the word embeddings to a vocabulary that you will be using, you
can eliminate all out-of-vocabulary (OOV) words that you would ... | WordEmbeddingSimilarityIndex |
python | wandb__wandb | wandb/vendor/pygments/lexers/basic.py | {
"start": 12933,
"end": 14156
} | class ____(RegexLexer):
"""
For CBM BASIC V2 sources.
.. versionadded:: 1.6
"""
name = 'CBM BASIC V2'
aliases = ['cbmbas']
filenames = ['*.bas']
flags = re.IGNORECASE
tokens = {
'root': [
(r'rem.*\n', Comment.Single),
(r'\s+', Text),
(r'... | CbmBasicV2Lexer |
python | neetcode-gh__leetcode | python/0904-fruit-into-baskets.py | {
"start": 20,
"end": 577
} | class ____:
def totalFruit(self, fruits: List[int]) -> int:
count = collections.defaultdict(int)
l, total, res = 0, 0, 0
for r in range(len(fruits)):
count[fruits[r]] += 1
total += 1
while len(count) > 2:
f = fruits[l]
cou... | Solution |
python | walkccc__LeetCode | solutions/261. Graph Valid Tree/261-2.py | {
"start": 557,
"end": 793
} | class ____:
def validTree(self, n: int, edges: list[list[int]]) -> bool:
if n == 0 or len(edges) != n - 1:
return False
uf = UnionFind(n)
for u, v in edges:
uf.unionByRank(u, v)
return uf.count == 1
| Solution |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/packages.py | {
"start": 3069,
"end": 55988
} | class ____(NamedTuple):
"""Store details about python packages"""
package: str
version_required: str
@classmethod
def from_requirement(cls, requirement_string: str) -> PipRequirements:
from packaging.requirements import Requirement
req = Requirement(requirement_string)
pa... | PipRequirements |
python | pydata__xarray | xarray/computation/rolling.py | {
"start": 1530,
"end": 9114
} | class ____(Generic[T_Xarray]):
"""A object that implements the moving window pattern.
See Also
--------
xarray.Dataset.groupby
xarray.DataArray.groupby
xarray.Dataset.rolling
xarray.DataArray.rolling
"""
__slots__ = ("center", "dim", "min_periods", "obj", "window")
_attributes ... | Rolling |
python | ray-project__ray | python/ray/_private/thirdparty/pyamdsmi/pyamdsmi.py | {
"start": 4379,
"end": 4817
} | class ____(c_int):
RSMI_MEM_TYPE_FIRST = 0
RSMI_MEM_TYPE_VRAM = RSMI_MEM_TYPE_FIRST
RSMI_MEM_TYPE_VIS_VRAM = 1
RSMI_MEM_TYPE_GTT = 2
RSMI_MEM_TYPE_LAST = RSMI_MEM_TYPE_GTT
# memory_type_l includes names for with rsmi_memory_type_t
# Usage example to get corresponding names:
# memory_type_l[rsmi_me... | rsmi_memory_type_t |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/request_builder.py | {
"start": 404,
"end": 2036
} | class ____:
@classmethod
def get_endpoint(cls, endpoint: str) -> RequestBuilder:
return cls(endpoint=endpoint)
def __init__(self, endpoint: str) -> None:
self._endpoint: str = endpoint
self._query_params: MutableMapping[str, Any] = {}
self._headers: MutableMapping[str, str] ... | RequestBuilder |
python | kamyu104__LeetCode-Solutions | Python/lexicographically-minimum-string-after-removing-stars.py | {
"start": 67,
"end": 589
} | class ____(object):
def clearStars(self, s):
"""
:type s: str
:rtype: str
"""
result = list(s)
lookup = [[] for _ in range(26)]
for i, x in enumerate(s):
if x != '*':
lookup[ord(x)-ord('a')].append(i)
continue
... | Solution |
python | pdm-project__pdm | src/pdm/pytest.py | {
"start": 7170,
"end": 8006
} | class ____:
"""A mock Distribution"""
def __init__(
self,
key: str,
version: str,
editable: bool = False,
metadata: Metadata | None = None,
):
self.version = version
self.link_file = "editable" if editable else None
self.dependencies: list[str... | Distribution |
python | scipy__scipy | scipy/fft/_pocketfft/tests/test_real_transforms.py | {
"start": 7398,
"end": 13323
} | class ____:
def test_definition(self, rdt, type, fftwdata_size,
reference_data, ref_lock):
with ref_lock:
x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
y = dct(x, type=type)
assert_equal(y.dtype, dt)
dec = dec_map[(dct, rdt, ty... | TestDCT |
python | kamyu104__LeetCode-Solutions | Python/minimize-deviation-in-array.py | {
"start": 68,
"end": 642
} | class ____(object):
def minimumDeviation(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_heap = [-num*2 if num%2 else -num for num in nums]
heapq.heapify(max_heap)
min_elem = -max(max_heap)
result = float("inf")
while len(max_heap) =... | Solution |
python | astropy__astropy | astropy/extern/_strptime.py | {
"start": 1314,
"end": 8071
} | class ____(object):
"""Stores and handles locale-specific information related to time.
ATTRIBUTES:
f_weekday -- full weekday names (7-item list)
a_weekday -- abbreviated weekday names (7-item list)
f_month -- full month names (13-item list; dummy value in [0], which
... | LocaleTime |
python | google__jax | jax/_src/core.py | {
"start": 66265,
"end": 66321
} | class ____:
pass
@dataclass(frozen=True)
| QuasiDynamicData |
python | Pylons__pyramid | tests/test_config/test_assets.py | {
"start": 34658,
"end": 35303
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.config.assets import FileOverride
return FileOverride
def _makeOne(self, path, source):
klass = self._getTargetClass()
return klass(path, source)
def test_it_match(self):
source = DummyAssetSour... | TestFileOverride |
python | coleifer__peewee | tests/fields.py | {
"start": 25475,
"end": 25528
} | class ____(TestModel):
data = BlobField()
| BlobModel |
python | kamyu104__LeetCode-Solutions | Python/parallel-courses-ii.py | {
"start": 76,
"end": 1246
} | class ____(object):
def minNumberOfSemesters(self, n, dependencies, k):
"""
:type n: int
:type dependencies: List[List[int]]
:type k: int
:rtype: int
"""
reqs = [0]*n
for u, v in dependencies:
reqs[v-1] |= 1 << (u-1)
dp = [n]*(1<<n)... | Solution |
python | getsentry__sentry | src/sentry/api/endpoints/artifact_bundles.py | {
"start": 1357,
"end": 1926
} | class ____:
@classmethod
def derive_order_by(cls, sort_by: str) -> str | None:
is_desc = sort_by.startswith("-")
sort_by = sort_by.strip("-")
order_by = ORDER_BY_FIELDS_MAPPING.get(sort_by)
if order_by is not None:
return f"-{order_by}" if is_desc else order_by
... | ArtifactBundlesMixin |
python | scipy__scipy | scipy/special/tests/test_cdflib.py | {
"start": 607,
"end": 1144
} | class ____:
"""Generate a set of probabilities on [0, 1]."""
def __init__(self):
# Include the endpoints for compatibility with Arg et. al.
self.a = 0
self.b = 1
def values(self, n):
"""Return an array containing approximately n numbers."""
m = max(1, n//3)
... | ProbArg |
python | astropy__astropy | astropy/wcs/wcsapi/tests/test_high_level_api.py | {
"start": 770,
"end": 1986
} | class ____(DoubleLowLevelWCS, HighLevelWCSMixin):
"""
This example WCS has two of the world coordinates that use the same class,
which triggers a different path in the high level WCS code.
"""
@property
def pixel_n_dim(self):
return 2
@property
def world_n_dim(self):
re... | SimpleDuplicateWCS |
python | pola-rs__polars | py-polars/src/polars/io/partition.py | {
"start": 16524,
"end": 17067
} | class ____:
"""
Holds parsed directory sink options.
For internal use.
"""
base_path: str
file_path_provider: (
Callable[[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]] | None
)
partition_by: list[PyExpr] | None
partition_keys_sorted: bool | None
include_keys... | _SinkDirectoryInner |
python | redis__redis-py | redis/maint_notifications.py | {
"start": 3267,
"end": 5794
} | class ____(MaintenanceNotification):
"""
This notification is received when a node is replaced with a new node
during cluster rebalancing or maintenance operations.
"""
def __init__(
self,
id: int,
new_node_host: Optional[str],
new_node_port: Optional[int],
t... | NodeMovingNotification |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/op_decorator.py | {
"start": 10770,
"end": 13431
} | class ____(NamedTuple):
"""Wrapper around the decorated op function to provide commonly used util methods."""
decorated_fn: Callable[..., Any]
@property
def name(self):
return self.decorated_fn.__name__
@lru_cache(maxsize=1)
def has_context_arg(self) -> bool:
return is_context... | DecoratedOpFunction |
python | spack__spack | lib/spack/spack/util/web.py | {
"start": 2435,
"end": 5668
} | class ____(HTTPSHandler):
"""A custom HTTPS handler that shows more detailed error messages on connection failure."""
def https_open(self, req):
try:
return super().https_open(req)
except HTTPError:
raise
except URLError as e:
raise DetailedURLError(r... | SpackHTTPSHandler |
python | Lightning-AI__lightning | tests/tests_pytorch/test_cli.py | {
"start": 37946,
"end": 42639
} | class ____(BoringModel):
def __init__(
self,
optimizer: OptimizerCallable = torch.optim.Adam,
scheduler: LRSchedulerCallable = torch.optim.lr_scheduler.ConstantLR,
activation: torch.nn.Module = lazy_instance(torch.nn.LeakyReLU, negative_slope=0.05),
):
super().__init__()
... | TestModelSaveHparams |
python | ray-project__ray | python/ray/experimental/channel/torch_tensor_accelerator_channel.py | {
"start": 15266,
"end": 34455
} | class ____(ChannelInterface):
def __init__(
self,
writer: ray.actor.ActorHandle,
reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]],
typ: "TorchTensorType",
_meta_channel: Optional["Channel"] = None,
):
"""
A helper channel for TorchTensorAcce... | _TorchTensorAcceleratorChannel |
python | pytorch__pytorch | test/distributed/algorithms/ddp_comm_hooks/test_ddp_hooks.py | {
"start": 1334,
"end": 1527
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.t0 = Task()
def forward(self, x, rank):
return self.t0(x ** (1 + rank))
| TestDdpCommHook |
python | tensorflow__tensorflow | tensorflow/python/training/input_test.py | {
"start": 2811,
"end": 3708
} | class ____(test_lib.TestCase):
def testNoLimit(self):
with ops.Graph().as_default(), self.cached_session():
seven = constant_op.constant(7)
seven_forever = inp.limit_epochs(seven)
variables.local_variables_initializer().run()
for _ in range(100):
self.assertEqual(7, self.evaluate(... | LimitEpochsTest |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 5656,
"end": 6240
} | class ____(nn.Module):
def __init__(self, config: GroupViTVisionConfig):
super().__init__()
self.attn = GroupViTAttention(config)
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.mlp = GroupViTMLP(config)
self.norm_post = nn.LayerNorm(config.hidde... | GroupViTCrossAttentionLayer |
python | Textualize__textual | src/textual/css/model.py | {
"start": 792,
"end": 2353
} | class ____(Enum):
"""Type of combinator."""
SAME = 1
"""Selector is combined with previous selector"""
DESCENDENT = 2
"""Selector is a descendant of the previous selector"""
CHILD = 3
"""Selector is an immediate child of the previous selector"""
def _check_universal(name: str, node: DOMNo... | CombinatorType |
python | kamyu104__LeetCode-Solutions | Python/interleaving-string.py | {
"start": 838,
"end": 1667
} | class ____(object):
# @return a boolean
def isInterleave(self, s1, s2, s3):
if len(s1) + len(s2) != len(s3):
return False
match = [[False for i in xrange(len(s2) + 1)] for j in xrange(len(s1) + 1)]
match[0][0] = True
for i in xrange(1, len(s1) + 1):
match[... | Solution2 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 15938,
"end": 16068
} | class ____(test.TestCase, _LUReconstruct):
use_static_shape = True
@test_util.run_all_in_graph_and_eager_modes
| LUReconstructStatic |
python | realpython__materials | python-contact-book/source_code_step_4/rpcontacts/model.py | {
"start": 160,
"end": 706
} | class ____:
def __init__(self):
self.model = self._createModel()
@staticmethod
def _createModel():
"""Create and set up the model."""
tableModel = QSqlTableModel()
tableModel.setTable("contacts")
tableModel.setEditStrategy(QSqlTableModel.OnFieldChange)
tableM... | ContactsModel |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 11985,
"end": 12645
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | VisualBertIntermediate |
python | getsentry__sentry | src/sentry_plugins/github/webhooks/events/pull_request.py | {
"start": 322,
"end": 4200
} | class ____(Webhook):
# https://developer.github.com/v3/activity/events/types/#pullrequestevent
def __call__(self, event, organization):
# TODO(maxbittker) handle is_apps correctly (What does this comment mean?)
is_apps = "installation" in event
try:
repo = Repository.objects.... | PullRequestEventWebhook |
python | PyCQA__isort | tests/unit/test_exceptions.py | {
"start": 359,
"end": 645
} | class ____(TestISortError):
def setup_class(self):
self.instance: exceptions.ExistingSyntaxErrors = exceptions.ExistingSyntaxErrors(
"file_path"
)
def test_variables(self):
assert self.instance.file_path == "file_path"
| TestExistingSyntaxErrors |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/ec.py | {
"start": 8195,
"end": 8437
} | class ____(EllipticCurve):
name = "secp521r1"
key_size = 521
group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 # noqa: E501
| SECP521R1 |
python | django__django | django/contrib/auth/hashers.py | {
"start": 10669,
"end": 12813
} | class ____(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256.
The result is a 64 byte binary string. Iterations may be changed
safely but you must rename the algorithm if you change SHA256.
"""
algorithm = "pb... | PBKDF2PasswordHasher |
python | Textualize__textual | src/textual/await_complete.py | {
"start": 376,
"end": 2598
} | class ____:
"""An 'optionally-awaitable' object which runs one or more coroutines (or other awaitables) concurrently."""
def __init__(
self, *awaitables: Awaitable, pre_await: CallbackType | None = None
) -> None:
"""Create an AwaitComplete.
Args:
awaitables: One or mor... | AwaitComplete |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 4285,
"end": 18903
} | class ____(NonStrictDataModel):
"""
:param id: Model id
:type id: str
:param name: Model name
:type name: str
:param user: Associated user id
:type user: str
:param company: Company id
:type company: str
:param created: Model creation time
:type created: datetime.datetime
... | Model |
python | walkccc__LeetCode | solutions/2429. Minimize XOR/2429.py | {
"start": 0,
"end": 624
} | class ____:
def minimizeXor(self, num1: int, num2: int) -> int:
MAX_BIT = 30
bits = num2.bit_count()
# Can turn off all the bits in `num1`.
if num1.bit_count() == bits:
return num1
ans = 0
# Turn off the MSB if we have `bits` quota.
for i in reversed(range(MAX_BIT)):
if num1 ... | Solution |
python | pypa__pipenv | pipenv/patched/pip/_internal/network/lazy_wheel.py | {
"start": 749,
"end": 1588
} | class ____(Exception):
pass
def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution:
"""Return a distribution object from the given wheel URL.
This uses HTTP range requests to only fetch the portion of the wheel
containing metadata, just enough for the object to be const... | HTTPRangeRequestUnsupported |
python | fastapi__sqlmodel | docs_src/tutorial/offset_and_limit/tutorial002.py | {
"start": 100,
"end": 1628
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | kubernetes-client__python | kubernetes/client/models/v1_node_config_status.py | {
"start": 383,
"end": 7722
} | 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... | V1NodeConfigStatus |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 107961,
"end": 109012
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook):
op = ExportModelOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
region=GCP_LOCATION,
... | TestVertexAIExportModelOperator |
python | google__pytype | pytype/rewrite/vm_test.py | {
"start": 400,
"end": 1865
} | class ____(unittest.TestCase):
def test_run_module_frame(self):
block = [
opcodes.LOAD_CONST(0, 0, 0, 0, 0, 0, None),
opcodes.RETURN_VALUE(0, 0, 0, 0, 0),
]
code = test_utils.FakeOrderedCode([block], [None])
vm = vm_lib.VirtualMachine(context.Context(src=''), code.Seal(), {})
self... | VmTest |
python | getsentry__sentry | src/sentry/core/endpoints/project_team_details.py | {
"start": 1175,
"end": 4706
} | class ____(ProjectEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.ENTERPRISE
permission_classes = (ProjectTeamsPermission,)
def convert_args(
self,
request: Request,
organization_id_or_slug:... | ProjectTeamDetailsEndpoint |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/failing_empty_install/package.py | {
"start": 216,
"end": 566
} | class ____(Package):
"""This package installs nothing, install should fail."""
homepage = "http://www.example.com/trivial_install"
url = "http://www.unit-test-should-replace-this-url/trivial_install-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
def install(self, spec, prefix)... | FailingEmptyInstall |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 440584,
"end": 440810
} | class ____(VegaLiteSchema):
"""GeoJsonProperties schema wrapper."""
_schema = {"$ref": "#/definitions/GeoJsonProperties"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| GeoJsonProperties |
python | sympy__sympy | sympy/physics/mechanics/pathway.py | {
"start": 17832,
"end": 26555
} | class ____(PathwayBase):
"""Pathway that wraps a geometry object.
Explanation
===========
A wrapping pathway interacts with a geometry object and forms a path that
wraps smoothly along its surface. The wrapping pathway along the geometry
object will be the geodesic that the geometry object def... | WrappingPathway |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/bedrock/_beta_messages.py | {
"start": 2749,
"end": 2966
} | class ____:
def __init__(self, messages: Messages) -> None:
self._messages = messages
self.create = to_streamed_response_wrapper(
messages.create,
)
| MessagesWithStreamingResponse |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py | {
"start": 2648,
"end": 4060
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger for RedshiftPauseClusterOperator.
The trigger will asynchronously poll the boto3 API and wait for the
Redshift cluster to be in the `paused` state.
:param cluster_identifier: A unique identifier for the cluster.
:param waiter_delay: The amount of ... | RedshiftPauseClusterTrigger |
python | pennersr__django-allauth | allauth/socialaccount/providers/apple/client.py | {
"start": 484,
"end": 537
} | class ____:
EMAIL = "email"
NAME = "name"
| Scope |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 300771,
"end": 300948
} | class ____(VegaLiteSchema):
"""Cursor schema wrapper."""
_schema = {"$ref": "#/definitions/Cursor"}
def __init__(self, *args):
super().__init__(*args)
| Cursor |
python | graphql-python__graphene | graphene/relay/tests/test_global_id.py | {
"start": 342,
"end": 1566
} | class ____:
def __init__(self, parent_type):
self.parent_type = GrapheneObjectType(
graphene_type=parent_type,
name=parent_type._meta.name,
description=parent_type._meta.description,
fields=None,
is_type_of=parent_type.is_type_of,
inter... | Info |
python | run-llama__llama_index | llama-index-core/tests/tools/tool_spec/test_base.py | {
"start": 443,
"end": 5316
} | class ____(BaseToolSpec):
spec_functions: List[Union[str, Tuple[str, str]]] = [
"foo",
"bar",
"abc",
"abc_with_ctx",
"async_only_fn",
]
def foo(self, arg1: str, arg2: int) -> str:
"""Foo."""
return f"foo {arg1} {arg2}"
def bar(self, arg1: bool) -... | TestToolSpec |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/metadata_checks_component.py | {
"start": 1553,
"end": 1939
} | class ____(Resolvable):
type: Literal["column_schema_change"]
severity: ResolvedAssetCheckSeverity = AssetCheckSeverity.WARN
def build_checks(self, key: AssetKey) -> Sequence[AssetChecksDefinition]:
return build_column_schema_change_checks(
assets=[key], **{k: v for k, v in as_dict(self... | ColumnSchemaChangeParams |
python | numpy__numpy | tools/swig/test/testSuperTensor.py | {
"start": 15217,
"end": 15492
} | class ____(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
| floatTestCase |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 43772,
"end": 44484
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, api_token: str, start_date: str):
"""Airbyte Source for Kustomer Singer.
Documentation can be found at https://docs.airbyte.com/integrations/sources/kustomer-singer
Args:
name (str): The name of the d... | KustomerSingerSource |
python | PyCQA__pylint | tests/functional/m/member/member_checks.py | {
"start": 4764,
"end": 4917
} | class ____(enum.IntEnum):
BAR = 0
SOME_VALUE = Cls.BAZ # [no-member]
# Does not crash when inferring the `append` attribute on the slice object
| Cls |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_column_values_to_be_equal_to_or_less_than_profile_max.py | {
"start": 2774,
"end": 6925
} | class ____(ColumnMapExpectation):
"""Expect the column values to be less than or equal to the maximum value of the respective column within the DataProfiler report.
This function builds upon the custom column map expectations of Great Expectations. This function asks a yes/no question of each row in the user-s... | ExpectColumnValuesToBeEqualToOrLessThanProfileMax |
python | crytic__slither | slither/core/expressions/elementary_type_name_expression.py | {
"start": 266,
"end": 707
} | class ____(Expression):
def __init__(self, t: ElementaryType) -> None:
assert isinstance(t, Type)
super().__init__()
self._type = t
@property
def type(self) -> Type:
return self._type
@type.setter
def type(self, new_type: Type):
assert isinstance(new_type, T... | ElementaryTypeNameExpression |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 3575,
"end": 3778
} | class ____(graphene.ObjectType):
boolValue = graphene.Field(graphene.Boolean)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "BoolMetadataEntry"
| GrapheneBoolMetadataEntry |
python | django__django | tests/backends/tests.py | {
"start": 6410,
"end": 7123
} | class ____(TestCase):
def test_bad_parameter_count(self):
"""
An executemany call with too many/not enough parameters will raise an
exception.
"""
with connection.cursor() as cursor:
query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
connectio... | ParameterHandlingTest |
python | ray-project__ray | python/ray/util/client/common.py | {
"start": 31367,
"end": 35219
} | class ____:
"""
Cache for streaming RPCs, i.e. the DataServicer. Relies on explicit
ack's from the client to determine when it can clean up cache entries.
"""
def __init__(self):
self.last_received = 0
self.cv = threading.Condition()
self.cache: Dict[int, Any] = OrderedDict(... | OrderedResponseCache |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 65309,
"end": 67891
} | class ____(fx.Interpreter):
def __init__(
self,
module: fx.GraphModule,
new_graph: fx.Graph,
decomposition_table: Optional[Mapping[OpOverload, Callable]] = None,
**kwargs: object,
) -> None:
super().__init__(module, **kwargs) # type: ignore[arg-type]
self... | DecompositionInterpreter |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 634,
"end": 964
} | class ____(PoolError):
"""Base exception for PoolErrors that have associated URLs."""
def __init__(self, pool, url, message):
self.url = url
PoolError.__init__(self, pool, message)
def __reduce__(self):
# For pickling purposes.
return self.__class__, (None, self.url, None)
... | RequestError |
python | celery__celery | t/unit/utils/test_functional.py | {
"start": 2253,
"end": 8567
} | class ____:
def test_list(self):
l = [1, 2]
r = regen(iter(l))
assert regen(l) is l
assert r == l
assert r == l # again
assert r.__length_hint__() == 0
fun, args = r.__reduce__()
assert fun(*args) == l
@pytest.fixture
def g(self):
r... | test_regen |
python | allegroai__clearml | clearml/utilities/pigar/modules.py | {
"start": 2450,
"end": 3251
} | class ____(dict):
"""_Locations store code locations(file, linenos)."""
def __init__(self) -> None:
super(_Locations, self).__init__()
self._sorted = None
def add(self, file: str, lineno: int) -> None:
if file in self and lineno not in self[file]:
self[file].append(line... | _Locations |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/sac/optimizer_torch.py | {
"start": 1213,
"end": 1662
} | class ____(OffPolicyHyperparamSettings):
batch_size: int = 128
buffer_size: int = 50000
buffer_init_steps: int = 0
tau: float = 0.005
steps_per_update: float = 1
save_replay_buffer: bool = False
init_entcoef: float = 1.0
reward_signal_steps_per_update: float = attr.ib()
@reward_sign... | SACSettings |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/executors/kubernetes_executor_types.py | {
"start": 1751,
"end": 2100
} | class ____(NamedTuple):
"""Watch event data from Kubernetes pods."""
pod_name: str
namespace: str
state: TaskInstanceState | str | None
annotations: dict[str, str]
resource_version: str
failure_details: FailureDetails | None
# TODO: Remove after Airflow 2 support is removed
CommandType = ... | KubernetesWatch |
python | kamyu104__LeetCode-Solutions | Python/making-file-names-unique.py | {
"start": 50,
"end": 628
} | class ____(object):
def getFolderNames(self, names):
"""
:type names: List[str]
:rtype: List[str]
"""
count = collections.Counter()
result, lookup = [], set()
for name in names:
while True:
name_with_suffix = "{}({})".format(name, c... | Solution |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 1231,
"end": 1400
} | class ____(BaseModel):
end_index: int | None = None
start_index: int | None = None
title: str
type: str = "url_citation"
url: str
| AnnotationURLCitation |
python | joke2k__faker | faker/providers/date_time/ja_JP/__init__.py | {
"start": 46,
"end": 1121
} | class ____(DateTimeProvider):
MONTH_NAMES = {
"01": "一月",
"02": "二月",
"03": "三月",
"04": "四月",
"05": "五月",
"06": "六月",
"07": "七月",
"08": "八月",
"09": "九月",
"10": "十月",
"11": "十一月",
"12": "十二月",
}
TRADITIONAL_MONTH... | Provider |
python | sympy__sympy | sympy/plotting/pygletplot/plot_mode.py | {
"start": 291,
"end": 14156
} | class ____(PlotObject):
"""
Grandparent class for plotting
modes. Serves as interface for
registration, lookup, and init
of modes.
To create a new plot mode,
inherit from PlotModeBase
or one of its children, such
as PlotSurface or PlotCurve.
"""
## Class-level attributes
... | PlotMode |
python | huggingface__transformers | src/transformers/models/eomt/modular_eomt.py | {
"start": 10873,
"end": 12442
} | class ____(Dinov2Embeddings):
def __init__(self, config: EomtConfig) -> None:
nn.Module.__init__(self)
self.config = config
self.patch_size = config.patch_size
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
self.register_tokens = nn.Parameter(torch.zer... | EomtEmbeddings |
python | encode__django-rest-framework | tests/test_renderers.py | {
"start": 1612,
"end": 1847
} | class ____(TestCase):
def test_expected_results(self):
for value, renderer_cls, expected in expected_results:
output = renderer_cls().render(value)
self.assertEqual(output, expected)
| BasicRendererTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.