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
huggingface__transformers
src/transformers/models/granite_speech/modeling_granite_speech.py
{ "start": 5032, "end": 8536 }
class ____(nn.Module): """Attention for conformer blocks using Shaw's relative positional embeddings. See the following [paper](https://huggingface.co/papers/1803.02155) for more details. """ def __init__(self, config: GraniteSpeechEncoderConfig): super().__init__() inner_dim = config....
GraniteSpeechConformerAttention
python
huggingface__transformers
src/transformers/models/deformable_detr/modeling_deformable_detr.py
{ "start": 15129, "end": 18547 }
class ____(nn.Module): """ Convolutional backbone, using either the AutoBackbone API or one from the timm library. nn.BatchNorm2d layers are replaced by DeformableDetrFrozenBatchNorm2d as defined above. """ def __init__(self, config): super().__init__() self.config = config ...
DeformableDetrConvEncoder
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/operations/freeze.py
{ "start": 8718, "end": 9864 }
class ____: def __init__( self, name: str, req: str, editable: bool, comments: Iterable[str] = (), ) -> None: self.name = name self.canonical_name = canonicalize_name(name) self.req = req self.editable = editable self.comments = com...
FrozenRequirement
python
sympy__sympy
sympy/simplify/gammasimp.py
{ "start": 17551, "end": 18485 }
class ____(Function): @classmethod def eval(cls, a, b): if b.is_Integer: if not b: return S.One n = int(b) if n > 0: return Mul(*[a + i for i in range(n)]) elif n < 0: return 1/Mul(*[a - i for i in range(1,...
_rf
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 10548, "end": 10689 }
class ____(_NumberBoundError): code = 'number.not_gt' msg_template = 'ensure this value is greater than {limit_value}'
NumberNotGtError
python
numpy__numpy
numpy/f2py/tests/test_array_from_pyobj.py
{ "start": 11439, "end": 23717 }
class ____: @pytest.fixture(autouse=True, scope="class", params=_type_names) def setup_type(self, request): request.cls.type = Type(request.param) request.cls.array = lambda self, dims, intent, obj: Array( Type(request.param), dims, intent, obj) @property def num2seq(self):...
TestSharedMemory
python
viewflow__viewflow
viewflow/workflow/migrations/0006_i18n.py
{ "start": 204, "end": 4728 }
class ____(migrations.Migration): dependencies = [ ("viewflow", "0005_rename_flowcls"), ] operations = [ migrations.AlterModelOptions( name="process", options={ "verbose_name_plural": "Process list", "ordering": ["-created"], ...
Migration
python
dagster-io__dagster
python_modules/dagster/dagster/_config/pythonic_config/resource.py
{ "start": 4337, "end": 5613 }
class ____(NestedResourcesResourceDefinition): def __init__( self, configurable_resource_cls: type, resource_fn: ResourceFunction, config_schema: Any, description: Optional[str], nested_resources: Mapping[str, Any], nested_partial_resources: Mapping[str, Any],...
ConfigurableResourceFactoryResourceDefinition
python
doocs__leetcode
solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/Solution2.py
{ "start": 0, "end": 756 }
class ____: def minimumMoves(self, grid: List[List[int]]) -> int: def cal(a: tuple, b: tuple) -> int: return abs(a[0] - b[0]) + abs(a[1] - b[1]) left, right = [], [] for i in range(3): for j in range(3): if grid[i][j] == 0: left.ap...
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py
{ "start": 6274, "end": 173921 }
class ____(test.TestCase, parameterized.TestCase): @test_util.run_v1_only("b/120545219") def testRefIdentity(self): with self.cached_session(): v = variable_v1.VariableV1(7) v = control_flow_ops._Identity(v) op = state_ops.assign(v, 9) v2 = control_flow_ops.with_dependencies([op], v) ...
ControlFlowTest
python
langchain-ai__langchain
libs/core/tests/unit_tests/_api/test_deprecation.py
{ "start": 12987, "end": 17315 }
class ____(BaseModel): @deprecated(since="2.0.0", removal="3.0.0") def deprecated_method(self) -> str: """Original doc.""" return "This is a deprecated method." def test_deprecated_method_pydantic() -> None: """Test deprecated method.""" with warnings.catch_warnings(record=True) as war...
MyModel
python
huggingface__transformers
src/transformers/models/tvp/processing_tvp.py
{ "start": 759, "end": 1030 }
class ____(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "truncation": True, "padding": "max_length", "pad_to_max_length": True, "return_token_type_ids": False, }, }
TvpProcessorKwargs
python
huggingface__transformers
src/transformers/models/phimoe/modular_phimoe.py
{ "start": 10978, "end": 12631 }
class ____(nn.Module): """ This implementation is strictly equivalent to standard MoE with full capacity (no dropped tokens). It's faster since it formulates MoE operations in terms of block-sparse operations to accommodate imbalanced assignments of tokens to experts, whereas standard MoE either...
PhimoeSparseMoeBlock
python
google__jax
tests/pmap_test.py
{ "start": 87514, "end": 89309 }
class ____(jtu.JaxTestCase): # TODO(apaszke) @parameterized.named_parameters(jtu.named_cases_from_sampler(lambda s: ({ "testcase_name": f"{shapes}_{vmap_in_axes}_{vmap_out_axes}_{pmap_in_axes}_{pmap_out_axes}", "shapes": shapes, "vmap_in_axes": vmap_in_axes, "vmap_out_axes": vmap_out_axes, ...
VmapOfPmapTest
python
crytic__slither
slither/detectors/reentrancy/reentrancy_events.py
{ "start": 583, "end": 7236 }
class ____(Reentrancy): ARGUMENT = "reentrancy-events" HELP = "Reentrancy vulnerabilities leading to out-of-order Events" IMPACT = DetectorClassification.LOW CONFIDENCE = DetectorClassification.MEDIUM WIKI = ( "https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnera...
ReentrancyEvent
python
kubernetes-client__python
kubernetes/client/api/node_v1_api.py
{ "start": 543, "end": 95659 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client ...
NodeV1Api
python
dask__distributed
distributed/utils_test.py
{ "start": 79388, "end": 80897 }
class ____(Worker): """Custom worker class which does not update `scheduler_delay`. This worker class is useful for some tests which make time comparisons using times reported from workers. See also -------- no_time_resync padded_time """ @property def scheduler_delay(self): ...
NoSchedulerDelayWorker
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_image/query/async_.py
{ "start": 310, "end": 457 }
class ____( Generic[Properties, References], _NearImageQueryExecutor[ConnectionAsync, Properties, References], ): pass
_NearImageQueryAsync
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_namers.py
{ "start": 71, "end": 224 }
class ____: def __init__(self, basedir='', subdir=''): self.thumbnail_basedir = basedir self.thumbnail_subdir = subdir
FakeThumbnailer
python
davidhalter__jedi
jedi/inference/base_value.py
{ "start": 10860, "end": 11618 }
class ____(HelperValueMixin): @safe_property def name(self): from jedi.inference.names import ValueName wrapped_name = self._wrapped_value.name if wrapped_name.tree_name is not None: return ValueName(self, wrapped_name.tree_name) else: from jedi.inference....
_ValueWrapperBase
python
gevent__gevent
src/greentest/3.13/test_threading.py
{ "start": 73710, "end": 76571 }
class ____(unittest.TestCase): def check_interrupt_main_with_signal_handler(self, signum): def handler(signum, frame): 1/0 old_handler = signal.signal(signum, handler) self.addCleanup(signal.signal, signum, old_handler) with self.assertRaises(ZeroDivisionError): ...
InterruptMainTests
python
jazzband__django-waffle
waffle/tests/test_testutils.py
{ "start": 9333, "end": 9540 }
class ____(OverrideSwitchOnClassTestsMixin, TestCase): """ Run tests with Django TestCase """ @override_switch('foo', active=False)
OverrideSwitchOnClassTestCase
python
getsentry__sentry
tests/sentry/api/serializers/test_fields.py
{ "start": 290, "end": 441 }
class ____(serializers.Serializer): b_field = serializers.CharField(max_length=64) d_field = serializers.CharField(max_length=64)
ChildSerializer
python
huggingface__transformers
tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py
{ "start": 13880, "end": 31476 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLModel, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenCla...
XLMRobertaXLModelTest
python
getsentry__sentry
tests/sentry/tasks/test_commit_context.py
{ "start": 1936, "end": 4228 }
class ____(TestCase): def setUp(self) -> None: self.project = self.create_project() self.repo = Repository.objects.create( organization_id=self.organization.id, name="example", integration_id=self.integration.id, ) self.code_mapping = self.create_c...
TestCommitContextIntegration
python
cython__cython
tests/run/class_scope.py
{ "start": 32, "end": 188 }
class ____(object): """ >>> MethodRedef().a(5) 7 """ def a(self, i): return i+1 def a(self, i): return i+2
MethodRedef
python
kamyu104__LeetCode-Solutions
Python/maximize-the-distance-between-points-on-a-square.py
{ "start": 4971, "end": 6262 }
class ____(object): def maxDistance(self, side, points, k): """ :type side: int :type points: List[List[int]] :type k: int :rtype: int """ def binary_search_right(left, right, check): while left <= right: mid = left + (right-left)//...
Solution4
python
walkccc__LeetCode
solutions/1618. Maximum Font to Fit a Sentence in a Screen/1618.py
{ "start": 324, "end": 1095 }
class ____: def maxFont( self, text: str, w: int, h: int, fonts: list[int], fontInfo: 'FontInfo', ) -> int: count = collections.Counter(text) l = 0 r = len(fonts) - 1 while l < r: m = (l + r + 1) // 2 if fontInfo.getHeight( fonts[m]) <= ...
Solution
python
python-jsonschema__jsonschema
jsonschema/tests/test_utils.py
{ "start": 2273, "end": 4163 }
class ____(TestCase): def test_equal_lists(self): list_1 = ["a", "b", "c"] list_2 = ["a", "b", "c"] self.assertTrue(equal(list_1, list_2)) def test_equal_lists_with_nan(self): list_1 = ["a", nan, "c"] list_2 = ["a", nan, "c"] self.assertTrue(equal(list_1, list_2)...
TestListEqual
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 11251, "end": 12223 }
class ____(nn.Module): # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TConformerFeatureProjection.__init__ def __init__(self, config): super().__init__() self.layer_norm = nn.LayerNorm(config.feature_projection_input_dim, eps=config.layer_norm_eps) self.pr...
SeamlessM4Tv2ConformerFeatureProjection
python
ansible__ansible
test/units/cli/test_cli.py
{ "start": 3880, "end": 17591 }
class ____(unittest.TestCase): def setUp(self): self.fake_loader = DictDataLoader({}) self.tty_patcher = patch('ansible.cli.sys.stdin.isatty', return_value=True) self.mock_isatty = self.tty_patcher.start() self.display_v_patcher = patch('ansible.cli.display.verbosity', return_value=...
TestCliSetupVaultSecrets
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 95002, "end": 95280 }
class ____(MMTemplateConfigMixin, MTIAConfigHeuristic): """Standard MM template heuristic for MTIA""" @register_template_heuristic(mm_template.uid, "mtia", op_name="addmm") @register_template_heuristic(bmm_template.uid, "mtia", op_name="baddbmm")
MTIAMMTemplateConfigHeuristic
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/data_table_style_order.py
{ "start": 622, "end": 1716 }
class ____(App): """Regression test snapshot app which ensures that styles are layered on top of each other correctly in the DataTable. In this example, the colour of the text in the cells under the cursor should not be red, because the CSS should be applied on top.""" CSS = """ DataTable {...
DataTableCursorStyles
python
pandas-dev__pandas
asv_bench/benchmarks/tslibs/normalize.py
{ "start": 344, "end": 1209 }
class ____: params = [ _sizes, _tzs, ] param_names = ["size", "tz"] def setup(self, size, tz): # use an array that will have is_date_array_normalized give True, # so we do not short-circuit early. dti = pd.date_range("2016-01-01", periods=10, tz=tz).repeat(size ...
Normalize
python
huggingface__transformers
src/transformers/models/timesfm/modeling_timesfm.py
{ "start": 11651, "end": 12147 }
class ____(PreTrainedModel): config: TimesFmConfig base_model_prefix = "timesfm" _no_split_modules = ["TimesFmDecoderLayer"] main_input_name = "past_values" input_modalities = ("time",) _supports_sdpa = True @torch.no_grad() def _init_weights(self, module): super()._init_weights...
TimesFmPreTrainedModel
python
tensorflow__tensorflow
tensorflow/python/keras/engine/training_distributed_v1.py
{ "start": 29105, "end": 29780 }
class ____(training_utils_v1.TrainingLoop): """Training loop for distribution strategy with multiple worker.""" def __init__(self, single_worker_loop): self._single_worker_loop = single_worker_loop def fit(self, *args, **kwargs): return _train_with_multi_worker(self._single_worker_loop.fit)( *ar...
DistributionMultiWorkerTrainingLoop
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/unit_tests/integration/test_users.py
{ "start": 1415, "end": 2187 }
class ____(TestCase): @staticmethod def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput: return read_output( config_builder=config_, stream_name=_STREAM_NAME, sync_mode=SyncMode.full_refresh, expecting_exception=expecti...
TestFullRefresh
python
huggingface__transformers
src/transformers/masking_utils.py
{ "start": 64904, "end": 66448 }
class ____(torch.Tensor): def __new__(cls, data, style=None): # Create a new instance of AttentionMask as a Tensor cls.style = style return torch.Tensor._make_subclass(cls, data, require_grad=False) def __init__(self, data): # You can initialize any additional metadata here if n...
AttentionMask
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py
{ "start": 7235, "end": 7542 }
class ____(BaseFSHandler): @web.authenticated @authorized def post(self): path = self.get_path_argument("path") truncate = (self.get_argument("truncate", "true").lower() == "true") result = self.fs_touch(path, truncate=truncate) self.write_json(result)
TouchHandler
python
mwaskom__seaborn
seaborn/_core/plot.py
{ "start": 7467, "end": 33453 }
class ____: """ An interface for declaratively specifying statistical graphics. Plots are constructed by initializing this class and adding one or more layers, comprising a `Mark` and optional `Stat` or `Move`. Additionally, faceting variables or variable pairings may be defined to divide the spac...
Plot
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/conditional1.py
{ "start": 231, "end": 304 }
class ____: def __bool__(self) -> bool: return True
ReturnsBool
python
ray-project__ray
python/ray/tune/integration/keras.py
{ "start": 359, "end": 582 }
class ____: """Deprecated. Use :class:`ray.train.tensorflow.keras.ReportCheckpointCallback` instead.""" def __new__(cls, *args, **kwargs): raise DeprecationWarning(_DEPRECATION_MESSAGE)
TuneReportCallback
python
scikit-learn__scikit-learn
sklearn/externals/array_api_compat/torch/_info.py
{ "start": 264, "end": 11889 }
class ____: """ Get the array API inspection namespace for PyTorch. The array API inspection namespace defines the following functions: - capabilities() - default_device() - default_dtypes() - dtypes() - devices() See https://data-apis.org/array-api/latest/API_specification/in...
__array_namespace_info__
python
fluentpython__example-code-2e
15-more-types/protocol/random/erp.py
{ "start": 87, "end": 326 }
class ____(Generic[T]): def __init__(self, items: Iterable[T]) -> None: self._items: List[T] = list(items) random.shuffle(self._items) def pop_random(self) -> T: return self._items.pop()
EnterpriserRandomPopper
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 20410, "end": 21511 }
class ____: @patch('bokeh.embed.util.standalone_docs_json_and_render_items') def test_delgation(self, mock_sdjari: MagicMock) -> None: p1 = SomeModel() p2 = SomeModel() d = Document() d.add_root(p1) d.add_root(p2) # ignore error unpacking None mock result, just ch...
Test_standalone_docs_json
python
scikit-image__scikit-image
src/skimage/_shared/utils.py
{ "start": 21393, "end": 36621 }
class ____: """Decorate a deprecated function and warn when it is called. Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>. Parameters ---------- deprecated_version : str The package version when the deprecation was introduced. removed_version : str The package...
deprecate_func
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess4.py
{ "start": 622, "end": 704 }
class ____(Protocol): def must_have(self) -> None: pass
HasItemProtocol2
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/reshape_transpose_test.py
{ "start": 3497, "end": 4536 }
class ____(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): # Add a block with compatible transposes. compatible_transpose = array_ops.transpose( inp, [0, 3, 1, 2], name="transpose-1") compatible_transpose = array_ops.transpose( compatible_transpose, [0, 2, 3, 1], name="transpo...
TransposeTest
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/test_threaded_message_reader.py
{ "start": 1129, "end": 6878 }
class ____(PipesThreadedMessageReader): def __init__(self, *, log_readers, path: Optional[str] = None): self.path = path self.file_position = 0 super().__init__(log_readers=log_readers) def on_launched(self, launched_payload: PipesLaunchedData) -> None: if "path" in launched_pa...
PipesFileMessageReader
python
conda__conda
conda/models/channel.py
{ "start": 1984, "end": 13682 }
class ____(metaclass=ChannelType): """ Channel: scheme <> auth <> location <> token <> channel <> subchannel <> platform <> package_filename Package Spec: channel <> subchannel <> namespace <> package_name """ _cache_ = {} @staticmethod def _reset_state() -> None: Channel...
Channel
python
google__jax
jax/_src/scipy/spatial/transform.py
{ "start": 7462, "end": 17634 }
class ____(typing.NamedTuple): """Spherical Linear Interpolation of Rotations. JAX implementation of :class:`scipy.spatial.transform.Slerp`. Examples: Create a Slerp instance from a series of rotations: >>> import math >>> from jax.scipy.spatial.transform import Rotation, Slerp >>> rots = jnp.a...
Slerp
python
walkccc__LeetCode
solutions/148. Sort List/148.py
{ "start": 0, "end": 1063 }
class ____: def sortList(self, head: ListNode) -> ListNode: def split(head: ListNode, k: int) -> ListNode: while k > 1 and head: head = head.next k -= 1 rest = head.next if head else None if head: head.next = None return rest def merge(l1: ListNode, l2: ListNod...
Solution
python
django__django
django/contrib/gis/admin/options.py
{ "start": 134, "end": 627 }
class ____: gis_widget = OSMWidget gis_widget_kwargs = {} def formfield_for_dbfield(self, db_field, request, **kwargs): if isinstance(db_field, models.GeometryField) and ( db_field.dim < 3 or self.gis_widget.supports_3d ): kwargs["widget"] = self.gis_widget(**self.gi...
GeoModelAdminMixin
python
PyCQA__pylint
tests/functional/e/enum_subclasses.py
{ "start": 1235, "end": 1544 }
class ____(TestBase): """Tests the false positive for enums.""" a = auto() b = auto() test_enum = TestEnum.a assert test_enum.hello_pylint() == test_enum.name # Check combinations of Flag members using the bitwise operators (&, |, ^, ~) # https://github.com/pylint-dev/pylint/issues/7381
TestEnum
python
PrefectHQ__prefect
src/prefect/serializers.py
{ "start": 7831, "end": 9225 }
class ____(Serializer[D]): """ Wraps another serializer, compressing its output. Uses `lzma` by default. See `compressionlib` for using alternative libraries. Attributes: serializer: The serializer to use before compression. compressionlib: The import path of a compression module to use...
CompressedSerializer
python
PyCQA__pylint
tests/functional/i/invalid/invalid_hash_returned.py
{ "start": 826, "end": 956 }
class ____: """ __hash__ returns a float""" def __hash__(self): # [invalid-hash-returned] return 1.11
ThirdBadHash
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_crc32.py
{ "start": 1566, "end": 3845 }
class ____(ColumnMapExpectation): """Expect column values to be hashes that match valid CRC32 format.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_crc32...
ExpectColumnValuesToBeValidCrc32
python
walkccc__LeetCode
solutions/1882. Process Tasks Using Servers/1882.py
{ "start": 0, "end": 842 }
class ____: def assignTasks(self, servers: list[int], tasks: list[int]) -> list[int]: ans = [] free = [] # (weight, index, freeTime) used = [] # (freeTime, weight, index) for i, weight in enumerate(servers): heapq.heappush(free, (weight, i, 0)) for i, executionTime in enumerate(tasks): ...
Solution
python
geekcomputers__Python
BlackJack_game/blackjack_rr.py
{ "start": 695, "end": 865 }
class ____: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + " of " + self.suit
Card
python
tensorflow__tensorflow
tensorflow/python/ops/sparse_ops.py
{ "start": 36689, "end": 141691 }
class ____: def __repr__(self): # This is needed to make documentation without fully qualified module paths return "KeywordRequired()" @tf_export(v1=["sparse.split", "sparse_split"]) @deprecation.deprecated_endpoints("sparse_split") @deprecation.deprecated_args( None, "split_dim is deprecated, use axis...
KeywordRequired
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 46843, "end": 47672 }
class ____(BiffRecord): """ Record DIMENSIONS, BIFF8: Offset Size Contents 0 4 Index to first used row 4 4 Index to last used row, increased by 1 8 2 Index to first used column 10 2 Index to last used column, increased by 1 12 2 ...
DimensionsRecord
python
langchain-ai__langchain
libs/partners/anthropic/tests/unit_tests/middleware/test_file_search.py
{ "start": 8068, "end": 14924 }
class ____: """Tests for filesystem-backed grep search.""" def test_grep_content_mode(self) -> None: """Test grep with content output mode.""" middleware = StateFileSearchMiddleware() state: AnthropicToolsState = { "messages": [], "text_editor_files": { ...
TestFilesystemGrepSearch
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/test_threaded_message_reader.py
{ "start": 515, "end": 1129 }
class ____(PipesChunkedLogReader): def __init__(self, *, path: str, interval: float = 10, target_stream: TextIO): super().__init__(interval=interval, target_stream=target_stream) self.path = path self.file_position = 0 def target_is_readable(self, params: PipesParams) -> bool: ...
PipesFileLogReader
python
getsentry__sentry
src/sentry/profiles/flamegraph.py
{ "start": 1147, "end": 1376 }
class ____(TypedDict): project_id: int profiler_id: str chunk_id: str thread_id: NotRequired[str] start: NotRequired[str] end: NotRequired[str] transaction_id: NotRequired[str]
ContinuousProfileCandidate
python
FactoryBoy__factory_boy
examples/django_demo/generic_foreignkey/factories.py
{ "start": 855, "end": 998 }
class ____(TaggedItemFactory): content_object = factory.SubFactory(GroupFactory) class Meta: model = TaggedItem
TaggedGroupFactory
python
pytest-dev__pytest
testing/example_scripts/unittest/test_setup_skip_class.py
{ "start": 185, "end": 310 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): assert 0 @unittest.skip("skip all tests")
Base
python
fluentpython__example-code-2e
14-inheritance/diamond.py
{ "start": 896, "end": 1081 }
class ____(Root): # <2> def ping(self): print(f'{self}.ping() in A') super().ping() def pong(self): print(f'{self}.pong() in A') super().pong()
A
python
openai__openai-python
src/openai/resources/webhooks.py
{ "start": 4158, "end": 7820 }
class ____(AsyncAPIResource): def unwrap( self, payload: str | bytes, headers: HeadersLike, *, secret: str | None = None, ) -> UnwrapWebhookEvent: """Validates that the given payload was sent by OpenAI and parses the payload.""" if secret is None: ...
AsyncWebhooks
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py
{ "start": 17025, "end": 24342 }
class ____: @pytest.mark.usefixtures("sample_hitl_detail") def test_should_respond_200_with_existing_response( self, test_client: TestClient, expected_sample_hitl_detail_dict: dict[str, Any], ) -> None: with assert_queries_count(3): response = test_client.get("/da...
TestGetHITLDetailsEndpoint
python
facebookresearch__faiss
faiss/gpu/test/test_gpu_index_ivfsq.py
{ "start": 6398, "end": 7029 }
class ____(unittest.TestCase): def test_fp16(self): do_multi_test(faiss.ScalarQuantizer.QT_fp16) def test_8bit(self): do_multi_test(faiss.ScalarQuantizer.QT_8bit) def test_8bit_uniform(self): do_multi_test(faiss.ScalarQuantizer.QT_8bit_uniform) def test_6bit(self): do_...
TestSQ
python
getsentry__sentry
src/sentry/utils/concurrent.py
{ "start": 9285, "end": 10722 }
class ____: """\ Coordinates a set of ``Future`` objects (either from ``concurrent.futures``, or otherwise API compatible), and allows for attaching a callback when all futures have completed execution. """ def __init__(self, futures): self.__pending = set(futures) self.__comple...
FutureSet
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_cond_format06.py
{ "start": 345, "end": 3622 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional formatting.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle...
TestAssembleWorksheet
python
apache__airflow
providers/redis/tests/integration/redis/hooks/test_redis.py
{ "start": 931, "end": 1536 }
class ____: def test_real_ping(self): hook = RedisHook(redis_conn_id="redis_default") redis = hook.get_conn() assert redis.ping(), "Connection to Redis with PING works." def test_real_get_and_set(self): hook = RedisHook(redis_conn_id="redis_default") redis = hook.get_co...
TestRedisHook
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 683996, "end": 684311 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("UserStatus", graphql_name="node")
UserStatusEdge
python
walkccc__LeetCode
solutions/3272. Find the Count of Good Integers/3272.py
{ "start": 0, "end": 953 }
class ____: def countGoodIntegers(self, n: int, k: int) -> int: halfLength = (n + 1) // 2 minHalf = 10**(halfLength - 1) maxHalf = 10**halfLength ans = 0 seen = set() for num in range(minHalf, maxHalf): palindrome = str(num) + str(num)[::-1][n % 2:] sortedDigits = ''.join(sorted(p...
Solution
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 13912, "end": 18452 }
class ____(TestCase): def test_empty(self): with self.assertRaisesRegex( ValueError, "At least one dataset should be passed" ): StackDataset() def test_mixed(self): with self.assertRaisesRegex(ValueError, "Supported either"): StackDataset( ...
TestStackDataset
python
pydata__xarray
xarray/core/_aggregations.py
{ "start": 615, "end": 45421 }
class ____: __slots__ = () def reduce( self, func: Callable[..., Any], dim: Dims = None, *, axis: int | Sequence[int] | None = None, keep_attrs: bool | None = None, keepdims: bool = False, **kwargs: Any, ) -> Self: raise NotImplemented...
DataTreeAggregations
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 3477, "end": 3581 }
class ____(_TestSchema): _schema = {"$ref": "#/definitions/Bar"} _rootschema = Derived._schema
Bar
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-milvus/destination_milvus/config.py
{ "start": 864, "end": 1185 }
class ____(BaseModel): mode: Literal["no_auth"] = Field("no_auth", const=True) class Config(OneOfOptionConfig): title = "No auth" description = "Do not authenticate (suitable for locally running test clusters, do not use for clusters with public IP addresses)" discriminator = "mode"
NoAuth
python
tox-dev__tox
src/tox/tox_env/python/pip/pip_install.py
{ "start": 835, "end": 1803 }
class ____(Installer[Python], ABC): def __init__(self, tox_env: Python, with_list_deps: bool = True) -> None: # noqa: FBT001, FBT002 self._with_list_deps = with_list_deps super().__init__(tox_env) def _register_config(self) -> None: if self._with_list_deps: # pragma: no branch ...
PythonInstallerListDependencies
python
walkccc__LeetCode
solutions/2551. Put Marbles in Bags/2551.py
{ "start": 0, "end": 581 }
class ____: def putMarbles(self, weights: list[int], k: int) -> int: # To distribute marbles into k bags, there will be k - 1 cuts. If there's a # cut after weights[i], then weights[i] and weights[i + 1] will be added to # the cost. Also, no matter how we cut, weights[0] and weights[n - 1] will # be c...
Solution
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 5199, "end": 5879 }
class ____(_desc_classes_injector, nodes.Inline, nodes.TextElement): """Node for a signature fragment in inline text. This is for example used for roles like :rst:role:`cpp:expr`. This node always has the classes ``sig``, ``sig-inline``, and the name of the domain it belongs to. """ classes =...
desc_inline
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_templatetags.py
{ "start": 14630, "end": 20319 }
class ____(test.BaseTest): def setUp(self): super().setUp() self.storage = test.TemporaryStorage() # Save a test image. self.filename = self.create_image(self.storage, 'test.svg', image_format='SVG') # Required so that IOError's get wrapped as TemplateSyntaxError se...
ThumbnailSVGImage
python
boto__boto3
boto3/exceptions.py
{ "start": 2905, "end": 3483 }
class ____(Boto3Error): """Raised for operations that are not supported for an operand.""" def __init__(self, operation, value): msg = ( f'{operation} operation cannot be applied to value {value} of type ' f'{type(value)} directly. Must use AttributeBase object methods ' ...
DynamoDBOperationNotSupportedError
python
fastai__fastai
fastai/losses.py
{ "start": 9040, "end": 9763 }
class ____(BaseLoss): "Same as `LabelSmoothingCrossEntropy`, but flattens input and target." y_int = True @use_kwargs_dict(keep=True, eps=0.1, reduction='mean') def __init__(self, *args, axis:int=-1, # Class axis **kwargs ): super().__init__(LabelSmoothingCrossEntr...
LabelSmoothingCrossEntropyFlat
python
ray-project__ray
python/ray/serve/tests/test_handle_streaming.py
{ "start": 753, "end": 1530 }
class ____: def __call__( self, n: int, should_error: bool = False ) -> Generator[int, None, None]: if should_error: raise RuntimeError("oopsies") for i in range(n): yield i def other_method(self, n: int) -> Generator[int, None, None]: for i in range...
SyncStreamer
python
doocs__leetcode
solution/0200-0299/0291.Word Pattern II/Solution.py
{ "start": 0, "end": 828 }
class ____: def wordPatternMatch(self, pattern: str, s: str) -> bool: def dfs(i, j): if i == m and j == n: return True if i == m or j == n or n - j < m - i: return False for k in range(j, n): t = s[j : k + 1] ...
Solution
python
pypa__warehouse
tests/unit/test_sanity.py
{ "start": 838, "end": 2511 }
class ____: def test_valid(self): request = Request( { "REQUEST_METHOD": "POST", "CONTENT_TYPE": ( "multipart/form-data; boundary=c397e2aa2980f1a53dee37c05b8fb45a" ), "wsgi.input": io.BytesIO( ...
TestInvalidForms
python
tornadoweb__tornado
tornado/test/wsgi_test.py
{ "start": 235, "end": 1947 }
class ____: # TODO: Now that WSGIAdapter is gone, this is a pretty weak test. def get_executor(self): raise NotImplementedError() def get_app(self): executor = self.get_executor() # The barrier test in DummyExecutorTest will always wait the full # value of this timeout, so w...
WSGIAppMixin
python
zostera__django-bootstrap4
example/app/views.py
{ "start": 579, "end": 834 }
class ____(TemplateView): template_name = "app/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) messages.info(self.request, "hello http://example.com") return context
HomePageView
python
doocs__leetcode
solution/2700-2799/2736.Maximum Sum Queries/Solution.py
{ "start": 418, "end": 1122 }
class ____: def maximumSumQueries( self, nums1: List[int], nums2: List[int], queries: List[List[int]] ) -> List[int]: nums = sorted(zip(nums1, nums2), key=lambda x: -x[0]) nums2.sort() n, m = len(nums1), len(queries) ans = [-1] * m j = 0 tree = BinaryIndex...
Solution
python
bokeh__bokeh
tests/test_defaults.py
{ "start": 1230, "end": 2575 }
class ____: def test_defaults(self) -> None: baseline = Path(__file__).parent / "baselines" / "defaults.json5" defaults = collect_defaults() output_defaults(baseline, defaults) status, out, _ = diff_baseline(baseline) if status != 0: print(out) asser...
TestDefaults
python
ray-project__ray
python/ray/data/tests/unit/test_datatype.py
{ "start": 10109, "end": 10866 }
class ____: """Test string representation methods.""" @pytest.mark.parametrize( "datatype,expected_repr", [ (DataType.from_arrow(pa.int64()), "DataType(arrow:int64)"), (DataType.from_arrow(pa.string()), "DataType(arrow:string)"), (DataType.from_numpy(np.dtype...
TestDataTypeStringRepresentation
python
Lightning-AI__lightning
tests/tests_fabric/test_connector.py
{ "start": 2285, "end": 33944 }
class ____(Mock): def __instancecheck__(self, instance): return True @pytest.mark.parametrize( ("accelerator", "devices"), [("tpu", "auto"), ("tpu", 1), ("tpu", [1]), ("tpu", 8), ("auto", 1), ("auto", 8)] ) @RunIf(min_python="3.9") # mocking issue def test_accelerator_choice_tpu(accelerator, devices,...
DeviceMock
python
openai__openai-python
src/openai/types/realtime/conversation_item_create_event.py
{ "start": 280, "end": 1089 }
class ____(BaseModel): item: ConversationItem """A single item within a Realtime conversation.""" type: Literal["conversation.item.create"] """The event type, must be `conversation.item.create`.""" event_id: Optional[str] = None """Optional client-generated ID used to identify this event.""" ...
ConversationItemCreateEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-faker/source_faker/source.py
{ "start": 292, "end": 1367 }
class ____(AbstractSource): def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Any]: if type(config["count"]) == int or type(config["count"]) == float: return True, None else: return False, "Count option is missing" def streams(s...
SourceFaker
python
ray-project__ray
python/ray/serve/_private/common.py
{ "start": 25665, "end": 25739 }
class ____(str, Enum): REPLICA = "replica" @dataclass
ServeComponentType
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/_collections.py
{ "start": 9527, "end": 12403 }
class ____(Generic[_T]): """Appends items to a collection ensuring uniqueness. Additional appends() of the same object are ignored. Membership is determined by identity (``is a``) not equality (``==``). """ __slots__ = "data", "_data_appender", "_unique" data: Union[Iterable[_T], Set[_T], Li...
UniqueAppender
python
scikit-image__scikit-image
benchmarks/benchmark_transform_warp.py
{ "start": 2073, "end": 2711 }
class ____: params = ( [np.float32, np.float64], [(512, 512), (2048, 2048), (48, 48, 48), (192, 192, 192)], [(512, 512), (2048, 2048), (48, 48, 48), (192, 192, 192)], ) param_names = ['dtype', 'shape_in', 'shape_out'] timeout = 180 def setup(self, dtype, shape_in, shape_out...
ResizeLocalMeanSuite
python
pennersr__django-allauth
allauth/socialaccount/providers/oauth/views.py
{ "start": 1576, "end": 1904 }
class ____: @classmethod def adapter_view(cls, adapter): @login_not_required def view(request, *args, **kwargs): self = cls() self.request = request self.adapter = adapter(request) return self.dispatch(request, *args, **kwargs) return view...
OAuthView