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 | doocs__leetcode | solution/2400-2499/2490.Circular Sentence/Solution.py | {
"start": 0,
"end": 197
} | class ____:
def isCircularSentence(self, sentence: str) -> bool:
ss = sentence.split()
n = len(ss)
return all(s[-1] == ss[(i + 1) % n][0] for i, s in enumerate(ss))
| Solution |
python | huggingface__transformers | src/transformers/models/sew/modeling_sew.py | {
"start": 41072,
"end": 46010
} | class ____(SEWPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Sequence classification does not support the use of SEW adapters (config.add_adapter=True)"
)
... | SEWForSequenceClassification |
python | scikit-image__scikit-image | tests/skimage/graph/test_connect.py | {
"start": 196,
"end": 2367
} | class ____(mcp.MCP_Connect):
def _reset(self):
"""Reset the id map."""
mcp.MCP_Connect._reset(self)
self._conn = {}
self._bestconn = {}
def create_connection(self, id1, id2, pos1, pos2, cost1, cost2):
# Process data
hash = min(id1, id2), max(id1, id2)
val... | MCP |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py | {
"start": 9923,
"end": 10181
} | class ____(graphene.ObjectType):
message = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneError,)
name = "AutoMaterializeAssetEvaluationNeedsMigrationError"
| GrapheneAutoMaterializeAssetEvaluationNeedsMigrationError |
python | graphql-python__graphene | graphene/validation/tests/test_disable_introspection.py | {
"start": 144,
"end": 842
} | class ____(ObjectType):
name = String(required=True)
@staticmethod
def resolve_name(root, info):
return "Hello world!"
schema = Schema(query=Query)
def run_query(query: str):
document = parse(query)
return validate(
schema=schema.graphql_schema,
document_ast=document,
... | Query |
python | pennersr__django-allauth | allauth/socialaccount/providers/cilogon/provider.py | {
"start": 509,
"end": 1694
} | class ____(OAuth2Provider):
id = "cilogon"
name = "CILogon"
account_class = CILogonAccount
oauth2_adapter_class = CILogonOAuth2Adapter
def get_default_scope(self):
scope = [Scope.PROFILE, Scope.USERINFO, Scope.OPENID]
if QUERY_EMAIL:
scope.append(Scope.EMAIL)
ret... | CILogonProvider |
python | lepture__authlib | authlib/oauth2/rfc7523/jwt_bearer.py | {
"start": 479,
"end": 6970
} | class ____(BaseGrant, TokenEndpointMixin):
GRANT_TYPE = JWT_BEARER_GRANT_TYPE
#: Options for verifying JWT payload claims. Developers MAY
#: overwrite this constant to create a more strict options.
CLAIMS_OPTIONS = {
"iss": {"essential": True},
"aud": {"essential": True},
"exp":... | JWTBearerGrant |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol41.py | {
"start": 1237,
"end": 1335
} | class ____(Protocol[AnyStr_contra]):
def write(self, __b: AnyStr_contra) -> Any: ...
| WriteBuffer |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 127374,
"end": 130112
} | class ____(Response):
"""
Response of tasks.completed endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param published: Number of tasks published (0 or 1)
:type published: int
"""
_s... | CompletedResponse |
python | wandb__wandb | wandb/apis/public/history.py | {
"start": 636,
"end": 4656
} | class ____:
"""Iterator for scanning complete run history.
<!-- lazydoc-ignore-class: internal -->
"""
def __init__(
self,
api: public.Api,
run: runs.Run,
min_step: int,
max_step: int,
keys: list[str] | None = None,
page_size: int = 1000,
):
... | BetaHistoryScan |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 30008,
"end": 30366
} | class ____(StringEnumProperty):
"""Descriptor for overflow styles that forces widgets to refresh scrollbars."""
def _before_refresh(self, obj: StylesBase, value: str | None) -> None:
from textual.widget import Widget # Avoid circular import
if isinstance(obj.node, Widget):
obj.nod... | OverflowProperty |
python | kamyu104__LeetCode-Solutions | Python/find-longest-awesome-substring.py | {
"start": 37,
"end": 602
} | class ____(object):
def longestAwesome(self, s):
"""
:type s: str
:rtype: int
"""
ALPHABET_SIZE = 10
result, mask, lookup = 0, 0, [len(s)]*(2**ALPHABET_SIZE)
lookup[0] = -1
for i, ch in enumerate(s):
mask ^= 2**(ord(ch)-ord('0'))
... | Solution |
python | ray-project__ray | python/ray/train/v2/_internal/execution/local_mode/torch.py | {
"start": 1244,
"end": 3190
} | class ____(LocalController):
def _set_train_fn_utils(self) -> None:
world_size = 1
global_rank = 0
local_rank = 0
nproc_per_node = 1
node_rank = 0
if has_torchrun_env():
assert not dist.is_initialized(), "torch.distributed is already initialized"
... | LocalTorchController |
python | davidhalter__jedi | jedi/inference/compiled/value.py | {
"start": 13462,
"end": 13979
} | class ____(ParamNameInterface, AbstractNameDefinition):
def __init__(self, compiled_value, name, default):
self.parent_context = compiled_value.parent_context
self.string_name = name
self._default = default
def get_kind(self):
return Parameter.POSITIONAL_ONLY
def to_string(... | UnresolvableParamName |
python | kamyu104__LeetCode-Solutions | Python/flip-square-submatrix-vertically.py | {
"start": 39,
"end": 440
} | class ____(object):
def reverseSubmatrix(self, grid, x, y, k):
"""
:type grid: List[List[int]]
:type x: int
:type y: int
:type k: int
:rtype: List[List[int]]
"""
for i in xrange(k//2):
for j in xrange(k):
grid[x+i][y+j], gri... | Solution |
python | scikit-learn__scikit-learn | sklearn/mixture/_gaussian_mixture.py | {
"start": 18675,
"end": 35776
} | class ____(BaseMixture):
"""Gaussian Mixture.
Representation of a Gaussian mixture model probability distribution.
This class allows to estimate the parameters of a Gaussian mixture
distribution.
Read more in the :ref:`User Guide <gmm>`.
.. versionadded:: 0.18
Parameters
----------
... | GaussianMixture |
python | google__jax | tests/pallas/tpu_pallas_async_test.py | {
"start": 6279,
"end": 25086
} | class ____(parameterized.TestCase):
# TODO(b/368123537): add more tests
def setUp(self):
super().setUp()
if not jtu.is_device_tpu_at_least(4):
self.skipTest('DMAs only guaranteed to work ou TPU v4+')
def test_basic_async_copy(self):
@jax.jit
def f(x):
copy_start, copy_done = make_asy... | PallasCallAsyncCopyTest |
python | tensorflow__tensorflow | tensorflow/python/keras/callbacks.py | {
"start": 106644,
"end": 109715
} | class ____(Callback):
r"""Callback for creating simple, custom callbacks on-the-fly.
This callback is constructed with anonymous functions that will be called
at the appropriate time (during `Model.{fit | evaluate | predict}`).
Note that the callbacks expects positional arguments, as:
- `on_epoch_begin` and... | LambdaCallback |
python | fluentpython__example-code | attic/metaprog/spreadsheet2.py | {
"start": 794,
"end": 1385
} | class ____:
def __init__(self, **tools):
self._cells = {}
self._tools = {'__builtins__' : {}}
self._tools.update(tools)
def __setitem__(self, key, formula):
try:
compile(formula, '<__setitem__>', 'eval')
except SyntaxError as exc:
msg = '{} [{!r}... | Spreadsheet |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/cx_oracle.py | {
"start": 24742,
"end": 25017
} | class ____(_LOBDataType, sqltypes.Text):
def get_dbapi_type(self, dbapi):
# previously, this was dbapi.CLOB.
# DB_TYPE_NVARCHAR will instead be passed to setinputsizes()
# when this datatype is used.
return dbapi.DB_TYPE_NVARCHAR
| _OracleText |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 152065,
"end": 152238
} | class ____(TempNode):
# TempNode holding a Python value.
def __init__(self, pos, env):
TempNode.__init__(self, pos, PyrexTypes.py_object_type, env)
| PyTempNode |
python | django-compressor__django-compressor | compressor/storage.py | {
"start": 645,
"end": 2163
} | class ____(FileSystemStorage):
"""
Standard file system storage for files handled by django-compressor.
The defaults for ``location`` and ``base_url`` are ``COMPRESS_ROOT`` and
``COMPRESS_URL``.
"""
def __init__(self, location=None, base_url=None, *args, **kwargs):
if location is None... | CompressorFileStorage |
python | wandb__wandb | wandb/vendor/pygments/lexers/theorem.py | {
"start": 479,
"end": 6399
} | class ____(RegexLexer):
"""
For the `Coq <http://coq.inria.fr/>`_ theorem prover.
.. versionadded:: 1.5
"""
name = 'Coq'
aliases = ['coq']
filenames = ['*.v']
mimetypes = ['text/x-coq']
keywords1 = (
# Vernacular commands
'Section', 'Module', 'End', 'Require', 'Imp... | CoqLexer |
python | kamyu104__LeetCode-Solutions | Python/frequencies-of-shortest-supersequences.py | {
"start": 118,
"end": 2205
} | class ____(object):
def supersequences(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def f(x):
x = ord(x)-ord('a')
if char_to_int[x] == -1:
int_to_char[len(indegree)] = x
char_to_int[x] = len(indeg... | Solution |
python | gevent__gevent | src/gevent/tests/test__pool.py | {
"start": 7940,
"end": 8817
} | class ____(object):
def __init__(self, func):
self.func = func
self.elapsed = None
def __call__(self, *args, **kwds):
t = time()
try:
return self.func(*args, **kwds)
finally:
self.elapsed = time() - t
def sqr(x, wait=0.0):
gevent.sleep(wait... | TimingWrapper |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 112679,
"end": 112951
} | class ____:
xlChart = -4109 # from enum XlSheetType
xlDialogSheet = -4116 # from enum XlSheetType
xlExcel4IntlMacroSheet = 4 # from enum XlSheetType
xlExcel4MacroSheet = 3 # from enum XlSheetType
xlWorksheet = -4167 # from enum XlSheetType
| SheetType |
python | getsentry__sentry | src/sentry/api/endpoints/api_tokens.py | {
"start": 2553,
"end": 5163
} | class ____(Endpoint):
owner = ApiOwner.SECURITY
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
authentication_classes = (SessionNoAuthTokenAuthentication,)
permission_classes = (SentryIsAuthenticated... | ApiTokensEndpoint |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/query_metrics/query_table/base_query_table.py | {
"start": 132,
"end": 288
} | class ____(QueryTable):
metric_name = "base_query.table"
value_keys = ("base_query",)
query_param_name: ClassVar[str] = "base_query"
| BaseQueryTable |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 3513,
"end": 4533
} | class ____:
@pytest.mark.parametrize("mode", _all_modes.keys())
def test_zero_padding_shortcuts(self, mode):
test = np.arange(120).reshape(4, 5, 6)
pad_amt = [(0, 0) for _ in test.shape]
assert_array_equal(test, np.pad(test, pad_amt, mode=mode))
@pytest.mark.parametrize("mode", ['ma... | TestConditionalShortcuts |
python | huggingface__transformers | src/transformers/models/vipllava/modeling_vipllava.py | {
"start": 4207,
"end": 5256
} | class ____(nn.Module):
def __init__(self, config: VipLlavaConfig):
super().__init__()
num_feature_layers = 1 if isinstance(config.vision_feature_layers, int) else len(config.vision_feature_layers)
self.projector_layernorm = nn.LayerNorm(
num_feature_layers * config.vision_config.... | VipLlavaMultiModalProjector |
python | pypa__setuptools | setuptools/_distutils/tests/test_install_lib.py | {
"start": 353,
"end": 3612
} | class ____(
support.TempdirManager,
):
def test_finalize_options(self):
dist = self.create_dist()[1]
cmd = install_lib(dist)
cmd.finalize_options()
assert cmd.compile == 1
assert cmd.optimize == 0
# optimize must be 0, 1, or 2
cmd.optimize = 'foo'
... | TestInstallLib |
python | django__django | tests/backends/postgresql/tests.py | {
"start": 984,
"end": 24747
} | class ____(TestCase):
databases = {"default", "other"}
def test_nodb_cursor(self):
"""
The _nodb_cursor() fallbacks to the default connection database when
access to the 'postgres' database is not granted.
"""
orig_connect = BaseDatabaseWrapper.connect
def mocke... | Tests |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_where_op_test.py | {
"start": 9492,
"end": 16974
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.parameters([
#=========================================================================
# Coordinate-retrieval mode
#=========================================================================
dict( # shape=[D1]
... | RaggedWhereV2OpTest |
python | kamyu104__LeetCode-Solutions | Python/process-restricted-friend-requests.py | {
"start": 758,
"end": 1444
} | class ____(object):
def friendRequests(self, n, restrictions, requests):
"""
:type n: int
:type restrictions: List[List[int]]
:type requests: List[List[int]]
:rtype: List[bool]
"""
result = []
uf = UnionFind(n)
for u, v in requests:
... | Solution |
python | pytorch__pytorch | test/test_testing.py | {
"start": 64296,
"end": 73446
} | class ____(TestCase):
def test_default_names(self):
class TestParametrized(TestCase):
@parametrize("x", range(5))
def test_default_names(self, x):
pass
@parametrize("x,y", [(1, 2), (2, 3), (3, 4)])
def test_two_things_default_names(self, x, y... | TestTestParametrization |
python | huggingface__transformers | src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py | {
"start": 1575,
"end": 2574
} | class ____:
module: nn.Module
traced: list[nn.Module] = field(default_factory=list)
handles: list = field(default_factory=list)
name2module: dict[str, nn.Module] = field(default_factory=OrderedDict)
def _forward_hook(self, m, inputs: Tensor, outputs: Tensor, name: str):
has_not_submodules =... | Tracker |
python | buildout__buildout | zc.recipe.egg_/src/zc/recipe/egg/egg.py | {
"start": 5513,
"end": 8614
} | class ____(Eggs):
def __init__(self, buildout, name, options):
super(Scripts, self).__init__(buildout, name, options)
options['bin-directory'] = buildout['buildout']['bin-directory']
options['_b'] = options['bin-directory'] # backward compat.
self.extra_paths = [
os.p... | Scripts |
python | oauthlib__oauthlib | oauthlib/oauth1/rfc5849/errors.py | {
"start": 2245,
"end": 2334
} | class ____(OAuth1Error):
error = 'invalid_signature_method'
| InvalidSignatureMethodError |
python | pyca__cryptography | tests/x509/test_ocsp.py | {
"start": 3058,
"end": 6738
} | class ____:
def test_bad_request(self):
with pytest.raises(ValueError):
ocsp.load_der_ocsp_request(b"invalid")
def test_load_request(self):
req = _load_data(
os.path.join("x509", "ocsp", "req-sha1.der"),
ocsp.load_der_ocsp_request,
)
assert is... | TestOCSPRequest |
python | lepture__authlib | authlib/oidc/core/grants/code.py | {
"start": 3696,
"end": 5681
} | class ____(OpenIDToken):
"""An extension from OpenID Connect for "grant_type=code" request. Developers
MUST implement the missing methods::
class MyOpenIDCode(OpenIDCode):
def get_jwt_config(self, grant):
return {...}
def exists_nonce(self, nonce, request):
... | OpenIDCode |
python | realpython__materials | emacs-the-best-python-editor/PyEval/pyeval_operand.py | {
"start": 104,
"end": 439
} | class ____:
"""
Common operator class used by the evaluator.
"""
def __init__(self, operand_string):
"""Create a new operator object."""
# String to hold the operand literal
self.op_string = operand_string
# Integer value of the operand
self.op_value = int(oper... | Operand |
python | scipy__scipy | scipy/integrate/_ivp/common.py | {
"start": 3899,
"end": 15745
} | class ____:
"""Continuous ODE solution.
It is organized as a collection of `DenseOutput` objects which represent
local interpolants. It provides an algorithm to select a right interpolant
for each given point.
The interpolants cover the range between `t_min` and `t_max` (see
Attributes below).... | OdeSolution |
python | getsentry__sentry | src/sentry/issues/endpoints/group_stats.py | {
"start": 526,
"end": 1174
} | class ____(GroupEndpoint, StatsMixin):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, group) -> Response:
try:
environment_id = get_environment_id(request, group.project.organization_id)
except Environment.DoesNotExist:
... | GroupStatsEndpoint |
python | huggingface__transformers | tests/models/beit/test_image_processing_beit.py | {
"start": 1105,
"end": 3604
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_center_crop=True,
crop_size=None,
do_normalize=True,
image... | BeitImageProcessingTester |
python | pennersr__django-allauth | allauth/socialaccount/providers/edmodo/provider.py | {
"start": 219,
"end": 436
} | class ____(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("profile_url")
def get_avatar_url(self):
return self.account.extra_data.get("avatar_url")
| EdmodoAccount |
python | django-guardian__django-guardian | guardian/testapp/tests/conf.py | {
"start": 349,
"end": 897
} | class ____:
def setUp(self):
super().setUp()
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
User = get_user_model()
Group.objects.create(pk=1, name="admins")
jack_group = Group.objects.create(pk=2, name="jackGroup")
... | TestDataMixin |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 31281,
"end": 34909
} | class ____(MobileViTPreTrainedModel):
def __init__(self, config: MobileViTConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.mobilevit = MobileViTModel(config, expand_output=False)
self.segmentation_head = MobileViTDeepLabV3(config)
# Initial... | MobileViTForSemanticSegmentation |
python | dask__dask | dask/tests/test_typing.py | {
"start": 3356,
"end": 5665
} | class ____(DaskMethodsMixin):
def __init__(self, based_on: DaskCollection) -> None:
self.based_on = based_on
def __dask_graph__(self) -> Graph:
return self.based_on.__dask_graph__()
def __dask_keys__(self) -> NestedKeys:
return self.based_on.__dask_keys__()
def __dask_postcomp... | NotHLGCollection |
python | huggingface__transformers | tests/models/cpmant/test_modeling_cpmant.py | {
"start": 6907,
"end": 8883
} | class ____(unittest.TestCase):
@tooslow
def test_inference_causal(self):
texts = "今天天气真好!"
model_path = "openbmb/cpm-ant-10b"
model = CpmAntForCausalLM.from_pretrained(model_path)
tokenizer = CpmAntTokenizer.from_pretrained(model_path)
inputs = tokenizer(texts, return_ten... | CpmAntForCausalLMlIntegrationTest |
python | sympy__sympy | sympy/functions/special/error_functions.py | {
"start": 71214,
"end": 76488
} | class ____(FresnelIntegral):
r"""
Fresnel integral C.
Explanation
===========
This function is defined by
.. math:: \operatorname{C}(z) = \int_0^z \cos{\frac{\pi}{2} t^2} \mathrm{d}t.
It is an entire function.
Examples
========
>>> from sympy import I, oo, fresnelc
>>> ... | fresnelc |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 16111,
"end": 16518
} | class ____(AbstractGenericGetTestCase):
kind = queue.SimpleQueue
Timeout = Full
def setUp(self):
super(TestPutInterrupt, self).setUp()
self.queue = self._makeOne()
def wait(self, timeout):
while not self.queue.full():
self.queue.put(1)
return self.queue.put(... | TestPutInterrupt |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 15840,
"end": 16281
} | class ____(Source):
desc: Optional[str] = None
def guard_source(self) -> GuardSource:
return GuardSource.EPHEMERAL
def name(self) -> str:
return f"<ephemeral{': ' + self.desc if self.desc is not None else ''}>"
def make_guard(self, fn: Callable[..., Any]) -> Guard:
raise NotIm... | EphemeralSource |
python | kamyu104__LeetCode-Solutions | Python/longest-uncommon-subsequence-i.py | {
"start": 37,
"end": 259
} | class ____(object):
def findLUSlength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
if a == b:
return -1
return max(len(a), len(b))
| Solution |
python | huggingface__transformers | src/transformers/models/mpnet/modeling_mpnet.py | {
"start": 20751,
"end": 24085
} | class ____(MPNetPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.mpnet = MPNetModel(config, add_pooling_layer=False)
self.classifier = MPNetClassificationHead(config)
# Initialize weights and apply final process... | MPNetForSequenceClassification |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py | {
"start": 39394,
"end": 45684
} | class ____(GoogleCloudBaseOperator):
"""
Restore a service from a backup.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param service_id: Required. The ID of the m... | DataprocMetastoreRestoreServiceOperator |
python | davidhalter__parso | parso/python/tree.py | {
"start": 22545,
"end": 22997
} | class ____(Flow):
type = 'try_stmt'
__slots__ = ()
def get_except_clause_tests(self):
"""
Returns the ``test`` nodes found in ``except_clause`` nodes.
Returns ``[None]`` for except clauses without an exception given.
"""
for node in self.children:
if node... | TryStmt |
python | ethereum__web3.py | web3/main.py | {
"start": 11446,
"end": 16163
} | class ____(BaseWeb3, Generic[AsyncProviderT]):
# mypy Types
eth: AsyncEth
net: AsyncNet
geth: AsyncGeth
# Providers
AsyncHTTPProvider = AsyncHTTPProvider
WebSocketProvider = WebSocketProvider
AsyncEthereumTesterProvider = AsyncEthereumTesterProvider
def __init__(
self,
... | AsyncWeb3 |
python | walkccc__LeetCode | solutions/3034. Number of Subarrays That Match a Pattern I/3034.py | {
"start": 0,
"end": 1341
} | class ____:
def countMatchingSubarrays(self, nums: list[int], pattern: list[int]) -> int:
def getNum(a: int, b: int) -> int:
if a < b:
return 1
if a > b:
return -1
return 0
numsPattern = [getNum(a, b) for a, b in itertools.pairwise(nums)]
return self._kmp(numsPattern, pa... | Solution |
python | PyCQA__pylint | doc/data/messages/i/invalid-class-object/bad.py | {
"start": 0,
"end": 70
} | class ____:
pass
Apple.__class__ = 1 # [invalid-class-object]
| Apple |
python | doocs__leetcode | lcof/面试题32 - III. 从上到下打印二叉树 III/Solution.py | {
"start": 164,
"end": 707
} | class ____:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
ans = []
while q:
t = []
for _ in range(len(q)):
node = q.popleft()
t.append(node.va... | Solution |
python | django__django | django/contrib/messages/storage/cookie.py | {
"start": 1571,
"end": 1812
} | class ____:
def dumps(self, obj):
return [
json.dumps(
o,
separators=(",", ":"),
cls=MessageEncoder,
)
for o in obj
]
| MessagePartSerializer |
python | keras-team__keras | keras/src/backend/common/variables_test.py | {
"start": 18705,
"end": 21585
} | class ____(test_case.TestCase):
"""tests for dtype, shape, ndim, __repr__"""
def test_variable_dtype(self):
"""Test retrieving the dtype of a variable."""
v = backend.Variable(
initializer=np.array([1.0, 2.0, 3.0], dtype=np.float32)
)
self.assertEqual(v.dtype, "float... | VariableDtypeShapeNdimRepr |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/concatenation_test.py | {
"start": 1140,
"end": 2888
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Testing Concatenation in TF-TRT conversion."""
def GraphFn(self, x):
dtype = x.dtype
# scale
a = constant_op.constant(np.random.randn(3, 1, 1), dtype=dtype)
r1 = x / a
a = constant_op.constant(np.random.randn(3, 1, 1), dtype=dtype)
r2 = a / ... | ConcatenationTest |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/_stubs.py | {
"start": 471,
"end": 592
} | class ____(dj_template.RequestContext):
template: dj_template.Template
render_context: RenderContext
| RequestContext |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_styles01.py | {
"start": 380,
"end": 3101
} | class ____(unittest.TestCase):
"""
Test assembling a complete Styles file.
"""
def test_assemble_xml_file(self):
"""Test for styles.xml file with default styles."""
self.maxDiff = None
fh = StringIO()
style = Styles()
style._set_filehandle(fh)
workbook... | TestAssembleStyles |
python | getsentry__sentry | src/sentry/discover/compare_tables.py | {
"start": 1155,
"end": 1476
} | class ____(Enum):
BOTH_FAILED = "both_requests_failed"
EAP_FAILED = "eap_failed"
FIELD_NOT_FOUND = "field_not_found"
METRICS_FAILED = "metrics_failed"
NO_DATA = "no_data"
NO_FIELDS = "no_fields"
NO_PROJECT = "no_project"
PASSED = "passed"
QUERY_FAILED = "query_failed"
| CompareTableResult |
python | ray-project__ray | python/ray/train/_internal/worker_group.py | {
"start": 1671,
"end": 2815
} | class ____:
"""Class representing a Worker."""
actor: ActorHandle
metadata: WorkerMetadata
def create_executable_class(executable_cls: Optional[Type] = None) -> Type:
"""Create the executable class to use as the Ray actors."""
if not executable_cls:
return RayTrainWorker
elif issubcla... | Worker |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 22540,
"end": 25010
} | class ____(ViTMAEPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = ViTMAEEmbeddings(config)
self.encoder = ViTMAEEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
... | ViTMAEModel |
python | encode__starlette | starlette/formparsers.py | {
"start": 1479,
"end": 1595
} | class ____(Exception):
def __init__(self, message: str) -> None:
self.message = message
| MultiPartException |
python | pexpect__pexpect | pexpect/pty_spawn.py | {
"start": 642,
"end": 37382
} | class ____(SpawnBase):
'''This is the main class interface for Pexpect. Use this class to start
and control child applications. '''
# This is purely informational now - changing it has no effect
use_native_pty_fork = use_native_pty_fork
def __init__(self, command, args=[], timeout=30, maxread=2000... | spawn |
python | getsentry__sentry | tests/sentry/workflow_engine/migrations/test_0104_action_data_fallthrough_type.py | {
"start": 234,
"end": 1473
} | class ____(TestMigrations):
migrate_from = "0103_add_unique_constraint"
migrate_to = "0104_action_data_fallthrough_type"
app = "workflow_engine"
def setup_initial_state(self) -> None:
self.org = self.create_organization(name="test-org")
self.project = self.create_project(organization=se... | TestActionDataFallthroughType |
python | huggingface__transformers | src/transformers/models/chameleon/modeling_chameleon.py | {
"start": 28247,
"end": 32206
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.num_resolutions = len(config.channel_multiplier)
self.num_res_blocks = config.num_res_blocks
base_channels = config.base_channels
resolution = config.resolution
in_channels = config.in_channel... | ChameleonVQVAEEncoder |
python | tensorflow__tensorflow | tensorflow/python/ops/clustering_ops.py | {
"start": 2105,
"end": 25455
} | class ____:
"""Creates the graph for k-means clustering."""
def __init__(self,
inputs,
num_clusters,
initial_clusters=RANDOM_INIT,
distance_metric=SQUARED_EUCLIDEAN_DISTANCE,
use_mini_batch=False,
mini_batch_steps_per_iterati... | KMeans |
python | realpython__materials | python-double-underscore/shapes.py | {
"start": 178,
"end": 478
} | class ____:
def __init__(self, side):
self.side = _validate(side)
def calculate_area(self):
return round(self.side**2, 2)
def _validate(value):
if not isinstance(value, int | float) or value <= 0:
raise ValueError("positive number expected")
return value
| Square |
python | tensorflow__tensorflow | tensorflow/python/distribute/combinations.py | {
"start": 4860,
"end": 5482
} | class ____(combinations_lib.TestCombination):
"""Sets up distribution strategy for tests."""
def should_execute_combination(self, kwargs):
distributions = [
v for v in kwargs.values() if isinstance(v, NamedDistribution)
]
if test_util.is_xla_enabled() and any(d.no_xla for d in distributions):
... | DistributionCombination |
python | ray-project__ray | release/long_running_tests/workloads/serve_failure.py | {
"start": 1600,
"end": 2839
} | class ____:
def __init__(self, kill_period_s=1):
self.kill_period_s = kill_period_s
self.sanctuary = set()
async def run(self):
while True:
chosen = random.choice(self._get_serve_actors())
print(f"Killing {chosen}")
ray.kill(chosen, no_restart=False)
... | RandomKiller |
python | neetcode-gh__leetcode | python/0045-jump-game-ii.py | {
"start": 0,
"end": 331
} | class ____:
def jump(self, nums: List[int]) -> int:
l, r = 0, 0
res = 0
while r < (len(nums) - 1):
maxJump = 0
for i in range(l, r + 1):
maxJump = max(maxJump, i + nums[i])
l = r + 1
r = maxJump
res += 1
retu... | Solution |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 1730,
"end": 1852
} | class ____:
expr_str: Annotated[str, 10]
hint: Annotated[Optional[SymExprHint], 20] = None
@_union_dataclass
| SymExpr |
python | kamyu104__LeetCode-Solutions | Python/projection-area-of-3d-shapes.py | {
"start": 31,
"end": 530
} | class ____(object):
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
result = 0
for i in xrange(len(grid)):
max_row, max_col = 0, 0
for j in xrange(len(grid)):
if grid[i][j]:
re... | Solution |
python | pytorch__pytorch | torch/_refs/fft.py | {
"start": 13042,
"end": 17980
} | class ____(NamedTuple):
shape: tuple[int, ...]
dim: tuple[int, ...]
last_dim_size: int
def _canonicalize_fft_c2r_shape_and_dim_args(
fname: str,
input: TensorLikeType,
s: Optional[ShapeType],
dim: Optional[DimsType],
) -> _CanonicalizeC2rReturn:
"""Canonicalize shape and dim arguments ... | _CanonicalizeC2rReturn |
python | streamlit__streamlit | lib/tests/streamlit/elements/markdown_test.py | {
"start": 5491,
"end": 8217
} | class ____(DeltaGeneratorTestCase):
"""Test st.caption APIs."""
def test_st_caption_with_help(self):
"""Test st.caption with help."""
st.caption("some caption", help="help text")
el = self.get_delta_from_queue().new_element
assert el.markdown.help == "help text"
def test_st... | StCaptionAPITest |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 17133,
"end": 17275
} | class ____(_TestIDSTBase):
def setup_method(self):
self.rdt = np.float64
self.dec = 12
self.type = 1
| TestIDSTIDouble |
python | django-haystack__django-haystack | test_haystack/whoosh_tests/testcases.py | {
"start": 93,
"end": 1258
} | class ____(TestCase):
fixtures = ["base_data"]
@classmethod
def setUpClass(cls):
for name, conn_settings in settings.HAYSTACK_CONNECTIONS.items():
if (
conn_settings["ENGINE"]
!= "haystack.backends.whoosh_backend.WhooshEngine"
):
... | WhooshTestCase |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/resources/resources.py | {
"start": 3230,
"end": 5509
} | class ____:
def __init__(self, connection: str):
self.connection = connection
@resource(config_schema={"connection": str})
def db_resource(init_context):
connection = init_context.resource_config["connection"]
return DatabaseConnection(connection)
# end_resource_config
def get_db_connection():... | DatabaseConnection |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 945,
"end": 1036
} | class ____(NameItemLoader):
name_in = MapCompose(lambda v: v.title())
| ProcessorItemLoader |
python | numba__numba | numba/tests/test_debug.py | {
"start": 7445,
"end": 12092
} | class ____(TestCase):
"""
Tests debug options associated with parfors
"""
# mutates env with os.environ so must be run serially
_numba_parallel_test_ = False
def check_parfors_warning(self, warn_list):
msg = ("'parallel=True' was specified but no transformation for "
"pa... | TestParforsDebug |
python | joke2k__faker | faker/providers/person/es_CO/__init__.py | {
"start": 83,
"end": 35579
} | class ____(PersonProvider):
formats_female = [
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}} {{last_name}}",
"{{first_name_female}} {{first_name_female}} {{last_name}} {{last_name}}",
]
... | Provider |
python | django__django | tests/test_runner_apps/failures/tests_failures.py | {
"start": 49,
"end": 142
} | class ____(TestCase):
def test_sample(self):
self.assertEqual(0, 1)
| FailureTestCase |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 7006,
"end": 7852
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("de_AT")
Faker.seed(0)
def test_vat_id(self):
for _ in range(100):
assert re.search(r"^ATU\d{8}$", self.fake.vat_id())
def test_ssn(self):
for _ in range(100):
ssn: str = self.fake.ssn... | TestDeAT |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 646392,
"end": 821574
} | class ____(FileDataError):
"""Raised when creating documents from zero-length data."""
pass
# propagate exception class to C-level code
#_set_FileDataError(FileDataError)
csRGB = Colorspace(CS_RGB)
csGRAY = Colorspace(CS_GRAY)
csCMYK = Colorspace(CS_CMYK)
# These don't appear to be visible in classic, but a... | EmptyFileError |
python | huggingface__transformers | src/transformers/models/phimoe/modeling_phimoe.py | {
"start": 14191,
"end": 20796
} | class ____(nn.Module):
"""Collection of expert weights stored as 3D tensors."""
def __init__(self, config: PhimoeConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.intermediate_size
... | PhimoeExperts |
python | fluentpython__example-code-2e | 23-descriptor/descriptorkinds.py | {
"start": 5580,
"end": 5794
} | class ____: # <5>
over = Overriding()
over_no_get = OverridingNoGet()
non_over = NonOverriding()
def spam(self): # <6>
print(f'-> Managed.spam({display(self)})')
# end::DESCR_KINDS[]
| Managed |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/common/sql/sql_processor.py | {
"start": 1874,
"end": 1957
} | class ____(enum.Enum):
APPEND = "append"
REPLACE = "replace"
| RecordDedupeMode |
python | walkccc__LeetCode | solutions/1066. Campus Bikes II/1066.py | {
"start": 0,
"end": 753
} | class ____:
def assignBikes(
self,
workers: list[list[int]],
bikes: list[list[int]],
) -> int:
def dist(p1: list[int], p2: list[int]) -> int:
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
@functools.lru_cache(None)
def dp(workerIndex: int, used: int) -> int:
"""
Ret... | Solution |
python | keras-team__keras | keras/src/backend/tensorflow/optimizer.py | {
"start": 465,
"end": 9307
} | class ____(KerasAutoTrackable, base_optimizer.BaseOptimizer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._distribution_strategy = tf.distribute.get_strategy()
def add_variable_from_reference(
self, reference_variable, name=None, initializer="zeros"
)... | TFOptimizer |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 28728,
"end": 28786
} | class ____(String):
""" Represents a comment. """
| Comment |
python | sympy__sympy | sympy/polys/polyoptions.py | {
"start": 16471,
"end": 17250
} | class ____(Option, metaclass=OptionType):
"""``modulus`` option to polynomial manipulation functions. """
option = 'modulus'
requires: list[str] = []
excludes = ['greedy', 'split', 'domain', 'gaussian', 'extension']
@classmethod
def preprocess(cls, modulus):
modulus = sympify(modulus)... | Modulus |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 22663,
"end": 26697
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "ad_performance_report_hourly"
report_file = "ad_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "ad_performance_report_hourly_incremental"
def mock_report_api... | TestAdPerformanceReportHourlyStream |
python | sqlalchemy__sqlalchemy | test/sql/test_deprecations.py | {
"start": 2624,
"end": 3691
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
table1 = table(
"mytable",
column("myid", Integer),
column("name", String),
column("description", String),
)
table2 = table(
"myothertable", column("otherid", Integer), column("othername"... | SubqueryCoercionsTest |
python | astropy__astropy | astropy/coordinates/polarization.py | {
"start": 349,
"end": 2055
} | class ____(NamedTuple):
"""Symbol for a Stokes coordinate."""
symbol: str = ""
description: str = ""
# This is table 29 in the FITS 4.0 paper
FITS_STOKES_VALUE_SYMBOL_MAP = {
1: StokesSymbol("I", "Standard Stokes unpolarized"),
2: StokesSymbol("Q", "Standard Stokes linear"),
3: StokesSymbol("... | StokesSymbol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.