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 | django__django | django/forms/models.py | {
"start": 12106,
"end": 21125
} | class ____(BaseForm, AltersData):
def __init__(
self,
data=None,
files=None,
auto_id="id_%s",
prefix=None,
initial=None,
error_class=ErrorList,
label_suffix=None,
empty_permitted=False,
instance=None,
use_required_attribute=None... | BaseModelForm |
python | django-import-export__django-import-export | import_export/exceptions.py | {
"start": 104,
"end": 204
} | class ____(ImportExportError):
"""Raised when a field encounters an error."""
pass
| FieldError |
python | weaviate__weaviate-python-client | weaviate/collections/batch/grpc_batch.py | {
"start": 1122,
"end": 15829
} | class ____(_BaseGRPC):
"""This class is used to insert multiple objects into Weaviate using the gRPC API.
It is used within the `_Data` and `_Batch` classes hence the necessary generalities
and abstractions so as not to couple to strongly to either use-case.
"""
def __init__(
self,
... | _BatchGRPC |
python | pyinstaller__pyinstaller | tests/functional/scripts/pyi_osx_aevent_logger_carbon.py | {
"start": 831,
"end": 965
} | class ____(ctypes.Structure):
_fields_ = [
("descKey", ctypes.c_int),
("descContent", ctypes.c_void_p),
]
| AEDesc |
python | getsentry__sentry | tests/sentry/replays/endpoints/test_project_replay_summary.py | {
"start": 752,
"end": 10970
} | class ____(
TransactionTestCase,
SnubaTestCase,
):
endpoint = "sentry-api-0-project-replay-summary"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.replay_id = uuid.uuid4().hex
self.url = reverse(
self.endpoint,
args=(self.o... | ProjectReplaySummaryTestCase |
python | google__pytype | pytype/pyc/compiler_test.py | {
"start": 220,
"end": 1341
} | class ____(unittest.TestCase):
"""Test python exe utilities."""
def test_parse_interpreter_version(self):
test_cases = (
("Python 3.8.3", (3, 8)),
("Python 3.8.4 :: Something custom (64-bit)", (3, 8)),
("[OS-Y 64-bit] Python 3.9.1", (3, 9)),
)
for version_str, expected in test_c... | PythonExeTest |
python | redis__redis-py | redis/asyncio/multidb/client.py | {
"start": 12420,
"end": 14461
} | class ____(AsyncRedisModuleCommands, AsyncCoreCommands):
"""
Pipeline implementation for multiple logical Redis databases.
"""
def __init__(self, client: MultiDBClient):
self._command_stack = []
self._client = client
async def __aenter__(self: "Pipeline") -> "Pipeline":
ret... | Pipeline |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 10119,
"end": 10304
} | class ____(_DeprecationTestCase):
# Deprecated in NumPy 1.25, 2023-01-16
def test_deprecated_none(self):
self.assert_deprecated(np.finfo, args=(None,))
| TestDeprecatedFinfo |
python | has2k1__plotnine | plotnine/scales/scale_size.py | {
"start": 1197,
"end": 1680
} | class ____(scale_continuous[Literal["legend"] | None]):
"""
Continuous area size scale
"""
_aesthetics = ["size"]
range: InitVar[tuple[float, float]] = (1, 6)
"""
Range ([Minimum, Maximum]) of the size.
"""
_: KW_ONLY
guide: Literal["legend"] | None = "legend"
def __post_i... | scale_size_continuous |
python | numba__numba | numba/tests/test_mixed_tuple_unroller.py | {
"start": 1191,
"end": 2313
} | class ____(MemoryLeakMixin, TestCase):
def check(self, func, var):
cres = func.overloads[func.signatures[0]]
ty = cres.fndesc.typemap[var]
self.assertTrue(isinstance(ty, types.Tuple))
for subty in ty:
self.assertTrue(isinstance(subty, types.Literal), "non literal")
... | TestLiteralTupleInterpretation |
python | vyperlang__vyper | vyper/venom/analysis/mem_ssa.py | {
"start": 2281,
"end": 2590
} | class ____(MemoryAccess):
"""Represents a use of memory state"""
def __init__(self, id: int, load_inst: IRInstruction, loc: MemoryLocation):
super().__init__(id)
self.load_inst = load_inst
self.loc = loc
@property
def inst(self):
return self.load_inst
| MemoryUse |
python | falconry__falcon | e2e-tests/server/hub.py | {
"start": 1225,
"end": 2305
} | class ____:
def __init__(self) -> None:
self._emitters: set[Emitter] = set()
self._users: dict[str, WebSocket] = {}
def _update_emitters(self) -> set[Emitter]:
done = {emitter for emitter in self._emitters if emitter.done}
self._emitters.difference_update(done)
return se... | Hub |
python | joke2k__faker | faker/providers/phone_number/fr_DZ/__init__.py | {
"start": 49,
"end": 180
} | class ____(PhoneNumberProvider):
formats = (
"055# ### ###",
"066# ### ###",
"077# ### ###",
)
| Provider |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_delete_field_simple_app/migrations/0003_delete.py | {
"start": 190,
"end": 494
} | class ____(CheckedMigration):
dependencies = [
("good_flow_delete_field_simple_app", "0002_set_pending"),
]
operations = [
SafeRemoveField(
model_name="testtable",
name="field",
deletion_action=DeletionAction.DELETE,
),
]
| Migration |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 7592,
"end": 7686
} | class ____(Message):
message = 't-string is missing placeholders'
| TStringMissingPlaceholders |
python | joke2k__faker | faker/providers/color/vi_VN/__init__.py | {
"start": 98,
"end": 2692
} | class ____(ColorProvider):
"""
Implement color provider for ``vi_VN`` locale.
#Sources: https://vi.wikipedia.org/wiki/Danh_s%C3%A1ch_m%C3%A0u
"""
all_colors = OrderedDict(
(
("Trắng Antique", "#FAEBD7"),
("Aquamarine", "#7FFFD4"),
("Azure", "#F0FFFF"),
... | Provider |
python | PrefectHQ__prefect | src/prefect/cli/transfer/_migratable_resources/automations.py | {
"start": 1069,
"end": 9627
} | class ____(MigratableResource[Automation]):
_instances: dict[uuid.UUID, Self] = {}
def __init__(self, automation: Automation):
self.source_automation = automation
self.destination_automation: Automation | None = None
self._dependencies: dict[uuid.UUID, MigratableProtocol] = {}
@pro... | MigratableAutomation |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/main_widget.py | {
"start": 1944,
"end": 2006
} | class ____:
Main = 'main'
| ProjectExplorerOptionsMenuSections |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 714,
"end": 833
} | class ____(Item):
name = Field()
age = Field(serializer=custom_serializer)
@dataclasses.dataclass
| CustomFieldItem |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/scrollable_pane.py | {
"start": 616,
"end": 19264
} | class ____(Container):
"""
Container widget that exposes a larger virtual screen to its content and
displays it in a vertical scrollbale region.
Typically this is wrapped in a large `HSplit` container. Make sure in that
case to not specify a `height` dimension of the `HSplit`, so that it will
s... | ScrollablePane |
python | graphql-python__graphene | examples/starwars_relay/schema.py | {
"start": 123,
"end": 393
} | class ____(graphene.ObjectType):
"""A ship in the Star Wars saga"""
class Meta:
interfaces = (relay.Node,)
name = graphene.String(description="The name of the ship.")
@classmethod
def get_node(cls, info, id):
return get_ship(id)
| Ship |
python | mlflow__mlflow | mlflow/entities/trace_location.py | {
"start": 716,
"end": 1455
} | class ____(TraceLocationBase):
"""
Represents the location of an MLflow experiment.
Args:
experiment_id: The ID of the MLflow experiment where the trace is stored.
"""
experiment_id: str
def to_proto(self):
return pb.TraceLocation.MlflowExperimentLocation(experiment_id=self.ex... | MlflowExperimentLocation |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/margins.py | {
"start": 8208,
"end": 10375
} | class ____(Margin):
"""
[Deprecated]
Create margin that displays a prompt.
This can display one prompt at the first line, and a continuation prompt
(e.g, just dots) on all the following lines.
This `PromptMargin` implementation has been largely superseded in favor of
the `get_line_prefix` ... | PromptMargin |
python | sqlalchemy__sqlalchemy | examples/space_invaders/space_invaders.py | {
"start": 6627,
"end": 6740
} | class ____(Glyph):
"""Describe an enemy."""
__mapper_args__ = {"polymorphic_identity": "enemy"}
| EnemyGlyph |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/structured_output.py | {
"start": 8893,
"end": 10678
} | class ____(Generic[SchemaT]):
"""Information for tracking structured output tool metadata.
This contains all necessary information to handle structured responses
generated via tool calls, including the original schema, its type classification,
and the corresponding tool implementation used by the tools... | OutputToolBinding |
python | celery__celery | celery/concurrency/eventlet.py | {
"start": 2302,
"end": 5126
} | class ____(base.BasePool):
"""Eventlet Task Pool."""
Timer = Timer
signal_safe = False
is_green = True
task_join_will_block = False
_pool = None
_pool_map = None
_quick_put = None
def __init__(self, *args, **kwargs):
from eventlet import greenthread
from eventlet.g... | TaskPool |
python | python-visualization__folium | folium/folium.py | {
"start": 2324,
"end": 17564
} | class ____(JSCSSMixin, Evented):
"""Create a Map with Folium and Leaflet.js
Generate a base map of given width and height with either default
tilesets or a custom tileset URL. Folium has built-in all tilesets
available in the ``xyzservices`` package. For example, you can pass
any of the following t... | Map |
python | realpython__materials | tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/library/src/tic_tac_toe/logic/exceptions.py | {
"start": 161,
"end": 245
} | class ____(Exception):
"""Raised when the game score is unknown."""
| UnknownGameScore |
python | fluentpython__example-code | attic/metaprog/plainpoint.py | {
"start": 173,
"end": 688
} | class ____(object):
__slots__ = ['x', 'y'] # save memory in the likely event there are many instances
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({!r}, {!r})'.format(self.x, self.y)
def __eq__(self, other):
if not isinstance(other... | Point |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_event_frequency_handlers.py | {
"start": 13623,
"end": 18789
} | class ____(ConditionTestCase):
def setUp(self) -> None:
super().setUp()
self.condition = Condition.EVENT_UNIQUE_USER_FREQUENCY_COUNT
self.payload: dict[str, str | int | float] = {
"interval": "1h",
"id": EventUniqueUserFrequencyConditionWithConditions.id,
... | TestEventUniqueUserFrequencyConditionWithConditions |
python | geekcomputers__Python | Grocery calculator.py | {
"start": 502,
"end": 1573
} | class ____(dict):
def __init__(self):
self = {}
def addToList(self, item, price):
self.update({item: price})
def Total(self):
total = 0
for items in self:
total += (self[items]) * 0.07 + (self[items])
return total
def Subtotal(self):
subtota... | GroceryList |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/test_trainer.py | {
"start": 47073,
"end": 47364
} | class ____(LightningDataModule):
def __init__(self, dataloaders):
super().__init__()
self._dataloaders = dataloaders
def test_dataloader(self):
return self._dataloaders
def predict_dataloader(self):
return self._dataloaders
| TestLightningDataModule |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/backends/base_backend.py | {
"start": 236,
"end": 454
} | class ____(ABC):
"""
Interface to be shared between the file backend and the database backend(s)
"""
@abstractmethod
def write(self, airbyte_messages: Iterable[AirbyteMessage]) -> None: ...
| BaseBackend |
python | openai__openai-python | src/openai/types/audio/transcription.py | {
"start": 630,
"end": 872
} | class ____(BaseModel):
audio_tokens: Optional[int] = None
"""Number of audio tokens billed for this request."""
text_tokens: Optional[int] = None
"""Number of text tokens billed for this request."""
| UsageTokensInputTokenDetails |
python | numba__numba | numba/tests/test_types.py | {
"start": 11472,
"end": 16048
} | class ____(TestCase):
def test_properties(self):
def check(ty, dtypes, ndim, layout, indexers=None):
self.assertEqual(ty.ndim, ndim)
self.assertEqual(ty.layout, layout)
self.assertEqual(ty.dtypes, dtypes)
views = [types.Array(dtype, 0, "C") for dtype in dtype... | TestNdIter |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 6353,
"end": 12165
} | class ____(nn.Module):
def __init__(self, config):
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 number of attention... | IBertSelfAttention |
python | ansible__ansible | test/lib/ansible_test/_internal/test.py | {
"start": 3499,
"end": 5497
} | class ____(TestResult):
"""Test timeout."""
def __init__(self, timeout_duration: int | float) -> None:
super().__init__(command='timeout', test='')
self.timeout_duration = timeout_duration
def write(self, args: TestConfig) -> None:
"""Write the test results to various locations.""... | TestTimeout |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/types.py | {
"start": 285,
"end": 630
} | class ____(abc.ABC):
"""
Allows serialization of content by casting to a JSON-compatible type.
"""
def jsonable(self) -> Any:
# Default implementation for dataclasses
if is_dataclass(self) and not isinstance(self, type):
return dataclasses.asdict(self)
raise NotImpl... | Serializable |
python | kamyu104__LeetCode-Solutions | Python/similar-string-groups.py | {
"start": 654,
"end": 1981
} | class ____(object):
def numSimilarGroups(self, A):
def isSimilar(a, b):
diff = 0
for x, y in itertools.izip(a, b):
if x != y:
diff += 1
if diff > 2:
return False
return diff == 2
N, L... | Solution |
python | apache__airflow | providers/http/tests/unit/http/notifications/test_http.py | {
"start": 957,
"end": 3435
} | class ____:
def test_class_and_notifier_are_same(self):
assert send_http_notification is HttpNotifier
@mock.patch("airflow.providers.http.notifications.http.HttpHook")
def test_http_notifier(self, mock_http_hook):
notifier = HttpNotifier(
http_conn_id="test_conn_id",
... | TestHttpNotifier |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 21874,
"end": 21937
} | class ____(TestCase):
pass
add(Test1234, '1.2.3.4')
| Test1234 |
python | doocs__leetcode | solution/3300-3399/3312.Sorted GCD Pair Queries/Solution.py | {
"start": 0,
"end": 463
} | class ____:
def gcdValues(self, nums: List[int], queries: List[int]) -> List[int]:
mx = max(nums)
cnt = Counter(nums)
cnt_g = [0] * (mx + 1)
for i in range(mx, 0, -1):
v = 0
for j in range(i, mx + 1, i):
v += cnt[j]
cnt_g[i] -= ... | Solution |
python | pytorch__pytorch | test/dynamo/test_trace_rules.py | {
"start": 19361,
"end": 20243
} | class ____(torch._dynamo.test_case.TestCase):
@unittest.skipIf(
not torch.distributed.is_available(),
"need to import MLP module from distributed",
)
@skipIfWindows(
msg="AssertionError: False is not true : MLP did not survive skip files"
)
def test_module_survive_skip_files(... | TestModuleSurviveSkipFiles |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 10993,
"end": 11973
} | class ____(Widget):
"""A representation of ``st.chat_input``."""
_value: str | None
proto: ChatInputProto = field(repr=False)
placeholder: str
def __init__(self, proto: ChatInputProto, root: ElementTree) -> None:
super().__init__(proto, root)
self.type = "chat_input"
def set_v... | ChatInput |
python | pytorch__pytorch | torch/_dynamo/variables/streams.py | {
"start": 5793,
"end": 7343
} | class ____(FxTracebackAnnotateVariable):
"""This represents torch.cuda.StreamContext"""
@staticmethod
def create(
tx: "InstructionTranslator",
stream_to_enter: "StreamVariable",
**kwargs: dict[str, Any],
) -> "StreamContextVariable":
return StreamContextVariable(
... | StreamContextVariable |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 1979,
"end": 2087
} | class ____(RequestHandler):
def post(self, path):
resources[path] = self.request.body
| PostResource |
python | pydantic__pydantic | tests/test_json_schema.py | {
"start": 92845,
"end": 92950
} | class ____(BaseModel):
class NestedModel(BaseModel):
b: float
nested: NestedModel
| ModelTwo |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-box/llama_index/readers/box/BoxReaderTextExtraction/base.py | {
"start": 500,
"end": 3513
} | class ____(BoxReaderBase):
"""
A reader class for loading text content from Box files.
This class inherits from the `BaseReader` class and specializes in
extracting plain text content from Box files. It utilizes the provided
BoxClient object to interact with the Box API and retrieves the text
r... | BoxReaderTextExtraction |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 25070,
"end": 32379
} | class ____(Patch):
"""
A rectangle defined via an anchor point *xy* and its *width* and *height*.
The rectangle extends from ``xy[0]`` to ``xy[0] + width`` in x-direction
and from ``xy[1]`` to ``xy[1] + height`` in y-direction. ::
: +------------------+
: | ... | Rectangle |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_cleanup_pods.py | {
"start": 14954,
"end": 16332
} | class ____:
"""Tests cleanup of service accounts."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"cleanup": {
"enabled": True,
"labels": {"test_label": "test_label_value"},
},
... | TestCleanupServiceAccount |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-chroma/destination_chroma/destination.py | {
"start": 844,
"end": 4559
} | class ____(Destination):
indexer: Indexer
embedder: Embedder
def _init_indexer(self, config: ConfigModel):
self.embedder = (
create_from_config(config.embedding, config.processing)
if config.embedding.mode != "no_embedding"
else NoEmbedder(config.embedding)
... | DestinationChroma |
python | gevent__gevent | src/gevent/tests/test__local.py | {
"start": 1904,
"end": 2008
} | class ____(local):
@classmethod
def a_classmethod(cls):
return cls
| LocalWithClassMethod |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail.py | {
"start": 1455,
"end": 1531
} | class ____(Model):
model_config = ConfigDict(frozen=False)
| InheritingModel |
python | pytorch__pytorch | torch/_inductor/scheduler.py | {
"start": 2947,
"end": 12596
} | class ____:
"""
This class contains utility functions to decide if we should fuse reductions
reducing across different dimensions of the same input tensor.
"""
@staticmethod
def is_split_reduction(node: BaseSchedulerNode) -> bool:
return node.is_reduction() and all(
subnode.... | MixOrderReduction |
python | TheAlgorithms__Python | data_structures/queues/priority_queue_using_list.py | {
"start": 2636,
"end": 5717
} | class ____:
"""
Element Priority Queue is the same as Fixed Priority Queue except that the value of
the element itself is the priority. The rules for priorities are the same the as
Fixed Priority Queue.
>>> epq = ElementPriorityQueue()
>>> epq.enqueue(10)
>>> epq.enqueue(70)
>>> epq.enq... | ElementPriorityQueue |
python | doocs__leetcode | solution/2100-2199/2136.Earliest Possible Day of Full Bloom/Solution.py | {
"start": 0,
"end": 270
} | class ____:
def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:
ans = t = 0
for pt, gt in sorted(zip(plantTime, growTime), key=lambda x: -x[1]):
t += pt
ans = max(ans, t + gt)
return ans
| Solution |
python | getsentry__sentry | tests/sentry/web/test_urls.py | {
"start": 79,
"end": 354
} | class ____(TestCase):
def test_response(self) -> None:
path = reverse("sentry-docs-redirect")
resp = self.client.get(path)
assert resp["Location"] == "https://docs.sentry.io/"
assert resp.status_code == 302, resp.status_code
| DocsRedirectTest |
python | kamyu104__LeetCode-Solutions | Python/longest-balanced-substring-i.py | {
"start": 638,
"end": 1223
} | class ____(object):
def longestBalanced(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for i in xrange(len(s)):
cnt = [0]*26
mx = unique = 0
for j in xrange(i, len(s)):
if cnt[ord(s[j])-ord('a')] == 0:
... | Solution2 |
python | openai__gym | tests/wrappers/test_nested_dict.py | {
"start": 227,
"end": 2987
} | class ____(gym.Env):
def __init__(self, observation_space, render_mode=None):
self.observation_space = observation_space
self.obs_keys = self.observation_space.spaces.keys()
self.action_space = Box(shape=(1,), low=-1, high=1, dtype=np.float32)
self.render_mode = render_mode
def ... | FakeEnvironment |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/_streaming.py | {
"start": 250,
"end": 982
} | class ____(typing.Protocol[T]):
"""Types for streaming callback handlers.
This is a common mixin that the callback handlers
for both astream events and astream log inherit from.
The `tap_output_aiter` method is invoked in some contexts
to produce callbacks for intermediate results.
"""
de... | _StreamingCallbackHandler |
python | getsentry__sentry-python | sentry_sdk/envelope.py | {
"start": 6198,
"end": 10473
} | class ____:
def __init__(
self,
payload, # type: Union[bytes, str, PayloadRef]
headers=None, # type: Optional[Dict[str, Any]]
type=None, # type: Optional[str]
content_type=None, # type: Optional[str]
filename=None, # type: Optional[str]
):
if headers ... | Item |
python | pypa__warehouse | tests/unit/accounts/test_forms.py | {
"start": 42126,
"end": 43337
} | class ____:
def test_validate(self):
user_service = pretend.stub(
find_userid=lambda userid: 1,
check_password=lambda userid, password, tags=None: True,
)
request = pretend.stub()
form = forms.ReAuthenticateForm(
formdata=MultiDict(
... | TestReAuthenticateForm |
python | scipy__scipy | scipy/integrate/tests/test_quadpack.py | {
"start": 3749,
"end": 4797
} | class ____:
def setup_method(self):
restype = ctypes.c_double
argtypes = (ctypes.c_int, ctypes.c_double)
for name in ['_multivariate_typical', '_multivariate_indefinite',
'_multivariate_sin']:
func = get_clib_test_routine(name, restype, *argtypes)
... | TestMultivariateCtypesQuad |
python | kamyu104__LeetCode-Solutions | Python/number-of-excellent-pairs.py | {
"start": 591,
"end": 1174
} | class ____(object):
def countExcellentPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def popcount(x):
return bin(x)[2:].count('1')
sorted_cnts = sorted(popcount(x) for x in set(nums))
result = 0
left, ... | Solution2 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_mwaa.py | {
"start": 5283,
"end": 7607
} | class ____:
def test_overwritten_conn_passed_to_hook(self):
OVERWRITTEN_CONN = "new-conn-id"
op = MwaaTaskCompletedTrigger(**TRIGGER_TASK_KWARGS, aws_conn_id=OVERWRITTEN_CONN)
assert op.hook().aws_conn_id == OVERWRITTEN_CONN
def test_no_conn_passed_to_hook(self):
DEFAULT_CONN = ... | TestMwaaTaskCompletedTrigger |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B032.py | {
"start": 321,
"end": 385
} | class ____:
def test_self(self):
self.test: int | TestClass |
python | pytorch__pytorch | torch/_export/non_strict_utils.py | {
"start": 35663,
"end": 42340
} | class ____(torch.overrides.TorchFunctionMode):
"""
1. Handles data-dependent errors raised by torch function calls in non-strict.
Any data-dependent error is due to some condition on unbacked symints
that cannot be resolved. A mechanical way of fixing the error is to use
a torch._check() call to as... | _NonStrictTorchFunctionHandler |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/callbacks/test_file.py | {
"start": 240,
"end": 2094
} | class ____(Chain):
"""Fake chain class for testing purposes."""
be_correct: bool = True
the_input_keys: list[str] = ["foo"]
the_output_keys: list[str] = ["bar"]
@property
def input_keys(self) -> list[str]:
"""Input keys."""
return self.the_input_keys
@property
def outp... | FakeChain |
python | getsentry__sentry | tests/sentry/sentry_apps/api/parsers/test_schema.py | {
"start": 169,
"end": 7060
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.schema = {
"elements": [
{
"type": "issue-link",
"link": {
"uri": "/sentry/issues/link",
"required_fields": [
... | TestSchemaValidation |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 55456,
"end": 55831
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("starrable_id", "client_mutation_id")
starrable_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="starrableId"
)
client_mutation_id = sgqlc.types.Fi... | AddStarInput |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 62840,
"end": 64925
} | class ____(_CollectionWithSizes):
"""A collection of n-sided regular polygons."""
_path_generator = mpath.Path.unit_regular_polygon
_factor = np.pi ** (-1/2)
def __init__(self,
numsides,
*,
rotation=0,
sizes=(1,),
**k... | RegularPolyCollection |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 150468,
"end": 153487
} | class ____(LogitsProcessor):
r"""Specialized processor that ensures certain properties around EOS sampling:
1. Only channel 0 can generate EOS
2. If channel 0 has EOS with highest logit, it will be the only candidate
3. If channel 0 has EOS not with highest logit, it will be suppressed
... | DiaEOSChannelFilterLogitsProcessor |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 44771,
"end": 45234
} | class ____(TestCase):
def test_model_field(self):
class ExampleSerializer(serializers.ModelSerializer):
class Meta:
model = OneToOneSourceTestModel
fields = ('target',)
target = OneToOneTargetTestModel(id=1, text='abc')
source = OneToOneSourceTest... | TestModelFieldValues |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_attribute.py | {
"start": 319,
"end": 1636
} | class ____:
a = ""
b = ""
def __init__(self, c):
A.b = _test_source()
self.c = c
self.d = _test_source()
def sink_a(self):
_test_sink(A.a)
def sink_b(self):
# TODO(T145247918): False negative, request from seceng to
# find this issue even without an... | A |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-trello/unit_tests/test_components.py | {
"start": 132,
"end": 2717
} | class ____(Stream):
def __init__(self, records):
self.records = records
def primary_key(self):
return
def read_records(self, sync_mode):
return self.records
# test cases as a list of tuples (boards_records, organizations_records, expected_board_ids)
test_cases = [
(
#... | MockStream |
python | doocs__leetcode | solution/1100-1199/1177.Can Make Palindrome from Substring/Solution.py | {
"start": 0,
"end": 453
} | class ____:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
n = len(s)
ss = [[0] * 26 for _ in range(n + 1)]
for i, c in enumerate(s, 1):
ss[i] = ss[i - 1][:]
ss[i][ord(c) - ord("a")] += 1
ans = []
for l, r, k in queries:
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/snapshot_test.py | {
"start": 42082,
"end": 49557
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_snapshot_dataset(self,
num_threads=1,
repeat=False,
pending_snapshot_expiry_seconds=-1,
... | LegacySnapshotCheckpointTest |
python | geekcomputers__Python | bank_managment_system/backend.py | {
"start": 27,
"end": 5258
} | class ____:
def __init__(self, db_name="bankmanaging.db"):
self.db_path = os.path.join(os.path.dirname(__file__), db_name)
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.cur = self.conn.cursor()
self._setup_tables()
self.acc_no = self._get_last_acc_no... | DatabaseManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_dimension_performance_report.py | {
"start": 27895,
"end": 37016
} | class ____(TestBaseProductDimensionPerformanceReport):
stream_name = "product_dimension_performance_report_monthly"
report_file = "product_dimension_performance_report_monthly"
incremental_report_file = "product_dimension_performance_report_monthly_incremental"
incremental_report_file_with_records_furth... | TestProductDimensionPerformanceReportMonthlyStream |
python | scrapy__scrapy | scrapy/extensions/httpcache.py | {
"start": 1792,
"end": 9737
} | class ____:
MAXAGE = 3600 * 24 * 365 # one year
def __init__(self, settings: BaseSettings):
self.always_store: bool = settings.getbool("HTTPCACHE_ALWAYS_STORE")
self.ignore_schemes: list[str] = settings.getlist("HTTPCACHE_IGNORE_SCHEMES")
self._cc_parsed: WeakKeyDictionary[
... | RFC2616Policy |
python | astropy__astropy | astropy/coordinates/tests/test_earth.py | {
"start": 3476,
"end": 16723
} | class ____:
def setup_method(self):
self.lon = Longitude(
[0.0, 45.0, 90.0, 135.0, 180.0, -180, -90, -45],
u.deg,
wrap_angle=180 * u.deg,
)
self.lat = Latitude([+0.0, 30.0, 60.0, +90.0, -90.0, -60.0, -30.0, 0.0], u.deg)
self.h = u.Quantity([0.1, 0.... | TestInput |
python | mlflow__mlflow | mlflow/transformers/__init__.py | {
"start": 73266,
"end": 132314
} | class ____:
def __init__(self, pipeline, flavor_config=None, model_config=None, prompt_template=None):
self.pipeline = pipeline
self.flavor_config = flavor_config
# The predict method updates the model_config several times. This should be done over a
# deep copy of the original model... | _TransformersWrapper |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/aio/_connection.py | {
"start": 6107,
"end": 8528
} | class ____(AsyncConnectionPool):
"""Async connection pool for Azure Database for PostgreSQL connections."""
def __init__(
self,
conninfo: str = "",
*,
azure_conn_info: AsyncConnectionInfo = AsyncConnectionInfo(),
**kwargs,
):
if isinstance(azure_conn_info.cre... | AsyncAzurePGConnectionPool |
python | pandas-dev__pandas | pandas/tests/indexes/ranges/test_indexing.py | {
"start": 5161,
"end": 5593
} | class ____:
def test_where_putmask_range_cast(self):
# GH#43240
idx = RangeIndex(0, 5, name="test")
mask = np.array([True, True, False, False, False])
result = idx.putmask(mask, 10)
expected = Index([10, 10, 2, 3, 4], dtype=np.int64, name="test")
tm.assert_index_equa... | TestWhere |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 17074,
"end": 17610
} | class ____(GroupType):
type_id = 1018
slug = "performance_p95_endpoint_regression"
description = "Endpoint Regression"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.METRIC.value
enable_auto_resolve = False
enable_escalation_detection = False
default_priority = Pr... | PerformanceP95EndpointRegressionGroupType |
python | PrefectHQ__prefect | src/prefect/cli/transfer/_migratable_resources/base.py | {
"start": 957,
"end": 1844
} | class ____(Generic[T], abc.ABC):
@property
@abc.abstractmethod
def source_id(self) -> uuid.UUID: ...
@property
@abc.abstractmethod
def destination_id(self) -> uuid.UUID | None: ...
# Using this construct method because we may want to persist a serialized version of the object
# to disk... | MigratableResource |
python | huggingface__transformers | src/transformers/models/vaultgemma/modular_vaultgemma.py | {
"start": 9127,
"end": 10544
} | class ____(Gemma2DecoderLayer):
def __init__(self, **super_kwargs):
super().__init__(**super_kwargs)
del self.post_attention_layernorm
del self.post_feedforward_layernorm
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, tor... | VaultGemmaDecoderLayer |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14432,
"end": 14548
} | class ____(QueryExecutionError):
"""
Exception raised when a query is not valid.
"""
| SchemaValidationError |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/tokenize_stage.py | {
"start": 1878,
"end": 2213
} | class ____(StatefulStage):
"""
A stage that tokenizes the input.
"""
fn: Type[StatefulStageUDF] = TokenizeUDF
def get_required_input_keys(self) -> Dict[str, str]:
"""The required input keys of the stage and their descriptions."""
return {"prompt": "The text prompt (str) to tokenize... | TokenizeStage |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 39652,
"end": 44401
} | class ____(RemBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.rembert = RemBertModel(config)
self.dropout = nn.Dropout(config.classifier_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final pro... | RemBertForMultipleChoice |
python | keon__algorithms | algorithms/tree/deepest_left.py | {
"start": 246,
"end": 985
} | class ____:
def __init__(self):
self.depth = 0
self.Node = None
def find_deepest_left(root, is_left, depth, res):
if not root:
return
if is_left and depth > res.depth:
res.depth = depth
res.Node = root
find_deepest_left(root.left, True, depth + 1, res)
find_... | DeepestLeft |
python | django__django | django/contrib/contenttypes/models.py | {
"start": 5011,
"end": 6844
} | class ____(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(_("python model class name"), max_length=100)
objects = ContentTypeManager()
class Meta:
verbose_name = _("content type")
verbose_name_plural = _("content types")
db_table = "django_c... | ContentType |
python | django__django | tests/template_tests/test_parser.py | {
"start": 428,
"end": 8573
} | class ____(SimpleTestCase):
def test_token_smart_split(self):
"""
#7027 -- _() syntax should work with spaces
"""
token = Token(
TokenType.BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")'
)
split = token.split_contents()
self.assertEqua... | ParserTests |
python | doocs__leetcode | solution/0200-0299/0209.Minimum Size Subarray Sum/Solution.py | {
"start": 0,
"end": 347
} | class ____:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n = len(nums)
s = list(accumulate(nums, initial=0))
ans = n + 1
for i, x in enumerate(s):
j = bisect_left(s, x + target)
if j <= n:
ans = min(ans, j - i)
return ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/add-to-array-form-of-integer.py | {
"start": 36,
"end": 526
} | class ____(object):
def addToArrayForm(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: List[int]
"""
A.reverse()
carry, i = K, 0
A[i] += carry
carry, A[i] = divmod(A[i], 10)
while carry:
i += 1
if i < le... | Solution |
python | getsentry__sentry | tests/sentry/workflow_engine/migration_helpers/test_migrate_alert_rule.py | {
"start": 47124,
"end": 49553
} | class ____(BaseMetricAlertMigrationTest):
def setUp(self) -> None:
self.metric_alert = self.create_alert_rule()
self.alert_rule_trigger = self.create_alert_rule_trigger(
alert_rule=self.metric_alert, label="critical"
)
self.alert_rule_trigger_action = self.create_alert_ru... | DualDeleteAlertRuleTriggerActionTest |
python | walkccc__LeetCode | solutions/817. Linked List Components/817.py | {
"start": 0,
"end": 300
} | class ____:
def numComponents(self, head: ListNode | None, nums: list[int]) -> int:
ans = 0
numsSet = set(nums)
while head:
if head.val in numsSet and (
head.next == None or head.next.val not in numsSet):
ans += 1
head = head.next
return ans
| Solution |
python | PyCQA__pylint | tests/checkers/unittest_unicode/__init__.py | {
"start": 1803,
"end": 2274
} | class ____:
"""Simple Faker representing a Module node.
Astroid crashes in a number of cases if we want to lint unsupported encodings.
So, this is used to test the behaviour of the encoding checker.
This shall ensure that our checks keep working once Python supports UTF16/32.
"""
file: Path
... | FakeNode |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadb.py | {
"start": 2258,
"end": 2479
} | class ____(MySQLTypeCompiler):
def visit_INET4(self, type_: INET4, **kwargs: Any) -> str:
return "INET4"
def visit_INET6(self, type_: INET6, **kwargs: Any) -> str:
return "INET6"
| MariaDBTypeCompiler |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 15516,
"end": 17173
} | class ____(LossFunctionWrapper):
"""Computes the squared hinge loss between `y_true` & `y_pred`.
Formula:
```python
loss = square(maximum(1 - y_true * y_pred, 0))
```
`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.
A... | SquaredHinge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.