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/0100-0199/0130.Surrounded Regions/Solution.py | {
"start": 0,
"end": 719
} | class ____:
def solve(self, board: List[List[str]]) -> None:
def dfs(i: int, j: int):
if not (0 <= i < m and 0 <= j < n and board[i][j] == "O"):
return
board[i][j] = "."
for a, b in pairwise((-1, 0, 1, 0, -1)):
dfs(i + a, j + b)
m,... | Solution |
python | pytorch__pytorch | test/lazy/test_extract_compiled_graph.py | {
"start": 1759,
"end": 2079
} | class ____(nn.Module):
"""
Handle the corner case that the same tensor appears multiple times in the
returned tuple. torchbench like drq will hit this corner case when running
thru torchdynamo..
"""
def forward(self, a, b):
c = a + b
return a - b, c, a + 1, c
| ModuleReturnDupTensor |
python | plotly__plotly.py | plotly/graph_objs/parcoords/_legendgrouptitle.py | {
"start": 233,
"end": 2953
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path_str = "parcoords.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be spe... | Legendgrouptitle |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 241702,
"end": 245101
} | class ____(rv_continuous):
r"""A non-central chi-squared continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `ncx2` is:
.. math::
f(x, k, \lambda) = \frac{1}{2} \exp(-(\lambda+x)/2)
(x/\lambda)^{(k-2)/4} I_{(k-2)/2}(\sqrt{\lambda... | ncx2_gen |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 420945,
"end": 422453
} | class ____(ExprNode, ModuleNameMixin):
# Helper class holds Python3 namespace object
#
# All this are not owned by this node
# class_def_node PyClassDefNode PyClassDefNode defining this class
# doc ExprNode or None Doc string (owned)
subexprs = ['doc']
def analyse_types(self... | PyClassNamespaceNode |
python | google__pytype | pytype/abstract/_typing.py | {
"start": 36157,
"end": 36689
} | class ____(_base.BaseValue):
"""Container for a Final annotation."""
def __init__(self, annotation: _base.BaseValue, ctx: "context.Context"):
super().__init__("FinalAnnotation", ctx)
self.annotation = annotation
def __repr__(self) -> str:
return f"Final[{self.annotation}]"
def instantiate(
... | FinalAnnotation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_set_column04.py | {
"start": 315,
"end": 1424
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | Netflix__metaflow | test/core/tests/card_extension_test.py | {
"start": 72,
"end": 2453
} | class ____(MetaflowTest):
"""
- Requires on tests/extensions/packages to be installed.
"""
PRIORITY = 5
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recurs... | CardExtensionsImportTest |
python | sqlalchemy__sqlalchemy | test/sql/test_selectable.py | {
"start": 133480,
"end": 134529
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_direct_element_hierarchy(self):
t = table("t", column("c"))
a1 = t.alias()
a2 = a1.alias()
a3 = a2.alias()
is_(a1.element, t)
is_(a2.element, a1)
is_(a3.element, a2)
... | AliasTest |
python | catalyst-team__catalyst | catalyst/contrib/datasets/movielens.py | {
"start": 9294,
"end": 27369
} | class ____(Dataset):
"""
MovieLens data sets (ml-20m) were collected by
the GroupLens Research Project at the University of Minnesota.
This data set consists of:
* 20,000,263 ratings (1-5)
and 465,564 tag applications from 138,493 users on 27,278 movies.
* Each user has rated at least 20 mo... | MovieLens20M |
python | openai__openai-python | src/openai/types/responses/response_text_delta_event.py | {
"start": 715,
"end": 1374
} | class ____(BaseModel):
content_index: int
"""The index of the content part that the text delta was added to."""
delta: str
"""The text delta that was added."""
item_id: str
"""The ID of the output item that the text delta was added to."""
logprobs: List[Logprob]
"""The log probabiliti... | ResponseTextDeltaEvent |
python | walkccc__LeetCode | solutions/2015. Average Height of Buildings in Each Segment/2015.py | {
"start": 0,
"end": 665
} | class ____:
def averageHeightOfBuildings(self, buildings: list[list[int]]) -> list[list[int]]:
ans = []
events = []
for start, end, height in buildings:
events.append((start, height))
events.append((end, -height))
prev = 0
count = 0
sumHeight = 0
for curr, height in sorted(e... | Solution |
python | getsentry__sentry | src/sentry/preprod/pull_request/comment_types.py | {
"start": 3885,
"end": 4175
} | class ____(BaseModel):
"""
Complete comments data for a pull request.
Organizes both general comments and file-specific review comments.
"""
general_comments: list[IssueComment]
file_comments: dict[str, list[ReviewComment]] # Grouped by file path
| PullRequestComments |
python | scrapy__scrapy | tests/test_utils_signal.py | {
"start": 2932,
"end": 3100
} | class ____(TestSendCatchLog):
def _get_result(self, signal, *a, **kw):
return deferred_from_coro(send_catch_log_async(signal, *a, **kw))
| TestSendCatchLogAsync |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/chat_store/base_db.py | {
"start": 457,
"end": 3069
} | class ____(BaseModel):
"""
Base class for DB-based chat stores.
Meant to implement a FIFO queue to manage short-term memory and
general conversation history.
"""
@abstractmethod
async def get_messages(
self,
key: str,
status: Optional[MessageStatus] = MessageStatus.... | AsyncDBChatStore |
python | ray-project__ray | python/ray/data/_internal/execution/operators/join.py | {
"start": 14812,
"end": 19362
} | class ____(HashShufflingOperatorBase):
def __init__(
self,
data_context: DataContext,
left_input_op: PhysicalOperator,
right_input_op: PhysicalOperator,
left_key_columns: Tuple[str],
right_key_columns: Tuple[str],
join_type: JoinType,
*,
num_pa... | JoinOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass11.py | {
"start": 234,
"end": 585
} | class ____(metaclass=MetaA):
pass
# This should generate an error because var0 isn't
# accessible via an instance of this class.
ClassA().var0
reveal_type(ClassA.var0, expected_text="int")
ClassA.var0 = 1
reveal_type(ClassA().var1, expected_text="str")
reveal_type(ClassA.var1, expected_text="str")
ClassA.var1 =... | ClassA |
python | qdrant__qdrant-client | qdrant_client/http/api/service_api.py | {
"start": 4085,
"end": 5586
} | class ____(_ServiceApi):
async def healthz(
self,
) -> str:
"""
An endpoint for health checking used in Kubernetes.
"""
return await self._build_for_healthz()
async def livez(
self,
) -> str:
"""
An endpoint for health checking used in Kub... | AsyncServiceApi |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 16526,
"end": 17385
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def bold(self):
raise NotImplementedError()
@bold.setter
def bold(self, value):
raise NotImplementedError()
@property
def italic(self):
raise NotImplementedError()
@italic.s... | Font |
python | openai__openai-python | src/openai/types/beta/realtime/response_function_call_arguments_delta_event.py | {
"start": 217,
"end": 793
} | class ____(BaseModel):
call_id: str
"""The ID of the function call."""
delta: str
"""The arguments delta as a JSON string."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the function call item."""
output_index: int
"""The index of the outp... | ResponseFunctionCallArgumentsDeltaEvent |
python | great-expectations__great_expectations | great_expectations/data_context/data_context/cloud_data_context.py | {
"start": 3906,
"end": 33109
} | class ____(SerializableDataContext):
"""Subclass of AbstractDataContext that contains functionality necessary to work in a GX Cloud-backed environment.""" # noqa: E501 # FIXME CoP
def __init__( # noqa: PLR0913 # FIXME CoP
self,
project_config: Optional[Union[DataContextConfig, Mapping]] = Non... | CloudDataContext |
python | huggingface__transformers | src/transformers/pipelines/text_to_audio.py | {
"start": 1387,
"end": 12139
} | class ____(Pipeline):
"""
Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This
pipeline generates an audio file from an input text and optional other conditional inputs.
Unless the model you're using explicitly sets these generation parameter... | TextToAudioPipeline |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 4163,
"end": 5581
} | class ____:
params = ["String", "Float", "Int"]
param_names = ["dtype"]
def setup(self, dtype):
N = 10**6
if dtype == "String":
self.idx = Index([f"i-{i}" for i in range(N)], dtype=object)
elif dtype == "Float":
self.idx = Index(np.arange(N), dtype=np.float64... | Indexing |
python | pytest-dev__pytest | testing/test_terminal.py | {
"start": 67825,
"end": 69547
} | class ____:
"""Ensure classic output style works as expected (#3883)"""
@pytest.fixture
def test_files(self, pytester: Pytester) -> None:
pytester.makepyfile(
**{
"test_one.py": "def test_one(): pass",
"test_two.py": "def test_two(): assert 0",
... | TestClassicOutputStyle |
python | kamyu104__LeetCode-Solutions | Python/split-two-strings-to-make-palindrome.py | {
"start": 29,
"end": 687
} | class ____(object):
def checkPalindromeFormation(self, a, b):
"""
:type a: str
:type b: str
:rtype: bool
"""
def is_palindrome(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j... | Solution |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 27918,
"end": 30366
} | class ____(ContainerHolder):
"""
Accordion menu object. It wraps `AccordionGroup` objects in a container
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
css_class : str, optional
CSS classes to be applied to the `... | Accordion |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1053250,
"end": 1053420
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (Bot, Organization, User)
| AuditEntryActor |
python | has2k1__plotnine | plotnine/ggplot.py | {
"start": 2052,
"end": 24662
} | class ____:
"""
Create a new ggplot object
Parameters
----------
data :
Default data for plot. Every layer that does not
have data of its own will use this one.
mapping :
Default aesthetics mapping for the plot. These will be used
by all layers unless specificall... | ggplot |
python | ray-project__ray | python/ray/serve/_private/replica.py | {
"start": 56833,
"end": 88635
} | class ____:
"""Wraps a user-provided callable that is used to handle requests to a replica."""
service_unavailable_exceptions = (BackPressureError, DeploymentUnavailableError)
def __init__(
self,
deployment_def: Callable,
init_args: Tuple,
init_kwargs: Dict,
*,
... | UserCallableWrapper |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/resources.py | {
"start": 4165,
"end": 7077
} | class ____(dg.ConfigurableResource):
"""Compute configuration resource for ML training and inference.
This resource supports both local compute and AWS compute configurations.
For local compute, it manages device selection and batch processing.
For AWS compute, it provides SageMaker configuration and i... | ComputeResource |
python | doocs__leetcode | lcof2/剑指 Offer II 064. 神奇的字典/Solution.py | {
"start": 0,
"end": 832
} | class ____:
def __init__(self):
"""
Initialize your data structure here.
"""
def _patterns(self, word):
return [word[:i] + '*' + word[i + 1 :] for i in range(len(word))]
def buildDict(self, dictionary: List[str]) -> None:
self.words = set(dictionary)
self.co... | MagicDictionary |
python | qdrant__qdrant-client | tools/async_client_generator/transformers/call_transformer.py | {
"start": 48,
"end": 842
} | class ____(ast.NodeTransformer):
def __init__(
self,
class_replace_map: Optional[dict[str, str]] = None,
async_methods: Optional[list[str]] = None,
):
self.class_replace_map = class_replace_map if class_replace_map is not None else {}
self.async_methods = async_methods if... | CallTransformer |
python | dateutil__dateutil | tests/test_relativedelta.py | {
"start": 27638,
"end": 28325
} | class ____(unittest.TestCase):
"""Test the weeks property getter"""
def test_one_day(self):
rd = relativedelta(days=1)
self.assertEqual(rd.days, 1)
self.assertEqual(rd.weeks, 0)
def test_minus_one_day(self):
rd = relativedelta(days=-1)
self.assertEqual(rd.days, -1)
... | RelativeDeltaWeeksPropertyGetterTest |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/hitl.py | {
"start": 15826,
"end": 18242
} | class ____(HITLOperator, BranchMixIn):
"""BranchOperator based on Human-in-the-loop Response."""
inherits_from_skipmixin = True
def __init__(self, *, options_mapping: dict[str, str] | None = None, **kwargs) -> None:
"""
Initialize HITLBranchOperator.
Args:
options_mapp... | HITLBranchOperator |
python | bottlepy__bottle | test/test_sendfile.py | {
"start": 1535,
"end": 7107
} | class ____(unittest.TestCase):
def setUp(self):
e = dict()
wsgiref.util.setup_testing_defaults(e)
b = Bottle()
request.bind(e)
response.bind()
def test_valid(self):
""" SendFile: Valid requests"""
out = static_file(basename, root=root)
self.assert... | TestSendFile |
python | python-pillow__Pillow | src/PIL/QoiImagePlugin.py | {
"start": 4640,
"end": 8572
} | class ____(ImageFile.PyEncoder):
_pushes_fd = True
_previous_pixel: tuple[int, int, int, int] | None = None
_previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {}
_run = 0
def _write_run(self) -> bytes:
data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN
self._run = 0
... | QoiEncoder |
python | conda__conda | conda/exception_handler.py | {
"start": 521,
"end": 14976
} | class ____:
# FUTURE: Python 3.10+, use typing.ParamSpec
def __call__(self, func: Callable[..., T], *args, **kwargs) -> T | int:
try:
return func(*args, **kwargs)
except:
_, exc_val, exc_tb = sys.exc_info()
return self.handle_exception(exc_val, exc_tb)
de... | ExceptionHandler |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/spacy.py | {
"start": 598,
"end": 2323
} | class ____(TextSplitter):
"""Splitting text using Spacy package.
Per default, Spacy's `en_core_web_sm` model is used and
its default max_length is 1000000 (it is the length of maximum character
this model takes which can be increased for large files). For a faster, but
potentially less accurate spl... | SpacyTextSplitter |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 10075,
"end": 10180
} | class ____(_ConfigCreateModel):
generative: Union[GenerativeSearches, _EnumLikeStr]
| _GenerativeProvider |
python | sympy__sympy | sympy/physics/quantum/qubit.py | {
"start": 13462,
"end": 25958
} | class ____(IntQubitState, QubitBra):
"""A qubit bra that store integers as binary numbers in qubit values."""
@classmethod
def dual_class(self):
return IntQubit
#-----------------------------------------------------------------------------
# Qubit <---> Matrix conversion functions
#--------------... | IntQubitBra |
python | Textualize__textual | docs/examples/how-to/containers07.py | {
"start": 278,
"end": 667
} | class ____(App):
"""Simple app to play with containers."""
CSS = """
.with-border {
border: heavy green;
}
"""
def compose(self) -> ComposeResult:
with HorizontalScroll(classes="with-border"):
for n in range(10):
yield Box(label=f"Box {n+1}")
if __... | ContainerApp |
python | scrapy__scrapy | tests/test_http2_client_protocol.py | {
"start": 3894,
"end": 4249
} | class ____(LeafResource):
def render_GET(self, request: TxRequest):
request.setHeader(b"Content-Length", b"1024")
self.deferRequest(request, 0, self._delayed_render, request)
return NOT_DONE_YET
@staticmethod
def _delayed_render(request: TxRequest):
request.write(Data.DATALO... | Dataloss |
python | google__pytype | pytype/tests/test_flow2.py | {
"start": 111,
"end": 2332
} | class ____(test_base.BaseTest):
"""Tests for control flow.
These tests primarily test instruction ordering and CFG traversal of the
bytecode interpreter, i.e., their primary focus isn't the inferred types.
Even though they check the validity of the latter, they're mostly smoke tests.
"""
def test_loop_and... | FlowTest |
python | falconry__falcon | falcon/routing/compiled.py | {
"start": 43021,
"end": 43392
} | class ____(_CxChild):
def __init__(self, unique_idx: int) -> None:
self._unique_idx = unique_idx
self.dict_variable_name = 'dict_match_{0}'.format(unique_idx)
def src(self, indentation: int) -> str:
return '{0}{1} = match.groupdict()'.format(
_TAB_STR * indentation, self.dic... | _CxVariableFromPatternMatch |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/core.py | {
"start": 12604,
"end": 14916
} | class ____(Dropout):
"""Spatial 3D version of Dropout.
This version performs the same function as Dropout, however, it drops
entire 3D feature maps instead of individual elements. If adjacent voxels
within feature maps are strongly correlated (as is normally the case in
early convolution layers) then regular... | SpatialDropout3D |
python | weaviate__weaviate-python-client | weaviate/users/users.py | {
"start": 440,
"end": 519
} | class ____(UserBase):
user_type: UserTypes
active: bool
@dataclass
| UserDB |
python | pytorch__pytorch | test/ao/sparsity/test_parametrization.py | {
"start": 235,
"end": 1162
} | class ____(nn.Module):
def __init__(self, bias=True):
super().__init__()
self.linear = nn.Linear(16, 16, bias=bias)
self.seq = nn.Sequential(
nn.Linear(16, 16, bias=bias), nn.Linear(16, 16, bias=bias)
)
# Make sure the weights are not random
self.linear.w... | ModelUnderTest |
python | Netflix__metaflow | metaflow/event_logger.py | {
"start": 62,
"end": 780
} | class ____(object):
TYPE = "nullSidecarLogger"
def __init__(self, *args, **kwargs):
# Currently passed flow and env in kwargs
self._sidecar = Sidecar(self.TYPE)
def start(self):
return self._sidecar.start()
def terminate(self):
return self._sidecar.terminate()
def... | NullEventLogger |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-directory/source_google_directory/api.py | {
"start": 2855,
"end": 3851
} | class ____(ABC):
results_per_page = 100
def __init__(self, api: API, *args, **kwargs):
super().__init__(*args, **kwargs)
self._api = api
def _api_get(self, resource: str, params: Dict = None):
return self._api.get(resource, params=params)
@abstractmethod
def list(self, fie... | StreamAPI |
python | doocs__leetcode | solution/1700-1799/1760.Minimum Limit of Balls in a Bag/Solution.py | {
"start": 0,
"end": 266
} | class ____:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
def check(mx: int) -> bool:
return sum((x - 1) // mx for x in nums) <= maxOperations
return bisect_left(range(1, max(nums) + 1), True, key=check) + 1
| Solution |
python | Pylons__pyramid | tests/pkgs/restbugapp/views.py | {
"start": 166,
"end": 396
} | class ____(BaseRESTView):
"""REST Controller to control action of an avatar"""
def __init__(self, context, request):
super().__init__(context, request)
def GET(self):
return Response('gotten')
| PetRESTView |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 10437,
"end": 10867
} | class ____(BaseConfig):
format: Optional[str] = Field(
default=None,
description="The default format of the cursor value will be used for all streams except those defined in the streams section",
)
streams: List[FutureStateCursorFormatStreamConfiguration] = Field(
default_factory=lis... | FutureStateCursorFormatConfiguration |
python | google__jax | tests/pmap_test.py | {
"start": 129221,
"end": 129348
} | class ____(EagerPmapMixin, PmapWithDevicesTest):
pass
@jtu.pytest_mark_if_available('multiaccelerator')
| PmapWithDevicesEagerTest |
python | walkccc__LeetCode | solutions/209. Minimum Size Subarray Sum/209.py | {
"start": 0,
"end": 320
} | class ____:
def minSubArrayLen(self, target: int, nums: list[int]) -> int:
ans = math.inf
summ = 0
j = 0
for i, num in enumerate(nums):
summ += num
while summ >= target:
ans = min(ans, i - j + 1)
summ -= nums[j]
j += 1
return 0 if ans == math.inf else ans
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_combined05.py | {
"start": 315,
"end": 1591
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_combined05.xlsx")
self.ignore_elements = {
"xl/charts/chart1.xml": [
"<c:dispBlanksAs",
"<c:t... | TestCompareXLSXFiles |
python | pytorch__pytorch | test/test_testing.py | {
"start": 101486,
"end": 102631
} | class ____(TestCase):
@ops(op_db, dtypes=OpDTypes.any_one)
def test_opinfo_sample_generators(self, device, dtype, op):
# Test op.sample_inputs doesn't generate multiple samples when called
samples = op.sample_inputs(device, dtype)
self.assertIsInstance(samples, Iterator)
@ops([op f... | TestOpInfoSampleFunctions |
python | huggingface__transformers | tests/quantization/quanto_integration/test_quanto.py | {
"start": 4367,
"end": 12074
} | class ____(unittest.TestCase):
"""
Test 8-bit weights only quantization
"""
model_name = "bigscience/bloom-560m"
weights = "int8"
activations = None
device_map = "cpu"
input_text = "Hello my name is"
EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer and I... | QuantoQuantizationTest |
python | numba__numba | numba/tests/test_intwidth.py | {
"start": 642,
"end": 2703
} | class ____(TestCase):
def check_nullary_func(self, pyfunc, **kwargs):
cfunc = jit(**kwargs)(pyfunc)
self.assertPreciseEqual(cfunc(), pyfunc())
def test_global_uint64(self, nopython=False):
pyfunc = usecase_uint64_global
self.check_nullary_func(pyfunc, nopython=nopython)
de... | IntWidthTest |
python | getsentry__sentry | tests/sentry/search/test_utils.py | {
"start": 6111,
"end": 28947
} | class ____(APITestCase, SnubaTestCase):
@property
def rpc_user(self):
return user_service.get_user(user_id=self.user.id)
@property
def current_rpc_user(self):
# This doesn't include useremails. Used in filters
# where the current user is passed back
return serialize_rpc_... | ParseQueryTest |
python | pennersr__django-allauth | allauth/account/models.py | {
"start": 4297,
"end": 6029
} | class ____(EmailConfirmationMixin, models.Model):
email_address = models.ForeignKey(
EmailAddress,
verbose_name=_("email address"),
on_delete=models.CASCADE,
)
created = models.DateTimeField(verbose_name=_("created"), default=timezone.now)
sent = models.DateTimeField(verbose_name... | EmailConfirmation |
python | weaviate__weaviate-python-client | weaviate/collections/classes/batch.py | {
"start": 10654,
"end": 12168
} | class ____:
"""This class contains the results of a batch `insert_many_references` operation.
Since the individual references within the batch can error for differing reasons, the data is split up within this class for ease use when performing error checking, handling, and data revalidation.
Attributes:
... | BatchReferenceReturn |
python | huggingface__transformers | src/transformers/models/glm4/modeling_glm4.py | {
"start": 8805,
"end": 11930
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Glm4Config, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", conf... | Glm4Attention |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_X.py | {
"start": 1495,
"end": 2778
} | class ____(Benchmark):
r"""
Xin-She Yang 2 objective function.
This class defines the Xin-She Yang 2 [1]_ global optimization problem.
This is a multimodal minimization problem defined as follows:
.. math::
f_{\text{XinSheYang02}}(\x) = \frac{\sum_{i=1}^{n} \lvert{x_{i}}\rvert}
... | XinSheYang02 |
python | ray-project__ray | python/ray/serve/llm/__init__.py | {
"start": 1398,
"end": 1653
} | class ____(_LoraConfig):
"""The configuration for loading an LLM model with LoRA."""
pass
#############
# Deployments
#############
@Deprecated(
old="ray.serve.llm.LLMServer", new="ray.serve.llm.deployment.LLMServer", error=False
)
| LoraConfig |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_details.py | {
"start": 1001,
"end": 1411
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-details"
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(email="a@example.com", is_managed=False, name="example name")
self.superuser = self.create_user(is_superuser=True)
self.staff_user = self.create_... | UserDetailsTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 37596,
"end": 37974
} | class ____(sgqlc.types.Enum):
"""The possible default commit messages for merges.
Enumeration Choices:
* `BLANK`: Default to a blank commit message.
* `PR_BODY`: Default to the pull request's body.
* `PR_TITLE`: Default to the pull request's title.
"""
__schema__ = github_schema
__cho... | MergeCommitMessage |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 45267,
"end": 45590
} | class ____(DateArg):
def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> str:
value = super().normalize(value, params, combinator)
# SnQL interprets string types as string, so strip the
# quotes added in StringArg.normalize.
return value[1:-1]
| SnQLDateArg |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py | {
"start": 4267,
"end": 12924
} | class ____:
G1_edges = [
(1, 2),
(1, 4),
(1, 5),
(2, 3),
(2, 4),
(3, 4),
(4, 5),
(1, 6),
(6, 7),
(6, 8),
(8, 9),
(7, 9),
]
mapped = {
0: "x",
1: "a",
2: "b",
3: "c",
4: "d"... | TestGraphCandidateSelection |
python | numpy__numpy | numpy/f2py/tests/test_isoc.py | {
"start": 98,
"end": 1434
} | class ____(util.F2PyTest):
sources = [
util.getpath("tests", "src", "isocintrin", "isoCtests.f90"),
]
# gh-24553
@pytest.mark.slow
def test_c_double(self):
out = self.module.coddity.c_add(1, 2)
exp_out = 3
assert out == exp_out
# gh-9693
def test_bindc_funct... | TestISOC |
python | huggingface__transformers | tests/models/idefics2/test_modeling_idefics2.py | {
"start": 15704,
"end": 25245
} | class ____(GenerationTesterMixin, ModelTesterMixin, unittest.TestCase):
"""
Model tester for `Idefics2ForConditionalGeneration`.
"""
all_model_classes = (Idefics2ForConditionalGeneration,) if is_torch_available() else ()
pipeline_model_mapping = {"image-text-to-text": Idefics2ForConditionalGenerati... | Idefics2ForConditionalGenerationModelTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/events.py | {
"start": 25946,
"end": 26484
} | class ____(_EventsHold[_ET]):
all_holds: weakref.WeakKeyDictionary[Any, Any] = (
weakref.WeakKeyDictionary()
)
def resolve(self, class_: Type[_O]) -> Optional[ClassManager[_O]]:
return instrumentation.opt_manager_of_class(class_)
# this fails on pyright if you use Any. Fails on mypy i... | _InstanceEventsHold |
python | pytorch__pytorch | test/inductor/test_compile.py | {
"start": 1414,
"end": 1567
} | class ____(MyModule):
def forward(self, x): # takes a dict of list
a, b = x["key"]
return {"result": super().forward(a) + b}
| MyModule2 |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 53556,
"end": 56574
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that works similarly to [`NoRepeatNGramLogitsProcessor`], but applied exclusively to prevent
the repetition of n-grams present in the prompt.
It was designed to promote chattiness in a language model, by preventing the generation of n-grams present ... | EncoderNoRepeatNGramLogitsProcessor |
python | openai__openai-python | tests/lib/test_pydantic.py | {
"start": 7801,
"end": 10381
} | class ____(BaseModel):
color: Color = Field(description="The detected color")
hex_color_code: str = Field(description="The hex color code of the detected color")
def test_enums() -> None:
if not PYDANTIC_V1:
assert openai.pydantic_function_tool(ColorDetection)["function"] == snapshot(
... | ColorDetection |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict18.py | {
"start": 1203,
"end": 1404
} | class ____(TD5[Literal[1]]):
z: str
def func4(a: TD6) -> Literal[1]: ...
func4({"x": 1, "y": 1, "z": "a"})
f2: TD6 = {"x": 1, "y": 1, "z": "a"}
reveal_type(func4({"x": 1, "y": 1, "z": "a"}))
| TD6 |
python | PrefectHQ__prefect | src/prefect/settings/profiles.py | {
"start": 3378,
"end": 12795
} | class ____:
""" "
A utility class for working with a collection of profiles.
Profiles in the collection must have unique names.
The collection may store the name of the active profile.
"""
def __init__(self, profiles: Iterable[Profile], active: str | None = None) -> None:
self.profile... | ProfilesCollection |
python | nedbat__coveragepy | coverage/files.py | {
"start": 8604,
"end": 12245
} | class ____:
"""A matcher for files by file name pattern."""
def __init__(self, pats: Iterable[str], name: str = "unknown") -> None:
self.pats = list(pats)
self.re = globs_to_regex(self.pats, case_insensitive=env.WINDOWS)
self.name = name
def __repr__(self) -> str:
return f"... | GlobMatcher |
python | Lightning-AI__lightning | src/lightning/pytorch/profilers/profiler.py | {
"start": 970,
"end": 5531
} | class ____(ABC):
"""If you wish to write a custom profiler, you should inherit from this class."""
def __init__(
self,
dirpath: Optional[Union[str, Path]] = None,
filename: Optional[str] = None,
) -> None:
self.dirpath = dirpath
self.filename = filename
self... | Profiler |
python | pytorch__pytorch | torch/utils/_content_store.py | {
"start": 5624,
"end": 7447
} | class ____:
# Structure:
# storages/
# 00/
# 0000..00
# tensors/
# name
def __init__(self, loc: str, stable_hash: bool = False) -> None:
self.loc: str = loc
self.seen_storage_hashes: set[str] = set()
self.stable_hash = stable_hash
# TODO: offer ... | ContentStoreWriter |
python | celery__celery | celery/utils/abstract.py | {
"start": 1225,
"end": 2874
} | class ____(CallableTask): # pragma: no cover
"""Celery Signature interface."""
__required_attributes__ = frozenset({
'clone', 'freeze', 'set', 'link', 'link_error', '__or__',
})
@property
@abstractmethod
def name(self):
pass
@property
@abstractmethod
def type(self... | CallableSignature |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 20337,
"end": 20444
} | class ____(StringEnum):
iter = "iter"
timestamp = "timestamp"
iso_time = "iso_time"
| ScalarKeyEnum |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-firestore/llama_index/readers/firestore/base.py | {
"start": 340,
"end": 2876
} | class ____(BaseReader):
"""
Simple Firestore reader.
Args:
project_id (str): The Google Cloud Project ID.
*args (Optional[Any]): Additional arguments.
**kwargs (Optional[Any]): Additional keyword arguments.
Returns:
FirestoreReader: A FirestoreReader object.
"""
... | FirestoreReader |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 31941,
"end": 32393
} | class ____(ExtensionType):
oid = ExtensionOID.PRECERT_POISON
def __eq__(self, other: object) -> bool:
if not isinstance(other, PrecertPoison):
return NotImplemented
return True
def __hash__(self) -> int:
return hash(PrecertPoison)
def __repr__(self) -> str:
... | PrecertPoison |
python | streamlit__streamlit | lib/streamlit/runtime/scriptrunner_utils/script_run_context.py | {
"start": 2136,
"end": 10893
} | class ____:
"""A context object that contains data for a "script run" - that is,
data that's scoped to a single ScriptRunner execution (and therefore also
scoped to a single connected "session").
ScriptRunContext is used internally by virtually every `st.foo()` function.
It is accessed only from th... | ScriptRunContext |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail.py | {
"start": 1035,
"end": 1093
} | class ____(BaseModel, extra=1):
pass
| KwargsBadExtraModel |
python | django__django | django/contrib/gis/db/models/aggregates.py | {
"start": 2205,
"end": 2306
} | class ____(GeoAggregate):
name = "Collect"
output_field_class = GeometryCollectionField
| Collect |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 44508,
"end": 46082
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 4]"):
l_x_ = L_x_
add_: "f32[3, 4]" = l_x_.add_(1.0)
relu_: "f32[3, 4]" = torch.relu_(l_x_); l_x_ = None
add: "f32[3, 4]" = add_ + relu_; add_ = relu_ = None
return (add,)
""",
)
self.assertTrue(t... | GraphModule |
python | joke2k__faker | faker/providers/phone_number/de_AT/__init__.py | {
"start": 49,
"end": 2505
} | class ____(PhoneNumberProvider):
"""Phone number provider for `de_AT` locale.
Sources:
- https://de.wikipedia.org/wiki/Telefonvorwahl_(%C3%96sterreich)
"""
dialing_codes = (
"650",
"655",
"660",
"661",
"663",
"664",
"665",
"667",
... | Provider |
python | django-crispy-forms__django-crispy-forms | crispy_forms/exceptions.py | {
"start": 41,
"end": 288
} | class ____(CrispyError):
"""
This is raised when building a form via helpers throws an error.
We want to catch form helper errors as soon as possible because
debugging templatetags is never fun.
"""
pass
| FormHelpersException |
python | modin-project__modin | modin/core/dataframe/pandas/interchange/dataframe_protocol/dataframe.py | {
"start": 1671,
"end": 7859
} | class ____(ProtocolDataframe):
"""
A data frame class, with only the methods required by the interchange protocol defined.
Instances of this (private) class are returned from ``modin.pandas.DataFrame.__dataframe__``
as objects with the methods and attributes defined on this class.
A "data frame" r... | PandasProtocolDataframe |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/tests/test_gh_base_url.py | {
"start": 78,
"end": 1230
} | class ____:
pass
@pytest.fixture()
def github_reader():
return GithubRepositoryReader(
github_client=MockGithubClient(), owner="owner", repo="repo"
)
@pytest.mark.parametrize(
("blob_url", "expected_base_url"),
[
("https://github.com/owner/repo/blob/main/file.py", "https://github... | MockGithubClient |
python | sphinx-doc__sphinx | sphinx/ext/napoleon/__init__.py | {
"start": 502,
"end": 18649
} | class ____:
"""Sphinx napoleon extension settings in `conf.py`.
Listed below are all the settings used by napoleon and their default
values. These settings can be changed in the Sphinx `conf.py` file. Make
sure that "sphinx.ext.napoleon" is enabled in `conf.py`::
# conf.py
# Add any S... | Config |
python | python__mypy | mypyc/test/test_typeops.py | {
"start": 3003,
"end": 3935
} | class ____(unittest.TestCase):
def test_simple_type_result(self) -> None:
assert RUnion.make_simplified_union([int_rprimitive]) == int_rprimitive
def test_remove_duplicate(self) -> None:
assert RUnion.make_simplified_union([int_rprimitive, int_rprimitive]) == int_rprimitive
def test_cannot... | TestUnionSimplification |
python | justquick__django-activity-stream | actstream/managers.py | {
"start": 315,
"end": 4052
} | class ____(GFKManager):
"""
Default manager for Actions, accessed through Action.objects
"""
def public(self, *args, **kwargs):
"""
Only return public actions
"""
kwargs['public'] = True
return self.filter(*args, **kwargs)
@stream
def actor(self, obj: Mo... | ActionManager |
python | pandas-dev__pandas | pandas/tests/tools/test_to_datetime.py | {
"start": 84751,
"end": 102676
} | class ____:
def test_to_datetime_barely_out_of_bounds(self):
# GH#19529
# GH#19382 close enough to bounds that dropping nanos would result
# in an in-bounds datetime
arr = np.array(["2262-04-11 23:47:16.854775808"], dtype=object)
msg = "^Out of bounds nanosecond timestamp: .... | TestToDatetimeMisc |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigquery.py | {
"start": 69328,
"end": 71709
} | class ____(GoogleCloudBaseOperator):
"""
Retrieve the list of tables in the specified dataset.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigQueryGetDatasetTablesOperator`
:param dataset_id: the dataset ID of the reques... | BigQueryGetDatasetTablesOperator |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 69561,
"end": 70132
} | class ____(BaseModel):
active_bytes: int = Field(..., description="Total number of bytes in active pages allocated by the application")
allocated_bytes: int = Field(..., description="Total number of bytes allocated by the application")
metadata_bytes: int = Field(..., description="Total number of bytes dedi... | MemoryTelemetry |
python | python-openxml__python-docx | src/docx/text/run.py | {
"start": 746,
"end": 10117
} | class ____(StoryChild):
"""Proxy object wrapping `<w:r>` element.
Several of the properties on Run take a tri-state value, |True|, |False|, or |None|.
|True| and |False| correspond to on and off respectively. |None| indicates the
property is not specified directly on the run and its effective value is ... | Run |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 20952,
"end": 21512
} | class ____(MarianIntegrationTest):
"""Cover low resource/high perplexity setting. This breaks without adjust_logits_generation overwritten"""
src = "mt"
tgt = "en"
src_text = ["Billi messu b'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem."]
expected_text = ["Touching ge... | TestMarian_MT_EN |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_created_by.py | {
"start": 314,
"end": 402
} | class ____(GQLResult):
artifact: Optional[ArtifactCreatedByArtifact]
| ArtifactCreatedBy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.