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 | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 224346,
"end": 226194
} | class ____(Response):
"""
Response of tasks.edit endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "edit"
_version = "2.20"
_schema = {
"de... | EditResponse |
python | walkccc__LeetCode | solutions/3405. Count the Number of Arrays with K Matching Adjacent Elements/3405.py | {
"start": 0,
"end": 170
} | class ____:
def countGoodArrays(self, n: int, m: int, k: int) -> int:
MOD = 1_000_000_007
return m * pow(m - 1, n - k - 1, MOD) * math.comb(n - 1, k) % MOD
| Solution |
python | huggingface__transformers | src/transformers/models/edgetam/configuration_edgetam.py | {
"start": 1277,
"end": 5641
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`EdgeTamVisionModel`]. It is used to instantiate a SAM
vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
defaults will yield a similar con... | EdgeTamVisionConfig |
python | pandas-dev__pandas | pandas/tests/reductions/test_reductions.py | {
"start": 18990,
"end": 42969
} | class ____:
# Note: the name TestSeriesReductions indicates these tests
# were moved from a series-specific test file, _not_ that these tests are
# intended long-term to be series-specific
def test_sum_inf(self):
s = Series(np.random.default_rng(2).standard_normal(10))
s2 = s.copy()
... | TestSeriesReductions |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass5.py | {
"start": 137,
"end": 203
} | class ____:
a: int
b: int
__match_args__ = ("a", "b")
| B |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 28743,
"end": 33077
} | class ____(unittest.TestCase):
def _makeConfig(self):
def hello_view(request):
return {'message': 'Hello!'}
from pyramid.config import Configurator
config = Configurator()
config.add_route('hello', '/hello')
config.add_view(
hello_view,
r... | AcceptContentTypeTest |
python | pyinstaller__pyinstaller | PyInstaller/archive/writers.py | {
"start": 959,
"end": 4250
} | class ____:
"""
Writer for PyInstaller's PYZ (ZlibArchive) archive. The archive is used to store collected byte-compiled Python
modules, as individually-compressed entries.
"""
_PYZ_MAGIC_PATTERN = b'PYZ\0'
_HEADER_LENGTH = 12 + 5
_COMPRESSION_LEVEL = 6 # zlib compression level
def __i... | ZlibArchiveWriter |
python | kamyu104__LeetCode-Solutions | Python/cracking-the-safe.py | {
"start": 609,
"end": 1466
} | class ____(object):
def crackSafe(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
total = k**n
M = total//k
unique_rolling_hash = 0
result = [str(0)]*(n-1)
lookup = set()
while len(lookup) < total:
for i i... | Solution2 |
python | getsentry__sentry | tests/sentry/workflow_engine/migrations/test_0088_remove_monitor_slug_conditions.py | {
"start": 161,
"end": 4022
} | class ____(TestMigrations):
migrate_from = "0087_relink_crons_to_compatible_issue_workflows"
migrate_to = "0088_remove_monitor_slug_conditions"
app = "workflow_engine"
def setup_initial_state(self) -> None:
self.org = self.create_organization(name="test-org")
self.project = self.create_... | RemoveMonitorSlugConditionsTest |
python | Textualize__textual | src/textual/signal.py | {
"start": 634,
"end": 4241
} | class ____(Generic[SignalT]):
"""A signal that a widget may subscribe to, in order to invoke callbacks when an associated event occurs."""
def __init__(self, owner: DOMNode, name: str) -> None:
"""Initialize a signal.
Args:
owner: The owner of this signal.
name: An iden... | Signal |
python | PyCQA__pylint | pylint/reporters/text.py | {
"start": 3000,
"end": 5400
} | class ____(BaseReporter):
"""Reports messages and layouts in plain text."""
name = "text"
extension = "txt"
line_format = "{path}:{line}:{column}: {msg_id}: {msg} ({symbol})"
def __init__(self, output: TextIO | None = None) -> None:
super().__init__(output)
self._modules: set[str] ... | TextReporter |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 227563,
"end": 227882
} | class ____(TestCase):
@xpassIfTorchDynamo_np # (reason="TODO")
def test_flat_element_deletion(self):
it = np.ones(3).flat
try:
del it[1]
del it[1:2]
except TypeError:
pass
except Exception:
raise AssertionError from None
| TestDelMisc |
python | scrapy__scrapy | tests/test_cmdline/__init__.py | {
"start": 206,
"end": 2551
} | class ____:
def setup_method(self):
self.env = get_testenv()
tests_path = Path(__file__).parent.parent
self.env["PYTHONPATH"] += os.pathsep + str(tests_path.parent)
self.env["SCRAPY_SETTINGS_MODULE"] = "tests.test_cmdline.settings"
def _execute(self, *new_args, **kwargs):
... | TestCmdline |
python | falconry__falcon | tests/test_uri_templates.py | {
"start": 1646,
"end": 1849
} | class ____:
def __init__(self):
self.file_id = None
self.called = False
def on_get(self, req, resp, file_id):
self.file_id = file_id
self.called = True
| FileResource |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP039.py | {
"start": 138,
"end": 164
} | class ____():
pass
# OK
| A |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-qualaroo/components.py | {
"start": 360,
"end": 740
} | class ____(BasicHttpAuthenticator):
@property
def token(self):
key = str(self._username.eval(self.config)).encode("latin1")
token = self._password.eval(self.config).encode("latin1")
encoded_credentials = b64encode(b":".join((key, token))).strip()
token = "Basic " + encoded_creden... | CustomAuthenticator |
python | pyinstaller__pyinstaller | bootloader/waflib/Scripting.py | {
"start": 12470,
"end": 15382
} | class ____(Dist):
fun = 'distcheck'
cmd = 'distcheck'
def execute(self):
self.recurse([os.path.dirname(Context.g_module.root_path)])
self.archive()
self.check()
def make_distcheck_cmd(self, tmpdir):
cfg = []
if Options.options.distcheck_args:
cfg = s... | DistCheck |
python | numpy__numpy | numpy/_core/_exceptions.py | {
"start": 3272,
"end": 5159
} | class ____(MemoryError):
""" Thrown when an array cannot be allocated"""
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
@property
def _total_size(self):
num_bytes = self.dtype.itemsize
for dim in self.shape:
num_bytes *= dim
r... | _ArrayMemoryError |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 833,
"end": 904
} | class ____:
name: str
age: int
@dataclasses.dataclass
| MyDataClass |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_ticketing.py | {
"start": 1244,
"end": 1378
} | class ____(BaseTicketingActionValidatorTest):
__test__ = True
provider = Action.Type.AZURE_DEVOPS
| TestAzureDevOpsActionValidator |
python | bokeh__bokeh | src/bokeh/protocol/message.py | {
"start": 3425,
"end": 11728
} | class ____(Generic[Content]):
''' The Message base class encapsulates creating, assembling, and
validating the integrity of Bokeh Server messages. Additionally, it
provide hooks
'''
msgtype: ClassVar[str]
_header: Header
_header_json: str | None
_content: Content
_content_json: s... | Message |
python | kamyu104__LeetCode-Solutions | Python/remove-all-adjacent-duplicates-in-string-ii.py | {
"start": 29,
"end": 449
} | class ____(object):
def removeDuplicates(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
stk = [['^', 0]]
for c in s:
if stk[-1][0] == c:
stk[-1][1] += 1
if stk[-1][1] == k:
stk.pop()
... | Solution |
python | scipy__scipy | scipy/optimize/tests/test__basinhopping.py | {
"start": 2715,
"end": 12407
} | class ____:
def setup_method(self):
""" Tests setup.
Run tests based on the 1-D and 2-D functions described above.
"""
self.x0 = (1.0, [1.0, 1.0])
self.sol = (-0.195, np.array([-0.195, -0.1]))
self.tol = 3 # number of decimal places
self.niter = 100
... | TestBasinHopping |
python | openai__openai-python | src/openai/lib/azure.py | {
"start": 1368,
"end": 1628
} | class ____(OpenAIError):
def __init__(self) -> None:
super().__init__(
"The `api_key`, `azure_ad_token` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time"
)
| MutuallyExclusiveAuthError |
python | scipy__scipy | scipy/special/_mptestutils.py | {
"start": 4661,
"end": 5444
} | class ____:
def __init__(self, a=-1000, b=1000):
self.a = a
self.b = b
def values(self, n):
v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int)
v2 = np.arange(-5, 5)
v = np.unique(np.r_[v1, v2])
v = v[(v >= self.a) & (v < self.b)]
return v
d... | IntArg |
python | django__django | tests/inspectdb/models.py | {
"start": 3436,
"end": 3642
} | class ____(models.Model):
char_field = models.CharField(max_length=10, db_collation=test_collation)
class Meta:
required_db_features = {"supports_collation_on_charfield"}
| CharFieldDbCollation |
python | scrapy__scrapy | scrapy/exceptions.py | {
"start": 749,
"end": 960
} | class ____(Exception):
"""Raise this from callbacks to request the spider to be closed"""
def __init__(self, reason: str = "cancelled"):
super().__init__()
self.reason = reason
| CloseSpider |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc.py | {
"start": 17755,
"end": 18218
} | class ____(Benchmark):
params = [np.int32, np.int64]
param_names = ['dtype']
def setup(self, dtype):
N = 1000000
self.a = np.random.randint(20, size=N).astype(dtype)
self.b = np.random.randint(4, size=N).astype(dtype)
def time_pow(self, dtype):
np.power(self.a, self.b)
... | BinaryBenchInteger |
python | huggingface__transformers | src/transformers/models/bridgetower/image_processing_bridgetower.py | {
"start": 4449,
"end": 4539
} | class ____(ImagesKwargs, total=False):
size_divisor: int
| BridgeTowerImageProcessorKwargs |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 9028,
"end": 9131
} | class ____(*ssl_error_bases): # type: ignore[misc]
"""Response ssl error."""
| ClientConnectorSSLError |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 95054,
"end": 98333
} | class ____(Scope):
"""Scope for comprehensions (but not generator expressions, which use ClosureScope).
As opposed to generators, these can be easily inlined in some cases, so all
we really need is a scope that holds the loop variable(s).
"""
is_comprehension_scope = True
def __init__(self, out... | ComprehensionScope |
python | instagram__MonkeyType | demo/inbox.py | {
"start": 3430,
"end": 5279
} | class ____:
def __init__(self, user: User, repo: RepoInterface) -> None:
self.user = user
self.repo = repo
self.events = self.repo.get_inbox_events_for_user_id(self.user.id)
def aggregate(self):
aggregators: List[AggregatorInterface] = [
CommentsAggregator(self.repo... | Inbox |
python | python-openxml__python-docx | tests/oxml/test_xmlchemy.py | {
"start": 24920,
"end": 25145
} | class ____(BaseIntType):
@classmethod
def validate(cls, value):
cls.validate_int(value)
if value < 1 or value > 42:
raise ValueError("value must be in range 1 to 42 inclusive")
| ST_IntegerType |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property1.py | {
"start": 1626,
"end": 1794
} | class ____:
@property
def prop1(self) -> type[Self]: ...
def method1(self) -> None:
reveal_type(self.prop1, expected_text="type[Self@ClassC]")
| ClassC |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 19760,
"end": 20570
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.output_embedding_size)
self.decoder = nn.Linear(config.output_embedding_size, config.vocab_size)
self.activation = ACT2FN[config.hidden_act]
self.LayerNorm ... | RemBertLMPredictionHead |
python | coleifer__peewee | tests/pool.py | {
"start": 10795,
"end": 12389
} | class ____(ModelTestCase):
database = PooledTestDatabase('test_pooled.db')
requires = [Register]
def tearDown(self):
super(TestLivePooledDatabase, self).tearDown()
self.database.close_idle()
if os.path.exists('test_pooled.db'):
os.unlink('test_pooled.db')
def test_r... | TestLivePooledDatabase |
python | django__django | tests/db_functions/comparison/test_collate.py | {
"start": 182,
"end": 2083
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.author1 = Author.objects.create(alias="a", name="Jones 1")
cls.author2 = Author.objects.create(alias="A", name="Jones 2")
def test_collate_filter_ci(self):
collation = connection.features.test_collations.get("ci")
... | CollateTests |
python | kubernetes-client__python | kubernetes/client/models/v1_windows_security_context_options.py | {
"start": 383,
"end": 8455
} | 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... | V1WindowsSecurityContextOptions |
python | Pylons__pyramid | src/pyramid/viewderivers.py | {
"start": 1032,
"end": 17135
} | class ____:
def __init__(self, **kw):
self.attr = kw.get('attr')
def __call__(self, view):
if is_unbound_method(view) and self.attr is None:
raise ConfigurationError(
'Unbound method calls are not supported, please set the '
'class as your `view` and ... | DefaultViewMapper |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/state.py | {
"start": 37512,
"end": 38576
} | class ____:
"""A writable placeholder for an unloaded collection.
Stores items appended to and removed from a collection that has not yet
been loaded. When the collection is loaded, the changes stored in
PendingCollection are applied to it to produce the final result.
"""
__slots__ = ("delete... | PendingCollection |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial003_an_py310.py | {
"start": 114,
"end": 673
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Annotated[
Item,
Body(
examples=[
{
"name": "Foo",
... | Item |
python | django__django | tests/multiple_database/models.py | {
"start": 1357,
"end": 1823
} | class ____(models.Model):
title = models.CharField(max_length=100)
published = models.DateField()
authors = models.ManyToManyField(Person)
editor = models.ForeignKey(
Person, models.SET_NULL, null=True, related_name="edited"
)
reviews = GenericRelation(Review)
pages = models.IntegerF... | Book |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_inlinehilite.py | {
"start": 11344,
"end": 12195
} | class ____(util.MdCase):
"""Test custom InlineHilite cases."""
extension = [
'pymdownx.highlight',
'pymdownx.inlinehilite',
]
extension_configs = {
'pymdownx.inlinehilite': {
'css_class': 'inlinehilite',
'custom_inline': [
{
... | TestInlineHiliteCustom2 |
python | TheAlgorithms__Python | sorts/external_sort.py | {
"start": 2182,
"end": 2867
} | class ____:
def __init__(self, merge_strategy):
self.merge_strategy = merge_strategy
def merge(self, filenames, outfilename, buffer_size):
buffers = FilesArray(self.get_file_handles(filenames, buffer_size))
with open(outfilename, "w", buffer_size) as outfile:
while buffers.r... | FileMerger |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 1741,
"end": 1915
} | class ____(Exception): # noqa: N818
"""An exception that is raised by the fragment
when it has handled the exception itself.
"""
pass
| FragmentHandledException |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 545398,
"end": 545719
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("PushAllowance", graphql_name="node")
| PushAllowanceEdge |
python | huggingface__transformers | examples/modular-transformers/modular_my_new_model.py | {
"start": 151,
"end": 8464
} | class ____(LlamaConfig):
r"""
This is the configuration class to store the configuration of a [`MyNewModelModel`]. It is used to instantiate an MyNewModel
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar con... | MyNewModelConfig |
python | getsentry__sentry | src/sentry/seer/explorer/custom_tool_utils.py | {
"start": 301,
"end": 556
} | class ____(StrEnum):
"""Allowed parameter types for Explorer tools."""
STRING = "string"
INTEGER = "integer"
NUMBER = "number"
BOOLEAN = "boolean"
ARRAY = "array"
# Type specifications for different parameter types
| ExplorerParamType |
python | walkccc__LeetCode | solutions/110. Balanced Binary Tree/110-3.py | {
"start": 0,
"end": 534
} | class ____:
def isBalanced(self, root: TreeNode | None) -> bool:
def maxDepth(root: TreeNode | None) -> int:
"""Returns the height of root if root is balanced; otherwise, returns -1."""
if not root:
return 0
left = maxDepth(root.left)
if left == -1:
return -1
right =... | Solution |
python | modin-project__modin | modin/experimental/core/storage_formats/pandas/parsers.py | {
"start": 4508,
"end": 5108
} | class ____(PandasParser):
@staticmethod
@doc(_doc_parse_func, parameters=_doc_parse_parameters_common)
def parse(fname, **kwargs):
warnings.filterwarnings("ignore")
num_splits = 1
single_worker_read = kwargs.pop("single_worker_read", None)
df = pandas.read_parquet(fname, **kw... | ExperimentalPandasParquetParser |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py | {
"start": 37205,
"end": 42620
} | class ____(CloudSQLBaseOperator):
"""
Export data from a Cloud SQL instance to a Cloud Storage bucket.
The exported format can be a SQL dump or CSV file.
Note: This operator is idempotent. If executed multiple times with the same
export file URI, the export file in GCS will simply be overridden.
... | CloudSQLExportInstanceOperator |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/rapidsmpf/io.py | {
"start": 1740,
"end": 21894
} | class ____:
"""
Linearizer that ensures ordered delivery from multiple concurrent producers.
Creates one input channel per producer and streams messages to output
in sequence-number order, buffering only out-of-order arrivals.
"""
def __init__(
self, context: Context, ch_out: Channel[T... | Lineariser |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/assets/asset_config.py | {
"start": 69,
"end": 283
} | class ____(Config):
api_endpoint: str
@asset
def my_downstream_asset(config: MyDownstreamAssetConfig):
data = requests.get(f"{config.api_endpoint}/data").json()
...
# end_example
| MyDownstreamAssetConfig |
python | openai__openai-python | src/openai/types/beta/thread.py | {
"start": 1097,
"end": 2132
} | class ____(BaseModel):
id: str
"""The identifier, which can be referenced in API endpoints."""
created_at: int
"""The Unix timestamp (in seconds) for when the thread was created."""
metadata: Optional[Metadata] = None
"""Set of 16 key-value pairs that can be attached to an object.
This ca... | Thread |
python | falconry__falcon | falcon/redirects.py | {
"start": 1647,
"end": 2589
} | class ____(HTTPStatus):
"""302 Found.
The 302 (Found) status code indicates that the target resource
resides temporarily under a different URI. Since the redirection
might be altered on occasion, the client ought to continue to use the
effective request URI for future requests.
Note:
... | HTTPFound |
python | numpy__numpy | tools/swig/test/testArray.py | {
"start": 8739,
"end": 13051
} | class ____(unittest.TestCase):
def setUp(self):
self.length = 5
self.array3 = Array.ArrayZ(self.length)
def testConstructor0(self):
"Test ArrayZ default constructor"
a = Array.ArrayZ()
self.assertTrue(isinstance(a, Array.ArrayZ))
self.assertTrue(len(a) == 0)
... | ArrayZTestCase |
python | doocs__leetcode | solution/0100-0199/0123.Best Time to Buy and Sell Stock III/Solution.py | {
"start": 0,
"end": 350
} | class ____:
def maxProfit(self, prices: List[int]) -> int:
# 第一次买入,第一次卖出,第二次买入,第二次卖出
f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0
for price in prices[1:]:
f1 = max(f1, -price)
f2 = max(f2, f1 + price)
f3 = max(f3, f2 - price)
f4 = max(f4, f3 +... | Solution |
python | ray-project__ray | doc/source/custom_directives.py | {
"start": 2714,
"end": 4998
} | class ____:
"""
This class downloads markdown readme files for various
ecosystem libraries, saves them in specified locations and preprocesses
them before sphinx build starts.
If you have ecosystem libraries that live in a separate repo from Ray,
adding them here will allow for their docs to be... | DownloadAndPreprocessEcosystemDocs |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 341843,
"end": 342857
} | class ____(_CollectiveKernel):
def __init__(
self,
layout: OutputSpec,
kernel: _OpOverloads,
tensor_args: Sequence[IRNode],
nontensor_args: Sequence[Any],
unflatten_args: Callable[..., Any],
kwargs: Optional[dict[str, Any]] = None,
*,
unbacked_... | _AllReduce_Kernel |
python | jina-ai__jina | jina/serve/runtimes/gateway/http/__init__.py | {
"start": 274,
"end": 427
} | class ____(HTTPServer, BaseGateway):
"""
:class:`HTTPGateway` is a FastAPIBaseGateway that uses the default FastAPI app
"""
pass
| HTTPGateway |
python | run-llama__llama_index | llama-index-core/llama_index/core/llms/mock.py | {
"start": 3151,
"end": 5068
} | class ____(MockLLM):
"""
Mock LLM that keeps track of chat messages of function calls.
The idea behind this is to be able to easily checks whether the right messages would have been passed to an actual LLM.
"""
last_chat_messages: Optional[Sequence[ChatMessage]] = Field(
default=None, excl... | MockLLMWithChatMemoryOfLastCall |
python | astropy__astropy | astropy/uncertainty/tests/test_containers.py | {
"start": 4662,
"end": 6061
} | class ____:
@classmethod
def setup_class(cls):
cls.lon = Distribution(np.linspace(0.0, 360 * u.deg, 10, endpoint=False))
cls.lat = Angle([-45.0, 0.0, 45.0], u.deg)
cls.r = 6000 * u.km # Sort of OK for Geodetic representations.
cls.sph = SphericalRepresentation(
cls.l... | TestRepresentation |
python | sphinx-doc__sphinx | sphinx/builders/epub3.py | {
"start": 1711,
"end": 12745
} | class ____(_epub_base.EpubBuilder):
"""Builder that outputs epub3 files.
It creates the metainfo files content.opf, nav.xhtml, toc.ncx, mimetype,
and META-INF/container.xml. Afterwards, all necessary files are zipped to
an epub file.
"""
name = 'epub'
epilog = __('The ePub file is in %(out... | Epub3Builder |
python | django__django | tests/bulk_create/tests.py | {
"start": 35293,
"end": 36758
} | class ____(TransactionTestCase):
available_apps = ["bulk_create"]
def get_unused_country_id(self):
# Find a serial ID that hasn't been used already and has enough of a
# buffer for the following `bulk_create` call without an explicit pk
# not to conflict.
return getattr(Country.... | BulkCreateTransactionTests |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/websocket_client.py | {
"start": 13312,
"end": 15089
} | class ____:
def __init__(
self,
queue: asyncio.Queue[dict[str, t.Any]],
websocket: aiohttp.ClientWebSocketResponse,
session: _Session,
channel_name: str,
):
self._queue = queue
self._websocket = websocket
self.session = session
self.channel... | _WebSocketChannel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 17502,
"end": 17595
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "inAppClose"
| InAppClose |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 14201,
"end": 14397
} | class ____:
path: Path
@classmethod
def from_raw(cls, raw: "DgRawWorkspaceProjectSpec") -> Self:
return cls(
path=Path(raw["path"]),
)
| DgWorkspaceProjectSpec |
python | keon__algorithms | tests/test_maths.py | {
"start": 1925,
"end": 2516
} | class ____(unittest.TestCase):
"""
Test for the file decimal_to_binary_ip.py
Arguments:
unittest {[type]} -- [description]
"""
def test_decimal_to_binary_ip(self):
self.assertEqual("00000000.00000000.00000000.00000000",
decimal_to_binary_ip("0.0.0.0"))
... | TestDecimalToBinaryIP |
python | tiangolo__fastapi | fastapi/exceptions.py | {
"start": 4081,
"end": 4172
} | class ____(RuntimeError):
"""
A generic, FastAPI-specific error.
"""
| FastAPIError |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v2/adagrad.py | {
"start": 1152,
"end": 6699
} | class ____(optimizer_v2.OptimizerV2):
r"""Optimizer that implements the Adagrad algorithm.
Adagrad is an optimizer with parameter-specific learning rates,
which are adapted relative to how frequently a parameter gets
updated during training. The more updates a parameter receives,
the smaller the updates.
... | Adagrad |
python | jina-ai__jina | tests/integration/v2_api/test_docs_matrix_tail_pea.py | {
"start": 771,
"end": 1173
} | class ____(Executor):
@requests
def merge(self, docs_matrix, **kwargs):
results = OrderedDict()
for docs in docs_matrix:
for doc in docs:
if doc.id in results:
results[doc.id].matches.extend(doc.matches)
else:
re... | MatchMerger |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_blocks/test_captions.py | {
"start": 62,
"end": 8771
} | class ____(util.MdCase):
"""Test Blocks caption cases with default configuration."""
extension = ['pymdownx.blocks.caption', 'md_in_html', 'pymdownx.blocks.html']
extension_configs = {
'pymdownx.blocks.caption': {
'auto': False
}
}
def test_caption(self):
"""Tes... | TestBlocksCaption |
python | Textualize__textual | docs/examples/how-to/containers02.py | {
"start": 270,
"end": 555
} | class ____(App):
"""Simple app to play with containers."""
def compose(self) -> ComposeResult:
with Vertical(): # (1)!
yield Box()
yield Box()
yield Box()
if __name__ == "__main__":
app = ContainerApp()
app.run()
| ContainerApp |
python | huggingface__transformers | src/transformers/models/nemotron/modeling_nemotron.py | {
"start": 24415,
"end": 28113
} | class ____(GradientCheckpointingLayer):
# Ignore copy
def __init__(self, config: NemotronConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = NEMOTRON_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
... | NemotronDecoderLayer |
python | kubernetes-client__python | kubernetes/client/models/v1_node_swap_status.py | {
"start": 383,
"end": 3500
} | 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... | V1NodeSwapStatus |
python | getsentry__sentry | tests/sentry/utils/test_committers.py | {
"start": 1857,
"end": 2917
} | class ____(unittest.TestCase):
def test_forward_slash(self) -> None:
assert list(tokenize_path("foo/bar")) == ["bar", "foo"]
def test_back_slash(self) -> None:
assert list(tokenize_path("foo\\bar")) == ["bar", "foo"]
def test_dot_does_not_separate(self) -> None:
assert list(tokeniz... | TokenizePathTestCase |
python | ray-project__ray | python/ray/tune/search/optuna/optuna_search.py | {
"start": 2336,
"end": 26571
} | class ____(Searcher):
"""A wrapper around Optuna to provide trial suggestions.
`Optuna <https://optuna.org/>`_ is a hyperparameter optimization library.
In contrast to other libraries, it employs define-by-run style
hyperparameter definitions.
This Searcher is a thin wrapper around Optuna's search... | OptunaSearch |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/rpc_test.py | {
"start": 31885,
"end": 158805
} | class ____(RpcAgentTestFixture, RpcTestCommon):
@dist_init
def test_worker_id(self):
n = self.rank + 1
peer_rank = n % self.world_size
self_worker_info = rpc.get_worker_info()
peer_worker_info = rpc.get_worker_info(worker_name(peer_rank))
self.assertEqual(self_worker_inf... | RpcTest |
python | PrefectHQ__prefect | src/prefect/server/schemas/responses.py | {
"start": 18570,
"end": 19422
} | class ____(schemas.core.WorkQueue):
work_pool_name: Optional[str] = Field(
default=None,
description="The name of the work pool the work pool resides within.",
)
status: Optional[schemas.statuses.WorkQueueStatus] = Field(
default=None, description="The queue status."
)
@clas... | WorkQueueResponse |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 17924,
"end": 20069
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: SegGptConfig, drop_path_rate: float) -> None:
super().__init__()
self.attention = SegGptAttention(config)
self.mlp = SegGptMlp(config)
self.drop_path = SegGptDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Id... | SegGptLayer |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 56156,
"end": 62151
} | class ____(
fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL
):
"""test for #5082"""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
foos = r... | JoinedloadWPolyOfTypeContinued |
python | doocs__leetcode | solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/Solution.py | {
"start": 192,
"end": 526
} | class ____:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def dfs(l: int, r: int) -> Optional[TreeNode]:
if l > r:
return None
mid = (l + r) >> 1
return TreeNode(nums[mid], dfs(l, mid - 1), dfs(mid + 1, r))
return dfs(0, len(n... | Solution |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 24642,
"end": 27616
} | class ____(Operation):
def __init__(self, num=None, axis=0, *, name=None):
super().__init__(name=name)
self.num = num
self.axis = axis
def call(self, x):
return backend.core.unstack(x, self.num, self.axis)
def compute_output_spec(self, x):
axis = self.axis
i... | Unstack |
python | mlflow__mlflow | tests/langchain/conftest.py | {
"start": 1178,
"end": 1681
} | class ____(Embeddings, BaseModel):
size: int
def _get_embedding(self, text: str) -> list[float]:
import numpy as np
seed = abs(hash(text)) % (10**8)
np.random.seed(seed)
return list(np.random.normal(size=self.size))
def embed_documents(self, texts: list[str]) -> list[list[... | DeterministicDummyEmbeddings |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py | {
"start": 1280,
"end": 1447
} | class ____(Enum):
Cocoa = "cocoa"
ReactNative = "react-native"
Java = "java"
Native = "native"
Dart = "dart"
Dotnet = "dotnet"
@dataclass
| SdkName |
python | dagster-io__dagster | python_modules/libraries/dagster-omni/dagster_omni/workspace.py | {
"start": 357,
"end": 5893
} | class ____(dg.Resolvable, dg.Model):
"""Handles all interactions with the Omni API to fetch and manage state."""
base_url: str = Field(
description="The base URL to your Omni instance.", examples=["https://acme.omniapp.co"]
)
api_key: str = Field(
description="The API key to your Omni i... | OmniWorkspace |
python | langchain-ai__langchain | libs/core/langchain_core/indexing/base.py | {
"start": 8060,
"end": 14597
} | class ____(RecordManager):
"""An in-memory record manager for testing purposes."""
def __init__(self, namespace: str) -> None:
"""Initialize the in-memory record manager.
Args:
namespace: The namespace for the record manager.
"""
super().__init__(namespace)
... | InMemoryRecordManager |
python | walkccc__LeetCode | solutions/2403. Minimum Time to Kill All Monsters/2403.py | {
"start": 0,
"end": 534
} | class ____:
def minimumTime(self, power: list[int]) -> int:
n = len(power)
maxMask = 1 << n
# dp[i] := the minimum number of days needed to defeat the monsters, where
# i is the bitmask of the monsters
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(1, maxMask):
currentGain = ... | Solution |
python | walkccc__LeetCode | solutions/758. Bold Words in String/758.py | {
"start": 0,
"end": 704
} | class ____:
def boldWords(self, words: list[str], s: str) -> str:
n = len(s)
ans = []
# bold[i] := True if s[i] should be bolded
bold = [0] * n
boldEnd = -1 # s[i:boldEnd] should be bolded
for i in range(n):
for word in words:
if s[i:].startswith(word):
boldEnd = max(... | Solution |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/inset_locator.py | {
"start": 1310,
"end": 2177
} | class ____(AnchoredLocatorBase):
def __init__(self, bbox_to_anchor, x_size, y_size, loc,
borderpad=0.5, bbox_transform=None):
super().__init__(
bbox_to_anchor, None, loc,
borderpad=borderpad, bbox_transform=bbox_transform
)
self.x_size = Size.from_an... | AnchoredSizeLocator |
python | django__django | tests/ordering/models.py | {
"start": 771,
"end": 1273
} | class ____(models.Model):
author = models.ForeignKey(Author, models.SET_NULL, null=True)
second_author = models.ForeignKey(
Author, models.SET_NULL, null=True, related_name="+"
)
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
class Meta:
ordering =... | Article |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/multi_device_iterator_test.py | {
"start": 5249,
"end": 13697
} | class ____(test_base.DatasetTestBase,
parameterized.TestCase):
def setUp(self):
super(MultiDeviceIteratorTest, self).setUp()
self._devices = self.configureDevicesForMultiDeviceTest(3)
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
... | MultiDeviceIteratorTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/runs.py | {
"start": 1329,
"end": 1592
} | class ____(graphene.ObjectType):
run = graphene.Field(graphene.NonNull("dagster_graphql.schema.pipelines.pipeline.GrapheneRun"))
class Meta:
interfaces = (GrapheneLaunchPipelineRunSuccess,)
name = "LaunchRunSuccess"
| GrapheneLaunchRunSuccess |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 261,
"end": 1879
} | class ____:
def test_scalar(self):
s = np.random.RandomState(0)
assert_equal(s.randint(1000), 684)
s = np.random.RandomState(4294967295)
assert_equal(s.randint(1000), 419)
def test_array(self):
s = np.random.RandomState(range(10))
assert_equal(s.randint(1000), 46... | TestSeed |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 342482,
"end": 343377
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateEnterpriseMembersCanUpdateProtectedBranchesSetting
"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "setting_value", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_na... | UpdateEnterpriseMembersCanUpdateProtectedBranchesSettingInput |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_settings.py | {
"start": 11362,
"end": 19994
} | class ____(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.step_count = 0
@rule()
def count_step(self):
self.step_count += 1
def teardown(self):
assert self.step_count <= settings_step_count
test_settings_decorator_applies_to_rule_based_state_machi... | StepCounter |
python | PyCQA__bandit | tests/unit/core/test_meta_ast.py | {
"start": 127,
"end": 916
} | class ____(testtools.TestCase):
def setUp(self):
super().setUp()
self.b_meta_ast = meta_ast.BanditMetaAst()
self.node = "fake_node"
self.parent_id = "fake_parent_id"
self.depth = 1
self.b_meta_ast.add_node(self.node, self.parent_id, self.depth)
self.node_id = ... | BanditMetaAstTests |
python | google__flatbuffers | tests/monster_test_generated.py | {
"start": 21972,
"end": 23158
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Referrable()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsReferrable(cls, buf, offset=0):
... | Referrable |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 26482,
"end": 26719
} | class ____(graphene.ObjectType):
"""Output indicating that asset history was deleted."""
assetPartitionRanges = non_null_list(GrapheneAssetPartitionRange)
class Meta:
name = "AssetWipeSuccess"
| GrapheneAssetWipeSuccess |
python | walkccc__LeetCode | solutions/2771. Longest Non-decreasing Subarray From Two Arrays/2771.py | {
"start": 0,
"end": 600
} | class ____:
def maxNonDecreasingLength(self, nums1: list[int], nums2: list[int]) -> int:
ans = 1
dp1 = 1 # the longest subarray that ends in nums1[i] so far
dp2 = 1 # the longest subarray that ends in nums2[i] so far
for i in range(1, len(nums1)):
dp11 = dp1 + 1 if nums1[i - 1] <= nums1[i] el... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.