language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | tests/models/wav2vec2/test_modeling_wav2vec2.py | {
"start": 26025,
"end": 42752
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (
(
Wav2Vec2ForCTC,
Wav2Vec2Model,
Wav2Vec2ForMaskedLM,
Wav2Vec2ForSequenceClassification,
Wav2Vec2ForPreTraining,
Wav2Vec2ForAudioFrameClassification,
Wav... | Wav2Vec2RobustModelTest |
python | astropy__astropy | astropy/utils/parsing.py | {
"start": 3085,
"end": 4843
} | class ____:
"""Wrap a parser produced by ``ply.yacc.yacc``.
It provides a :meth:`parse` method that is thread-safe.
"""
def __init__(self, parser: LRParser) -> None:
self.parser = parser
self._lock = threading.RLock()
def parse(self, *args, **kwargs):
"""Run the wrapped pa... | ThreadSafeParser |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1044178,
"end": 1044867
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
UpdateRepositoryWebCommitSignoffSetting
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "message", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique ... | UpdateRepositoryWebCommitSignoffSettingPayload |
python | pytorch__pytorch | torch/autograd/profiler_util.py | {
"start": 19030,
"end": 20089
} | class ____:
"""Helpers for FunctionEvent and FunctionEventAvg.
The subclass should define `*_time_total` and `count` attributes.
"""
cpu_time_str = _attr_formatter("cpu_time")
device_time_str = _attr_formatter("device_time")
cpu_time_total_str = _attr_formatter("cpu_time_total")
device_tim... | FormattedTimesMixin |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 395993,
"end": 403696
} | class ____(rv_continuous):
r"""A studentized range continuous random variable.
%(before_notes)s
See Also
--------
t: Student's t distribution
Notes
-----
The probability density function for `studentized_range` is:
.. math::
f(x; k, \nu) = \frac{k(k-1)\nu^{\nu/2}}{\Gamm... | studentized_range_gen |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 13286,
"end": 13658
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = FNetLMPredictionHead(config)
def forward(self, sequence_output):
prediction_scores = self.predictions(sequence_output)
return prediction_scores
# Copied from transformers.models.bert.model... | FNetOnlyMLMHead |
python | public-apis__public-apis | scripts/tests/test_validate_links.py | {
"start": 462,
"end": 5725
} | class ____(unittest.TestCase):
def setUp(self):
self.duplicate_links = [
'https://www.example.com',
'https://www.example.com',
'https://www.example.com',
'https://www.anotherexample.com',
]
self.no_duplicate_links = [
'https://www.... | TestValidateLinks |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 23788,
"end": 26455
} | class ____:
"""Descriptor for getting and setting the offset property.
Offset consists of two values, x and y, that a widget's position
will be adjusted by before it is rendered.
"""
def __set_name__(self, owner: StylesBase, name: str) -> None:
self.name = name
def __get__(
sel... | OffsetProperty |
python | python-openxml__python-docx | src/docx/oxml/table.py | {
"start": 13682,
"end": 27628
} | class ____(BaseOxmlElement):
"""`w:tc` table cell element."""
add_p: Callable[[], CT_P]
get_or_add_tcPr: Callable[[], CT_TcPr]
p_lst: list[CT_P]
tbl_lst: list[CT_Tbl]
_insert_tbl: Callable[[CT_Tbl], CT_Tbl]
_new_p: Callable[[], CT_P]
# -- tcPr has many successors, `._insert_tcPr()` is ... | CT_Tc |
python | davidhalter__parso | parso/normalizer.py | {
"start": 3132,
"end": 3354
} | class ____:
normalizer_class = Normalizer
def create_normalizer(self, grammar):
if self.normalizer_class is None:
return None
return self.normalizer_class(grammar, self)
| NormalizerConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 21100,
"end": 25184
} | class ____(GoogleCloudBaseOperator):
"""
Import a Redis RDB snapshot file from Cloud Storage into a Redis instance.
Redis may stop serving during this operation. Instance state will be IMPORTING for entire operation. When
complete, the instance will contain only data from the imported file.
.. see... | CloudMemorystoreImportOperator |
python | dateutil__dateutil | tests/test_tz.py | {
"start": 80718,
"end": 85384
} | class ____(unittest.TestCase, TzWinFoldMixin):
def setUp(self):
self.tzclass = tzwin.tzwinlocal
self.context = TZWinContext
def get_args(self, tzname):
return ()
def testLocal(self):
# Not sure how to pin a local time zone, so for now we're just going
# to run this... | TzWinLocalTest |
python | sqlalchemy__sqlalchemy | examples/sharding/separate_tables.py | {
"start": 2959,
"end": 3354
} | class ____(Base):
__tablename__ = "_prefix__weather_locations"
id: Mapped[int] = mapped_column(primary_key=True, default=id_generator)
continent: Mapped[str]
city: Mapped[str]
reports: Mapped[list[Report]] = relationship(back_populates="location")
def __init__(self, continent: str, city: str)... | WeatherLocation |
python | apache__airflow | providers/apache/druid/src/airflow/providers/apache/druid/hooks/druid.py | {
"start": 1465,
"end": 7568
} | class ____(BaseHook):
"""
Connection to Druid overlord for ingestion.
To connect to a Druid cluster that is secured with the druid-basic-security
extension, add the username and password to the druid ingestion connection.
:param druid_ingest_conn_id: The connection id to the Druid overlord machine... | DruidHook |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-coins-for-fruits-ii.py | {
"start": 788,
"end": 1263
} | class ____(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
sl = SortedList()
j = 0
for i in xrange(len(prices)):
sl.add((dp[i]+prices[i], i))
... | Solution2 |
python | bokeh__bokeh | tests/unit/bokeh/application/test_application.py | {
"start": 7679,
"end": 8154
} | class ____:
def test_abstract(self) -> None:
with pytest.raises(TypeError):
baa.SessionContext()
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#------------------------... | Test_SessionContext |
python | openai__openai-python | src/openai/types/beta/realtime/response_create_event.py | {
"start": 4427,
"end": 4763
} | class ____(BaseModel):
type: Literal["response.create"]
"""The event type, must be `response.create`."""
event_id: Optional[str] = None
"""Optional client-generated ID used to identify this event."""
response: Optional[Response] = None
"""Create a new Realtime response with these parameters"""... | ResponseCreateEvent |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 9147,
"end": 9732
} | class ____(WeaviateBaseError):
"""Is raised when inserting an invalid property."""
def __init__(self, data: dict):
msg = f"""It is forbidden to insert `id` or `vector` inside properties: {data}. Only properties defined in your collection's config can be inserted as properties of the object, `id` is tot... | WeaviateInsertInvalidPropertyError |
python | google__jax | jax/_src/config.py | {
"start": 34960,
"end": 35309
} | class ____:
def __init__(self, default_value):
self._obj = config_ext.Config("user_context", default_value, include_in_jit_key=True,
include_in_trace_context=True)
@property
def value(self):
return self._obj.value
def __call__(self, new_value):
return UserContext(... | UserConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/graph_definition.py | {
"start": 4828,
"end": 42026
} | class ____(NodeDefinition):
"""Defines a Dagster op graph.
An op graph is made up of
- Nodes, which can either be an op (the functional unit of computation), or another graph.
- Dependencies, which determine how the values produced by nodes as outputs flow from
one node to another. This tells Da... | GraphDefinition |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis07.py | {
"start": 315,
"end": 1579
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis07.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | pyinstaller__pyinstaller | PyInstaller/utils/win32/icon.py | {
"start": 2431,
"end": 2534
} | class ____(Structure):
_names_ = "idReserved", "idType", "idCount"
_format_ = "hhh"
| ICONDIRHEADER |
python | huggingface__transformers | src/transformers/models/tapas/modeling_tapas.py | {
"start": 2648,
"end": 6424
} | class ____(nn.Module):
"""
Construct the embeddings from word, position and token_type embeddings. Same as BertEmbeddings but with a number of
additional token type embeddings to encode tabular structure.
"""
def __init__(self, config):
super().__init__()
# we do not include config.... | TapasEmbeddings |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 25020,
"end": 25732
} | class ____(SuperClassPositionalArgs):
"""Loading this model should accept hparams and init in the super class."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def test_args(tmp_path):
"""Test for inheritance: super class takes positional arg, subclass takes varar... | SubClassVarArgs |
python | django__django | tests/mail/tests.py | {
"start": 8976,
"end": 82152
} | class ____(MailTestsMixin, SimpleTestCase):
"""
Non-backend specific tests.
"""
def test_ascii(self):
email = EmailMessage(
"Subject", "Content\n", "from@example.com", ["to@example.com"]
)
message = email.message()
self.assertEqual(message["Subject"], "Subjec... | MailTests |
python | sympy__sympy | sympy/core/logic.py | {
"start": 7836,
"end": 8939
} | class ____(Logic):
def __new__(cls, *args):
bargs = []
for a in args:
if a == cls.op_x_notx:
return a
elif a == (not cls.op_x_notx):
continue # skip this argument
bargs.append(a)
args = sorted(set(cls.flatten(bargs)), k... | AndOr_Base |
python | PyCQA__pylint | pylint/checkers/format.py | {
"start": 4191,
"end": 28293
} | class ____(BaseTokenChecker, BaseRawFileChecker):
"""Formatting checker.
Checks for :
* unauthorized constructions
* strict indentation
* line length
"""
# configuration section name
name = "format"
# messages
msgs = MSGS
# configuration options
# for available dict key... | FormatChecker |
python | getsentry__sentry | tests/sentry/api/helpers/test_group_index.py | {
"start": 14763,
"end": 20994
} | class ____(TestCase):
@patch("sentry.api.helpers.group_index.update.handle_merge")
def test_simple(self, mock_handle_merge: MagicMock) -> None:
group_ids = [self.create_group().id, self.create_group().id]
project = self.project
request = self.make_request(method="PUT")
request.u... | MergeGroupsTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 331861,
"end": 353200
} | class ____(Request):
"""
Return first frame per unique URI for the given dataview specification. Note: 'count_range' option for label rules is not supported and does not affect the returned snippets
:param dataview: Dataview specification
:type dataview: Dataview
:param page_size: The amount of sni... | GetSnippetsForDataviewRequest |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 5147,
"end": 5240
} | class ____(Enum):
OPEN = 1
CLOSED = 2
WARNING = 10
CRITICAL = 20
| IncidentStatus |
python | getsentry__sentry | src/sentry/utils/redis.py | {
"start": 1613,
"end": 3017
} | class ____:
def __init__(self, options_manager: OptionsManager) -> None:
self._clusters: dict[str, rb.Cluster] = {}
self._options_manager = options_manager
def _factory(
self,
*,
hosts: list[dict[int, Any]] | dict[int, Any] | None = None,
**config: Any,
) -> ... | RBClusterManager |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 1608,
"end": 1674
} | class ____(Parent):
name = models.CharField(max_length=10)
| Child |
python | astral-sh__uv | scripts/benchmark/src/benchmark/tools.py | {
"start": 513,
"end": 2143
} | class ____(abc.ABC):
"""Abstract base class for packaging tools."""
def command(self, benchmark: Benchmark, *, cwd: str) -> Command | None:
"""Generate a command to benchmark a given tool."""
match benchmark:
case Benchmark.INSTALL_COLD:
return self.install_cold(cwd=... | Suite |
python | huggingface__transformers | tests/models/markuplm/test_processing_markuplm.py | {
"start": 1308,
"end": 6179
} | class ____(unittest.TestCase):
tokenizer_class = MarkupLMTokenizer
rust_tokenizer_class = MarkupLMTokenizerFast
def setUp(self):
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
vocab = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "... | MarkupLMProcessorTest |
python | keras-team__keras | keras/src/distribution/distribution_lib.py | {
"start": 28832,
"end": 34542
} | class ____(collections.abc.MutableMapping):
"""A dict-like object that maps string to `TensorLayout` instances.
`LayoutMap` uses a string as key and a `TensorLayout` as value. There is a
behavior difference between a normal Python dict and this class. The string
key will be treated as a regex when retr... | LayoutMap |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 2592,
"end": 2679
} | class ____(UpdateView):
model = Poll
fields = ["question", "pub_date"]
| PollUpdate |
python | scrapy__scrapy | tests/test_spider.py | {
"start": 18662,
"end": 32186
} | class ____(TestSpider):
spider_class = SitemapSpider
BODY = b"SITEMAP"
f = BytesIO()
g = gzip.GzipFile(fileobj=f, mode="w+b")
g.write(BODY)
g.close()
GZBODY = f.getvalue()
def assertSitemapBody(self, response: Response, body: bytes | None) -> None:
crawler = get_crawler()
... | TestSitemapSpider |
python | python__mypy | mypy/plugin.py | {
"start": 16711,
"end": 17252
} | class ____(NamedTuple):
args: list[list[Expression]] # Actual expressions for each formal argument
default_signature: CallableType # Original signature of the method
context: Context # Relevant location context (e.g. for error messages)
api: CheckerPluginInterface
# A context for a function hook th... | FunctionSigContext |
python | ray-project__ray | release/long_running_tests/workloads/serve_failure.py | {
"start": 2839,
"end": 6344
} | class ____:
def __init__(self, random_killer_handle, max_applications=1):
self.max_applications = max_applications
self.weighted_actions = [
(self.create_application, 1),
(self.verify_application, 4),
]
self.applications = []
self.random_killer = rand... | RandomTest |
python | kamyu104__LeetCode-Solutions | Python/count-and-say.py | {
"start": 37,
"end": 519
} | class ____(object):
# @return a string
def countAndSay(self, n):
seq = "1"
for i in xrange(n - 1):
seq = self.getNext(seq)
return seq
def getNext(self, seq):
i, next_seq = 0, ""
while i < len(seq):
cnt = 1
while i < len(seq) - 1 an... | Solution |
python | plotly__plotly.py | plotly/graph_objs/layout/ternary/caxis/_tickformatstop.py | {
"start": 235,
"end": 8537
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.ternary.caxis"
_path_str = "layout.ternary.caxis.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", ... | Tickformatstop |
python | explosion__spaCy | spacy/training/alignment.py | {
"start": 150,
"end": 614
} | class ____:
x2y: AlignmentArray
y2x: AlignmentArray
@classmethod
def from_indices(cls, x2y: List[List[int]], y2x: List[List[int]]) -> "Alignment":
x2y = AlignmentArray(x2y)
y2x = AlignmentArray(y2x)
return Alignment(x2y=x2y, y2x=y2x)
@classmethod
def from_strings(cls, A... | Alignment |
python | pypa__pip | tests/unit/test_search_scope.py | {
"start": 125,
"end": 1502
} | class ____:
def test_get_formatted_locations_basic_auth(self) -> None:
"""
Test that basic authentication credentials defined in URL
is not included in formatted output.
"""
index_urls = [
"https://pypi.org/simple",
"https://repo-user:repo-pass@repo.do... | TestSearchScope |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 184702,
"end": 186428
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of CreateIssue"""
__schema__ = github_schema
__field_names__ = (
"repository_id",
"title",
"body",
"assignee_ids",
"milestone_id",
"label_ids",
"project_ids",
"issue_template",
... | CreateIssueInput |
python | google__jax | tests/pretty_printer_test.py | {
"start": 698,
"end": 3883
} | class ____(jtu.JaxTestCase):
def testSourceMap(self):
doc = pp.concat([
pp.text("abc"),
pp.source_map(pp.text("def"), 101),
pp.source_map(
pp.concat([pp.text("gh"), pp.brk(""), pp.text("ijkl")]), 77
),
pp.text("mn"),
])
source_map = []
out = doc.for... | PrettyPrinterTest |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py | {
"start": 6266,
"end": 7431
} | class ____(BaseEnvironment):
def __init__(self, paths: Sequence[str]) -> None:
self._paths = paths
@classmethod
def default(cls) -> BaseEnvironment:
return cls(sys.path)
@classmethod
def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:
if paths is None:
... | Environment |
python | huggingface__transformers | src/transformers/models/ibert/quant_modules.py | {
"start": 25588,
"end": 25851
} | class ____(Function):
"""
Straight-through Estimator(STE) for torch.floor()
"""
@staticmethod
def forward(ctx, x):
return torch.floor(x)
@staticmethod
def backward(ctx, grad_output):
return grad_output.clone()
| floor_ste |
python | pydantic__pydantic | pydantic/types.py | {
"start": 73891,
"end": 74935
} | class ____(EncoderProtocol):
"""Standard (non-URL-safe) Base64 encoder."""
@classmethod
def decode(cls, data: bytes) -> bytes:
"""Decode the data from base64 encoded bytes to original bytes data.
Args:
data: The data to decode.
Returns:
The decoded data.
... | Base64Encoder |
python | doocs__leetcode | solution/0300-0399/0300.Longest Increasing Subsequence/Solution.py | {
"start": 0,
"end": 277
} | class ____:
def lengthOfLIS(self, nums: List[int]) -> int:
n = len(nums)
f = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
f[i] = max(f[i], f[j] + 1)
return max(f)
| Solution |
python | Netflix__metaflow | test/core/tests/card_default_editable.py | {
"start": 514,
"end": 5146
} | class ____:
at = 0
def get(self):
return self.at
"""
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursiv... | MyNativeType |
python | pypa__pipenv | pipenv/patched/pip/_vendor/pygments/sphinxext.py | {
"start": 752,
"end": 8071
} | class ____(Directive):
"""
A directive to collect all lexers/formatters/filters and generate
autoclass directives for them.
"""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {}
def run(self):
self.filena... | PygmentsDoc |
python | pytorch__pytorch | torch/export/_trace.py | {
"start": 3789,
"end": 4815
} | class ____:
"""
Manage Export-specific configurations of Dynamo.
"""
allow_rnn: bool = True
reorderable_logging_functions: set[Callable] = dataclasses.field(
default_factory=set
)
# Emit runtime asserts after AOTAutograd instead.
# This isn't really necessary, and isn't much mor... | ExportDynamoConfig |
python | mlflow__mlflow | examples/pyfunc/model_as_code.py | {
"start": 724,
"end": 1998
} | class ____(pyfunc.PythonModel):
@mlflow.trace(name="chain", span_type="CHAIN")
def predict(self, context, model_input):
if isinstance(model_input, pd.DataFrame):
model_input = model_input["input"].tolist()
responses = []
for user_input in model_input:
response = ... | AIModel |
python | pydantic__pydantic | tests/mypy/modules/fail_defaults.py | {
"start": 40,
"end": 462
} | class ____(BaseModel):
# Required
undefined_default_no_args: int = Field()
undefined_default: int = Field(description='my desc')
positional_ellipsis_default: int = Field(...)
named_ellipsis_default: int = Field(default=...)
# Not required
positional_default: int = Field(1)
named_default... | Model |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_styles04.py | {
"start": 380,
"end": 8870
} | class ____(unittest.TestCase):
"""
Test assembling a complete Styles file.
"""
def test_assemble_xml_file(self):
"""Test for border styles."""
self.maxDiff = None
fh = StringIO()
style = Styles()
style._set_filehandle(fh)
workbook = Workbook()
... | TestAssembleStyles |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultFunction1.py | {
"start": 622,
"end": 1304
} | class ____(Generic[P]):
def __init__(self, x: Callable[P, None]) -> None: ...
def func2(x: int | ClassA[P]) -> ClassA[P]: ...
def callback1(x: str) -> None: ...
v2_1 = func2(ClassA(callback1))
reveal_type(v2_1, expected_text="ClassA[(x: str)]")
v2_2 = func2(3)
reveal_type(v2_2, expected_text="ClassA[(int, s... | ClassA |
python | pandas-dev__pandas | pandas/tests/window/test_timeseries_window.py | {
"start": 735,
"end": 25130
} | class ____:
# rolling time-series friendly
# xref GH13327
def test_doc_string(self):
df = DataFrame(
{"B": [0, 1, 2, np.nan, 4]},
index=[
Timestamp("20130101 09:00:00"),
Timestamp("20130101 09:00:02"),
Timestamp("20130101 09:00... | TestRollingTS |
python | Farama-Foundation__Gymnasium | tests/vector/testing_utils.py | {
"start": 1469,
"end": 2530
} | class ____(gym.Env):
"""A custom slow environment."""
def __init__(self, slow_reset=0.3):
"""Initialises the environment with a slow reset parameter used in the `step` and `reset` functions."""
super().__init__()
self.slow_reset = slow_reset
self.observation_space = Box(
... | SlowEnv |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/pep604.py | {
"start": 140,
"end": 292
} | class ____:
"""docstring"""
attr: int | str #: docstring
def meth(self, x: int | str, y: int | str) -> int | str:
"""docstring"""
| Foo |
python | facelessuser__soupsieve | tests/test_api.py | {
"start": 125,
"end": 14744
} | class ____(util.TestCase):
"""Test Soup Sieve."""
def test_select(self):
"""Test select."""
markup = """
<!-- before header -->
<html>
<head>
</head>
<body>
<!-- comment -->
<p id="1"><code id="2"></code><img id="3" src="./image.png"/></p... | TestSoupSieve |
python | pytorch__pytorch | torch/_appdirs.py | {
"start": 20027,
"end": 26197
} | class ____:
"""Convenience wrapper for getting application dirs."""
def __init__(
self, appname=None, appauthor=None, version=None, roaming=False, multipath=False
):
self.appname = appname
self.appauthor = appauthor
self.version = version
self.roaming = roaming
... | AppDirs |
python | django__django | tests/template_tests/filter_tests/test_addslashes.py | {
"start": 897,
"end": 1332
} | class ____(SimpleTestCase):
def test_quotes(self):
self.assertEqual(
addslashes("\"double quotes\" and 'single quotes'"),
"\\\"double quotes\\\" and \\'single quotes\\'",
)
def test_backslashes(self):
self.assertEqual(addslashes(r"\ : backslashes, too"), "\\\\ : ... | FunctionTests |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_minnesota_zip.py | {
"start": 1759,
"end": 4110
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Minnesota zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [... | ExpectColumnValuesToBeValidMinnesotaZip |
python | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 17045,
"end": 18261
} | class ____(MetaEstimatorMixin, RegressorMixin, BaseEstimator):
"""A meta-regressor which is also a consumer."""
def __init__(self, estimator, registry=None):
self.estimator = estimator
self.registry = registry
def fit(self, X, y, sample_weight=None, **fit_params):
if self.registry ... | WeightedMetaRegressor |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/split_op_test.py | {
"start": 1479,
"end": 17189
} | class ____(test.TestCase):
def _makeData(self, shape, dtype):
data = np.random.rand(*shape).astype(dtype.as_numpy_dtype)
if dtype.is_complex:
data -= 1j * data
return data
@test_util.run_deprecated_v1
def testShapeInference(self):
model_input = array_ops.placeholder(dtypes.float32, shape=(... | SplitOpTest |
python | getsentry__sentry | src/sentry/api/serializers/models/project_template.py | {
"start": 554,
"end": 622
} | class ____(StrEnum):
OPTIONS = "options"
| ProjectTemplateAttributes |
python | getsentry__sentry | tests/sentry/organizations/services/test_organization.py | {
"start": 291,
"end": 2999
} | class ____(TestCase):
def test_check_active_organization_by_slug(self) -> None:
self.organization = self.create_organization(slug="test")
assert (
organization_service.check_organization_by_slug(slug="test", only_visible=True)
== self.organization.id
)
assert ... | CheckOrganizationTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/secrets/systems_manager.py | {
"start": 1120,
"end": 8496
} | class ____(BaseSecretsBackend, LoggingMixin):
"""
Retrieves Connection or Variables from AWS SSM Parameter Store.
Configurable via ``airflow.cfg`` like so:
.. code-block:: ini
[secrets]
backend = airflow.providers.amazon.aws.secrets.systems_manager.SystemsManagerParameterStoreBackend
... | SystemsManagerParameterStoreBackend |
python | cython__cython | tests/run/test_asyncgen.py | {
"start": 3554,
"end": 4250
} | class ____(Exception):
pass
@types_coroutine
def awaitable(*, throw=False):
if throw:
yield ('throw',)
else:
yield ('result',)
def run_until_complete(coro):
exc = False
while True:
try:
if exc:
exc = False
fut = coro.throw(Await... | AwaitException |
python | jina-ai__jina | jina/excepts.py | {
"start": 2541,
"end": 2664
} | class ____(RuntimeError, BaseJinaException):
"""Raised when trying to use a port which is already used"""
| PortAlreadyUsed |
python | RaRe-Technologies__gensim | gensim/test/test_tmdiff.py | {
"start": 356,
"end": 2944
} | class ____(unittest.TestCase):
def setUp(self):
self.dictionary = common_dictionary
self.corpus = common_corpus
self.num_topics = 5
self.n_ann_terms = 10
self.model = LdaModel(corpus=self.corpus, id2word=self.dictionary, num_topics=self.num_topics, passes=10)
def test_ba... | TestLdaDiff |
python | django__django | django/db/migrations/operations/models.py | {
"start": 42754,
"end": 44444
} | class ____(IndexOperation):
category = OperationCategory.REMOVAL
option_name = "constraints"
def __init__(self, model_name, name):
self.model_name = model_name
self.name = name
def state_forwards(self, app_label, state):
state.remove_constraint(app_label, self.model_name_lower,... | RemoveConstraint |
python | getsentry__sentry | tests/sentry/notifications/platform/msteams/test_provider.py | {
"start": 8815,
"end": 11973
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.integration, self.org_integration = self.create_provider_integration_for(
provider=IntegrationProviderSlug.MSTEAMS,
organization=self.organization,
user=self.user,
name="test-msteams",... | MSTeamsNotificationProviderSendTest |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/bedrock/_beta.py | {
"start": 459,
"end": 1372
} | class ____(SyncAPIResource):
@cached_property
def messages(self) -> Messages:
return Messages(self._client)
@cached_property
def with_raw_response(self) -> BetaWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return the
the raw respo... | Beta |
python | langchain-ai__langchain | libs/core/langchain_core/exceptions.py | {
"start": 183,
"end": 283
} | class ____(LangChainException):
"""Base class for exceptions in tracers module."""
| TracerException |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1004980,
"end": 1005668
} | class ____(ValueChannelMixin, core.ValueDefnumber):
"""
XErrorValue schema wrapper.
Definition object for a constant value (primitive value or gradient definition) of an
encoding channel.
Parameters
----------
value : float
A constant value in visual domain (e.g., ``"red"`` / ``"#0... | XErrorValue |
python | getsentry__sentry | src/sentry/auth_v2/utils/session.py | {
"start": 341,
"end": 853
} | class ____(TypedDict, total=False):
# Flags to control the authentication flow on frontend.
# Keep the keys sorted in order of importance!!
# Maintaining the hierarchy is good context for future engineers.
todoEmailVerification: bool | None
todo2faVerification: bool | None
todoPasswordReset: boo... | SessionSerializerResponse |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 95479,
"end": 96109
} | class ____(nn.Module):
def __init__(self, config: DFineConfig):
super().__init__()
self.layers = nn.ModuleList([DFineEncoderLayer(config) for _ in range(config.encoder_layers)])
def forward(self, src, src_mask=None, pos_embed=None, output_attentions: bool = False) -> torch.Tensor:
hidd... | DFineEncoder |
python | lepture__authlib | tests/flask/test_oauth1/oauth1_server.py | {
"start": 1691,
"end": 2227
} | class ____(TokenCredentialMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User")
client_id = db.Column(db.String(48), index=True)
oauth_token = db.Column(db.String(84), unique=True, i... | TokenCredential |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 21270,
"end": 22142
} | class ____(AbstractTemplate):
key = "static_getitem"
def generic(self, args, kws):
# Resolution of members for record and structured arrays
ary, idx = args
if (isinstance(ary, types.Array) and isinstance(idx, str) and
isinstance(ary.dtype, types.Record)):
if ... | StaticGetItemArray |
python | joke2k__faker | tests/providers/test_bank.py | {
"start": 4421,
"end": 4887
} | class ____:
"""Test fi_FI bank provider"""
def test_bban(self, faker, num_samples):
for _ in range(num_samples):
assert re.fullmatch(r"\d{14}", faker.bban())
def test_iban(self, faker, num_samples):
for _ in range(num_samples):
iban = faker.iban()
assert... | TestFiFi |
python | huggingface__transformers | src/transformers/models/bit/modeling_bit.py | {
"start": 6995,
"end": 8043
} | class ____(nn.MaxPool2d):
def __init__(
self,
kernel_size: int,
stride=None,
dilation=1,
ceil_mode=False,
padding=(0, 0),
padding_value=0,
use_dynamic_padding=True,
):
kernel_size = kernel_size if isinstance(kernel_size, collections.abc.Ite... | BitMaxPool2d |
python | gevent__gevent | src/gevent/tests/test__greenness.py | {
"start": 1781,
"end": 1948
} | class ____(SimpleHTTPRequestHandler, object):
def log_message(self, *args): # pylint:disable=arguments-differ
self.server.messages += ((args,),)
| QuietHandler |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows.py | {
"start": 208997,
"end": 209564
} | class ____(object):
# https://argoproj.github.io/argo-workflows/fields/#arguments
def __init__(self):
tree = lambda: defaultdict(tree)
self.payload = tree()
def parameters(self, parameters):
if "parameters" not in self.payload:
self.payload["parameters"] = []
fo... | Arguments |
python | celery__celery | t/unit/worker/test_bootsteps.py | {
"start": 3857,
"end": 5005
} | class ____:
class Def(bootsteps.StartStopStep):
name = 'test_StartStopStep.Def'
def setup_method(self):
self.steps = []
def test_start__stop(self):
x = self.Def(self)
x.create = Mock()
# include creates the underlying object and sets
# its x.obj attribute ... | test_StartStopStep |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_poly_persistence.py | {
"start": 2884,
"end": 5763
} | class ____(PolymorphTest):
def test_insert_order(self):
"""test that classes of multiple types mix up mapper inserts
so that insert order of individual tables is maintained"""
person_join = polymorphic_union(
{
"engineer": people.join(engineers),
... | InsertOrderTest |
python | google__pytype | pytype/errors/error_printer.py | {
"start": 371,
"end": 493
} | class ____:
expected: str
bad_actual: str
full_actual: str
error_details: list[str]
@dataclasses.dataclass
| BadReturn |
python | tensorflow__tensorflow | tensorflow/python/framework/memory_checker_test.py | {
"start": 987,
"end": 3885
} | class ____(test.TestCase):
def testNoLeakEmpty(self):
with MemoryChecker() as memory_checker:
memory_checker.record_snapshot()
memory_checker.record_snapshot()
memory_checker.record_snapshot()
memory_checker.record_snapshot()
memory_checker.report()
memory_checker.assert_no_leak_... | MemoryCheckerTest |
python | doocs__leetcode | lcof/面试题51. 数组中的逆序对/Solution2.py | {
"start": 343,
"end": 674
} | class ____:
def reversePairs(self, nums: List[int]) -> int:
alls = sorted(set(nums))
m = len(alls)
tree = BinaryIndexedTree(m)
ans = 0
for v in nums[::-1]:
x = bisect_left(alls, v) + 1
ans += tree.query(x - 1)
tree.update(x, 1)
retu... | Solution |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 63514,
"end": 63772
} | class ____(ActionTool):
''' A tool that allows to enlarge a UI element to fullscreen. '''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| FullscreenTool |
python | django__django | tests/admin_inlines/admin.py | {
"start": 5579,
"end": 5687
} | class ____(admin.TabularInline):
model = ShoppingWeakness
form = WeaknessForm
| WeaknessInlineCustomForm |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 89556,
"end": 91497
} | class ____(gdb.Command):
def __init__(self, command, actual_command):
super().__init__(command, gdb.COMMAND_DATA,
gdb.COMPLETE_NONE)
self.actual_command = actual_command
def fix_gdb(self):
"""
It seems that invoking either 'cy exec' a... | FixGdbCommand |
python | django__django | tests/delete_regress/tests.py | {
"start": 9347,
"end": 11926
} | class ____(TestCase):
"""
Test different queries which alter the SELECT clause of the query. We
also must be using a subquery for the deletion (that is, the original
query has a join in it). The deletion should be done as "fast-path"
deletion (that is, just one query for the .delete() call).
No... | Ticket19102Tests |
python | joke2k__faker | faker/providers/geo/en_IE/__init__.py | {
"start": 41,
"end": 3029
} | class ____(GeoProvider):
# Source: https://www.latlong.net/category/towns-106-55.html
land_coords = (
(
"53.944000",
"-8.095000",
"Carrish on Shannon, Leitrim,",
"IE",
"Europe/Dublin",
),
("52.354279", "-7.695040", "Clonmel, Co.... | Provider |
python | pytorch__pytorch | torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py | {
"start": 481,
"end": 3878
} | class ____(BaseScheduling):
"""
Partial Scheduling implementation for ROCm C++ Kernels.
This class is intended to be used in combination with TritonScheduling,
and delegated to by CUDACombinedScheduling.
It handles fusion decisions and ROCm C++ specific template code generation.
"""
def gr... | ROCmCPPScheduling |
python | tiangolo__fastapi | fastapi/security/http.py | {
"start": 7069,
"end": 10264
} | class ____(HTTPBase):
"""
HTTP Bearer token authentication.
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be an `HTTPAuthorizationCredentials` object containing
the `scheme` and the `credentials`.
## Example
```py... | HTTPBearer |
python | numba__llvmlite | llvmlite/ir/types.py | {
"start": 18490,
"end": 20079
} | class ____(BaseStructType):
"""
A type which is a named alias for another struct type, akin to a typedef.
While literal struct types can be structurally equal (see
LiteralStructType), identified struct types are compared by name.
Do not use this directly.
"""
null = 'zeroinitializer'
d... | IdentifiedStructType |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 40342,
"end": 40445
} | class ____(GenericForTokenClassification, MiniMaxPreTrainedModel):
pass
| MiniMaxForTokenClassification |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 61,
"end": 500
} | class ____:
def keys(self):
raise NotImplementedError()
def add(self, spec=None, add_book=None, xl=None, visible=None):
raise NotImplementedError()
@staticmethod
def cleanup():
raise NotImplementedError()
def __iter__(self):
raise NotImplementedError()
def __l... | Apps |
python | pytorch__pytorch | test/distributed/_composable/test_checkpoint.py | {
"start": 2848,
"end": 11220
} | class ____(TestCase):
def _get_graph_size(self, out: torch.Tensor) -> int:
q = deque([out.grad_fn])
num_functions = 0
while len(q):
fn = q.pop()
num_functions += 1
for next_fn, _ in fn.next_functions:
if next_fn:
q.appen... | TestCheckpoint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.