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 | matplotlib__matplotlib | lib/matplotlib/backends/backend_wx.py | {
"start": 13161,
"end": 31504
} | class ____(FigureCanvasBase, wx.Panel):
"""
The FigureCanvas contains the figure and does event handling.
In the wxPython backend, it is derived from wxPanel, and (usually) lives
inside a frame instantiated by a FigureManagerWx. The parent window
probably implements a wx.Sizer to control the displa... | _FigureCanvasWxBase |
python | keon__algorithms | algorithms/tree/avl/avl.py | {
"start": 58,
"end": 3476
} | class ____(object):
"""
An avl tree.
"""
def __init__(self):
# Root node of the tree.
self.node = None
self.height = -1
self.balance = 0
def insert(self, key):
"""
Insert new key into node
"""
# Create new node
node = TreeNode... | AvlTree |
python | walkccc__LeetCode | solutions/2538. Difference Between Maximum and Minimum Price Sum/2538.py | {
"start": 0,
"end": 1448
} | class ____:
def maxOutput(self, n: int, edges: list[list[int]], price: list[int]) -> int:
ans = 0
tree = [[] for _ in range(n)]
maxSums = [0] * n # maxSums[i] := the maximum the sum of path rooted at i
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
def maxSum(u: int, prev: i... | Solution |
python | django__django | tests/postgres_tests/test_array.py | {
"start": 37442,
"end": 38585
} | class ____(PostgreSQLSimpleTestCase):
field_values = [["Django", "Python", None], ["Джанго", "פייתון", None, "król"]]
@staticmethod
def create_json_data(array_field_value):
fields = {"field": json.dumps(array_field_value, ensure_ascii=False)}
return json.dumps(
[{"model": "postg... | TestStringSerialization |
python | FactoryBoy__factory_boy | examples/django_demo/generic_foreignkey/factories.py | {
"start": 285,
"end": 400
} | class ____(factory.django.DjangoModelFactory):
name = 'group'
class Meta:
model = Group
| GroupFactory |
python | conda__conda | conda/exceptions.py | {
"start": 19550,
"end": 20497
} | class ____(CondaError):
def __init__(
self,
url: str,
target_full_path: PathType,
checksum_type: str,
expected_checksum: str,
actual_checksum: str,
partial_download: bool = False,
):
message = dals(
"""
Conda detected a mismatch... | ChecksumMismatchError |
python | spyder-ide__spyder | spyder/widgets/config.py | {
"start": 1542,
"end": 2483
} | class ____:
"""Mixin to access config options in SpyderConfigPages."""
CONF_SECTION = None
def set_option(
self,
option,
value,
section=None,
recursive_notification=False,
secure=False,
):
section = self.CONF_SECTION if section is None else sectio... | ConfigAccessMixin |
python | kamyu104__LeetCode-Solutions | Python/lonely-pixel-ii.py | {
"start": 58,
"end": 839
} | class ____(object):
def findBlackPixel(self, picture, N):
"""
:type picture: List[List[str]]
:type N: int
:rtype: int
"""
rows, cols = [0] * len(picture), [0] * len(picture[0])
lookup = collections.defaultdict(int)
for i in xrange(len(picture)):
... | Solution |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0131_increase_env_var_size.py | {
"start": 150,
"end": 545
} | class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("projects", "0130_addons_remove_old_fields"),
]
operations = [
migrations.AlterField(
model_name="environmentvariable",
name="value",
field=models.CharField(help_text="Va... | Migration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/backfill_policy.py | {
"start": 405,
"end": 3987
} | class ____(
NamedTuple(
"_BackfillPolicy",
[
("max_partitions_per_run", Optional[int]),
],
)
):
"""A BackfillPolicy specifies how Dagster should attempt to backfill a partitioned asset.
There are two main kinds of backfill policies: single-run and multi-run.
An ... | BackfillPolicy |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qbatchnorm_test.py | {
"start": 1611,
"end": 2513
} | class ____(QBatchNormBenchmark):
def _init(self, M, N, K, device):
self.set_module_name("QBatchNorm2d")
# Note: quantized implementation requires rank 4, which is why we
# add a 1 as the last dimension
self.input_one = torch.rand(
M, N, K, 1, device=device, requires_grad=... | QBatchNorm2dBenchmark |
python | pytorch__pytorch | test/distributed/test_c10d_pypg.py | {
"start": 1084,
"end": 2418
} | class ____(dist.ProcessGroup):
"""
This PG only supports world_size of 1
"""
def __init__(self, rank, world, use_wrapper):
super().__init__(rank, world)
assert rank == 0
assert world == 1
self._rank = rank
self._world = world
self.wait_count = 0
... | LonelyRankProcessGroup |
python | pandas-dev__pandas | pandas/tests/reshape/concat/test_datetimes.py | {
"start": 17348,
"end": 21118
} | class ____:
def test_concat_period_series(self):
x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D"))
y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="D"))
expected = Series([x[0], x[1], y[0], y[1]], dtype="Period[D]")
result = concat([x, y], ignore_index=T... | TestPeriodConcat |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_identity_details.py | {
"start": 224,
"end": 923
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-identity-details"
method = "delete"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
def test_simple(self) -> None:
auth_provider = AuthProvider.objects.create(
organization_id=self.organization... | DeleteUserIdentityTest |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 3923,
"end": 4272
} | class ____(MPTTModel):
name = models.CharField(max_length=50)
parent = TreeForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
# just testing it's actually possible to override the tree manager
objects = CustomTreeManager()
def __str__(self):
... | Person |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 16916,
"end": 19496
} | class ____(Metafield):
"""
{
products(query: "updated_at:>='2023-01-08T00:00:00+00:00' AND updated_at:<='2024-08-02T15:12:41.689153+00:00'", sortKey: UPDATED_AT) {
edges {
node {
__typename
id
product_updated_at: upd... | MetafieldProductImage |
python | davidhalter__parso | parso/python/diff.py | {
"start": 22628,
"end": 34206
} | class ____:
def __init__(self, module):
self._base_node = _NodesTreeNode(module)
self._working_stack = [self._base_node]
self._module = module
self._prefix_remainder = ''
self.prefix = ''
self.indents = [0]
@property
def parsed_until_line(self):
retur... | _NodesTree |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 14835,
"end": 14932
} | class ____(ApeException):
"""
Raised when problems occur in a project.
"""
| ProjectError |
python | crytic__slither | slither/core/expressions/assignment_operation.py | {
"start": 2899,
"end": 4176
} | class ____(Expression):
def __init__(
self,
left_expression: Expression,
right_expression: Expression,
expression_type: AssignmentOperationType,
expression_return_type: Optional["Type"],
) -> None:
assert isinstance(left_expression, Expression)
assert isin... | AssignmentOperation |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 2270,
"end": 2789
} | class ____(TestSpiderMiddleware):
"""Invalid return value for process_spider_output method"""
@deferred_f_from_coro_f
async def test_invalid_process_spider_output(self):
class InvalidProcessSpiderOutputMiddleware:
def process_spider_output(self, response, result):
return... | TestProcessSpiderOutputInvalidOutput |
python | neetcode-gh__leetcode | python/0048-rotate-image.py | {
"start": 0,
"end": 832
} | class ____:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
l, r = 0, len(matrix) - 1
while l < r:
for i in range(r - l):
top, bottom = l, r
# save the topleft
... | Solution |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/weibo/tests.py | {
"start": 238,
"end": 1358
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = WeiboProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{"bi_followers_count": 0,
"domain": "", "avatar_large": "http://tp3.sinaimg.cn/3195025850/180/0/0",
"block_word": 0, "star": 0, "id":... | WeiboTests |
python | google__jax | jaxlib/weakref_lru_cache_test.py | {
"start": 793,
"end": 6777
} | class ____(absltest.TestCase):
def testMultiThreaded(self):
insert_evs = [threading.Event() for _ in range(2)]
insert_evs_i = 0
class WRKey:
pass
class ClashingKey:
def __eq__(self, other):
return False
def __hash__(self):
return 333 # induce maximal caching pro... | WeakrefLRUCacheTest |
python | wandb__wandb | wandb/vendor/pygments/lexers/textfmts.py | {
"start": 3716,
"end": 7000
} | class ____(RegexLexer):
"""
Lexer for HTTP sessions.
.. versionadded:: 1.5
"""
name = 'HTTP'
aliases = ['http']
flags = re.DOTALL
def get_tokens_unprocessed(self, text, stack=('root',)):
"""Reset the content-type state."""
self.content_type = None
return Regex... | HttpLexer |
python | pypa__warehouse | warehouse/oidc/forms/gitlab.py | {
"start": 4455,
"end": 4909
} | class ____(GitLabPublisherBase, PendingPublisherMixin):
__params__ = GitLabPublisherBase.__params__ + ["project_name"]
def __init__(self, *args, route_url, check_project_name, user, **kwargs):
super().__init__(*args, **kwargs)
self._route_url = route_url
self._check_project_name = check... | PendingGitLabPublisherForm |
python | ray-project__ray | python/ray/autoscaler/_private/cli_logger.py | {
"start": 1919,
"end": 6746
} | class ____:
_proxy_allowlist = [
"disable",
"reset",
"bold",
"italic",
"underlined",
# used instead of `gray` as `dimmed` adapts to
# both light and dark themes
"dimmed",
"dodgerBlue", # group
"limeGreen", # success
"red", # ... | _ColorfulProxy |
python | apache__airflow | providers/sftp/tests/unit/sftp/hooks/test_sftp.py | {
"start": 27840,
"end": 28510
} | class ____:
def __init__(self):
pass
async def listdir(self, path: str):
if path == "/path/does_not/exist/":
raise SFTPNoSuchFile("File does not exist")
return ["..", ".", "file"]
async def readdir(self, path: str):
if path == "/path/does_not/exist/":
... | MockSFTPClient |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 37233,
"end": 51435
} | class ____(PForTestCase):
def test_create_outside_and_write(self):
handle1 = list_ops.tensor_list_reserve([], 2, dtypes.int32)
handle2 = list_ops.tensor_list_reserve([], 2, dtypes.int32)
def loop_fn(i):
h1 = list_ops.tensor_list_set_item(handle1, 0, i)
h1 = list_ops.tensor_list_set_item(h1, ... | TensorListTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 502616,
"end": 514983
} | class ____(LatLongDef):
r"""
LatLongFieldDef schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, ... | LatLongFieldDef |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 2431,
"end": 6246
} | class ____(test_util.TensorFlowTestCase):
def testNonBatchMatrix(self):
matrix = [[1, 2, 3], [4, 5, 6]] # Shape (2, 3)
expected_transposed = [[1, 4], [2, 5], [3, 6]] # Shape (3, 2)
transposed = array_ops.matrix_transpose(matrix)
self.assertEqual((3, 2), transposed.get_shape())
self.assertAllEqu... | BatchMatrixTransposeTest |
python | tox-dev__tox | src/tox/config/source/toml_tox.py | {
"start": 127,
"end": 180
} | class ____(TomlSection):
PREFIX = ()
| TomlToxSection |
python | walkccc__LeetCode | solutions/1062. Longest Repeating Substring/1062.py | {
"start": 0,
"end": 413
} | class ____:
def longestRepeatingSubstring(self, s: str) -> int:
n = len(s)
ans = 0
# dp[i][j] := the number of repeating characters of s[0..i) and s[0..j)
dp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if s[i - 1] == s[j - 1]:
... | Solution |
python | dask__dask | dask/dataframe/dask_expr/_merge.py | {
"start": 28618,
"end": 31059
} | class ____(Merge, Blockwise):
"""Merge two dataframes with aligned partitions
This operation will directly merge partition i of the
left dataframe with partition i of the right dataframe.
The two dataframes must be shuffled or partitioned
by the merge key(s) before this operation is performed.
... | BlockwiseMerge |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 56473,
"end": 56910
} | class ____(NamedFromClause):
"""mark a FROM clause as being able to render directly as LATERAL"""
# FromClause ->
# AliasedReturnsRows
# -> Alias only for FromClause
# -> Subquery only for SelectBase
# -> CTE only for HasCTE -> SelectBase, DML
# -> Lateral -> FromClause, but we ac... | LateralFromClause |
python | tensorflow__tensorflow | tensorflow/lite/tools/flatbuffer_utils_test.py | {
"start": 5407,
"end": 9587
} | class ____(test_util.TensorFlowTestCase):
def testRandomizeWeights(self):
# 1. SETUP
# Define the initial model
initial_model = test_utils.build_mock_model()
final_model = copy.deepcopy(initial_model)
# 2. INVOKE
# Invoke the randomize_weights function
flatbuffer_utils.randomize_weights(... | RandomizeWeightsTest |
python | bokeh__bokeh | tests/cross/cases/regressions/issue_13637.py | {
"start": 403,
"end": 569
} | class ____(TypedDict):
top_left: NotRequired[int]
top_right: NotRequired[int]
bottom_right: NotRequired[int]
bottom_left: NotRequired[int]
| BorderRadiusTD |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 13329,
"end": 13414
} | class ____(PydanticTypeError):
msg_template = 'value is not a valid uuid'
| UUIDError |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 30343,
"end": 30607
} | class ____(graphene.Union):
class Meta:
name = "InstigationStateOrError"
types = (
GrapheneInstigationState,
GrapheneInstigationStateNotFoundError,
GraphenePythonError,
)
| GrapheneInstigationStateOrError |
python | huggingface__transformers | tests/models/donut/test_image_processing_donut.py | {
"start": 1129,
"end": 3129
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_thumbnail=True,
do_align_axis=False,
do_pad=True,
do_norma... | DonutImageProcessingTester |
python | keon__algorithms | algorithms/linkedlist/linkedlist.py | {
"start": 690,
"end": 809
} | class ____(object):
def __init__(self, value):
self.value = value
self.next = None
| SinglyLinkedListNode |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_pattern04.py | {
"start": 315,
"end": 3559
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_pattern04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes5.py | {
"start": 5231,
"end": 5343
} | class ____(Protocol):
Config1: ClassVar[type[ConfigBase]]
Config2: ClassVar[type[ConfigBase]]
| ParentClass3 |
python | chroma-core__chroma | chromadb/api/__init__.py | {
"start": 18544,
"end": 27014
} | class ____(BaseAPI, AdminAPI, Component):
"""An API instance that extends the relevant Base API methods by passing
in a tenant and database. This is the root component of the Chroma System"""
@abstractmethod
@override
def count_collections(
self, tenant: str = DEFAULT_TENANT, database: str ... | ServerAPI |
python | walkccc__LeetCode | solutions/929. Unique Email Addresses/929.py | {
"start": 0,
"end": 263
} | class ____:
def numUniqueEmails(self, emails: list[str]) -> int:
seen = set()
for email in emails:
local, domain = email.split('@')
local = local.split('+')[0].replace('.', '')
seen.add(local + '@' + domain)
return len(seen)
| Solution |
python | pandas-dev__pandas | pandas/tests/generic/test_generic.py | {
"start": 10501,
"end": 17027
} | class ____:
# tests that don't fit elsewhere
@pytest.mark.parametrize(
"ser",
[
Series(range(10), dtype=np.float64),
Series([str(i) for i in range(10)], dtype=object),
],
)
def test_squeeze_series_noop(self, ser):
# noop
tm.assert_series_e... | TestNDFrame |
python | python__mypy | mypy/types.py | {
"start": 147295,
"end": 158512
} | class ____(BoolTypeQuery):
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
def visit_type_alias_type(self, t: TypeAliasType) -> bool:
return t.is_recursive or self.query_types(t.args)
# Use singleton since this is hot (note: call reset() before using)
_has_recursive_type: Final = H... | HasRecursiveType |
python | facebook__pyre-check | client/backend_arguments.py | {
"start": 1568,
"end": 2071
} | class ____:
elements: Sequence[search_path.Element] = dataclasses.field(default_factory=list)
def serialize(self) -> Dict[str, object]:
return {
"kind": "simple",
"paths": [element.command_line_argument() for element in self.elements],
}
def get_checked_directory_al... | SimpleSourcePath |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/dagster/development_to_production/resources/resources_v1.py | {
"start": 126,
"end": 849
} | class ____(ConfigurableResource):
"""Hacker News client that fetches live data."""
def fetch_item_by_id(self, item_id: int) -> Optional[dict[str, Any]]:
"""Fetches a single item from the Hacker News API by item id."""
item_url = f"https://hacker-news.firebaseio.com/v0/item/{item_id}.json"
... | HNAPIClient |
python | python-visualization__folium | tests/selenium/conftest.py | {
"start": 467,
"end": 1969
} | class ____(Chrome):
"""Selenium WebDriver wrapper that adds folium test specific features."""
def __init__(self):
options = ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-gpu")
options.... | DriverFolium |
python | huggingface__transformers | tests/models/nougat/test_tokenization_nougat.py | {
"start": 5178,
"end": 6014
} | class ____(unittest.TestCase):
def test_two_level_lines(self):
input_str = "* Item 1 * Item 2"
expected_output = "* Item 1\n* Item 2\n"
self.assertEqual(normalize_list_like_lines(input_str), expected_output)
def test_three_level_lines(self):
input_str = "- I. Item 1 - II. Item 2... | TestNormalizeListLikeLines |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_object/generate/executor.py | {
"start": 994,
"end": 19647
} | class ____(
Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType]
):
@overload
def near_object(
self,
near_object: UUID,
*,
single_prompt: Union[str, _SinglePrompt, None] = None,
grouped_task: Union[str, _GroupedTask, None] = None,
gro... | _NearObjectGenerateExecutor |
python | django__django | tests/admin_views/customadmin.py | {
"start": 2094,
"end": 2905
} | class ____(admin.ModelAdmin):
def get_deleted_objects(self, objs, request):
return ["a deletable object"], {"books": 1}, set(), []
site = Admin2(name="admin2")
site.register(models.Article, base_admin.ArticleAdmin)
site.register(models.Book, BookAdmin)
site.register(
models.Section, inlines=[base_adm... | BookAdmin |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 8726,
"end": 8924
} | class ____(IncrementalShopifyStream):
data_field = "tender_transactions"
cursor_field = "processed_at"
filter_field = "processed_at_min"
order_field = "processed_at"
| TenderTransactions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py | {
"start": 21264,
"end": 37395
} | class ____(SalesforceStream):
def __init__(self, **kwargs) -> None:
self._stream_slicer_cursor = None
self._switch_from_bulk_to_rest = False
self._rest_stream = None
super().__init__(**kwargs)
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:... | BulkSalesforceStream |
python | pytorch__pytorch | torchgen/utils.py | {
"start": 1049,
"end": 3484
} | class ____(Enum):
# top level namespace (not including at)
DEFINITION = auto()
DECLARATION = auto()
# TORCH_LIBRARY(...) { ... }
REGISTRATION = auto()
# namespace { ... }
ANONYMOUS_DEFINITION = auto()
# namespace cpu { ... }
NAMESPACED_DEFINITION = auto()
NAMESPACED_DECLARATION =... | Target |
python | doocs__leetcode | solution/3700-3799/3739.Count Subarrays With Majority Element II/Solution.py | {
"start": 404,
"end": 772
} | class ____:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
n = len(nums)
tree = BinaryIndexedTree(n * 2 + 1)
s = n + 1
tree.update(s, 1)
ans = 0
for x in nums:
s += 1 if x == target else -1
ans += tree.query(s - 1)
... | Solution |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_action_export.py | {
"start": 14812,
"end": 17499
} | class ____(AdminTestMixin, TestCase):
def setUp(self):
super().setUp()
self.cat1 = Category.objects.create(name="Cat 1")
self.change_url = reverse(
"%s:%s_%s_change"
% (
"admin",
"core",
"category",
),
... | TestExportButtonOnChangeForm |
python | spack__spack | lib/spack/spack/cmd/mirror.py | {
"start": 18236,
"end": 25886
} | class ____:
def __init__(self, args):
self.exclude_specs = []
if args.exclude_file:
self.exclude_specs.extend(specs_from_text_file(args.exclude_file, concretize=False))
if args.exclude_specs:
self.exclude_specs.extend(spack.cmd.parse_specs(str(args.exclude_specs).spli... | IncludeFilter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams1.py | {
"start": 263,
"end": 295
} | class ____[T3, S1, T3]: ...
| ClassC |
python | huggingface__transformers | src/transformers/models/lfm2/modeling_lfm2.py | {
"start": 2984,
"end": 5978
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Lfm2Config, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.co... | Lfm2RotaryEmbedding |
python | django__django | tests/admin_utils/admin.py | {
"start": 109,
"end": 543
} | class ____(forms.ModelForm):
nolabel_form_field = forms.BooleanField(required=False)
class Meta:
model = Article
fields = ["title"]
@property
def changed_data(self):
data = super().changed_data
if data:
# Add arbitrary name to changed_data to test
... | ArticleAdminForm |
python | plotly__plotly.py | plotly/graph_objs/icicle/_pathbar.py | {
"start": 233,
"end": 5683
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.pathbar"
_valid_props = {"edgeshape", "side", "textfont", "thickness", "visible"}
@property
def edgeshape(self):
"""
Determines which shape is used for edges between `barpath`
labels.
... | Pathbar |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 4156,
"end": 8468
} | class ____(nn.Module):
def __init__(self, config, 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 multiple of the num... | GitSelfAttention |
python | openai__openai-python | src/openai/types/responses/easy_input_message.py | {
"start": 309,
"end": 817
} | class ____(BaseModel):
content: Union[str, ResponseInputMessageContentList]
"""
Text, image, or audio input to the model, used to generate a response. Can also
contain previous assistant responses.
"""
role: Literal["user", "assistant", "system", "developer"]
"""The role of the message inpu... | EasyInputMessage |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 29948,
"end": 40207
} | class ____(DFinePreTrainedModel):
"""
D-FINE Decoder implementing Fine-grained Distribution Refinement (FDR).
This decoder refines object detection predictions through iterative updates across multiple layers,
utilizing attention mechanisms, location quality estimators, and distribution refinement tech... | DFineDecoder |
python | getsentry__sentry | tests/sentry/models/test_recentsearch.py | {
"start": 270,
"end": 651
} | class ____(TestCase):
def test_query_hash(self) -> None:
recent_search = RecentSearch.objects.create(
organization=self.organization, user_id=self.user.id, type=0, query="hello"
)
recent_search = RecentSearch.objects.get(id=recent_search.id)
assert recent_search.query_has... | RecentSearchTest |
python | django-haystack__django-haystack | haystack/indexes.py | {
"start": 3198,
"end": 13939
} | class ____(threading.local, metaclass=DeclarativeMetaclass):
"""
Base class for building indexes.
An example might look like this::
import datetime
from haystack import indexes
from myapp.models import Note
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
... | SearchIndex |
python | apache__airflow | providers/redis/tests/unit/redis/triggers/test_redis_await_message.py | {
"start": 973,
"end": 3041
} | class ____:
def test_trigger_serialization(self):
trigger = AwaitMessageTrigger(
channels=["test_channel"],
redis_conn_id="redis_default",
poll_interval=30,
)
assert isinstance(trigger, AwaitMessageTrigger)
classpath, kwargs = trigger.serialize()... | TestAwaitMessageTrigger |
python | python-openxml__python-docx | src/docx/oxml/xmlchemy.py | {
"start": 3677,
"end": 5103
} | class ____:
"""Base class for OptionalAttribute and RequiredAttribute.
Provides common methods.
"""
def __init__(self, attr_name: str, simple_type: Type[BaseXmlEnum] | Type[BaseSimpleType]):
super(BaseAttribute, self).__init__()
self._attr_name = attr_name
self._simple_type = s... | BaseAttribute |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/bedrock/_beta_messages.py | {
"start": 2287,
"end": 2510
} | class ____:
def __init__(self, messages: Messages) -> None:
self._messages = messages
self.create = _legacy_response.to_raw_response_wrapper(
messages.create,
)
| MessagesWithRawResponse |
python | python-pillow__Pillow | src/PIL/ImageStat.py | {
"start": 709,
"end": 5495
} | class ____:
def __init__(
self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None
) -> None:
"""
Calculate statistics for the given image. If a mask is included,
only the regions covered by that mask are included in the
statistics. You can also pass ... | Stat |
python | justquick__django-activity-stream | actstream/templatetags/activity_tags.py | {
"start": 286,
"end": 1133
} | class ____(Node):
def __init__(self, actor, actor_only=True, flag=''):
self.actor = Variable(actor)
self.actor_only = actor_only
self.flag = flag
def render(self, context):
actor_instance = self.actor.resolve(context)
content_type = ContentType.objects.get_for_model(acto... | DisplayActivityFollowUrl |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serde.py | {
"start": 4787,
"end": 5241
} | class ____:
__version__: ClassVar[int] = 1
def __init__(self, x):
self.x = x
def serialize(self) -> dict:
return dict({"x": self.x})
@staticmethod
def deserialize(data: dict, version: int):
if version != 1:
raise TypeError("version != 1")
return Z(data[... | Z |
python | django__django | tests/auth_tests/test_context_processors.py | {
"start": 620,
"end": 2087
} | class ____(SimpleTestCase):
"""
Test some details of the PermWrapper implementation.
"""
class EQLimiterObject:
"""
This object makes sure __eq__ will not be called endlessly.
"""
def __init__(self):
self.eq_calls = 0
def __eq__(self, other):
... | PermWrapperTests |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py | {
"start": 16940,
"end": 20660
} | class ____(object):
"""Operator that ensures an RNNCell runs on a particular device."""
def __init__(self, cell, device, **kwargs):
"""Construct a `DeviceWrapper` for `cell` with device `device`.
Ensures the wrapped `cell` is called with `tf.device(device)`.
Args:
cell: An instance of `RNNCell`... | DeviceWrapperBase |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 134956,
"end": 135644
} | class ____(Operation):
def call(self, x):
return backend.numpy.log2(x)
def compute_output_spec(self, x):
dtype = (
backend.floatx()
if backend.standardize_dtype(x.dtype) == "int64"
else dtypes.result_type(x.dtype, float)
)
return KerasTensor(x... | Log2 |
python | huggingface__transformers | src/transformers/models/mobilevitv2/configuration_mobilevitv2.py | {
"start": 788,
"end": 6348
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MobileViTV2Model`]. It is used to instantiate a
MobileViTV2 model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a simil... | MobileViTV2Config |
python | django__django | tests/apps/apps.py | {
"start": 612,
"end": 723
} | class ____(AppConfig):
name = "apps"
default_auto_field = "django.db.models.BigAutoField"
| ModelPKAppsConfig |
python | optuna__optuna | optuna/storages/_rdb/storage.py | {
"start": 3588,
"end": 45194
} | class ____(BaseStorage, BaseHeartbeat):
"""Storage class for RDB backend.
Note that library users can instantiate this class, but the attributes
provided by this class are not supposed to be directly accessed by them.
Example:
Create an :class:`~optuna.storages.RDBStorage` instance with custo... | RDBStorage |
python | apache__airflow | airflow-core/src/airflow/callbacks/callback_requests.py | {
"start": 3531,
"end": 4142
} | class ____(BaseCallbackRequest):
"""A Class with information about the success/failure DAG callback to be executed."""
dag_id: str
run_id: str
context_from_server: DagRunContext | None = None
is_failure_callback: bool | None = True
"""Flag to determine whether it is a Failure Callback or Succes... | DagCallbackRequest |
python | allegroai__clearml | clearml/backend_config/bucket_config.py | {
"start": 3945,
"end": 9909
} | class ____(BaseBucketConfigurations):
def __init__(
self,
buckets: Optional[List[S3BucketConfig]] = None,
default_key: str = "",
default_secret: str = "",
default_region: str = "",
default_use_credentials_chain: bool = False,
default_token: str = "",
d... | S3BucketConfigurations |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 2385,
"end": 3368
} | class ____(AsyncHTTPTestCase):
def get_app(self):
return HTTPMethodRouter(Application())
def test_http_method_router(self):
response = self.fetch("/post_resource", method="POST", body="data")
self.assertEqual(response.code, 200)
response = self.fetch("/get_resource")
se... | HTTPMethodRouterTestCase |
python | ray-project__ray | python/ray/train/v2/_internal/execution/controller/state.py | {
"start": 4403,
"end": 4673
} | class ____(TrainControllerState):
def __init__(
self,
training_failed_error: TrainingFailedError,
):
super().__init__(state_type=TrainControllerStateType.RESTARTING)
self.training_failed_error = training_failed_error
| RestartingState |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_embed_image08.py | {
"start": 315,
"end": 903
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("embed_image08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Wo... | TestCompareXLSXFiles |
python | django-compressor__django-compressor | compressor/filters/yui.py | {
"start": 548,
"end": 730
} | class ____(YUICompressorFilter):
type = "js"
options = (
("binary", settings.COMPRESS_YUI_BINARY),
("args", settings.COMPRESS_YUI_JS_ARGUMENTS),
)
| YUIJSFilter |
python | cython__cython | tests/run/methodmangling_T5.py | {
"start": 1246,
"end": 2135
} | class ____(CyTest):
"""
>>> cy = CyTestSub()
>>> '_CyTestSub__private' in dir(cy)
True
>>> cy._CyTestSub__private()
9
>>> '_CyTest__private' in dir(cy)
True
>>> cy._CyTest__private()
8
>>> '__private' in dir(cy)
False
>>> '_CyTestSub__x' in dir(cy)
False
>>> ... | CyTestSub |
python | doocs__leetcode | solution/3100-3199/3179.Find the N-th Value After K Seconds/Solution.py | {
"start": 0,
"end": 249
} | class ____:
def valueAfterKSeconds(self, n: int, k: int) -> int:
a = [1] * n
mod = 10**9 + 7
for _ in range(k):
for i in range(1, n):
a[i] = (a[i] + a[i - 1]) % mod
return a[n - 1]
| Solution |
python | apache__airflow | providers/standard/src/airflow/providers/standard/decorators/bash.py | {
"start": 1377,
"end": 4132
} | class ____(DecoratedOperator, BashOperator):
"""
Wraps a Python callable and uses the callable return value as the Bash command to be executed.
:param python_callable: A reference to an object that is callable.
:param op_kwargs: A dictionary of keyword arguments that will get unpacked
in your f... | _BashDecoratedOperator |
python | doocs__leetcode | solution/2000-2099/2053.Kth Distinct String in an Array/Solution.py | {
"start": 0,
"end": 248
} | class ____:
def kthDistinct(self, arr: List[str], k: int) -> str:
cnt = Counter(arr)
for s in arr:
if cnt[s] == 1:
k -= 1
if k == 0:
return s
return ""
| Solution |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 103845,
"end": 103906
} | class ____(ShapeGuardPythonPrinter):
pass
| ShapeGuardPrinter |
python | django__django | tests/i18n/test_extraction.py | {
"start": 37350,
"end": 38435
} | class ____(ExtractorTests):
def test_no_wrap_enabled(self):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_wrap=True
)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
s... | NoWrapExtractorTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass9.py | {
"start": 431,
"end": 557
} | class ____(metaclass=Meta1, param2="", param1=1): ...
# This should generate an error because param1 is the wrong type.
| Class1_2 |
python | python-openxml__python-docx | src/docx/oxml/text/parfmt.py | {
"start": 1292,
"end": 1523
} | class ____(BaseOxmlElement):
"""``<w:jc>`` element, specifying paragraph justification."""
val: WD_ALIGN_PARAGRAPH = RequiredAttribute( # pyright: ignore[reportAssignmentType]
"w:val", WD_ALIGN_PARAGRAPH
)
| CT_Jc |
python | dagster-io__dagster | python_modules/libraries/dagster-duckdb-pandas/dagster_duckdb_pandas/duckdb_pandas_type_handler.py | {
"start": 408,
"end": 6023
} | class ____(DbTypeHandler[pd.DataFrame]):
"""Stores and loads Pandas DataFrames in DuckDB.
To use this type handler, return it from the ``type_handlers` method of an I/O manager that inherits from ``DuckDBIOManager``.
Example:
.. code-block:: python
from dagster_duckdb import DuckDBIOM... | DuckDBPandasTypeHandler |
python | pytorch__pytorch | test/inductor/test_selective_lowering.py | {
"start": 406,
"end": 2918
} | class ____(InductorTestCase):
"""
Tests for user-controllable selective lowering using node.meta annotations.
"""
device = GPU_TYPE
def _mark_nodes_for_fallback(
self, gm: torch.fx.GraphModule, predicate: Callable[[torch.fx.Node], bool]
) -> torch.fx.GraphModule:
"""
He... | SelectiveLoweringTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 14786,
"end": 14853
} | class ____(TupleCompare):
pass
@infer_global(operator.lt)
| TupleLe |
python | sympy__sympy | sympy/combinatorics/prufer.py | {
"start": 281,
"end": 12061
} | class ____(Basic):
"""
The Prufer correspondence is an algorithm that describes the
bijection between labeled trees and the Prufer code. A Prufer
code of a labeled tree is unique up to isomorphism and has
a length of n - 2.
Prufer sequences were first used by Heinz Prufer to give a
proof of... | Prufer |
python | doocs__leetcode | solution/0900-0999/0985.Sum of Even Numbers After Queries/Solution.py | {
"start": 0,
"end": 408
} | class ____:
def sumEvenAfterQueries(
self, nums: List[int], queries: List[List[int]]
) -> List[int]:
s = sum(x for x in nums if x % 2 == 0)
ans = []
for v, i in queries:
if nums[i] % 2 == 0:
s -= nums[i]
nums[i] += v
if nums[i] ... | Solution |
python | doocs__leetcode | solution/2300-2399/2382.Maximum Segment Sum After Removals/Solution.py | {
"start": 0,
"end": 759
} | class ____:
def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def merge(a, b):
pa, pb = find(a), find(b)
p[pa] = pb
s[pb] += s[pa]
... | Solution |
python | pezy__LeetCode | 099. Same Tree/solution.py | {
"start": 129,
"end": 1052
} | class ____:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p is q
if __name__ == "__main__":
... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.