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 | ipython__ipython | tests/test_completerlib.py | {
"start": 776,
"end": 2995
} | class ____(unittest.TestCase):
files = ["aao.py", "a.py", "b.py", "aao.txt"]
dirs = ["adir/", "bdir/"]
def setUp(self):
self.BASETESTDIR = tempfile.mkdtemp()
for fil in self.files:
with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile:
sfile.writ... | Test_magic_run_completer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/test/utils.py | {
"start": 1189,
"end": 1244
} | class ____(TypedDict):
key: str
value: str
| GqlTag |
python | pypa__warehouse | tests/unit/cache/test_http.py | {
"start": 3376,
"end": 8446
} | class ____:
def test_has_last_modified(self):
response = pretend.stub(
last_modified=pretend.stub(),
status_code=200,
etag=None,
conditional_response=False,
app_iter=iter([b"foo"]),
content_length=None,
)
handler = prete... | TestConditionalHTTPTween |
python | mwaskom__seaborn | seaborn/matrix.py | {
"start": 17203,
"end": 25447
} | class ____:
"""Object for drawing tree of similarities between data rows/columns"""
def __init__(self, data, linkage, metric, method, axis, label, rotate):
"""Plot a dendrogram of the relationships between the columns of data
Parameters
----------
data : pandas.DataFrame
... | _DendrogramPlotter |
python | tox-dev__tox | src/tox/execute/pep517_backend.py | {
"start": 712,
"end": 4063
} | class ____(Execute):
"""Executor holding the backend process."""
def __init__(self, colored: bool, cmd: Sequence[str], env: dict[str, str], cwd: Path) -> None: # noqa: FBT001
super().__init__(colored)
self.cmd = cmd
self.env = env
self.cwd = cwd
self._local_execute: tup... | LocalSubProcessPep517Executor |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial004_py39.py | {
"start": 104,
"end": 676
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
"""
Create an item with all the information:
... | Item |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 6849,
"end": 10830
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers... | RTDetrModelOutput |
python | jd__tenacity | tenacity/_utils.py | {
"start": 849,
"end": 3211
} | class ____(typing.Protocol):
"""
Protocol used by utils expecting a logger (eg: before_log).
Compatible with logging, structlog, loguru, etc...
"""
def log(
self, level: int, msg: str, /, *args: typing.Any, **kwargs: typing.Any
) -> typing.Any: ...
def find_ordinal(pos_num: int) -> s... | LoggerProtocol |
python | doocs__leetcode | solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py | {
"start": 0,
"end": 222
} | class ____:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
cnt = Counter()
ans = 0
for w in words:
ans += cnt[w[::-1]]
cnt[w] += 1
return ans
| Solution |
python | great-expectations__great_expectations | tests/integration/fluent/test_integration_datasource.py | {
"start": 20274,
"end": 21736
} | class ____:
datasource: SparkDatasource
dataframe: SparkDataFrame
def _validate_whole_dataframe_batch(
source_and_frame: PandasDataSourceAndFrame | SparkDataSourceAndFrame,
):
my_expectation = gxe.ExpectColumnMeanToBeBetween(
column="column_name", min_value=2.5, max_value=3.5
)
asset =... | SparkDataSourceAndFrame |
python | pytorch__pytorch | torch/_inductor/runtime/autotune_cache.py | {
"start": 3496,
"end": 11174
} | class ____:
configs_hash: str
local_cache: tuple[RemoteCache[JsonDataTy], str] | None = None
remote_cache: tuple[RemoteCache[JsonDataTy], str] | None = None
# Create a AutotuneCache. Returns None if none of the caches can be used.
@staticmethod
def create(
inductor_meta: _InductorMetaTy... | AutotuneCache |
python | google__jax | jax/experimental/key_reuse/_core.py | {
"start": 4228,
"end": 4506
} | class ____(NamedTuple):
in_idx: int
out_idx: int
def __repr__(self):
return f"Forward({self.in_idx}, {self.out_idx})"
# KeyReuseSignature is essentially a frozen set of Source/Sink/Forward
# objects, with a few convenience methods related to key reuse checking.
| Forward |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1535064,
"end": 1535357
} | class ____(sgqlc.types.Type, Node, GitObject):
"""Represents a Git tree."""
__schema__ = github_schema
__field_names__ = ("entries",)
entries = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(TreeEntry)), graphql_name="entries")
"""A list of tree entries."""
| Tree |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/ops.py | {
"start": 4124,
"end": 7694
} | class ____(SyncConfig):
resync_parameters: Optional[dict[str, Any]] = Field(
None,
description=(
"Optional resync parameters to send in the payload to the Fivetran API. You can"
" find an example resync payload here:"
" https://fivetran.com/docs/rest-api/connector... | FivetranResyncConfig |
python | davidhalter__jedi | test/completion/pep0526_variables.py | {
"start": 1245,
"end": 1873
} | class ____(VarClass):
var_class3: typing.ClassVar[int]
def __init__(self):
#? int()
self.var_class3
#? ['var_class1', 'var_class2', 'var_instance1', 'var_class3', 'var_instance2']
VarClass.var_
#? int()
VarClass.var_instance1
#? float()
VarClass.var_instance2
#? str()
VarClass.var_class1
#? by... | VarClass2 |
python | doocs__leetcode | solution/3300-3399/3362.Zero Array Transformation III/Solution.py | {
"start": 0,
"end": 552
} | class ____:
def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int:
queries.sort()
pq = []
d = [0] * (len(nums) + 1)
s = j = 0
for i, x in enumerate(nums):
s += d[i]
while j < len(queries) and queries[j][0] <= i:
heappus... | Solution |
python | ansible__ansible | lib/ansible/module_utils/_internal/_json/_legacy_encoder.py | {
"start": 165,
"end": 1191
} | class ____(_tagless.Encoder):
"""Compatibility wrapper over `legacy` profile JSON encoder to support trust stripping and vault value plaintext conversion."""
def __init__(self, preprocess_unsafe: bool = False, vault_to_text: bool = False, _decode_bytes: bool = False, **kwargs) -> None:
self._decode_byt... | LegacyTargetJSONEncoder |
python | django__django | tests/admin_changelist/admin.py | {
"start": 4235,
"end": 4511
} | class ____(admin.ModelAdmin):
actions = None # prevent ['action_checkbox'] + list(list_display)
list_display = ("origin", "load", "speed", "swallowonetoone")
list_editable = ["load", "speed"]
list_per_page = 3
site.register(Swallow, SwallowAdmin)
| SwallowAdmin |
python | facebook__pyre-check | client/command_arguments.py | {
"start": 8915,
"end": 9138
} | class ____:
paths: Optional[List[Path]] = None
log_identifier: Optional[str] = None
log_results: bool = False
aggregate: bool = False
print_summary: bool = False
@dataclass(frozen=True)
| StatisticsArguments |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_init.py | {
"start": 2983,
"end": 6018
} | class ____(FSDPTestMultiThread):
"""Tests that DTensor parameters are moved to the expected device."""
@property
def world_size(self) -> int:
return 4
@skip_if_lt_x_gpu(1)
def test_move_states_to_device_dtensor_valid(self):
assert self.world_size >= 4, f"{self.world_size}"
... | TestFullyShardDeviceDTensor |
python | python-openxml__python-docx | tests/image/test_jpeg.py | {
"start": 10014,
"end": 13313
} | class ____:
def it_can_construct_from_a_stream_and_offset(
self, _App1Marker__init_, _tiff_from_exif_segment_
):
bytes_ = b"\x00\x42Exif\x00\x00"
marker_code, offset, length = JPEG_MARKER_CODE.APP1, 0, 66
horz_dpi, vert_dpi = 42, 24
stream = StreamReader(io.BytesIO(bytes_... | Describe_App1Marker |
python | ansible__ansible | test/units/_internal/_errors/test_error_utils.py | {
"start": 449,
"end": 722
} | class ____(Exception, _error_utils.ContributesToTaskResult):
@property
def omit_failed_key(self) -> bool:
return True
@property
def result_contribution(self) -> c.Mapping[str, object]:
return dict(unreachable=True)
| _TestContributesUnreachable |
python | tiangolo__fastapi | scripts/people.py | {
"start": 1590,
"end": 1668
} | class ____(BaseModel):
totalCount: int
nodes: list[CommentsNode]
| Replies |
python | django__django | django/contrib/gis/gdal/geometries.py | {
"start": 26735,
"end": 26802
} | class ____(GeometryCollection):
geos_support = False
| MultiSurface |
python | scipy__scipy | scipy/integrate/tests/test_cubature.py | {
"start": 14814,
"end": 31476
} | class ____:
"""
Tests that `cubature` gives the correct answer.
"""
@skip_xp_backends("dask.array",
reason="Dask hangs/takes a long time for some test cases")
@pytest.mark.parametrize("problem", [
# -- f1 --
(
# Function to integrate, like `f(x, *ar... | TestCubatureProblems |
python | getsentry__sentry | tests/sentry/api/serializers/test_organization.py | {
"start": 9527,
"end": 10252
} | class ____(TestCase):
def test_trusted_relay_serializer(self) -> None:
completion_seen = timezone.now()
serializer = OnboardingTasksSerializer()
task = OrganizationOnboardingTask.objects.create(
organization_id=self.organization.id,
task=OnboardingTask.FIRST_PROJECT,
... | TrustedRelaySerializer |
python | PyCQA__pylint | doc/data/messages/m/match-class-bind-self/bad.py | {
"start": 0,
"end": 339
} | class ____:
__match_args__ = ("title", "year")
def __init__(self, title, year):
self.title = title
self.year = year
def func(item: Book):
match item:
case Book(title=str(title)): # [match-class-bind-self]
...
case Book(year=int(year)): # [match-class-bind-sel... | Book |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 86953,
"end": 88178
} | class ____:
def test_func_is_a_flow(self, tmp_path):
flow_code = """
from prefect import flow
@flow
def dog():
return "woof!"
"""
fpath = tmp_path / "f.py"
fpath.write_text(dedent(flow_code))
flow = load_function_and_convert_to_flow(f"{fp... | TestLoadFunctionAndConvertToFlow |
python | keras-team__keras | keras/src/activations/activations_test.py | {
"start": 1283,
"end": 39617
} | class ____(testing.TestCase):
def test_softmax(self):
x = np.random.random((2, 5))
result = activations.softmax(x[np.newaxis, :])[0]
expected = _ref_softmax(x[0])
self.assertAllClose(result[0], expected, rtol=1e-05)
def test_softmax_2d_axis_0(self):
x = np.random.random... | ActivationsTest |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 44532,
"end": 44697
} | class ____(Exception):
"""
Signals cases that should skip FakeTensor caching.
"""
reason: str
@dataclass(frozen=True, slots=True)
| _BypassDispatchCache |
python | eth-brownie__brownie | brownie/exceptions.py | {
"start": 1134,
"end": 1185
} | class ____(Exception):
pass
@final
| UnknownAccount |
python | viewflow__viewflow | tests/json/test_json__nullboolean.py | {
"start": 95,
"end": 223
} | class ____(models.Model):
data = models.JSONField()
nullboolean_field = jsonstore.NullBooleanField()
| NullBooleanFieldModel |
python | scikit-image__scikit-image | src/skimage/measure/fit.py | {
"start": 14726,
"end": 22667
} | class ____(_BaseModel):
"""Total least squares estimator for 2D circles.
The functional model of the circle is::
r**2 = (x - xc)**2 + (y - yc)**2
This estimator minimizes the squared distances from all points to the
circle::
min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) }
... | CircleModel |
python | doocs__leetcode | solution/1900-1999/1918.Kth Smallest Subarray Sum/Solution.py | {
"start": 0,
"end": 458
} | class ____:
def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int:
def f(s):
t = j = 0
cnt = 0
for i, x in enumerate(nums):
t += x
while t > s:
t -= nums[j]
j += 1
cnt += i ... | Solution |
python | ray-project__ray | python/ray/train/error.py | {
"start": 74,
"end": 183
} | class ____(Exception):
"""Indicates a method or function was used outside of a session."""
| SessionMisuseError |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 59154,
"end": 60530
} | class ____(Request):
"""
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
"""
_service = "queues"
_action = "move_task_to_front"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"queue": {"description": "Queu... | MoveTaskToFrontRequest |
python | Textualize__textual | src/textual/widgets/_masked_input.py | {
"start": 649,
"end": 1622
} | class ____(Flag):
"""Misc flags for a single template character definition"""
NONE = 0
"""Empty flags value"""
REQUIRED = auto()
"""Is this character required for validation?"""
SEPARATOR = auto()
"""Is this character a separator?"""
UPPERCASE = auto()
"""Char is forced to be upp... | _CharFlags |
python | docker__docker-py | docker/api/config.py | {
"start": 38,
"end": 2706
} | class ____:
@utils.minimum_version('1.30')
def create_config(self, name, data, labels=None, templating=None):
"""
Create a config
Args:
name (string): Name of the config
data (bytes): Config data to be stored
labels (dict): A mappi... | ConfigApiMixin |
python | celery__celery | celery/utils/collections.py | {
"start": 5723,
"end": 9949
} | class ____(MutableMapping):
"""Key lookup on a sequence of maps."""
key_t = None
changes = None
defaults = None
maps = None
_observers = ()
def __init__(self, *maps, **kwargs):
# type: (*Mapping, **Any) -> None
maps = list(maps or [{}])
self.__dict__.update(
... | ChainMap |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1328488,
"end": 1328686
} | class ____(VegaLiteSchema):
"""TextDirection schema wrapper."""
_schema = {"$ref": "#/definitions/TextDirection"}
def __init__(self, *args):
super().__init__(*args)
| TextDirection |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 4723,
"end": 4887
} | class ____(BaseIntType):
@classmethod
def validate(cls, value: Any) -> None:
cls.validate_int_in_range(value, 0, 18446744073709551615)
| XsdUnsignedLong |
python | mlflow__mlflow | mlflow/entities/assessment_source.py | {
"start": 347,
"end": 3337
} | class ____(_MlflowObject):
"""
Source of an assessment (human, LLM as a judge with GPT-4, etc).
When recording an assessment, MLflow mandates providing a source information
to keep track of how the assessment is conducted.
Args:
source_type: The type of the assessment source. Must be one o... | AssessmentSource |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/atomic_function.py | {
"start": 2746,
"end": 23306
} | class ____(core.AtomicFunction):
"""A Python callable for functions in the TF Runtime.
Provides core functionality for tf.function including:
- automatic lifecycle management of runtime functions
- structured inputs (including captures) and structured outputs
- calls from both eager and graph mode
... | AtomicFunction |
python | Pylons__pyramid | tests/test_location.py | {
"start": 1332,
"end": 1381
} | class ____:
__name__ = __parent__ = None
| Location |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/asyncio/result.py | {
"start": 16744,
"end": 20886
} | class ____(AsyncCommon[_R]):
"""A wrapper for a :class:`_asyncio.AsyncResult` that returns scalar values
rather than :class:`_row.Row` values.
The :class:`_asyncio.AsyncScalarResult` object is acquired by calling the
:meth:`_asyncio.AsyncResult.scalars` method.
Refer to the :class:`_result.ScalarR... | AsyncScalarResult |
python | pypa__pip | tests/unit/test_index.py | {
"start": 11436,
"end": 19030
} | class ____:
@pytest.mark.parametrize(
"allow_all_prereleases, prefer_binary",
[
(False, False),
(False, True),
(True, False),
(True, True),
],
)
def test_create(self, allow_all_prereleases: bool, prefer_binary: bool) -> None:
ta... | TestCandidateEvaluator |
python | keon__algorithms | algorithms/graph/clone_graph.py | {
"start": 782,
"end": 3436
} | class ____:
"""
A node in an undirected graph. Contains a label and a list of neighbouring
nodes (initially empty).
"""
def __init__(self, label):
self.label = label
self.neighbors = []
def shallow_copy(self):
"""
Return a shallow copy of this node (ignoring any... | UndirectedGraphNode |
python | kamyu104__LeetCode-Solutions | Python/armstrong-number.py | {
"start": 33,
"end": 235
} | class ____(object):
def isArmstrong(self, N):
"""
:type N: int
:rtype: bool
"""
n_str = str(N)
return sum(int(i)**len(n_str) for i in n_str) == N
| Solution |
python | numpy__numpy | numpy/f2py/tests/test_crackfortran.py | {
"start": 13050,
"end": 13408
} | class ____(util.F2PyTest):
def test_end_if_comment(self):
# gh-23533
fpath = util.getpath("tests", "src", "crackfortran", "gh23533.f")
try:
crackfortran.crackfortran([str(fpath)])
except Exception as exc:
assert False, f"'crackfortran.crackfortran' raised an e... | TestFortranGroupCounters |
python | django__django | tests/i18n/tests.py | {
"start": 88326,
"end": 90033
} | class ____(SimpleTestCase):
@override_settings(USE_I18N=False)
def test_i18n_disabled(self):
mocked_sender = mock.MagicMock()
watch_for_translation_changes(mocked_sender)
mocked_sender.watch_dir.assert_not_called()
def test_i18n_enabled(self):
mocked_sender = mock.MagicMock(... | WatchForTranslationChangesTests |
python | plotly__plotly.py | plotly/graph_objs/mesh3d/_legendgrouptitle.py | {
"start": 233,
"end": 2932
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "mesh3d"
_path_str = "mesh3d.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 specified... | Legendgrouptitle |
python | prakhar1989__Algorithms | lists/singlylinkedlist.py | {
"start": 161,
"end": 1977
} | class ____(object):
def __init__(self, iterable=[]):
self.head = None
self.size = 0
for item in iterable: self.append(item)
def __repr__(self):
(current, nodes) = self.head, []
while current:
nodes.append(str(current))
current = current.next
... | SinglyLinkedList |
python | django__django | django/contrib/auth/context_processors.py | {
"start": 120,
"end": 724
} | class ____:
def __init__(self, user, app_label):
self.user, self.app_label = user, app_label
def __repr__(self):
return str(self.user.get_all_permissions())
def __getitem__(self, perm_name):
return self.user.has_perm("%s.%s" % (self.app_label, perm_name))
def __iter__(self):
... | PermLookupDict |
python | prabhupant__python-ds | data_structures/bst/insertion_recursive.py | {
"start": 0,
"end": 846
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insertion_recursive(root, val):
if not root:
return Node(val)
else:
if root.val < val:
if root.right is None:
root.right = Node(val)
... | Node |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/shell_windows.py | {
"start": 167,
"end": 1234
} | class ____(object):
# Windows shell documentation fragment
# FIXME: set_module_language don't belong here but must be set so they don't fail when someone
# get_option('set_module_language') on this plugin
DOCUMENTATION = r"""
options:
async_dir:
description:
- Directory in which ansible will... | ModuleDocFragment |
python | huggingface__transformers | src/transformers/models/edgetam_video/configuration_edgetam_video.py | {
"start": 6712,
"end": 23679
} | class ____(PreTrainedConfig):
r"""
[`EdgeTamVideoConfig`] is the configuration class to store the configuration of a [`EdgeTamVideoModel`]. It is used to instantiate a
EDGETAM model according to the specified arguments, defining the memory attention, memory encoder, and image encoder
configs. Instantiat... | EdgeTamVideoConfig |
python | psf__black | src/black/report.py | {
"start": 244,
"end": 354
} | class ____(UserWarning):
"""Raised when reformatted code is the same as source."""
@dataclass
| NothingChanged |
python | sympy__sympy | sympy/physics/vector/dyadic.py | {
"start": 214,
"end": 18042
} | class ____(Printable, EvalfMixin):
"""A Dyadic object.
See:
https://en.wikipedia.org/wiki/Dyadic_tensor
Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
A more powerful way to represent a rigid body's inertia. While it is more
complex, by choosing Dyadic components to ... | Dyadic |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 3652,
"end": 12075
} | class ____(scrapy.Spider):
name = 'aiosp'
custom_settings = {}
async def start(self):
await asyncio.sleep(0.01)
self.logger.debug('It works!')
return
yield
""")
self._append_settings(proj_mod_path, "LOG_LEVEL = 'DEBUG'\n")
@staticmethod
def _append_setting... | MySpider |
python | numba__numba | numba/core/types/containers.py | {
"start": 3238,
"end": 4577
} | class ____(ConstSized, Hashable):
"""
The base class for all tuple types (with a known size).
"""
@classmethod
def from_types(cls, tys, pyclass=None):
"""
Instantiate the right tuple type for the given element types.
"""
if pyclass is not None and pyclass is not tupl... | BaseTuple |
python | docker__docker-py | tests/integration/errors_test.py | {
"start": 104,
"end": 632
} | class ____(BaseAPIIntegrationTest):
def test_api_error_parses_json(self):
container = self.client.create_container(TEST_IMG, ['sleep', '10'])
self.client.start(container['Id'])
with pytest.raises(APIError) as cm:
self.client.remove_container(container['Id'])
explanation =... | ErrorsTest |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_errors.py | {
"start": 10244,
"end": 13103
} | class ____(AdminTestMixin, TestCase):
# issue 1724
def setUp(self):
super().setUp()
self.csvdata = "id,name,author\r\n" "1,Ulysses,666\r\n"
self.filedata = StringIO(self.csvdata)
self.data = {"format": "0", "import_file": self.filedata}
self._prepend_form_prefix(self.dat... | TestImportErrorMessageFormat |
python | django__django | tests/proxy_models/models.py | {
"start": 2550,
"end": 2726
} | class ____(UserProxy, AnotherUserProxy):
class Meta:
proxy = True
# We can still use `select_related()` to include related models in our
# querysets.
| MultiUserProxy |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 5705,
"end": 6101
} | class ____(BaseModel):
model_config = ConfigDict(extra="allow")
type: str
@model_validator(mode="after")
def check_type(self) -> "Tool":
if self.type == "function":
FunctionTool(**self.model_dump())
elif self.type not in {"file_search", "computer_use", "web_search"}:
... | Tool |
python | ApeWorX__ape | src/ape_test/provider.py | {
"start": 3634,
"end": 5242
} | class ____(EthereumTesterProvider):
def __init__(self, config: "ApeTestConfig", chain_id: int):
self.config = config
self.chain_id = chain_id
self._backend: Optional[ApeEVMBackend] = None
self._ethereum_tester: Optional[EthereumTester] = None
@property
def ethereum_tester(se... | ApeTester |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_avatar.py | {
"start": 338,
"end": 756
} | class ____(OrganizationAvatarTestBase):
def test_get(self) -> None:
response = self.get_success_response(self.organization.slug)
assert response.data["id"] == str(self.organization.id)
assert response.data["avatar"]["avatarType"] == "letter_avatar"
assert response.data["avatar"]["ava... | OrganizationAvatarTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/ingestion/pipeline.py | {
"start": 4918,
"end": 6013
} | class ____(str, Enum):
"""
Document de-duplication de-deduplication strategies work by comparing the hashes or ids stored in the document store.
They require a document store to be set which must be persisted across pipeline runs.
Attributes:
UPSERTS:
('upserts') Use upserts to h... | DocstoreStrategy |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_emr_modify_cluster.py | {
"start": 1630,
"end": 2864
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.mock_context = MagicMock()
self.operator = EmrModifyClusterOperator(
task_id="test_task",
cluster_id="j-8989898989",
step_concurrency_level=1,
aws... | TestEmrModifyClusterOperator |
python | walkccc__LeetCode | solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py | {
"start": 96,
"end": 500
} | class ____:
def equalToDescendants(self, root: TreeNode | None) -> int:
def dfs(root: TreeNode | None) -> T:
if not root:
return T(0, 0)
left = dfs(root.left)
right = dfs(root.right)
return T(root.val + left.summ + right.summ,
left.count + right.count +
... | Solution |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/trace_type_test.py | {
"start": 1814,
"end": 2113
} | class ____:
"""Helps test attrs collections."""
__attrs_attrs__ = (TestAttr('a'), TestAttr('b'))
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return isinstance(
other, TestAttrsClass) and self.a == other.a and self.b == other.b
| TestAttrsClass |
python | jazzband__django-oauth-toolkit | tests/test_authorization_code.py | {
"start": 81334,
"end": 82390
} | class ____(BaseTest):
def test_pre_auth_default_scopes(self):
"""
Test response for a valid client_id with response_type: code using default scopes
"""
self.client.login(username="test_user", password="123456")
query_data = {
"client_id": self.application.client_... | TestDefaultScopes |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 6330,
"end": 6824
} | class ____:
def setup(self):
arr = np.random.randint(-1 << 12, 1 << 12, (1 << 17, 5))
i = np.random.choice(len(arr), len(arr) * 5)
arr = np.vstack((arr, arr[i]))
i = np.random.permutation(len(arr))
arr = arr[i]
self.cols = list("abcde")
self.df = DataFrame(arr... | Int64 |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 2726,
"end": 3246
} | class ____(TypedDict):
id: str
name: str
def get_min_supported_for_source_dict(
source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict],
) -> Optional[Version]:
"""Get the minimum supported wandb version the source dict of wandb-job.json."""
min_seen = None
for key in source:
... | ArtifactInfoForJob |
python | plotly__plotly.py | plotly/graph_objs/scattergl/selected/_textfont.py | {
"start": 233,
"end": 2430
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergl.selected"
_path_str = "scattergl.selected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and may be specified a... | Textfont |
python | django__django | tests/prefetch_related/models.py | {
"start": 7199,
"end": 7404
} | class ____(models.Model):
name = models.CharField(max_length=50)
boss = models.ForeignKey("self", models.SET_NULL, null=True, related_name="serfs")
class Meta:
ordering = ["id"]
| Employee |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 25147,
"end": 25976
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.bypass_selection is False
def test_correct(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"bypass-selection": True}}}}}}
builder = WheelBu... | TestBypassSelection |
python | getsentry__sentry | src/sentry/relocation/api/endpoints/artifacts/details.py | {
"start": 1252,
"end": 3891
} | class ____(Endpoint):
owner = ApiOwner.HYBRID_CLOUD
publish_status = {
# TODO(getsentry/team-ospo#214): Stabilize before GA.
"GET": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (SuperuserOrStaffFeatureFlaggedPermission,)
def get(
self, request: Request, relocation_u... | RelocationArtifactDetailsEndpoint |
python | ethereum__web3.py | web3/middleware/base.py | {
"start": 4243,
"end": 5714
} | class ____(Web3Middleware):
@staticmethod
@abstractmethod
def build(
w3: Union["AsyncWeb3[Any]", "Web3"],
*args: Any,
**kwargs: Any,
) -> Web3Middleware:
"""
Implementation should initialize the middleware class that implements it,
load it with any of the ... | Web3MiddlewareBuilder |
python | pytorch__pytorch | test/functorch/test_vmap.py | {
"start": 3007,
"end": 46213
} | class ____(TestCase):
def test_non_tensor_output_raises(self):
with self.assertRaisesRegex(ValueError, "got type <class 'float'>"):
vmap(lambda x: 3.14)(torch.ones(3))
def multiple_outputs(x):
return x, 3
with self.assertRaisesRegex(ValueError, "got type <class 'int... | TestVmapAPI |
python | explosion__spaCy | spacy/lang/bo/__init__.py | {
"start": 217,
"end": 313
} | class ____(Language):
lang = "bo"
Defaults = TibetanDefaults
__all__ = ["Tibetan"]
| Tibetan |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/completion_html.py | {
"start": 1490,
"end": 3354
} | class ____(object):
"""a bound interval that follows a cursor
internally used to scoll the completion view when the cursor
try to go beyond the edges, and show '...' when rows are hidden
"""
_min = 0
_max = 1
_current = 0
def __init__(self, maximum=1, width=6, minimum=0, sticky_lenght=... | SlidingInterval |
python | pypa__warehouse | tests/unit/captcha/test_hcaptcha.py | {
"start": 1232,
"end": 6152
} | class ____:
@responses.activate
def test_verify_service_disabled(self):
responses.add(
responses.POST,
hcaptcha.VERIFY_URL,
body="",
)
service = hcaptcha.Service.create_service(
context=None,
request=pretend.stub(
... | TestVerifyResponse |
python | getsentry__sentry | src/sentry/ingest/inbound_filters.py | {
"start": 2020,
"end": 5210
} | class ____:
ERROR_MESSAGES = "error_messages"
RELEASES = "releases"
LOG_MESSAGES = "log_messages"
TRACE_METRIC_NAMES = "trace_metric_names"
def get_filter_key(flt):
return to_camel_case_name(flt.config_name.replace("-", "_"))
def get_all_filter_specs():
"""
Return metadata about the filt... | FilterTypes |
python | facelessuser__pymdown-extensions | pymdownx/tasklist.py | {
"start": 4289,
"end": 5359
} | class ____(Extension):
"""Tasklist extension."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'custom_checkbox': [
False,
"Add an empty label tag after the input tag to allow for custom styling - Default: False"
... | TasklistExtension |
python | django-import-export__django-import-export | import_export/mixins.py | {
"start": 9433,
"end": 10241
} | class ____(BaseExportMixin):
# Deprecated, and will be removed in a future release (see #1666)
form_class = SelectableFieldsExportForm
def get_export_data(self, file_format, queryset, **kwargs):
"""
Returns file_format representation for given queryset.
"""
data = self.get_d... | ExportViewMixin |
python | numba__llvmlite | llvmlite/ir/_utils.py | {
"start": 87,
"end": 856
} | class ____(object):
def __init__(self):
self._useset = set([''])
self._basenamemap = defaultdict(int)
def is_used(self, name):
return name in self._useset
def register(self, name, deduplicate=False):
if deduplicate:
name = self.deduplicate(name)
elif sel... | NameScope |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/benchmark_test.py | {
"start": 2450,
"end": 7972
} | class ____(test.TestCase):
def testGlobalBenchmarkRegistry(self):
registry = list(benchmark.GLOBAL_BENCHMARK_REGISTRY)
self.assertEqual(len(registry), 2)
self.assertTrue(SomeRandomBenchmark in registry)
self.assertTrue(TestReportingBenchmark in registry)
def testRunSomeRandomBenchmark(self):
#... | BenchmarkTest |
python | realpython__materials | contact-book-python-textual/source_code/rpcontacts/database.py | {
"start": 87,
"end": 1366
} | class ____:
def __init__(self, db_path=DATABASE_PATH):
self.db = sqlite3.connect(db_path)
self.cursor = self.db.cursor()
self._create_table()
def _create_table(self):
query = """
CREATE TABLE IF NOT EXISTS contacts(
id INTEGER PRIMARY KEY,
... | Database |
python | tensorflow__tensorflow | tensorflow/python/keras/callbacks.py | {
"start": 60067,
"end": 65320
} | class ____(Callback):
"""Callback to back up and restore the training state.
`BackupAndRestore` callback is intended to recover from interruptions that
happened in the middle of a model.fit execution by backing up the
training states in a temporary checkpoint file (based on TF CheckpointManager)
at the end o... | BackupAndRestore |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detector.py | {
"start": 333,
"end": 5593
} | class ____:
def __init__(
self,
config: SDKCrashDetectionConfig,
):
self.config = config
@property
def fields_containing_paths(self) -> set[str]:
return {"package", "module", "path", "abs_path", "filename"}
def replace_sdk_frame_path(self, path_field: str, path_valu... | SDKCrashDetector |
python | PyCQA__pylint | tests/functional/t/try_except_raise.py | {
"start": 1439,
"end": 2266
} | class ____:
error1 = FileNotFoundError
error2 = PermissionError
parent_error=OSError
try:
pass
except (NameSpace.error1, NameSpace.error2):
raise
except NameSpace.parent_error:
print("a failure")
# also consider tuples for subsequent exception handler instead of just bare except handler
try:
... | NameSpace |
python | scikit-image__scikit-image | benchmarks/benchmark_metrics.py | {
"start": 161,
"end": 776
} | class ____:
shape = (6, 6)
coords_a = np.zeros(shape, dtype=bool)
coords_b = np.zeros(shape, dtype=bool)
def setup(self):
points_a = (1, 0)
points_b = (5, 2)
self.coords_a[points_a] = True
self.coords_b[points_b] = True
def time_hausdorff_distance(self):
met... | SetMetricsSuite |
python | dagster-io__dagster | python_modules/libraries/dagster-duckdb-pyspark/dagster_duckdb_pyspark/duckdb_pyspark_type_handler.py | {
"start": 6400,
"end": 9557
} | class ____(DuckDBIOManager):
"""An I/O manager definition that reads inputs from and writes PySpark DataFrames to DuckDB. When
using the DuckDBPySparkIOManager, any inputs and outputs without type annotations will be loaded
as PySpark DataFrames.
Returns:
IOManagerDefinition
Examples:
... | DuckDBPySparkIOManager |
python | mlflow__mlflow | mlflow/server/jobs/__init__.py | {
"start": 1010,
"end": 7177
} | class ____:
fn_fullname: str
max_workers: int
transient_error_classes: list[type[Exception]] | None = None
python_env: _PythonEnv | None = None
def job(
max_workers: int,
transient_error_classes: list[type[Exception]] | None = None,
python_version: str | None = None,
pip_requirements: ... | JobFunctionMetadata |
python | protocolbuffers__protobuf | python/google/protobuf/symbol_database.py | {
"start": 1550,
"end": 5752
} | class ____():
"""A database of Python generated symbols."""
# local cache of registered classes.
_classes = {}
def __init__(self, pool=None):
"""Initializes a new SymbolDatabase."""
self.pool = pool or descriptor_pool.DescriptorPool()
def RegisterMessage(self, message):
"""Registers the given m... | SymbolDatabase |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/utils/time_window.py | {
"start": 1455,
"end": 1583
} | class ____(Enum):
MATERIALIZING = "MATERIALIZING"
MATERIALIZED = "MATERIALIZED"
FAILED = "FAILED"
| PartitionRangeStatus |
python | cherrypy__cherrypy | cherrypy/test/helper.py | {
"start": 5615,
"end": 13597
} | class ____(webtest.WebCase):
"""CherryPy web test case base."""
script_name = ''
scheme = 'http'
available_servers = {
'wsgi': LocalWSGISupervisor,
'wsgi_u': get_wsgi_u_supervisor,
'native': NativeServerSupervisor,
'cpmodpy': get_cpmodpy_supervisor,
'modpygw': g... | CPWebCase |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/training_generator_v1.py | {
"start": 21759,
"end": 24618
} | class ____(training_utils_v1.TrainingLoop):
"""Generator-like.
Input is Python generator, or Sequence object.
The difference between this class and `GeneratorLikeTrainingFunction` is that
this class only handles inputs that with x, y and sample_weight fused into one
param.
"""
def fit(self,
m... | GeneratorOrSequenceTrainingLoop |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methods1.py | {
"start": 778,
"end": 946
} | class ____:
def __init__(self, func: Callable[..., Any]):
self.func = func
def __call__(self) -> None:
print("Deco4.__call__:", f"{self=}")
| Deco4 |
python | huggingface__transformers | tests/models/cpmant/test_tokenization_cpmant.py | {
"start": 906,
"end": 2557
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "openbmb/cpm-ant-10b"
tokenizer_class = CpmAntTokenizer
test_rust_tokenizer = False
@classmethod
def setUpClass(cls):
super().setUpClass()
old_tmpdirname = cls.tmpdirname
cls.tmpdirname = tempfile.mkd... | CPMAntTokenizationTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.