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 | google__jax | jax/_src/custom_derivatives.py | {
"start": 45149,
"end": 54515
} | class ____(core.Primitive):
multiple_results = True
def bind(self, *args, **params):
return self._true_bind(*args, **params)
def bind_with_trace(self, trace, args, params):
fun, fwd, bwd, tracers = args[0], args[1], args[2], args[3:]
return trace.process_custom_vjp_call(self, fun, fwd, bwd, tracers,... | CustomVJPCallPrimitive |
python | fabric__fabric | fabric/testing/base.py | {
"start": 980,
"end": 2370
} | class ____:
"""
Data record specifying params of a command execution to mock/expect.
:param str cmd:
Command string to expect. If not given, no expectations about the
command executed will be set up. Default: ``None``.
:param bytes out: Data yielded as remote stdout. Default: ``b""``.
... | Command |
python | mlflow__mlflow | mlflow/entities/logged_model_tag.py | {
"start": 104,
"end": 850
} | class ____(_MlflowObject):
"""Tag object associated with a Model."""
def __init__(self, key, value):
self._key = key
self._value = value
def __eq__(self, other):
if type(other) is type(self):
# TODO deep equality here?
return self.__dict__ == other.__dict__
... | LoggedModelTag |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 663206,
"end": 663645
} | class ____(sgqlc.types.Type):
"""A funding platform link for a repository."""
__schema__ = github_schema
__field_names__ = ("platform", "url")
platform = sgqlc.types.Field(sgqlc.types.non_null(FundingPlatform), graphql_name="platform")
"""The funding platform this link is for."""
url = sgqlc.t... | FundingLink |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-self-discover/llama_index/packs/self_discover/base.py | {
"start": 6436,
"end": 6567
} | class ____(Event):
"""Event to create reasoning structure."""
task: str
reasoning_structure: str
| ReasoningStructureEvent |
python | Pylons__pyramid | src/pyramid/path.py | {
"start": 2922,
"end": 3851
} | class ____:
def __init__(self, package=CALLER_PACKAGE):
if package in (None, CALLER_PACKAGE):
self.package = package
else:
if isinstance(package, str):
try:
__import__(package)
except ImportError:
raise V... | Resolver |
python | django__django | tests/messages_tests/test_api.py | {
"start": 1752,
"end": 2016
} | class ____(ApiTests):
"""
add_message() should use ducktyping to allow request wrappers such as the
one in Django REST framework.
"""
def setUp(self):
super().setUp()
self.request = CustomRequest(self.request)
| CustomRequestApiTests |
python | dateutil__dateutil | tests/test_parser.py | {
"start": 15165,
"end": 17234
} | class ____(object):
def assert_equal_same_tz(self, dt1, dt2):
assert dt1 == dt2
assert dt1.tzinfo is dt2.tzinfo
def test_tzinfo_dict_could_return_none(self):
dstr = "2017-02-03 12:40 BRST"
result = parse(dstr, tzinfos={"BRST": None})
expected = datetime(2017, 2, 3, 12, 4... | TestTzinfoInputTypes |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/model_tests/model_handler.py | {
"start": 9854,
"end": 12622
} | class ____(_ModelHandlerBase):
"""Runs a model in TF1."""
@property
def meta_graph(self) -> meta_graph_pb2.MetaGraphDef:
return load_meta_graph(
saved_model_dir=self.model_config.saved_model_dir,
saved_model_tags=self.model_config.saved_model_tags,
saved_model_signature_key=self.model... | ModelHandlerV1 |
python | jazzband__django-model-utils | model_utils/managers.py | {
"start": 12399,
"end": 12503
} | class ____(QueryManagerMixin[ModelT], models.Manager[ModelT]): # type: ignore[misc]
pass
| QueryManager |
python | spack__spack | lib/spack/spack/new_installer.py | {
"start": 8498,
"end": 17415
} | class ____:
"""Manages the installation prefix during overwrite installations."""
def __init__(self, prefix: str, overwrite: bool, keep_prefix: bool = False) -> None:
"""Initialize the prefix pivoter.
Args:
prefix: The installation prefix path
overwrite: Whether to allo... | PrefixPivoter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format25.py | {
"start": 315,
"end": 1580
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format25.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 83778,
"end": 88572
} | class ____(fixtures.MappedTest):
"""Pending entities that are orphans"""
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"user_id",
Integer,
primary_key=True,
test_ne... | PendingOrphanTestSingleLevel |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/redshift_data.py | {
"start": 1552,
"end": 10854
} | class ____(AwsBaseOperator[RedshiftDataHook]):
"""
Executes SQL Statements against an Amazon Redshift cluster using Redshift Data.
... see also::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:RedshiftDataOperator`
:param database: the ... | RedshiftDataOperator |
python | astropy__astropy | astropy/coordinates/name_resolve.py | {
"start": 798,
"end": 1134
} | class ____(ScienceState):
"""
The URL(s) to Sesame's web-queryable database.
"""
_value = [
"https://cds.unistra.fr/cgi-bin/nph-sesame/",
"http://vizier.cfa.harvard.edu/viz-bin/nph-sesame/",
]
@classmethod
def validate(cls, value):
# TODO: Implement me
retur... | sesame_url |
python | pallets__click | examples/validation/validation.py | {
"start": 219,
"end": 1407
} | class ____(click.ParamType):
name = "url"
def convert(self, value, param, ctx):
if not isinstance(value, tuple):
value = urlparse.urlparse(value)
if value.scheme not in ("http", "https"):
self.fail(
f"invalid URL scheme ({value.scheme}). Only ... | URL |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_mixed_precision.py | {
"start": 16489,
"end": 26301
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(1)
def test_float16_on_one_submodule(self):
x = torch.zeros(2, 100, device=device_type)
# Subtest 1: use fp16 on the second child submodule -- does not require
# any addit... | TestFullyShardMixedPrecisionCasts |
python | openai__openai-python | src/openai/types/responses/response_error_event.py | {
"start": 223,
"end": 576
} | class ____(BaseModel):
code: Optional[str] = None
"""The error code."""
message: str
"""The error message."""
param: Optional[str] = None
"""The error parameter."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["error"]
"""The type of the event. ... | ResponseErrorEvent |
python | pdm-project__pdm | src/pdm/installers/synchronizers.py | {
"start": 599,
"end": 10805
} | class ____(BaseSynchronizer):
def install_candidate(self, key: str, progress: Progress) -> Candidate:
"""Install candidate"""
can = self.candidates[key]
job = progress.add_task(f"Installing {can.format()}...", text="", total=None)
can.prepare(self.environment, RichProgressReporter(pr... | Synchronizer |
python | getsentry__sentry | src/sentry/utils/datastructures.py | {
"start": 77,
"end": 1785
} | class ____(MutableMapping):
"""\
An associative data structure in which the ``(key, value)`` pairs form a
one-to-one correspondence in both directions.
For example, when ``(a, b)`` is added to the mapping, ``b`` can be found
when ``a`` is used as a key, and ``a`` can *also* be found when ``b`` is
... | BidirectionalMapping |
python | mahmoud__boltons | boltons/socketutils.py | {
"start": 26146,
"end": 28230
} | class ____:
"""
Reads and writes using the netstring protocol.
More info: https://en.wikipedia.org/wiki/Netstring
Even more info: http://cr.yp.to/proto/netstrings.txt
"""
def __init__(self, sock, timeout=DEFAULT_TIMEOUT, maxsize=DEFAULT_MAXSIZE):
self.bsock = BufferedSocket(sock)
... | NetstringSocket |
python | walkccc__LeetCode | solutions/2507. Smallest Value After Replacing With Sum of Prime Factors/2507.py | {
"start": 0,
"end": 355
} | class ____:
def smallestValue(self, n: int) -> int:
def getPrimeSum(n: int) -> int:
primeSum = 0
for i in range(2, n + 1):
while n % i == 0:
n //= i
primeSum += i
return primeSum
primeSum = getPrimeSum(n)
while n != primeSum:
n = primeSum
primeSum... | Solution |
python | django__django | tests/test_runner_apps/sample/tests_sample.py | {
"start": 361,
"end": 551
} | class ____(SimpleTestCase):
# Z is used to trick this test case to appear after Vanilla in default
# suite
def test_sample(self):
self.assertEqual(1, 1)
| TestZimpleTestCase |
python | getsentry__sentry | tests/sentry/workflow_engine/tasks/test_delayed_workflows.py | {
"start": 985,
"end": 7159
} | class ____(BaseWorkflowTest, BaseEventFrequencyPercentTest):
def setUp(self) -> None:
super().setUp()
self.workflow1, self.workflow1_if_dcgs = self.create_project_event_freq_workflow(
self.project, self.environment, has_when_slow_condition=True
)
self.workflow2, self.wor... | TestDelayedWorkflowTaskBase |
python | pytorch__pytorch | torch/_dynamo/symbolic_convert.py | {
"start": 8089,
"end": 10742
} | class ____:
"""
SpeculationLog replaces the prior copy_graphstate/restore_graphstate
checkpointing. Rather than saving/restoring state, we restart the
dynamo conversion process over from the beginning -- but when we
hit the start of the speculation that failed, we instead generate
a graph break... | SpeculationLog |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 19600,
"end": 20024
} | class ____(LocalizableStreamlitException):
"""Exception Raised when a time string argument is passed that cannot be parsed."""
def __init__(self, time_string: str) -> None:
super().__init__(
"Time string doesn't look right. It should be formatted as"
"`'1d2h34m'` or `2 days`, fo... | StreamlitBadTimeStringError |
python | walkccc__LeetCode | solutions/364. Nested List Weight Sum II/364.py | {
"start": 0,
"end": 402
} | class ____:
def depthSumInverse(self, nestedList: list[NestedInteger]) -> int:
ans = 0
prevSum = 0
q = collections.deque(nestedList)
while q:
for _ in range(len(q)):
ni = q.popleft()
if ni.isInteger():
prevSum += ni.getInteger()
else:
for nextNi in ni... | Solution |
python | PyCQA__pylint | tests/functional/a/access/access_to_protected_members.py | {
"start": 5481,
"end": 7340
} | class ____:
"""Test for GitHub issue 3066
Accessing of attributes/methods of inner and outer classes
https://github.com/pylint-dev/pylint/issues/3066"""
attr = 0
_attr = 1
@staticmethod
def _bar(i):
"""Docstring."""
@staticmethod
def foobar(i):
"""Test access from ... | Issue3066 |
python | encode__django-rest-framework | tests/test_filters.py | {
"start": 603,
"end": 1583
} | class ____(SimpleTestCase):
def test_keep_quoted_together_regardless_of_commas(self):
assert ['hello, world'] == list(filters.search_smart_split('"hello, world"'))
def test_strips_commas_around_quoted(self):
assert ['hello, world'] == list(filters.search_smart_split(',,"hello, world"'))
... | SearchSplitTests |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops_test.py | {
"start": 27577,
"end": 36449
} | class ____(test_util.TensorFlowTestCase):
# TODO(aselle): Test more types before exposing new division operators.
def intTestData(self):
nums = np.arange(-10, 10, 1).reshape(20, 1)
divs = np.arange(-3, 4, 2).reshape(1, 4)
return nums, divs
def floatTestData(self):
nums = np.arange(-10, 10, .25).... | DivAndModTest |
python | huggingface__transformers | src/transformers/models/qwen2_moe/modular_qwen2_moe.py | {
"start": 6703,
"end": 6968
} | class ____(MixtralPreTrainedModel):
_can_record_outputs = {
"router_logits": OutputRecorder(Qwen2MoeTopKRouter, index=0),
"hidden_states": Qwen2MoeDecoderLayer,
"attentions": Qwen2MoeAttention,
}
@auto_docstring
| Qwen2MoePreTrainedModel |
python | huggingface__transformers | src/transformers/models/sam/configuration_sam.py | {
"start": 780,
"end": 2838
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SamPromptEncoder`]. The [`SamPromptEncoder`]
module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield
a similar configuration to that of the SAM-... | SamPromptEncoderConfig |
python | getsentry__sentry | src/sentry/seer/similarity/utils.py | {
"start": 3338,
"end": 3644
} | class ____(StrEnum):
INGEST = "ingest"
BACKFILL = "backfill"
DELETION = "deletion"
SIMILAR_ISSUES_TAB = "similar_issues_tab"
def _get_value_if_exists(exception_value: Mapping[str, Any]) -> str:
return exception_value["values"][0] if exception_value.get("values") else ""
| ReferrerOptions |
python | doocs__leetcode | solution/2500-2599/2572.Count the Number of Square-Free Subsets/Solution.py | {
"start": 0,
"end": 729
} | class ____:
def squareFreeSubsets(self, nums: List[int]) -> int:
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
cnt = Counter(nums)
mod = 10**9 + 7
n = len(primes)
f = [0] * (1 << n)
f[0] = pow(2, cnt[1])
for x in range(2, 31):
if cnt[x] == 0 or x %... | Solution |
python | spyder-ide__spyder | spyder/plugins/profiler/widgets/main_widget.py | {
"start": 1408,
"end": 1503
} | class ____:
Locals = 'locals_section'
Other = "other_section"
| ProfilerContextMenuSections |
python | google__jax | tests/hijax_test.py | {
"start": 1645,
"end": 4493
} | class ____(HiType):
shape: tuple[int, int]
# how to lower to (lo)jax types
def lo_ty(self) -> list[ShapedArray]:
m, k = self.shape
return [ShapedArray((m, k), jnp.dtype('int8')),
ShapedArray((m, ), jnp.dtype('float32'))]
# these next two are essentially the pytree interface
def lower_val... | QArrayTy |
python | PrefectHQ__prefect | tests/server/models/test_artifacts.py | {
"start": 13790,
"end": 19289
} | class ____:
@pytest.fixture
async def artifacts(self, session, flow_run, task_run):
artifacts = [
schemas.core.Artifact(
key="key-1",
data=1,
type="markdown",
flow_run_id=flow_run.id,
description="Some info about... | TestReadLatestArtifacts |
python | google__jax | jax/_src/pallas/mosaic_gpu/pipeline.py | {
"start": 17247,
"end": 40303
} | class ____(Protocol):
"""Protocol for a warp specialized pipeline."""
def __call__(
self, *gmem_refs: Any, allocations: Any | None = None,
) -> None:
...
def get_allocations(self, *gmem_refs: Any) -> Any:
...
def emit_pipeline_warp_specialized(
body: Callable[..., None],
*,
grid: pa... | WarpSpecializedPipeline |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 2800,
"end": 3377
} | class ____(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:... | Data2VecVisionDropPath |
python | pandas-dev__pandas | pandas/tests/io/test_pickle.py | {
"start": 6121,
"end": 11211
} | class ____:
_extension_to_compression = icom.extension_to_compression
def compress_file(self, src_path, dest_path, compression):
if compression is None:
shutil.copyfile(src_path, dest_path)
return
if compression == "gzip":
f = gzip.open(dest_path, "w")
... | TestCompression |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 8382,
"end": 8970
} | class ____(ConcreteTemplate):
cases = list(integer_binop_cases)
# Ensure that float32 ** int doesn't go through DP computations
cases += [signature(types.float32, types.float32, op)
for op in (types.int32, types.int64, types.uint64)]
cases += [signature(types.float64, types.float64, op)
... | BinOpPower |
python | PyCQA__isort | isort/main.py | {
"start": 1633,
"end": 47521
} | class ____:
def __init__(self, incorrectly_sorted: bool, skipped: bool, supported_encoding: bool) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
self.supported_encoding = supported_encoding
def sort_imports(
file_name: str,
config: Config,
check: b... | SortAttempt |
python | python-excel__xlrd | xlrd/book.py | {
"start": 9265,
"end": 57527
} | class ____(BaseObject):
"""
Contents of a "workbook".
.. warning::
You should not instantiate this class yourself. You use the :class:`Book`
object that was returned when you called :func:`~xlrd.open_workbook`.
"""
#: The number of worksheets present in the workbook file.
#: This ... | Book |
python | pypa__setuptools | setuptools/_vendor/wheel/wheelfile.py | {
"start": 1348,
"end": 8411
} | class ____(ZipFile):
"""A ZipFile derivative class that also reads SHA-256 hashes from
.dist-info/RECORD and checks any read files against those.
"""
_default_algorithm = hashlib.sha256
def __init__(
self,
file: StrPath,
mode: Literal["r", "w", "x", "a"] = "r",
comp... | WheelFile |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_build.py | {
"start": 3420,
"end": 12202
} | class ____:
@mock.patch(CLOUD_BUILD_HOOK_PATH)
def test_cancel_build(self, mock_hook):
mock_hook.return_value.cancel_build.return_value = Build()
operator = CloudBuildCancelBuildOperator(id_=TRIGGER_ID, task_id="id")
operator.execute(context=mock.MagicMock())
mock_hook.assert_c... | TestCloudBuildOperator |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 22512,
"end": 26126
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | BridgeTowerCrossAttention |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 7022,
"end": 7456
} | class ____(BaseModel):
"""
Schema for updating TaskInstance to a up_for_reschedule state.
"""
model_config = ConfigDict(
extra="forbid",
)
state: Annotated[Literal["up_for_reschedule"] | None, Field(title="State")] = "up_for_reschedule"
reschedule_date: Annotated[AwareDatetime, Fiel... | TIRescheduleStatePayload |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 25462,
"end": 29627
} | class ____(TimeSeriesBaseModel, ObjectBaseModel):
name: str = Field(
default_factory=lambda: generate_slug(2), examples=["my-task-run"]
)
flow_run_id: Optional[UUID] = Field(
default=None, description="The flow run id of the task run."
)
task_key: str = Field(
default=..., de... | TaskRun |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 69260,
"end": 71619
} | class ____(SetupData):
def test_fail_replace_column(self, table_types):
"""Raise exception when trying to replace column via table.columns object"""
self._setup(table_types)
t = table_types.Table([self.a, self.b])
with pytest.raises(
ValueError,
match=r"Canno... | TestReplaceColumn |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 46463,
"end": 46657
} | class ____(BaseModel, extra="forbid"):
"""
ID-based filtering condition
"""
has_id: List["ExtendedPointId"] = Field(..., description="ID-based filtering condition")
| HasIdCondition |
python | getsentry__sentry | src/sentry/integrations/slack/webhooks/base.py | {
"start": 1572,
"end": 4726
} | class ____(Endpoint, abc.ABC):
slack_request_class = SlackDMRequest
def post_dispatcher(self, request: SlackDMRequest) -> Response:
"""
All Slack commands are handled by this endpoint. This block just
validates the request and dispatches it to the right handler.
"""
cmd_... | SlackDMEndpoint |
python | pypa__warehouse | tests/common/db/banners.py | {
"start": 137,
"end": 419
} | class ____(WarehouseFactory):
class Meta:
model = Banner
name = factory.Faker("word")
text = factory.Faker("sentence")
link_url = factory.Faker("uri")
link_label = factory.Faker("word")
active = True
end = factory.Faker("future_date")
| BannerFactory |
python | plotly__plotly.py | plotly/graph_objs/histogram/_marker.py | {
"start": 233,
"end": 25231
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram"
_path_str = "histogram.marker"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorbar",
"colorscale",
"colorsrc",
... | Marker |
python | kamyu104__LeetCode-Solutions | Python/minimum-size-subarray-sum.py | {
"start": 565,
"end": 1566
} | class ____(object):
# @param {integer} s
# @param {integer[]} nums
# @return {integer}
def minSubArrayLen(self, s, nums):
min_size = float("inf")
sum_from_start = [n for n in nums]
for i in xrange(len(sum_from_start) - 1):
sum_from_start[i + 1] += sum_from_start[i]
... | Solution2 |
python | coleifer__peewee | peewee.py | {
"start": 144983,
"end": 145763
} | class ____(object):
def __init__(self, db):
self.db = db
def __call__(self, fn):
@wraps(fn)
def inner(*args, **kwargs):
with _manual(self.db):
return fn(*args, **kwargs)
return inner
def __enter__(self):
top = self.db.top_transaction()
... | _manual |
python | ray-project__ray | python/ray/serve/_private/logging_utils.py | {
"start": 18350,
"end": 19041
} | class ____:
"""
Context manager to manage logging behaviors within a particular block, such as:
1) Overriding logging level
Source (python3 official documentation)
https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-manager-for-selective-logging # noqa: E501
"""
def __ini... | LoggingContext |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 20807,
"end": 21059
} | class ____(graphene.ObjectType):
class Meta:
name = "EventConnection"
events = non_null_list(GrapheneDagsterRunEvent)
cursor = graphene.NonNull(graphene.String)
hasMore = graphene.NonNull(graphene.Boolean)
| GrapheneEventConnection |
python | django__django | tests/admin_widgets/test_autocomplete_widget.py | {
"start": 311,
"end": 769
} | class ____(forms.ModelForm):
class Meta:
model = Album
fields = ["band", "featuring"]
widgets = {
"band": AutocompleteSelect(
Album._meta.get_field("band"),
admin.site,
attrs={"class": "my-class"},
),
"featur... | AlbumForm |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/progress_bar/formatters.py | {
"start": 7564,
"end": 8458
} | class ____(Formatter):
"""
Display the time left.
"""
template = HTML("<time-left>{time_left}</time-left>")
unknown = "?:??:??"
def format(
self,
progress_bar: ProgressBar,
progress: ProgressBarCounter[object],
width: int,
) -> AnyFormattedText:
time... | TimeLeft |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/test_basic.py | {
"start": 204,
"end": 1312
} | class ____(unittest.TestCase):
def testNone(self):
mg = modulegraph.ModuleGraph()
# empty packagepath
m = DummyModule(None)
sub_ms = []
for sm in mg._find_all_submodules(m):
sub_ms.append(sm)
self.assertEqual(sub_ms, [])
def testSimple(self):
... | FindAllSubmodulesTestCase |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared_tests/test_record.py | {
"start": 8596,
"end": 8654
} | class ____:
name: str
age: int
@record_custom
| Person |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_repository_commits.py | {
"start": 170,
"end": 1028
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user)
org = self.create_organization(owner=self.user, name="baz")
repo = Repository.objects.create(name="example", organization_id=org.id)
commit = Commit.objects.create(repository_id=repo.id, organizati... | OrganizationRepositoryCommitsTest |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 56808,
"end": 57999
} | class ____(SpeechT5PreTrainedModel):
"""
Wrapper around SpeechT5Encoder that applies SpeechT5SpeechEncoderPrenet to convert the audio waveform data to
hidden features.
"""
def __init__(self, config: SpeechT5Config):
super().__init__(config)
self.prenet = SpeechT5SpeechEncoderPrenet(... | SpeechT5EncoderWithSpeechPrenet |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor6.py | {
"start": 1486,
"end": 1772
} | class ____(Model):
pass
reveal_type(ForeignKey(Author, null=False), expected_text="ForeignKey[Author]")
reveal_type(ForeignKey(Author, null=True), expected_text="ForeignKey[Author | None]")
_T3 = TypeVar("_T3")
_T4 = TypeVar("_T4")
_S1 = TypeVar("_S1")
_S2 = TypeVar("_S2")
| Author |
python | huggingface__transformers | src/transformers/models/layoutxlm/tokenization_layoutxlm.py | {
"start": 8713,
"end": 47283
} | class ____(TokenizersBackend):
"""
Construct a "fast" LayoutXLM tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
[`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
[BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
This tokeniz... | LayoutXLMTokenizer |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 905,
"end": 1070
} | class ____(Web3Exception, ValueError):
"""
A web3.py exception wrapper for `ValueError`, for better control over
exception handling.
"""
| Web3ValueError |
python | huggingface__transformers | tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py | {
"start": 25396,
"end": 35836
} | class ____(unittest.TestCase):
# test that non-standard generation works
# test generation of: SeamlessM4Tv2Model, SeamlessM4Tv2ForSpeechToSpeech, SeamlessM4Tv2ForSpeechToText, SeamlessM4Tv2ForTextToSpeech
def setUp(self):
self.speech_model_tester = SeamlessM4Tv2ModelTester(self, input_modality="sp... | SeamlessM4Tv2GenerationTest |
python | tiangolo__fastapi | docs_src/generate_clients/tutorial001.py | {
"start": 159,
"end": 519
} | class ____(BaseModel):
message: str
@app.post("/items/", response_model=ResponseMessage)
async def create_item(item: Item):
return {"message": "item received"}
@app.get("/items/", response_model=List[Item])
async def get_items():
return [
{"name": "Plumbus", "price": 3},
{"name": "Portal... | ResponseMessage |
python | pytransitions__transitions | transitions/extensions/factory.py | {
"start": 3469,
"end": 3658
} | class ____(GraphMachine, AsyncMachine):
"""A machine that supports asynchronous event/callback processing with Graphviz support."""
transition_cls = AsyncTransition
| AsyncGraphMachine |
python | streamlit__streamlit | lib/streamlit/elements/arrow.py | {
"start": 5673,
"end": 9726
} | class ____:
"""DataframeSelectionSerde is used to serialize and deserialize the dataframe selection state."""
def deserialize(self, ui_value: str | None) -> DataframeState:
empty_selection_state: DataframeState = {
"selection": {
"rows": [],
"columns": [],
... | DataframeSelectionSerde |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 38362,
"end": 41702
} | class ____(InvariantUnitTestSetup):
def setup_method(self):
super().setup_method()
self.q[1, 1] = np.nan
def test_nanmax(self):
self.check(np.nanmax)
def test_nanmin(self):
self.check(np.nanmin)
def test_nanargmin(self):
out = np.nanargmin(self.q)
expec... | TestNanFunctions |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 4995,
"end": 11768
} | class ____:
stance: str = "default"
skip_guard_eval_unsafe: bool = False
backend: Union[str, Callable[..., Any], None] = None
_stance = DynamoStance()
def _set_stance(stance: DynamoStance) -> DynamoStance:
global _stance
from torch._C._dynamo.eval_frame import get_eval_frame_callback
callb... | DynamoStance |
python | doocs__leetcode | solution/2400-2499/2418.Sort the People/Solution2.py | {
"start": 0,
"end": 172
} | class ____:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
return [name for _, name in sorted(zip(heights, names), reverse=True)]
| Solution |
python | dagster-io__dagster | conftest.py | {
"start": 491,
"end": 5344
} | class ____:
scope: str
name: str
@lru_cache
def buildkite_quarantined_tests(annotation) -> set[TestId]:
quarantined_tests = set()
if os.getenv("BUILDKITE") or os.getenv("LOCAL_BUILDKITE_QUARANTINE"):
# Run our full test suite - warts and all - on the release branch
if os.getenv("BUILD... | TestId |
python | huggingface__transformers | src/transformers/models/m2m_100/modeling_m2m_100.py | {
"start": 2525,
"end": 3015
} | class ____(nn.Embedding):
"""
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
super().__init__(num_embeddings, embedding_dim, padding_idx)
... | M2M100ScaledWordEmbedding |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_dag.py | {
"start": 24338,
"end": 29268
} | class ____:
def test_cycle_empty(self):
# test empty
dag = DAG("dag", schedule=None, start_date=DEFAULT_DATE, default_args={"owner": "owner1"})
assert not dag.check_cycle()
def test_cycle_single_task(self):
# test single task
dag = DAG("dag", schedule=None, start_date=D... | TestCycleTester |
python | MongoEngine__mongoengine | tests/queryset/test_queryset.py | {
"start": 1069,
"end": 198039
} | class ____(unittest.TestCase):
def setUp(self):
connect(db="mongoenginetest")
connect(db="mongoenginetest2", alias="test2")
class PersonMeta(EmbeddedDocument):
weight = IntField()
class Person(Document):
name = StringField()
age = IntField()
... | TestQueryset |
python | huggingface__transformers | examples/pytorch/semantic-segmentation/run_semantic_segmentation.py | {
"start": 4821,
"end": 17145
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
default="nvidia/mit-b0",
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},
)
config_name: Optiona... | ModelArguments |
python | RaRe-Technologies__gensim | gensim/examples/dmlcz/dmlcorpus.py | {
"start": 433,
"end": 2266
} | class ____:
"""
DmlConfig contains parameters necessary for the abstraction of a 'corpus of
articles' (see the `DmlCorpus` class).
Articles may come from different sources (=different locations on disk/network,
different file formats etc.), so the main purpose of DmlConfig is to keep all
source... | DmlConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-surveycto/source_surveycto/helpers.py | {
"start": 351,
"end": 2329
} | class ____(object):
@staticmethod
def _base64_encode(string: str) -> str:
return base64.b64encode(string.encode("ascii")).decode("ascii")
@staticmethod
def call_survey_cto(config, form_id):
server_name = config["server_name"]
start_date = config["start_date"]
user_name_p... | Helpers |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 61628,
"end": 62522
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = postgresql.dialect()
@testing.combinations(
(postgresql.TIME(), "TIME WITHOUT TIME ZONE"),
(postgresql.TIME(precision=5), "TIME(5) WITHOUT TIME ZONE"),
(
postgresql.TIME(timezone=True, precision=5),
... | TimePrecisionCompileTest |
python | networkx__networkx | networkx/classes/graph.py | {
"start": 596,
"end": 1492
} | class ____:
"""Data Descriptor class for _adj that resets ``adj`` cached_property when needed
This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
``G._adj`` is set to a new value.
This object sits on a class and ensures that any instance of that
class clears its cached pro... | _CachedPropertyResetterAdj |
python | mlflow__mlflow | mlflow/deployments/plugin_manager.py | {
"start": 659,
"end": 2839
} | class ____(abc.ABC):
"""
Abstract class defining a entrypoint based plugin registration.
This class allows the registration of a function or class to provide an implementation
for a given key/name. Implementations declared though the entrypoints can be automatically
registered through the `register... | PluginManager |
python | pytest-dev__pytest | src/_pytest/capture.py | {
"start": 17075,
"end": 17718
} | class ____(FDCaptureBase[bytes]):
"""Capture IO to/from a given OS-level file descriptor.
snap() produces `bytes`.
"""
EMPTY_BUFFER = b""
def snap(self) -> bytes:
self._assert_state("snap", ("started", "suspended"))
self.tmpfile.seek(0)
res = self.tmpfile.buffer.read()
... | FDCaptureBinary |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1010845,
"end": 1011443
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnlockLockable"""
__schema__ = github_schema
__field_names__ = ("actor", "client_mutation_id", "unlocked_record")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
client_muta... | UnlockLockablePayload |
python | kamyu104__LeetCode-Solutions | Python/even-odd-tree.py | {
"start": 221,
"end": 1006
} | class ____(object):
def isEvenOddTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
q = [root]
is_odd = False
while q:
new_q = []
prev = None
for node in q:
if is_odd:
if node.val... | Solution |
python | getsentry__sentry-python | tests/integrations/beam/test_beam.py | {
"start": 1399,
"end": 3941
} | class ____(DoFn):
def process(self, x, timestamp=DoFn.TimestampParam, wx=DoFn.WindowParam):
if isinstance(timestamp, _DoFnParam) or isinstance(wx, _DoFnParam):
raise Exception("Bad instance")
if x:
1 / 0
yield True
def fail(x):
if x:
1 / 0
return [Tr... | PlaceHolderFunc |
python | rushter__MLAlgorithms | mla/neuralnet/layers/convnet.py | {
"start": 145,
"end": 2617
} | class ____(Layer, ParamMixin):
def __init__(
self,
n_filters=8,
filter_shape=(3, 3),
padding=(0, 0),
stride=(1, 1),
parameters=None,
):
"""A 2D convolutional layer.
Input shape: (n_images, n_channels, height, width)
Parameters
----... | Convolution |
python | miyuchina__mistletoe | mistletoe/html_renderer.py | {
"start": 313,
"end": 9612
} | class ____(BaseRenderer):
"""
HTML renderer class.
See mistletoe.base_renderer module for more info.
"""
def __init__(
self,
*extras,
html_escape_double_quotes=False,
html_escape_single_quotes=False,
process_html_tokens=True,
**kwargs
):
"... | HtmlRenderer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enum13.py | {
"start": 340,
"end": 572
} | class ____(StrEnum):
MEMBER_1 = "a"
MEMBER_2 = "b"
s1: Literal["a"] = StrEnum1.MEMBER_1.value
# This should generate an error.
s2: Literal["b"] = StrEnum1.MEMBER_1.value
s3: LiteralString = StrEnum1.MEMBER_1.value
| StrEnum1 |
python | pytest-dev__pytest | src/_pytest/terminal.py | {
"start": 1853,
"end": 2904
} | class ____(argparse.Action):
"""A modified copy of the argparse count action which counts down and updates
the legacy quiet attribute at the same time.
Used to unify verbosity handling.
"""
def __init__(
self,
option_strings: Sequence[str],
dest: str,
default: objec... | MoreQuietAction |
python | huggingface__transformers | src/transformers/models/gpt2/modeling_gpt2.py | {
"start": 21669,
"end": 24019
} | class ____(PreTrainedModel):
config: GPT2Config
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_no_split_modules = ["GPT2Block"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_supports_attention_backend = True
... | GPT2PreTrainedModel |
python | streamlit__streamlit | lib/tests/streamlit/connections/base_connection_test.py | {
"start": 1192,
"end": 5079
} | class ____(unittest.TestCase):
def setUp(self) -> None:
# st.secrets modifies os.environ, so we save it here and
# restore in tearDown.
self._prev_environ = dict(os.environ)
def tearDown(self) -> None:
os.environ.clear()
os.environ.update(self._prev_environ)
st.s... | BaseConnectionDefaultMethodTests |
python | docker__docker-py | tests/integration/models_services_test.py | {
"start": 195,
"end": 13200
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
client = docker.from_env(version=TEST_API_VERSION)
helpers.force_leave_swarm(client)
client.swarm.init('127.0.0.1', listen_addr=helpers.swarm_listen_addr())
@classmethod
def tearDownClass(cls):
helpers.forc... | ServiceTest |
python | geekcomputers__Python | Image-watermarker/watermark.py | {
"start": 116,
"end": 1379
} | class ____:
def __init__(self):
pass
def add_text_watermark(
self, image, text, text_color, font_style, font_size, position=(0, 0)
):
font = ImageFont.truetype(font_style, font_size)
draw = ImageDraw.Draw(image)
draw.text(position, text, fill=text_color, font=font)
... | Watermark |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 3402,
"end": 4011
} | class ____(nn.Embedding):
"""
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
super().__init__(num_embeddings, embedding_dim, padding_idx)
... | BigBirdPegasusScaledWordEmbedding |
python | realpython__materials | game-of-life-python/source_code_step_4/rplife/views.py | {
"start": 73,
"end": 902
} | class ____:
def __init__(self, pattern, gen=10, frame_rate=7, bbox=(0, 0, 20, 20)):
self.pattern = pattern
self.gen = gen
self.frame_rate = frame_rate
self.bbox = bbox
def show(self):
curses.wrapper(self._draw)
def _draw(self, screen):
current_grid = LifeGri... | CursesView |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 58186,
"end": 61376
} | class ____(ClapPreTrainedModel):
config: ClapAudioConfig
main_input_name = "input_features"
input_modalities = "audio"
def __init__(self, config: ClapAudioConfig):
super().__init__(config)
self.audio_encoder = ClapAudioEncoder(config)
# Initialize weights and apply final process... | ClapAudioModel |
python | spack__spack | lib/spack/spack/vendor/jinja2/bccache.py | {
"start": 1144,
"end": 3172
} | class ____:
"""Buckets are used to store the bytecode for one template. It's created
and initialized by the bytecode cache and passed to the loading functions.
The buckets get an internal checksum from the cache assigned and use this
to automatically reject outdated cache material. Individual bytecod... | Bucket |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 103453,
"end": 110839
} | class ____:
rgbAliceBlue = 16775408 # from enum XlRgbColor
rgbAntiqueWhite = 14150650 # from enum XlRgbColor
rgbAqua = 16776960 # from enum XlRgbColor
rgbAquamarine = 13959039 # from enum XlRgbColor
rgbAzure = 16777200 # from enum XlRgbColor
rgbBeige = 14480885 # from enum XlRgbColor
r... | RgbColor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.