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
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_server_tool_usage.py
{ "start": 157, "end": 352 }
class ____(BaseModel): web_fetch_requests: int """The number of web fetch tool requests.""" web_search_requests: int """The number of web search tool requests."""
BetaServerToolUsage
python
django__django
tests/aggregation/tests.py
{ "start": 1097, "end": 1455 }
class ____(Now): template = "CURRENT_TIMESTAMP" output_field = DateTimeField() def as_sql(self, compiler, connection, **extra_context): if connection.features.test_now_utc_template: extra_context["template"] = connection.features.test_now_utc_template return super().as_sql(compi...
NowUTC
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/tests/common/test_connection.py
{ "start": 413, "end": 976 }
class ____(BaseModel): """A minimal mock cursor base model used for testing DB interactions. Attributes: broken (bool): If True, simulates a broken cursor that fails queries. last_query (str | sql.SQL | None): Stores the last executed query for inspection. response (dict | None): Value ...
MockCursorBase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/kwargsUnpack1.py
{ "start": 2072, "end": 2151 }
class ____(Protocol): def __call__(self, *, v1: int) -> None: ...
TDProtocol4
python
marshmallow-code__apispec
tests/test_core.py
{ "start": 6798, "end": 24569 }
class ____(RefsSchemaTestMixin): properties = { "id": {"type": "integer", "format": "int64"}, "name": {"type": "string", "example": "doggie"}, } def test_schema(self, spec): spec.components.schema("Pet", {"properties": self.properties}) schemas = get_schemas(spec) as...
TestComponents
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 37214, "end": 42407 }
class ____(PerceiverPreTrainedModel): def __init__(self, config): super().__init__(config) trainable_position_encoding_kwargs_decoder = {"num_channels": config.d_latents, "index_dims": 1} self.num_labels = config.num_labels self.perceiver = PerceiverModel( config, ...
PerceiverForSequenceClassification
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/validators/base/data_condition.py
{ "start": 748, "end": 1382 }
class ____( CamelSnakeSerializer, Generic[ComparisonType, ConditionResult], ): id = serializers.IntegerField(required=False) type = serializers.ChoiceField(choices=[(t.value, t.value) for t in Condition]) comparison = serializers.JSONField(required=True) condition_result = serializers.JSONField(...
AbstractDataConditionValidator
python
tensorflow__tensorflow
tensorflow/python/keras/layers/convolutional.py
{ "start": 2060, "end": 15820 }
class ____(Layer): """Abstract N-D convolution layer (private, used as implementation base). This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector i...
Conv
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_protect04.py
{ "start": 315, "end": 1098 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("protect04.xlsx") def test_create_file(self): """Test the a simple XlsxWriter file with worksheet protection.""" workbook = Workboo...
TestCompareXLSXFiles
python
networkx__networkx
networkx/algorithms/link_analysis/tests/test_pagerank.py
{ "start": 6233, "end": 7282 }
class ____(TestPageRank): def test_scipy_pagerank(self): G = self.G p = _pagerank_scipy(G, alpha=0.9, tol=1.0e-08) for n in G: assert p[n] == pytest.approx(G.pagerank[n], abs=1e-4) personalize = {n: random.random() for n in G} p = _pagerank_scipy(G, alpha=0.9, tol...
TestPageRankScipy
python
Lightning-AI__lightning
examples/pytorch/domain_templates/computer_vision_fine_tuning.py
{ "start": 6046, "end": 9565 }
class ____(LightningModule): def __init__( self, backbone: str = "resnet50", train_bn: bool = False, milestones: tuple = (2, 4), batch_size: int = 32, lr: float = 1e-3, lr_scheduler_gamma: float = 1e-1, num_workers: int = 6, **kwargs, ) -> ...
TransferLearningModel
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/attributes.py
{ "start": 2149, "end": 2411 }
class ____: dictionary = {"text": "modelled as tainted", "other": "benign"} def test_issue_with_text_key_of_dictionary(c: C): _test_sink(c.dictionary["text"]) def test_no_issue_with_other_key_of_dictionary(c: C): _test_sink(c.dictionary["other"])
C
python
spyder-ide__spyder
spyder/utils/installers.py
{ "start": 1706, "end": 2147 }
class ____(SpyderInstallerError): """Error for PyLSP issues""" def _msg(self, msg): files = glob.glob(os.path.join(get_conf_path('lsp_logs'), '*.log')) cat = '' for file in files: cat += f'{file}\n' with open(file, 'r') as f: cat += textwrap.inden...
InstallerPylspError
python
tensorflow__tensorflow
tensorflow/python/checkpoint/saveable_compat_test.py
{ "start": 1349, "end": 2892 }
class ____(test.TestCase): def test_lookup_table_compatibility(self): saveable_compat.force_checkpoint_conversion(False) table_module = generate_checkpoint.TableModule() ckpt = checkpoint.Checkpoint(table_module) checkpoint_directory = self.get_temp_dir() checkpoint_path = os.path.join(checkpoin...
SaveableCompatTest
python
getsentry__sentry
tests/sentry/snuba/test_tasks.py
{ "start": 19645, "end": 45741 }
class ____(TestCase): aggregate_mappings: dict[SnubaQuery.Type, dict[Dataset, dict[str, Any]]] = { SnubaQuery.Type.ERROR: { Dataset.Events: { "count_unique(user)": lambda org_id: [ Function( function="uniq", para...
BuildSnqlQueryTest
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_indexing.py
{ "start": 22808, "end": 25245 }
class ____: @pytest.mark.parametrize("box", [date, datetime, Timestamp]) @pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)]) def test_get_slice_bounds_datetime_within( self, box, side, expected, tz_aware_fixture ): # GH 35690 tz = tz_aware_fixture inde...
TestGetSliceBounds
python
falconry__falcon
falcon/_typing.py
{ "start": 1861, "end": 2340 }
class ____(Enum): UNSET = auto() _T = TypeVar('_T') _UNSET = _Unset.UNSET UnsetOr = Union[Literal[_Unset.UNSET], _T] _ReqT = TypeVar('_ReqT', bound='Request', contravariant=True) _RespT = TypeVar('_RespT', bound='Response', contravariant=True) _AReqT = TypeVar('_AReqT', bound='AsgiRequest', contravariant=True) _...
_Unset
python
django__django
tests/auth_tests/test_management.py
{ "start": 59514, "end": 60027 }
class ____(TestCase): databases = {"default", "other"} def test_set_permissions_fk_to_using_parameter(self): Permission.objects.using("other").delete() with self.assertNumQueries(4, using="other") as captured_queries: create_permissions(apps.get_app_config("auth"), verbosity=0, usin...
CreatePermissionsMultipleDatabasesTests
python
xlwings__xlwings
xlwings/constants.py
{ "start": 1186, "end": 8394 }
class ____: xlNextToAxis = 4 # from enum Constants xlNoDocuments = 3 # from enum Constants xlNone = -4142 # from enum Constants xlNotes = -4144 # from enum Constants xlOff = -4146 # from enum Constants xl3DEffects1 = 13 # from enum Constants xl3DBar = -4099 # from enum Constants x...
Constants
python
python-poetry__poetry
tests/types.py
{ "start": 3429, "end": 3707 }
class ____(Protocol): def __call__( self, transformer_or_suffix: NormalizedNameTransformer | str, repository_name: str = "special", repository_url: str = "https://legacy.foo.bar", ) -> LegacyRepository: ...
SpecializedLegacyRepositoryMocker
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/port.py
{ "start": 1096, "end": 1334 }
class ____: @property def some_source(): return _test_source() def refer_to_method_as_field(foo: Foo): # This comes up in Instagram due to @cached_property decorators taint = foo.some_source _test_sink(taint)
Foo
python
pydantic__pydantic
pydantic/networks.py
{ "start": 28956, "end": 29437 }
class ____(AnyUrl): """A type that will accept any ClickHouse DSN. * User info required * TLD not required * Host not required """ _constraints = UrlConstraints( allowed_schemes=[ 'clickhouse+native', 'clickhouse+asynch', 'clickhouse+http', ...
ClickHouseDsn
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec53.py
{ "start": 374, "end": 476 }
class ____(Mixin): def __init__(self, data: int) -> None: pass Next.factory("", data=2)
Next
python
getsentry__sentry
src/sentry/api/serializers/models/group.py
{ "start": 3218, "end": 3288 }
class ____(TypedDict): displayName: str url: str
GroupAnnotation
python
wandb__wandb
wandb/apis/public/registries/_freezable_list.py
{ "start": 5887, "end": 6323 }
class ____(FreezableList[str]): def remove(self, value: str) -> None: try: super().remove(value) except ValueError: raise ValueError( f"Cannot remove artifact type: {value!r} that has been saved to the registry" ) def __repr__(self) -> str: ...
AddOnlyArtifactTypesList
python
tensorflow__tensorflow
tensorflow/python/keras/layers/pooling.py
{ "start": 34330, "end": 36865 }
class ____(GlobalPooling1D): """Global average pooling operation for temporal data. Examples: >>> input_shape = (2, 3, 4) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalAveragePooling1D()(x) >>> print(y.shape) (2, 4) Args: data_format: A string, one of `channels_last` (...
GlobalAveragePooling1D
python
sympy__sympy
sympy/printing/aesaracode.py
{ "start": 2818, "end": 18921 }
class ____(Printer): """ .. deprecated:: 1.14. The ``Aesara Code printing`` is deprecated.See its documentation for more information. See :ref:`deprecated-aesaraprinter` for details. Code printer which creates Aesara symbolic expression graphs. Parameters ========== cache : di...
AesaraPrinter
python
tiangolo__fastapi
docs_src/dependencies/tutorial003.py
{ "start": 167, "end": 635 }
class ____: def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit @app.get("/items/") async def read_items(commons=Depends(CommonQueryParams)): response = {} if commons.q: response.update({"q": common...
CommonQueryParams
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/tasks.py
{ "start": 13302, "end": 16865 }
class ____(GoogleCloudBaseOperator): """ Lists queues from Cloud Tasks. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudTasksQueuesListOperator` :param location: The location name in which the queues were created. :...
CloudTasksQueuesListOperator
python
skorch-dev__skorch
skorch/tests/callbacks/test_logging.py
{ "start": 12866, "end": 15265 }
class ____: @pytest.fixture def net_cls(self): from skorch import NeuralNetClassifier return NeuralNetClassifier @pytest.fixture def data(self, classifier_data): X, y = classifier_data # accelerate training since we don't care for the loss X, y = X[:40], y[:40] ...
TestWandb
python
pytorch__pytorch
test/jit/test_batch_mm.py
{ "start": 209, "end": 10132 }
class ____(JitTestCase): @staticmethod def _get_test_tensors(n: int): return [ ( torch.tensor([[1 + x, 2 + x, 3 + x], [4 + x, 5 + x, 6 + x]]) if x % 2 == 0 else torch.tensor([[1 + x, 2 + x], [3 + x, 4 + x], [5 + x, 6 + x]]) ) ...
TestBatchMM
python
astropy__astropy
astropy/coordinates/builtin_frames/galactocentric.py
{ "start": 1730, "end": 17997 }
class ____(ScienceState): """Global setting of default values for the frame attributes in the `~astropy.coordinates.Galactocentric` frame. These constancts may be updated in future versions of ``astropy``. Note that when using `~astropy.coordinates.Galactocentric`, changing values here will not affect ...
galactocentric_frame_defaults
python
walkccc__LeetCode
solutions/1007. Minimum Domino Rotations For Equal Row/1007.py
{ "start": 0, "end": 260 }
class ____: def minDominoRotations(self, tops: list[int], bottoms: list[int]) -> int: for num in range(1, 7): if all(num in pair for pair in zip(tops, bottoms)): return len(tops) - max(tops.count(num), bottoms.count(num)) return -1
Solution
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 1626, "end": 1685 }
class ____(Exception): """The base pip error."""
PipError
python
celery__celery
t/unit/worker/test_state.py
{ "start": 797, "end": 864 }
class ____(state.Persistent): storage = MockShelve()
MyPersistent
python
qdrant__qdrant-client
qdrant_client/http/api_client.py
{ "start": 2016, "end": 2944 }
class ____(Generic[ClientT]): def __init__(self, host: str, **kwargs: Any): self.client = ApiClient(host, **kwargs) self.aliases_api = SyncAliasesApi(self.client) self.beta_api = SyncBetaApi(self.client) self.collections_api = SyncCollectionsApi(self.client) self.distributed...
SyncApis
python
wandb__wandb
wandb/sdk/artifacts/_generated/input_types.py
{ "start": 1718, "end": 2139 }
class ____(GQLInput): graphql: Optional[int] = None sdk_graphql: Optional[int] = Field(alias="sdkGraphql", default=None) filestream_count: Optional[int] = Field(alias="filestreamCount", default=None) filestream_size: Optional[int] = Field(alias="filestreamSize", default=None) sdk_graphql_query_secon...
RateLimitsInput
python
getsentry__sentry
src/sentry/constants.py
{ "start": 20154, "end": 32988 }
class ____(Enum): HTTP = "http" DB = "db" ASSETS = "assets" # previously named resources APP_START = "app_start" SCREEN_LOAD = "screen_load" VITAL = "vital" CACHE = "cache" QUEUE = "queue" AGENTS = "agents" MCP = "mcp" StatsPeriod = namedtuple("StatsPeriod", ("segments", "inte...
InsightModules
python
ray-project__ray
python/ray/data/block.py
{ "start": 7700, "end": 8705 }
class ____(BlockMetadata): schema: Optional[Schema] = None def __init__(self, metadata: BlockMetadata, schema: Optional["Schema"] = None): super().__init__( input_files=metadata.input_files, size_bytes=metadata.size_bytes, num_rows=metadata.num_rows, exec...
BlockMetadataWithSchema
python
realpython__materials
top-python-game-engines/pygame/pygame_game.py
{ "start": 1422, "end": 5047 }
class ____(pygame.sprite.Sprite): def __init__(self): """Initialize the coin sprite""" super(Coin, self).__init__() # Get the image to draw for the coin coin_image = str(Path.cwd() / "images" / "coin_gold.png") # Load the image, preserve alpha channel for transparency ...
Coin
python
dateutil__dateutil
src/dateutil/parser/_parser.py
{ "start": 2002, "end": 8054 }
class ____(object): # Fractional seconds are sometimes split by a comma _split_decimal = re.compile("([.,])") def __init__(self, instream): if isinstance(instream, (bytes, bytearray)): instream = instream.decode() if isinstance(instream, text_type): instream = Strin...
_timelex
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/type_api.py
{ "start": 42134, "end": 49067 }
class ____(TypeEngineMixin): """mixin that defines attributes and behaviors specific to third-party datatypes. "Third party" refers to datatypes that are defined outside the scope of SQLAlchemy within either end-user application code or within external extensions to SQLAlchemy. Subclasses curr...
ExternalType
python
huggingface__transformers
src/transformers/models/pix2struct/modeling_pix2struct.py
{ "start": 24442, "end": 25122 }
class ____(nn.Module): def __init__(self, config: Pix2StructTextConfig): super().__init__() self.DenseReluDense = Pix2StructTextDenseGatedActDense(config) self.layer_norm = Pix2StructLayerNorm(config.hidden_size, eps=config.layer_norm_epsilon) self.dropout = nn.Dropout(config.dropou...
Pix2StructTextLayerFF
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 50056, "end": 52388 }
class ____(TreeTestCase): """ Tests for the ``recursetree`` template filter. """ fixtures = ["categories.json"] template = re.sub( r"(?m)^[\s]+", "", """ {% load mptt_tags %} <ul> {% recursetree nodes %} <li> {{...
RecurseTreeTestCase
python
networkx__networkx
networkx/algorithms/tree/tests/test_distance_measures.py
{ "start": 52, "end": 1922 }
class ____: @pytest.mark.parametrize("graph_type", (nx.Graph, nx.MultiGraph)) def test_center_simple_tree(self, graph_type): G = nx.Graph([(1, 2), (1, 3), (2, 4), (2, 5)], create_using=graph_type) assert set(nx.tree.center(G)) == {1, 2} @pytest.mark.parametrize("r", range(2, 5)) @pytest...
TestCenter
python
pypa__installer
tests/test_utils.py
{ "start": 440, "end": 974 }
class ____: def test_basics(self): result = parse_metadata_file( textwrap.dedent( """\ Name: package Version: 1.0.0 Multi-Use-Field: 1 Multi-Use-Field: 2 Multi-Use-Field: 3 """ ) ) ...
TestParseMetadata
python
django-debug-toolbar__django-debug-toolbar
tests/panels/test_profiling.py
{ "start": 3689, "end": 4165 }
class ____(IntegrationTestCase): def test_view_executed_once(self): self.assertEqual(User.objects.count(), 0) response = self.client.get("/new_user/") self.assertContains(response, "Profiling") self.assertEqual(User.objects.count(), 1) with self.assertRaises(IntegrityError)...
ProfilingPanelIntegrationTestCase
python
huggingface__transformers
tests/models/ovis2/test_processor_ovis2.py
{ "start": 963, "end": 4675 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Ovis2Processor @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") return tokenizer_class.from_pretrained("thisisiron/Ovis2-1B-hf") @staticmethod def pr...
Ovis2ProcessorTest
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 2133, "end": 2738 }
class ____(Parameter): """ Same as `Parameter` but can indicate its modified status via the ``dirty`` property. This flag also gets set automatically when a parameter is modified. This ability to track parameter's modified status is needed for automatic update of WCSLIB's prjprm structure (whic...
_ParameterDS
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 126783, "end": 133152 }
class ____(Request): """ Create or update a new model for a task :param task: Task id :type task: str :param uri: URI for the model. Exactly one of uri or override_model_id is a required. :type uri: str :param name: Model name Unique within the company. :type name: str :para...
UpdateForTaskRequest
python
coleifer__peewee
tests/regressions.py
{ "start": 55384, "end": 55455 }
class ____(TestModel): name = TextField() value = IntegerField()
DF
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_autofilter11.py
{ "start": 315, "end": 2462 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("autofilter11.xlsx") self.set_text_file("autofilter_data.txt") def test_create_file(self): """ Test the creation of a simple...
TestCompareXLSXFiles
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/xcom_arg.py
{ "start": 16195, "end": 16948 }
class ____(Sequence): values: Sequence[Sequence | dict] fillvalue: Any = attrs.field(default=NOTSET, kw_only=True) @staticmethod def _get_or_fill(container: Sequence | dict, index: Any, fillvalue: Any) -> Any: try: return container[index] except (IndexError, KeyError): ...
_ZipResult
python
ansible__ansible
lib/ansible/module_utils/urls.py
{ "start": 6891, "end": 6978 }
class ____(Exception): """Failed to connect to the server""" pass
ConnectionError
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 5827, "end": 6807 }
class ____(ImageRenderer): """ Renderer to display figures as static PDF images. This renderer requires either the kaleido package or the orca command-line utility and is compatible with JupyterLab and the LaTeX-based nbconvert export to PDF. mime type: 'application/pdf' """ def __init__(...
PdfRenderer
python
huggingface__transformers
tests/models/videomae/test_image_processing_videomae.py
{ "start": 3010, "end": 9531 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = VideoMAEImageProcessor if is_vision_available() else None def setUp(self): super().setUp() self.image_processor_tester = VideoMAEImageProcessingTester(self) @property def image_processor_dict(self): ...
VideoMAEImageProcessingTest
python
keras-team__keras
keras/src/layers/pooling/average_pooling_test.py
{ "start": 4318, "end": 7860 }
class ____(testing.TestCase): @parameterized.parameters( (2, 1, "valid", "channels_last", (3, 5, 4), (3, 4, 4)), (2, 1, "same", "channels_first", (3, 5, 4), (3, 5, 4)), ((2,), (2,), "valid", "channels_last", (3, 5, 4), (3, 2, 4)), ) def test_average_pooling1d( self, p...
AveragePoolingBasicTest
python
spyder-ide__spyder
external-deps/spyder-kernels/spyder_kernels/customize/umr.py
{ "start": 258, "end": 3554 }
class ____: """ User Module Reloader (UMR) aims at deleting user modules to force Python to deeply reload them during import pathlist [list]: blacklist in terms of module path namelist [list]: blacklist in terms of module name """ def __init__(self, namelist=None, pathlist=None, shell=None...
UserModuleReloader
python
anthropics__anthropic-sdk-python
tests/lib/streaming/test_messages.py
{ "start": 6388, "end": 12217 }
class ____: @pytest.mark.asyncio @pytest.mark.respx(base_url=base_url) async def test_basic_response(self, respx_mock: MockRouter) -> None: respx_mock.post("/v1/messages").mock( return_value=httpx.Response(200, content=to_async_iter(get_response("basic_response.txt"))) ) ...
TestAsyncMessages
python
psf__black
tests/data/miscellaneous/force_pyi.py
{ "start": 223, "end": 270 }
class ____: ... @baz def foo() -> None: ...
E
python
getsentry__sentry
tests/sentry/snuba/test_query_subscription_consumer.py
{ "start": 4869, "end": 7006 }
class ____(BaseQuerySubscriptionTest, unittest.TestCase): def run_test(self, message): parse_message_value(json.dumps(message).encode(), self.jsoncodec) def run_invalid_schema_test(self, message): with pytest.raises(InvalidSchemaError): self.run_test(message) def run_invalid_pa...
ParseMessageValueTest
python
falconry__falcon
falcon/asgi_spec.py
{ "start": 1637, "end": 2056 }
class ____: """WebSocket close codes used by the Falcon ASGI framework. See also: https://tools.ietf.org/html/rfc6455#section-7.4 """ NORMAL = 1000 SERVER_ERROR = 1011 FORBIDDEN = 3403 PATH_NOT_FOUND = 3404 HANDLER_NOT_FOUND = 3405 # TODO: use a typed dict for event dicts AsgiEvent =...
WSCloseCode
python
tox-dev__tox
src/tox/config/source/toml_pyproject.py
{ "start": 1785, "end": 1857 }
class ____(TomlSection): PREFIX = ("tool", "tox")
TomlPyProjectSection
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 58609, "end": 61628 }
class ____(fixtures.TablesTest): __backend__ = True """Test timezone-aware datetimes. psycopg will return a datetime with a tzinfo attached to it, if postgresql returns it. python then will not let you compare a datetime with a tzinfo to a datetime that doesn't have one. this test illustrate...
TimezoneTest
python
getlogbook__logbook
src/logbook/ticketing.py
{ "start": 1624, "end": 1925 }
class ____(LogRecord): """Represents an occurrence of a ticket.""" def __init__(self, db, row): self.update_from_dict(json.loads(row.data)) self.db = db self.time = row.time self.ticket_id = row.ticket_id self.occurrence_id = row.occurrence_id
Occurrence
python
coleifer__peewee
tests/regressions.py
{ "start": 35113, "end": 37056 }
class ____(ModelTestCase): requires = [Site, Page, PageItem] def setUp(self): super(TestModelFilterJoinOrdering, self).setUp() with self.database.atomic(): s1, s2 = [Site.create(url=s) for s in ('s1', 's2')] p11, p12, p21 = [Page.create(site=s, title=t) for s, t in ...
TestModelFilterJoinOrdering
python
celery__celery
t/unit/utils/test_saferepr.py
{ "start": 2005, "end": 2045 }
class ____(frozenset): pass
frozenset2
python
django__django
tests/order_with_respect_to/tests.py
{ "start": 407, "end": 1080 }
class ____(SimpleTestCase): @isolate_apps("order_with_respect_to") def test_duplicate_order_field(self): class Bar(models.Model): class Meta: app_label = "order_with_respect_to" class Foo(models.Model): bar = models.ForeignKey(Bar, models.CASCADE) ...
OrderWithRespectToTests
python
sanic-org__sanic
sanic/logging/formatter.py
{ "start": 3989, "end": 6069 }
class ____(AutoFormatter): """ The DebugFormatter is used for development and debugging purposes. It can be used directly, or it will be automatically selected if the environment is set up for development and is using the AutoFormatter. """ IDENT_LIMIT = 5 MESSAGE_START = 23 DATE_FORMA...
DebugFormatter
python
django__django
tests/db_functions/math/test_acos.py
{ "start": 269, "end": 2346 }
class ____(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_acos=ACos("normal")).first() self.assertIsNone(obj.null_acos) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-0.9"), n2=Decimal("0.6")) obj ...
ACosTests
python
cherrypy__cherrypy
cherrypy/test/test_core.py
{ "start": 522, "end": 28903 }
class ____(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose def index(self): return 'hello' favicon_ico = tools.staticfile.handler(filename=favicon_path) @cherrypy.expose def defct(self, newct)...
CoreRequestHandlingTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol11.py
{ "start": 277, "end": 439 }
class ____(Protocol): def __call__(self, x: T) -> A[list[T], T]: ... def func1() -> BProto: def make_a(x: T) -> A[list[T], T]: ... return make_a
BProto
python
realpython__materials
tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/library/src/tic_tac_toe/game/players_async.py
{ "start": 206, "end": 829 }
class ____(metaclass=abc.ABCMeta): def __init__(self, mark: Mark) -> None: self.mark = mark async def make_move(self, game_state: GameState) -> GameState: if self.mark is game_state.current_mark: if move := await self.get_move(game_state): return move.after_state ...
AsyncPlayer
python
davidhalter__jedi
jedi/file_io.py
{ "start": 2255, "end": 2337 }
class ____(file_io.KnownContentFileIO, FileIOFolderMixin): pass
KnownContentFileIO
python
getsentry__sentry
tests/sentry/integrations/slack/actions/notification/test_slack_notify_service_action.py
{ "start": 867, "end": 22974 }
class ____(RuleTestCase): rule_cls = SlackNotifyServiceAction def setUp(self) -> None: with assume_test_silo_mode(SiloMode.REGION): self.organization = self.create_organization(id=1, owner=self.user) self.project = self.create_project(organization=self.organization) wit...
TestInit
python
scrapy__scrapy
tests/test_addons.py
{ "start": 1032, "end": 1541 }
class ____: def test_update_settings(self): settings = BaseSettings() settings.set("KEY1", "default", priority="default") settings.set("KEY2", "project", priority="project") addon_config = {"KEY1": "addon", "KEY2": "addon", "KEY3": "addon"} testaddon = get_addon_cls(addon_con...
TestAddon
python
pytorch__pytorch
torch/ao/quantization/pt2e/_numeric_debugger.py
{ "start": 7044, "end": 8412 }
class ____: actual: torch.Tensor ref: torch.Tensor @property def mse_loss(self) -> object: return self.loss(F.mse_loss) @property def sqnr(self) -> object: return self.loss(compute_sqnr) def loss( self, loss_function: Callable[[torch.Tensor, torch.Tensor], torch.Te...
QuantizationComparisonResult
python
dask__dask
dask/_task_spec.py
{ "start": 29362, "end": 30545 }
class ____(MutableMapping): def __init__(self, dsk): self.dsk = dsk self._removed = set() # Set a copy of dsk to avoid dct resizing self._cache = dsk.copy() self._cache.clear() def __getitem__(self, key): if (val := self._cache.get(key)) is not None: ...
DependenciesMapping
python
pytorch__pytorch
test/dynamo/test_repros.py
{ "start": 21081, "end": 22567 }
class ____(collections.OrderedDict): """based on file_utils.py in HuggingFace""" def __getitem__(self, k): if isinstance(k, str): inner_dict = dict(self.items()) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__(self, name, value): ...
ModelOutput
python
pytest-dev__pytest
testing/python/collect.py
{ "start": 4931, "end": 10714 }
class ____: def test_class_with_init_warning(self, pytester: Pytester) -> None: pytester.makepyfile( """ class TestClass1(object): def __init__(self): pass """ ) result = pytester.runpytest() result.stdout.fnmatch_li...
TestClass
python
PrefectHQ__prefect
tests/test_futures.py
{ "start": 6905, "end": 8478 }
class ____: def test_wait_with_timeout(self): wrapped_future = Future() future = PrefectConcurrentFuture(uuid.uuid4(), wrapped_future) future.wait(timeout=0.01) # should not raise a TimeoutError assert ( future.state.is_pending() ) # should return a Pending sta...
TestPrefectConcurrentFuture
python
mahmoud__glom
glom/reduction.py
{ "start": 8567, "end": 11648 }
class ____(Fold): """By default, Merge turns an iterable of mappings into a single, merged :class:`dict`, leveraging the behavior of the :meth:`~dict.update` method. The start state can be customized with *init*, as well as the update operation, with *op*. Args: subspec: The location of the ...
Merge
python
numba__llvmlite
llvmlite/tests/test_ir.py
{ "start": 84867, "end": 95255 }
class ____(TestBase): """ Test various other features of the IRBuilder class. """ def test_attributes(self): block = self.block(name='start') builder = ir.IRBuilder(block) self.assertIs(builder.function, block.parent) self.assertIsInstance(builder.function, ir.Function) ...
TestBuilderMisc
python
sphinx-doc__sphinx
sphinx/ext/viewcode.py
{ "start": 1143, "end": 7757 }
class ____(Element): """Node for viewcode anchors. This node will be processed in the resolving phase. For viewcode supported builders, they will be all converted to the anchors. For not supported builders, they will be removed. """ def _get_full_modname(modname: str, attribute: str) -> str | Non...
viewcode_anchor
python
jazzband__django-oauth-toolkit
tests/test_models.py
{ "start": 12148, "end": 13453 }
class ____(BaseTestModels): def test_str(self): access_token = AccessToken(token="test_token") self.assertEqual("%s" % access_token, access_token.token) def test_user_can_be_none(self): app = Application.objects.create( name="test_app", redirect_uris="http://loca...
TestAccessTokenModel
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 5808, "end": 5953 }
class ____(BaseModel): role: str | None = None content: str | None = None tool_calls: list[ToolCallDelta] | None = None
ChatChoiceDelta
python
tensorflow__tensorflow
tensorflow/python/ops/image_grad_test_base.py
{ "start": 22299, "end": 25755 }
class ____(test.TestCase): TYPES = [np.float32, np.float64] def testShapeIsCorrectAfterOp(self): in_shape = [2, 20, 30, 3] out_shape = [2, 20, 30, 3] for nptype in self.TYPES: x = np.random.randint(0, high=255, size=[2, 20, 30, 3]).astype(nptype) rgb_input_tensor = constant_op.constant(x,...
RGBToHSVOpTestBase
python
Textualize__textual
tests/text_area/test_edit_via_api.py
{ "start": 593, "end": 18163 }
class ____(App): def compose(self) -> ComposeResult: text_area = TextArea() text_area.load_text(TEXT) yield text_area async def test_insert_text_start_maintain_selection_offset(): """Ensure that we can maintain the offset between the location an insert happens and the location of t...
TextAreaApp
python
facebook__pyre-check
tools/pysa_integration_tests/runner_lib.py
{ "start": 13163, "end": 18050 }
class ____: def __init__(self) -> None: self.function_annotations: Dict[str, FunctionTestAnnotations] = {} def set(self, function: str, annotations: FunctionTestAnnotations) -> None: self.function_annotations[function] = annotations def add(self, other: "DirectoryTestAnnotations") -> None:...
DirectoryTestAnnotations
python
huggingface__transformers
src/transformers/trainer_callback.py
{ "start": 1000, "end": 8580 }
class ____: """ A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing and passed to the [`TrainerCallback`]. <Tip> In all this class, one step is to be understood as one update step. When using gradient accumulation, one update step ...
TrainerState
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 3377, "end": 3557 }
class ____(FrozenModel, frozen=False, from_attributes=True): a: int = 1 KwargsNotFrozenModel(x=1).x = 2 KwargsNotFrozenModel.model_validate(model.__dict__)
KwargsNotFrozenModel
python
scipy__scipy
scipy/linalg/_matfuncs_sqrtm.py
{ "start": 215, "end": 3423 }
class ____(np.linalg.LinAlgError): pass from ._matfuncs_sqrtm_triu import within_block_loop # noqa: E402 def _sqrtm_triu(T, blocksize=64): """ Matrix square root of an upper triangular matrix. This is a helper function for `sqrtm` and `logm`. Parameters ---------- T : (N, N) array_like...
SqrtmError
python
xlwings__xlwings
xlwings/base_classes.py
{ "start": 17944, "end": 18238 }
class ____: @property def api(self): raise NotImplementedError() @property def text(self): raise NotImplementedError() @text.setter def text(self, value): raise NotImplementedError() def delete(self): raise NotImplementedError()
Note
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_deprecations.py
{ "start": 839, "end": 5777 }
class ____(fixtures.TestBase, AssertsCompiledSQL): """Legacy behavior tried to prevent schema-qualified tables from being rendered as dotted names, and were instead aliased. This behavior no longer seems to be required. """ def setup_test(self): metadata = MetaData() self.t1 = tab...
LegacySchemaAliasingTest
python
getsentry__sentry
src/sentry/grouping/fingerprinting/utils.py
{ "start": 924, "end": 972 }
class ____(TypedDict): family: str
_FamilyInfo
python
bokeh__bokeh
src/bokeh/server/server.py
{ "start": 17852, "end": 20870 }
class ____(Options): num_procs: int = Int(default=1, help=""" The number of worker processes to start for the HTTP server. If an explicit ``io_loop`` is also configured, then ``num_procs=1`` is the only compatible value. Use ``BaseServer`` to coordinate an explicit ``IOLoop`` with a multi-process H...
_ServerOpts
python
modin-project__modin
modin/tests/test_logging.py
{ "start": 889, "end": 4880 }
class ____: _loggers = {} def __init__(self, namespace): self.messages = collections.defaultdict(list) self.namespace = namespace def log(self, log_level, message, *args, **kw): self.messages[log_level].append(message.format(*args, **kw)) def exception(self, message, *args, **...
_FakeLogger
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 9938, "end": 10070 }
class ____(_TestDCTIVBase): def setup_method(self): self.rdt = int self.dec = 5 self.type = 3
TestDCTIVInt
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py
{ "start": 597, "end": 731 }
class ____: a: str = 0 b = field() c: int = foo() d = list() @frozen(auto_attribs=None) # auto_attribs = None => True
C
python
huggingface__transformers
tests/models/idefics2/test_modeling_idefics2.py
{ "start": 5658, "end": 15704 }
class ____(ModelTesterMixin, unittest.TestCase): """ Model tester for `Idefics2`. """ all_model_classes = (Idefics2Model,) if is_torch_available() else () test_resize_embeddings = True _is_composite = True def setUp(self): self.model_tester = Idefics2VisionText2TextModelTester(sel...
Idefics2ModelTest