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 | mlflow__mlflow | mlflow/tracing/utils/timeout.py | {
"start": 1704,
"end": 3900
} | class ____(Cache):
"""
This code is ported from cachetools library to avoid depending on the private class.
https://github.com/tkem/cachetools/blob/d44c98407030d2e91cbe82c3997be042d9c2f0de/src/cachetools/__init__.py#L376
"""
class _Timer:
def __init__(self, timer):
self.__timer ... | _TimedCache |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 4409,
"end": 6017
} | class ____(Schema):
name = fields.String()
age: fields.Field = fields.Float()
created = fields.DateTime()
created_formatted = fields.DateTime(
format="%Y-%m-%d", attribute="created", dump_only=True
)
created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
upd... | UserSchema |
python | explosion__spaCy | spacy/lang/el/__init__.py | {
"start": 410,
"end": 696
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
suffixes = TOKENIZER_SUFFIXES
infixes = TOKENIZER_INFIXES
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
| GreekDefaults |
python | facelessuser__pymdown-extensions | pymdownx/snippets.py | {
"start": 1518,
"end": 1595
} | class ____(Exception):
"""Snippet missing exception."""
| SnippetMissingError |
python | django__django | django/tasks/base.py | {
"start": 5272,
"end": 7527
} | class ____:
task: Task
id: str # Unique identifier for the task result.
status: TaskResultStatus
enqueued_at: Optional[datetime] # Time the task was enqueued.
started_at: Optional[datetime] # Time the task was started.
finished_at: Optional[datetime] # Time the task was finished.
# Tim... | TaskResult |
python | huggingface__transformers | src/transformers/models/falcon_h1/modular_falcon_h1.py | {
"start": 7983,
"end": 10127
} | class ____(LlamaAttention):
def __init__(self, config: FalconH1Config, layer_idx: int):
super().__init__(config, layer_idx)
self.key_multiplier = config.key_multiplier
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],... | FalconH1Attention |
python | numba__numba | numba/tests/test_boundscheck.py | {
"start": 4064,
"end": 6803
} | class ____(TestCase):
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
def test_basic_array_boundscheck(self):
self.assertIsNone(config.BOUNDSCHECK)
a = np.arange(5)
# Check the numpy behavior to make sure the test is correct
with self.assertRaises(IndexError)... | TestBoundsCheckError |
python | ray-project__ray | python/ray/llm/_internal/serve/serving_patterns/prefill_decode/pd_server.py | {
"start": 893,
"end": 6416
} | class ____(LLMServerProtocol):
"""Proxy between P/D LLM servers.
This class implements the LLMServerProtocol but doesn't have a real engine.
It forwards requests to prefill and decode servers for disaggregated inference.
For chat and completions, proxy sends the request to the prefill server and
t... | PDProxyServer |
python | apache__airflow | providers/trino/tests/unit/trino/hooks/test_trino.py | {
"start": 2156,
"end": 12323
} | class ____:
@patch(BASIC_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_basic_auth(self, mock_get_connection, mock_connect, mock_basic_auth):
self.set_get_connection_return_value(mock_get_connection, password="password")
TrinoHook().get_conn()
... | TestTrinoHookConn |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/common.py | {
"start": 884,
"end": 948
} | class ____(Exception):
"""Scheduled job failed"""
| JobException |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 65938,
"end": 66626
} | class ____(Operation):
def call(self, x):
return backend.numpy.cos(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type... | Cos |
python | scipy__scipy | scipy/signal/tests/test_peak_finding.py | {
"start": 11813,
"end": 16430
} | class ____:
def test_empty(self):
"""
Test if an empty array is returned if no peaks are provided.
"""
out = peak_prominences([1, 2, 3], [])
for arr, dtype in zip(out, [np.float64, np.intp, np.intp]):
assert arr.size == 0
assert arr.dtype == dtype
... | TestPeakProminences |
python | sympy__sympy | sympy/solvers/diophantine/diophantine.py | {
"start": 22434,
"end": 24995
} | class ____(DiophantineEquationType):
"""
Representation of a homogeneous ternary quadratic normal diophantine equation.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal
>>> HomogeneousTernaryQuadrati... | HomogeneousTernaryQuadraticNormal |
python | getsentry__sentry | tests/sentry/integrations/utils/test_sync.py | {
"start": 9000,
"end": 29093
} | class ____(TestCase):
@pytest.fixture(autouse=True)
def mock_where_should_sync(self):
with mock.patch(
"sentry.integrations.utils.sync.where_should_sync"
) as mock_where_should_sync:
mock_where_should_sync.return_value = [self.organization]
yield mock_where_s... | TestSyncAssigneeInboundByExternalActor |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 18244,
"end": 20657
} | class ____(DefaultFieldsModel):
"""
Represents a size comparison between two preprod artifact size analyses.
This is created when a user manually compares builds or when Git based comparisons are run.
"""
__relocation_scope__ = RelocationScope.Excluded
head_size_analysis = FlexibleForeignKey(
... | PreprodArtifactSizeComparison |
python | Delgan__loguru | loguru/_file_sink.py | {
"start": 2487,
"end": 5093
} | class ____:
@staticmethod
def forward_day(t):
return t + datetime.timedelta(days=1)
@staticmethod
def forward_weekday(t, weekday):
while True:
t += datetime.timedelta(days=1)
if t.weekday() == weekday:
return t
@staticmethod
def forward_i... | Rotation |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/bind_override.py | {
"start": 158,
"end": 494
} | class ____(Widget, can_focus=True):
BINDINGS = [
Binding("space", "app.bell", "Bell (Widget)"),
Binding("a", "app.notify('a widget')", "widget"),
Binding("b", "app.notify('b widget')", "widget"),
]
DEFAULT_CSS = """
MyWidget {
border: solid green;
height: 5;
... | MyWidget |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/matmul_op_test.py | {
"start": 5162,
"end": 7824
} | class ____(test_lib.TestCase):
pass # Will be filled in below.
def _GetMatMulGradientTest(a_np_, b_np_, use_static_shape_, **kwargs_):
@test_util.run_without_tensor_float_32("Tests matmul")
def Test(self):
if not use_static_shape_ or a_np_.dtype in (np.int32, np.int64, np.float16):
self.skipTest("Sk... | MatMulGradientTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-array-hopping-score-i.py | {
"start": 50,
"end": 369
} | class ____(object):
def maxScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = mx = 0
for i in reversed(xrange(1, len(nums))):
mx = max(mx, nums[i])
result += mx
return result
# Time: O(n^2)
# Space: O(n)
# dp
| Solution |
python | Textualize__textual | docs/examples/app/question_title02.py | {
"start": 126,
"end": 800
} | class ____(App[str]):
CSS_PATH = "question02.tcss"
TITLE = "A Question App"
SUB_TITLE = "The most important question"
def compose(self) -> ComposeResult:
yield Header()
yield Label("Do you love Textual?", id="question")
yield Button("Yes", id="yes", variant="primary")
yi... | MyApp |
python | ray-project__ray | python/ray/_common/usage/usage_lib.py | {
"start": 2697,
"end": 2933
} | class ____:
total_num_cpus: Optional[int] = None
total_num_gpus: Optional[int] = None
total_memory_gb: Optional[float] = None
total_object_store_memory_gb: Optional[float] = None
@dataclass(init=True)
| ClusterStatusToReport |
python | huggingface__transformers | src/transformers/models/gemma2/modular_gemma2.py | {
"start": 13907,
"end": 16603
} | class ____(GemmaAttention):
def __init__(self, config: Gemma2Config, layer_idx: int):
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
super().__init__(config, layer_idx)
self.attn_logit_softcapping = self.config.attn_logit_softcapping
self... | Gemma2Attention |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py | {
"start": 388,
"end": 459
} | class ____:
kind: str
kind_class: str
c: int
is_a: bool
| C |
python | walkccc__LeetCode | solutions/1632. Rank Transform of a Matrix/1632.py | {
"start": 575,
"end": 1570
} | class ____:
def matrixRankTransform(self, matrix: list[list[int]]) -> list[list[int]]:
m = len(matrix)
n = len(matrix[0])
ans = [[0] * n for _ in range(m)]
# {val: [(i, j)]}
valToGrids = collections.defaultdict(list)
# rank[i] := the maximum rank of the row or column so far
maxRankSoFar = ... | Solution |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 37685,
"end": 73064
} | class ____(UserDefinedVariable):
"""
Mostly objects of defined type. Catch-all for something where we only know the type.
"""
_nonvar_fields = {
"value",
"value_type",
"attrs_directly_modifed_on_dict",
*UserDefinedVariable._nonvar_fields,
}
def __init__(
... | UserDefinedObjectVariable |
python | redis__redis-py | redis/asyncio/cluster.py | {
"start": 67252,
"end": 72263
} | class ____(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands):
"""
Create a new ClusterPipeline object.
Usage::
result = await (
rc.pipeline()
.set("A", 1)
.get("A")
.hset("K", "F", "V")
.hgetall("K")
.mset_nonato... | ClusterPipeline |
python | walkccc__LeetCode | solutions/401. Binary Watch/401-2.py | {
"start": 0,
"end": 244
} | class ____:
def readBinaryWatch(self, turnedOn: int) -> list[str]:
ans = []
for h in range(12):
for m in range(60):
if h.bit_count() + m.bit_count() == turnedOn:
ans.append(f'{h}:{m:02d}')
return ans
| Solution |
python | ansible__ansible | lib/ansible/_internal/_templating/_access.py | {
"start": 174,
"end": 1199
} | class ____(metaclass=abc.ABCMeta):
"""Base class for a context manager that, when active, receives notification of managed access for types/tags in which it has registered an interest."""
_type_interest: t.FrozenSet[type] = frozenset()
"""Set of types (including tag types) for which this context will be no... | NotifiableAccessContextBase |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 64176,
"end": 65115
} | class ____(TestCase):
def setUp(self):
self.poll = PollWithExcludedFieldsWithDefaults.objects.create(
question="what's up?", pub_date=today, max_questions=12
)
self.historical = self.poll.history.order_by("pk")[0]
self.poll.delete()
def test_restore_deleted_poll_excl... | ExcludeFieldsForDeletedObjectTest |
python | davidhalter__parso | parso/python/tokenize.py | {
"start": 1385,
"end": 8263
} | class ____(NamedTuple):
pseudo_token: Pattern
single_quoted: Set[str]
triple_quoted: Set[str]
endpats: Dict[str, Pattern]
whitespace: Pattern
fstring_pattern_map: Dict[str, str]
always_break_tokens: Tuple[str]
BOM_UTF8_STRING = BOM_UTF8.decode('utf-8')
_token_collection_cache: Dict[Python... | TokenCollection |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 243616,
"end": 245695
} | class ____(Request):
"""
Get the list of task configurations
:param tasks: Task IDs
:type tasks: Sequence[str]
:param names: Names of the configuration items to retreive. If not passed or
empty then all the configurations will be retreived.
:type names: Sequence[str]
"""
_servi... | GetConfigurationsRequest |
python | openai__openai-python | tests/api_resources/beta/threads/test_messages.py | {
"start": 508,
"end": 12498
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.create(
thr... | TestMessages |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 22545,
"end": 24307
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.kaiser(6, 0.5, xp=xp),
xp.asarray([0.9403061933191572, 0.9782962393705389,
0.9975765035372042, 0.9975765035372042,
0.9782962393705389, 0.940306193319... | TestKaiser |
python | huggingface__transformers | src/transformers/integrations/tensor_parallel.py | {
"start": 30072,
"end": 31339
} | class ____(ColwiseParallel):
def shard_tensor(
self,
param,
param_type=None,
param_casting_dtype=None,
to_contiguous=None,
rank=None,
device_mesh=None,
tensor_idx=None,
):
device_mesh = device_mesh or self.device_mesh
empty_param = ... | PackedColwiseParallel |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 2494,
"end": 2709
} | class ____(CookiecutterException):
"""
Exception for incompatible modes.
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
"""
| InvalidModeException |
python | spack__spack | lib/spack/spack/traverse.py | {
"start": 1095,
"end": 1883
} | class ____:
"""A simple visitor that accepts all edges unconditionally and follows all
edges to dependencies of a given ``deptype``."""
def __init__(self, depflag: dt.DepFlag = dt.ALL):
self.depflag = depflag
def accept(self, item):
"""
Arguments:
item (EdgeAndDepth... | BaseVisitor |
python | allegroai__clearml | clearml/storage/helper.py | {
"start": 2385,
"end": 5739
} | class ____(metaclass=ABCMeta):
_certs_cache_context = "certs"
_file_server_hosts = None
@classmethod
def get_logger(cls) -> logging.Logger:
return get_logger("storage")
@abstractmethod
def get_container(
self,
container_name: str,
config: Optional[Any] = None,
... | _Driver |
python | aimacode__aima-python | gui/tsp.py | {
"start": 170,
"end": 1429
} | class ____(Problem):
"""subclass of Problem to define various functions"""
def two_opt(self, state):
"""Neighbour generating function for Traveling Salesman Problem"""
neighbour_state = state[:]
left = random.randint(0, len(neighbour_state) - 1)
right = random.randint(0, len(nei... | TSProblem |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_clip_grad_norm_.py | {
"start": 3888,
"end": 4937
} | class ____(_TestClipGradNormBase):
@property
def world_size(self) -> int:
return min(torch.get_device_module(device_type).device_count(), 2)
@skip_if_lt_x_gpu(2)
def test_clip_grad_norm_1d(self):
for norm_type in (2, 1, float("inf")):
torch.manual_seed(42)
model_... | TestClipGradNormWorldSize2 |
python | mlflow__mlflow | examples/tensorflow/train.py | {
"start": 561,
"end": 1196
} | class ____(tf.Module):
"""Linear Regression model class"""
def __init__(self):
self.built = False
@tf.function
def __call__(self, x):
# Initialize the model parameters on the first call
if not self.built:
# Randomly generate the weight vector and bias term
... | LinearRegression |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 123974,
"end": 124437
} | class ____(IterDataPipe):
def __init__(self, dp):
self.dp = dp
self.num_of_instances = 1
self.instance_id = 0
def apply_sharding(self, num_of_instances, instance_id):
self.num_of_instances = num_of_instances
self.instance_id = instance_id
def __iter__(self):
... | CustomShardingIterDataPipe |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/int.py | {
"start": 6676,
"end": 11289
} | class ____(BaseInt[np.dtypes.Int8DType, np.int8]):
"""
A Zarr data type for arrays containing 8-bit signed integers.
Wraps the [`np.dtypes.Int8DType`][numpy.dtypes.Int8DType] data type. Scalars for this data type are
instances of [`np.int8`][numpy.int8].
Attributes
----------
dtype_cls : n... | Int8 |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/filter.py | {
"start": 111,
"end": 1242
} | class ____:
"""Filters the set of Airflow objects to fetch.
Args:
dag_id_ilike (Optional[str]): A pattern used to match the set of dag_ids to retrieve. Uses the sql ILIKE operator Airflow-side.
airflow_tags (Optional[Sequence[str]]): Filters down to the set of Airflow DAGs whcih contain the par... | AirflowFilter |
python | pytoolz__toolz | toolz/tests/test_dicttoolz.py | {
"start": 6046,
"end": 6267
} | class ____(_defaultdict):
def __eq__(self, other):
return (super().__eq__(other) and
isinstance(other, _defaultdict) and
self.default_factory == other.default_factory)
| defaultdict |
python | getsentry__sentry | tests/sentry/sentry_apps/tasks/test_sentry_apps.py | {
"start": 55524,
"end": 58837
} | class ____(TestCase):
def setUp(self) -> None:
self.project = self.create_project()
self.user = self.create_user()
self.rpc_user = user_service.get_user(user_id=self.user.id)
self.sentry_app = self.create_sentry_app(organization=self.project.organization)
self.install = sel... | TestInstallationWebhook |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/interactive.py | {
"start": 170,
"end": 259
} | class ____:
"""Sentinel value for detecting parameters with unset values"""
| PARAM_UNSET |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 27557,
"end": 30542
} | class ____:
"""
Decomposes inductor ops
"""
@staticmethod
def identity(value: OpVarT) -> OpVarT:
# used to trigger cse
return value
@staticmethod
def reciprocal(x: OpVarT) -> OpVarT:
return ops.truediv(ops.constant(1, torch.int32), x)
@staticmethod
def squa... | OpDecompositions |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 37852,
"end": 42949
} | class ____(UserDefinedObjectVariable):
"""
Tracks an autograd.Function() context using mutation tracking in side_effects.py
"""
_nonvar_fields = {
"proxy",
"inference",
"saved_tensors",
*UserDefinedObjectVariable._nonvar_fields,
}
def __init__(
self,
... | AutogradFunctionContextVariable |
python | django__django | django/db/migrations/exceptions.py | {
"start": 140,
"end": 252
} | class ____(Exception):
"""There's a bad migration (unreadable/bad format/etc.)."""
pass
| BadMigrationError |
python | PyCQA__pylint | tests/functional/ext/typing/typing_deprecated_alias.py | {
"start": 2035,
"end": 2227
} | class ____(typing.NamedTuple):
my_var: List[int] # [deprecated-typing-alias]
CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) # [deprecated-typing-alias]
| CustomNamedTuple |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/lexers/pygments.py | {
"start": 896,
"end": 1672
} | class ____(metaclass=ABCMeta):
"""
Syntax synchronizer. This is a tool that finds a start position for the
lexer. This is especially important when editing big documents; we don't
want to start the highlighting by running the lexer from the beginning of
the file. That is very slow when editing.
... | SyntaxSync |
python | kamyu104__LeetCode-Solutions | Python/super-egg-drop.py | {
"start": 33,
"end": 1991
} | class ____(object):
def superEggDrop(self, K, N):
"""
:type K: int
:type N: int
:rtype: int
"""
def check(n, K, N):
# let f(n, K) be the max number of floors could be solved by n moves and K eggs,
# we want to do binary search to find min of n,... | Solution |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 43214,
"end": 44296
} | class ____(nn.Module):
def __init__(self, config: SeamlessM4Tv2Config, ffn_dim: int):
super().__init__()
self.fc1 = nn.Linear(config.hidden_size, ffn_dim)
self.fc2 = nn.Linear(ffn_dim, config.hidden_size)
self.dropout = nn.Dropout(config.activation_dropout)
self.act = ACT2FN[... | SeamlessM4Tv2FeedForwardNetwork |
python | doocs__leetcode | solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/Solution.py | {
"start": 705,
"end": 1427
} | class ____:
def maxXor(self, n: int, edges: List[List[int]], values: List[int]) -> int:
def dfs1(i, fa):
t = values[i]
for j in g[i]:
if j != fa:
t += dfs1(j, i)
s[i] = t
return t
def dfs2(i, fa):
nonloc... | Solution |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 12210,
"end": 13533
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.staticpermapp'
root_factory = 'tests.pkgs.staticpermapp:RootFactory'
def test_allowed(self):
result = self.testapp.get('/allowed/index.html', status=200)
_assertBody(
result.body, os.path.join(here, 'fixtures/... | TestStaticPermApp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-klaviyo/components.py | {
"start": 13555,
"end": 15001
} | class ____(StateMigration):
"""
Transforms the input state for per-partitioned streams from the legacy format to the low-code format.
The cursor field and partition ID fields are automatically extracted from the stream's DatetimebasedCursor and SubstreamPartitionRouter.
Example input state:
{
... | PerPartitionToSingleStateMigration |
python | RaRe-Technologies__gensim | gensim/test/test_datatype.py | {
"start": 356,
"end": 1965
} | class ____(unittest.TestCase):
def load_model(self, datatype):
path = datapath('high_precision.kv.txt')
kv = KeyedVectors.load_word2vec_format(path, binary=False,
datatype=datatype)
return kv
def test_high_precision(self):
kv = self... | TestDataType |
python | gevent__gevent | src/greentest/3.14/test_urllib.py | {
"start": 51282,
"end": 59133
} | class ____(unittest.TestCase):
"""Tests for urlencode()"""
def help_inputtype(self, given, test_type):
"""Helper method for testing different input types.
'given' must lead to only the pairs:
* 1st, 1
* 2nd, 2
* 3rd, 3
Test cannot assume anything ab... | urlencode_Tests |
python | mlflow__mlflow | mlflow/bedrock/stream.py | {
"start": 433,
"end": 2583
} | class ____:
"""
A wrapper class for a event stream to record events and accumulated response
in an MLflow span if possible.
A span should be ended when the stream is exhausted rather than when it is created.
Args:
stream: The original event stream to wrap.
span: The span to record ... | BaseEventStreamWrapper |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 29060,
"end": 30227
} | class ____(Response):
"""
Response of queues.delete endpoint.
:param deleted: Number of queues deleted (0 or 1)
:type deleted: int
"""
_service = "queues"
_action = "delete"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"deleted": {
... | DeleteResponse |
python | Delgan__loguru | tests/conftest.py | {
"start": 4137,
"end": 4209
} | class ____(io.StringIO):
def fileno(self):
return 1
| StubStream |
python | getsentry__sentry | src/sentry/utils/time_window.py | {
"start": 88,
"end": 2424
} | class ____:
# Timestamps are in seconds
start: float
end: float
def as_tuple(self) -> tuple[float, float]:
return (self.start, self.end)
@property
def duration_ms(self) -> float:
return (self.end - self.start) * 1000
def __add__(self, other: "TimeWindow") -> tuple[Optional... | TimeWindow |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 9316,
"end": 9801
} | class ____(UserMixin, TestBase):
def testGetUser(self):
with reversion.create_revision():
reversion.set_user(self.user)
self.assertEqual(reversion.get_user(), self.user)
def testGetUserDefault(self):
with reversion.create_revision():
self.assertEqual(reversi... | GetUserTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/bigquery.py | {
"start": 63907,
"end": 81547
} | class ____(BigQueryBaseCursor):
"""
A very basic BigQuery PEP 249 cursor implementation.
The PyHive PEP 249 implementation was used as a reference:
https://github.com/dropbox/PyHive/blob/master/pyhive/presto.py
https://github.com/dropbox/PyHive/blob/master/pyhive/common.py
"""
def __init_... | BigQueryCursor |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 59636,
"end": 60235
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layers = nn.ModuleList()
for _ in range(config.num_transition_layers):
l = EsmFoldStructureModuleTransitionLayer(config)
self.layers.append(l)
self.dropou... | EsmFoldStructureModuleTransition |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 4237,
"end": 5660
} | class ____(BasicTickFormatter):
''' A ``TickFormatter`` for values in WebMercator units.
Some map plot types internally use WebMercator to describe coordinates,
plot bounds, etc. These units are not very human-friendly. This tick
formatter will convert WebMercator units into Latitude and Longitude
... | MercatorTickFormatter |
python | numba__numba | numba/core/pythonapi.py | {
"start": 2062,
"end": 2692
} | class ____(namedtuple("_ReflectContext",
("context", "builder", "pyapi", "env_manager",
"is_error"))):
"""
The facilities required by reflection implementations.
"""
__slots__ = ()
# XXX the error bit is currently unused by consumers (e.g. PyCallWrapper)... | _ReflectContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 15826,
"end": 15913
} | class ____(IterableExportStreamAdjustableRange):
data_field = "emailClick"
| EmailClick |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 25647,
"end": 25891
} | class ____(MixinUnsafeUrl, TestRefererMiddleware):
settings = {
"REFERRER_POLICY": "scrapy.spidermiddlewares.referer.OriginWhenCrossOriginPolicy"
}
req_meta = {"referrer_policy": POLICY_UNSAFE_URL}
| TestRequestMetaPrecedence003 |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/users/main.py | {
"start": 1413,
"end": 1886
} | class ____(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
if users.is_current_user_admin():
self.response.write("You are an administrator.")
else:
self.response.write("You are not an administrator.")
el... | AdminPage |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 467,
"end": 643
} | class ____:
def __index__(self):
print("ruff") # [invalid-index-return]
# TODO: Once Ruff has better type checking
def return_index():
return "3"
| IndexNoReturn |
python | jina-ai__jina | tests/integration/deployments/test_deployment.py | {
"start": 10064,
"end": 11600
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
if doc.text == 'slow':
time.sleep(1.0)
def _create_regular_deployment(
port,
name='',
executor=None,
uses_before=False,
uses_after=False,
polling=PollingType.ANY,
sha... | FastSlowExecutor |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/data_utils.py | {
"start": 11662,
"end": 12884
} | class ____(object):
"""Wrap an iterator with a lock and propagate exceptions to all threads."""
def __init__(self, it):
self.it = it
self.lock = threading.Lock()
# After a generator throws an exception all subsequent next() calls raise a
# StopIteration Exception. This, however, presents an issue ... | ThreadsafeIter |
python | tensorflow__tensorflow | tensorflow/compiler/tests/ensure_shape_op_test.py | {
"start": 1003,
"end": 1861
} | class ____(xla_test.XLATestCase):
def testEnsureShape(self):
with self.session() as sess:
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
op = check_ops.ensure_shape(p, (None, 3))
expected_out = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
self.assertAllEqual(expected_out,
... | EnsureShapeOpTest |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 164239,
"end": 164478
} | class ____(RecvmsgTests, SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
| RecvmsgUDP6Test |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 24307,
"end": 24686
} | class ____(CompressionTestMixin):
"""Specialization of CompressionTestMixin when we expect no compression."""
def verify_wire_bytes(self, bytes_in, bytes_out):
# Bytes out includes the 4-byte mask key per message.
self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6))
self.assertEqual... | UncompressedTestMixin |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_3des.py | {
"start": 1773,
"end": 2793
} | class ____:
test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "OFB"),
[
"TOFBpermop.rsp",
"TOFBsubtab.rsp",
"TOFBvarkey.rsp",
"TOFBvartext.rsp",
"TOFBinvperm.rsp",
],
lambda keys, *... | TestTripleDESModeOFB |
python | dagster-io__dagster | python_modules/dagster/dagster/components/testing/deprecated/utils.py | {
"start": 810,
"end": 12346
} | class ____:
project_root: Path
defs_folder_path: Path
component_path: Path
project_name: str
component_format: ScaffoldFormatOptions
@contextmanager
def swap_defs_file(self, defs_path: Path, component_body: Optional[dict[str, Any]]):
check.invariant(
defs_path.suffix == ... | DefsPathSandbox |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/type_inference.py | {
"start": 18706,
"end": 19810
} | class ____(transformer.Base):
"""AST visitor that applies type inference to each function separately."""
def __init__(self, source_info, graphs, resolver):
super(FunctionVisitor, self).__init__(source_info)
self.graphs = graphs
self.resolver = resolver
def visit_FunctionDef(self, node):
subgraph... | FunctionVisitor |
python | django__django | tests/admin_views/models.py | {
"start": 29895,
"end": 30050
} | class ____(models.Model):
interesting_name = models.CharField(max_length=100)
def __str__(self):
return self.interesting_name
| CamelCaseModel |
python | pyinstaller__pyinstaller | PyInstaller/depend/dylib.py | {
"start": 8200,
"end": 13220
} | class ____:
def __init__(self, entries):
self._regex = re.compile('|'.join(entries), re.I) if entries else None
def check_library(self, libname):
if self._regex:
return self._regex.match(os.path.basename(libname))
return False
if compat.is_darwin:
import macholib.util
... | MatchList |
python | ApeWorX__ape | src/ape/managers/_contractscache.py | {
"start": 3077,
"end": 37704
} | class ____(BaseManager):
"""
A collection of cached contracts. Contracts can be cached in two ways:
1. An in-memory cache of locally deployed contracts
2. A cache of contracts per network (only permanent networks are stored this way)
When retrieving a contract, if a :class:`~ape.api.explorers.Expl... | ContractCache |
python | davidhalter__parso | parso/python/diff.py | {
"start": 8743,
"end": 19937
} | class ____:
"""
An advanced form of parsing a file faster. Unfortunately comes with huge
side effects. It changes the given module.
"""
def __init__(self, pgen_grammar, tokenizer, module):
self._pgen_grammar = pgen_grammar
self._tokenizer = tokenizer
self._module = module
... | DiffParser |
python | allegroai__clearml | clearml/utilities/pyhocon/config_parser.py | {
"start": 1257,
"end": 1795
} | class ____(object):
pass
def period(period_value, period_unit):
try:
from dateutil.relativedelta import relativedelta as period_impl
except Exception:
from datetime import timedelta as period_impl
if period_unit == 'nanoseconds':
period_unit = 'microseconds'
period_val... | STR_SUBSTITUTION |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 33532,
"end": 37974
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(
self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False, scale... | Sam3SinePositionEmbedding |
python | doocs__leetcode | solution/1200-1299/1256.Encode Number/Solution.py | {
"start": 0,
"end": 87
} | class ____:
def encode(self, num: int) -> str:
return bin(num + 1)[3:]
| Solution |
python | etianen__django-reversion | tests/test_app/tests/test_admin.py | {
"start": 4606,
"end": 7243
} | class ____(LoginMixin, AdminMixin, TestBase):
"""Test that Django model signals are muted during GET requests to revision views."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.signal_fired = None
def signal_receiver(self, sender, **kwargs):
"""Receiv... | AdminRevisionViewSignalsTest |
python | keras-team__keras | keras/src/backend/common/variables_test.py | {
"start": 47067,
"end": 47516
} | class ____(test_case.TestCase):
def test_standardize_shape_with_tensor_size(self):
import tensorflow as tf
shape = (3, tf.constant(4, dtype=tf.int64), 5)
standardized_shape = standardize_shape(shape)
self.assertEqual(standardized_shape, (3, 4, 5))
self.assertIs(type(standard... | TestStandardizeShapeWithTensorflow |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/_utils.py | {
"start": 6268,
"end": 7319
} | class ____:
command: list[str]
@property
def is_installed(self) -> bool:
"""Returns whether formatter is available"""
if not hasattr(self, "_is_installed"):
self._is_installed = self._is_available_via_cli()
return self._is_installed
def format(self, code: str, line_... | Formatter |
python | pytorch__pytorch | test/test_opaque_obj.py | {
"start": 520,
"end": 1520
} | class ____:
def __init__(self, queue: list[torch.Tensor], init_tensor_: torch.Tensor) -> None:
super().__init__()
self.queue = queue
self.init_tensor_ = init_tensor_
# For testing purposes
self._push_counter = 0
self._pop_counter = 0
self._size_counter = 0
... | OpaqueQueue |
python | getsentry__sentry | src/sentry/middleware/integrations/classifications.py | {
"start": 653,
"end": 1236
} | class ____(abc.ABC):
def __init__(self, response_handler: ResponseHandler) -> None:
self.response_handler = response_handler
def should_operate(self, request: HttpRequest) -> bool:
"""
Determines whether the classification should act on request.
Middleware will return self.get_r... | BaseClassification |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_s3.py | {
"start": 1061,
"end": 7360
} | class ____:
def test_serialization(self):
"""
Asserts that the TaskStateTrigger correctly serializes its arguments
and classpath.
"""
trigger = S3KeyTrigger(
bucket_key="s3://test_bucket/file",
bucket_name="test_bucket",
wildcard_match=True... | TestS3KeyTrigger |
python | openai__openai-python | src/openai/types/fine_tuning/alpha/grader_run_params.py | {
"start": 593,
"end": 1414
} | class ____(TypedDict, total=False):
grader: Required[Grader]
"""The grader used for the fine-tuning job."""
model_sample: Required[str]
"""The model sample to be evaluated.
This value will be used to populate the `sample` namespace. See
[the guide](https://platform.openai.com/docs/guides/grade... | GraderRunParams |
python | plotly__plotly.py | plotly/graph_objs/waterfall/_hoverlabel.py | {
"start": 233,
"end": 11255
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall"
_path_str = "waterfall.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc"... | Hoverlabel |
python | mwaskom__seaborn | tests/_core/test_plot.py | {
"start": 44127,
"end": 49835
} | class ____:
@pytest.fixture(scope="class", params=["row", "col"])
def dim(self, request):
return request.param
@pytest.fixture(scope="class", params=["reverse", "subset", "expand"])
def reorder(self, request):
return {
"reverse": lambda x: x[::-1],
"subset": lam... | TestFacetInterface |
python | tensorflow__tensorflow | tensorflow/python/trackable/base.py | {
"start": 3105,
"end": 4036
} | class ____(object):
"""A callable object that returns a CheckpointInitialValue.
See CheckpointInitialValue for more information.
"""
def __init__(self, checkpoint_position):
self._checkpoint_position = checkpoint_position
@property
def checkpoint_position(self):
return self._checkpoint_position
... | CheckpointInitialValueCallable |
python | huggingface__transformers | src/transformers/models/pvt/configuration_pvt.py | {
"start": 946,
"end": 6377
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PvtModel`]. It is used to instantiate an Pvt
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuratio... | PvtConfig |
python | spack__spack | lib/spack/spack/tengine.py | {
"start": 314,
"end": 1703
} | class ____(type):
"""Meta class for Context. It helps reducing the boilerplate in
client code.
"""
#: Keeps track of the context properties that have been added
#: by the class that is being defined
_new_context_properties: List[str] = []
def __new__(cls, name, bases, attr_dict):
#... | ContextMeta |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_grayscale_test.py | {
"start": 229,
"end": 4500
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.RandomGrayscale,
init_kwargs={
"factor": 0.5,
"data_format": "channels_last",
},
input_shape=(1, 2, 2, 3... | RandomGrayscaleTest |
python | weaviate__weaviate-python-client | weaviate/collections/batch/grpc_batch_delete.py | {
"start": 559,
"end": 2661
} | class ____(_BaseGRPC):
"""This class is used to delete multiple objects from Weaviate using the gRPC API."""
def __init__(
self,
weaviate_version: _ServerVersion,
consistency_level: Optional[ConsistencyLevel],
):
super().__init__(weaviate_version, consistency_level, False)
... | _BatchDeleteGRPC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.