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
getsentry__sentry
tests/sentry/issues/endpoints/test_group_tombstone.py
{ "start": 184, "end": 1463 }
class ____(APITestCase): def test_simple(self) -> None: self.user = self.create_user("foo@example.com") self.org = self.create_organization(owner=self.user, name="Rowdy Tiger") self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project = self.create_projec...
GroupTombstoneTest
python
getsentry__sentry
tests/sentry/api/endpoints/test_oauth_userinfo.py
{ "start": 256, "end": 3997 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.login_as(self.user) self.path = reverse( "sentry-api-0-oauth-userinfo", ) self.client = APIClient() def test_requires_access_token(self) -> None: response = self.client.get(self.pa...
OAuthUserInfoTest
python
tensorflow__tensorflow
tensorflow/python/data/util/options_test.py
{ "start": 978, "end": 1268 }
class ____(options.OptionsBase): x = options.create_option( name="x", ty=int, docstring="the answer to everything", default_factory=lambda: 42) y = options.create_option( name="y", ty=float, docstring="a tasty pie", default_factory=lambda: 3.14)
_TestOptions
python
run-llama__llama_index
llama-index-core/llama_index/core/postprocessor/structured_llm_rerank.py
{ "start": 2368, "end": 8282 }
class ____(BaseNodePostprocessor): """Structured LLM-based reranker.""" top_n: int = Field(description="Top N nodes to return.") choice_select_prompt: SerializeAsAny[BasePromptTemplate] = Field( description="Choice select prompt." ) choice_batch_size: int = Field(description="Batch size for...
StructuredLLMRerank
python
apache__airflow
providers/common/compat/tests/unit/common/compat/lineage/test_hook.py
{ "start": 11871, "end": 22637 }
class ____: def test_add_asset_basic_functionality(self, collector): """Test basic add_input_asset and add_output_asset functionality.""" mock_context = mock.MagicMock() collector.add_input_asset(mock_context, uri="s3://bucket/input-file") collector.add_output_asset(mock_context, ur...
TestCollectorAddAssets
python
tensorflow__tensorflow
tensorflow/python/ops/sobol_ops_test.py
{ "start": 1186, "end": 6877 }
class ____(test_util.TensorFlowTestCase): def test_basic(self): for dtype in [np.float64, np.float32]: expected = np.array([[.5, .5], [.75, .25], [.25, .75], [.375, .375]]) sample = self.evaluate(math_ops.sobol_sample(2, 4, dtype=dtype)) self.assertAllClose(expected, sample, 0.001) def test_...
SobolSampleOpTest
python
google__jax
jax/_src/numpy/einsum.py
{ "start": 1190, "end": 24373 }
class ____(opt_einsum.paths.PathOptimizer): """Unoptimized path for einsum.""" def __call__(self, inputs, *args, **kwargs): return [(0, 1)] * (len(inputs) - 1) @overload def einsum( subscript: str, /, *operands: ArrayLike, out: None = None, optimize: str | bool | list[tuple[int, ...]] = "auto",...
Unoptimized
python
ray-project__ray
python/ray/util/collective/types.py
{ "start": 3725, "end": 3886 }
class ____: timeout_ms = unset_timeout_ms # # @dataclass # class GatherOptions: # root_rank = 0 # timeout = unset_timeout @dataclass
AllGatherOptions
python
ray-project__ray
python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_tree.py
{ "start": 287, "end": 2008 }
class ____: """ Node in a prefix tree that represents a segment of text and can belong to multiple tenants. Each node also tracks the last access time for each tenant. Simple example of root node connected to two children Nodes: root = Node(text="", parent=None, edge_label_to_child={"f": fooNode...
Node
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/context_editing.py
{ "start": 5368, "end": 8901 }
class ____(AgentMiddleware): """Automatically prune tool results to manage context size. The middleware applies a sequence of edits when the total input token count exceeds configured thresholds. Currently the `ClearToolUsesEdit` strategy is supported, aligning with Anthropic's `clear_tool_uses_20...
ContextEditingMiddleware
python
pyparsing__pyparsing
examples/bf.py
{ "start": 1310, "end": 2411 }
class ____: """ Brainf*ck execution environment, with a memory array and pointer. """ def __init__(self, memory_size: int = 1024): self._ptr = 0 self._memory_size = memory_size self._memory = [0] * self._memory_size @property def ptr(self): return self._ptr ...
BFEngine
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/bcast_ops_test.py
{ "start": 1016, "end": 4933 }
class ____(test.TestCase): def _GetBroadcastShape(self, xs, ys): return self.evaluate(broadcast_args(xs, ys)) def _GetGradientArgs(self, xs, ys): return self.evaluate(broadcast_gradient_args(xs, ys)) def testBasic(self): r = self._GetBroadcastShape([2, 3, 5], [1]) self.assertAllEqual(r, [2, 3, ...
BcastOpsTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_mwaa.py
{ "start": 1794, "end": 4638 }
class ____: def test_init(self): op = MwaaTriggerDagRunOperator(**OP_KWARGS) assert op.env_name == OP_KWARGS["env_name"] assert op.trigger_dag_id == OP_KWARGS["trigger_dag_id"] assert op.trigger_run_id == OP_KWARGS["trigger_run_id"] assert op.logical_date == OP_KWARGS["logica...
TestMwaaTriggerDagRunOperator
python
django__django
tests/proxy_models/models.py
{ "start": 415, "end": 541 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().exclude(name="fred")
PersonManager
python
joke2k__faker
faker/providers/job/hu_HU/__init__.py
{ "start": 42, "end": 11879 }
class ____(BaseProvider): # Derived from KSH's FEOR'08 jobs = ( "Titkár(nő)", "Értékbecslő", "Közterület-felügyelő", "Építőmérnök", "Köszörűs", "Gépjármű- és motorkarbantartó", "Mezőgazdasági mérnök", "Számítógéphálózat- és rendszertechnikus", ...
Provider
python
google__jax
jax/experimental/mosaic/gpu/core.py
{ "start": 8571, "end": 8835 }
class ____: arrival_count: int num_barriers: int = 1 def __post_init__(self): if self.arrival_count < 1: raise ValueError( f"Arrival count must be at least 1, but got {self.arrival_count}" ) @dataclasses.dataclass(frozen=True)
Barrier
python
catalyst-team__catalyst
catalyst/contrib/layers/pooling.py
{ "start": 4238, "end": 5023 }
class ____(nn.Module): """@TODO: Docs (add `Example`). Contribution is welcome.""" def __init__(self, in_features, activation_fn="Sigmoid"): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.max = GlobalMaxPool2d() self.attn = GlobalAttnPool2d(in_features, acti...
GlobalMaxAttnPool2d
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/auth_generated.py
{ "start": 1008, "end": 1128 }
class ____(BaseModel): detail: Annotated[list[ValidationError] | None, Field(title="Detail")] = None
HTTPValidationError
python
numba__numba
numba/tests/test_parfors_passes.py
{ "start": 7154, "end": 10644 }
class ____(BaseTest): sub_pass_class = numba.parfors.parfor.ConvertNumpyPass def check_numpy_allocators(self, fn): def test_impl(): n = 10 a = fn(n) return a sub_pass = self.run_parfor_sub_pass(test_impl, ()) self.assertEqual(len(sub_pass.rewritten),...
TestConvertNumpyPass
python
ZoranPandovski__al-go-rithms
strings/suffix_array/suffix_array.py
{ "start": 1761, "end": 3844 }
class ____: def __init__(self): self.index = 0 self.rank = [0, 0] def buildSuffixArray(s): s = s + '$' suffixes = [suffix() for _ in range(len(s))] for i in range(len(s)): suffixes[i].index = i suffixes[i].rank[0] = ord(s[i]) - ord('a') suffixes[i].rank[1] = ord(...
suffix
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 9100, "end": 9232 }
class ____(_TestDCTIIBase): def setup_method(self): self.rdt = int self.dec = 5 self.type = 2
TestDCTIIInt
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 4462, "end": 6874 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'cmdline'] valid_subsets = ['cmdline'] fact_namespace = 'ansible_cmdline' collector_class = CmdLineFactCollector def test_parse_proc_cmdline_uefi(self): uefi_cmdline = r'initrd=\70ef65e1a04a47aea04f7b5145ea3537\4.10.0-1...
TestCmdLineFacts
python
huggingface__transformers
src/transformers/models/olmo/modular_olmo.py
{ "start": 2470, "end": 4923 }
class ____(LlamaRotaryEmbedding): @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids...
OlmoRotaryEmbedding
python
pandas-dev__pandas
pandas/tests/internals/test_internals.py
{ "start": 42158, "end": 47556 }
class ____: @pytest.fixture( params=[ lambda x: x, lambda x: x.to_series(), lambda x: x._data, lambda x: list(x), lambda x: x.astype(object), lambda x: np.asarray(x), lambda x: x[0], lambda x: x[:0], ] ...
TestCanHoldElement
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/utils/benchmark.py
{ "start": 347, "end": 3300 }
class ____: def __init__( self, *, output: TextIO = sys.stdout, name: Optional[str] = None, experiment_settings: Optional[Mapping[str, Any]] = None, ): self.entries: list[ProfilingEntry] = [] self.output = Console() self.name = name or "anonymous" ...
ProfilingSession
python
Lightning-AI__lightning
src/lightning/fabric/strategies/launchers/xla.py
{ "start": 1128, "end": 5002 }
class ____(_Launcher): r"""Launches processes that run a given function in parallel on XLA supported hardware, and joins them all at the end. The main process in which this launcher is invoked creates N so-called worker processes (using the `torch_xla` :func:`xmp.spawn`) that run the given function. ...
_XLALauncher
python
apache__airflow
airflow-core/src/airflow/serialization/enums.py
{ "start": 1130, "end": 2270 }
class ____(str, Enum): """Enum of supported attribute types of DAG.""" DAG = "dag" ASSET_EVENT_ACCESSORS = "asset_event_accessors" ASSET_EVENT_ACCESSOR = "asset_event_accessor" OP = "operator" DATETIME = "datetime" TIMEDELTA = "timedelta" TIMEZONE = "timezone" RELATIVEDELTA = "relat...
DagAttributeTypes
python
getsentry__sentry
tests/sentry/issues/endpoints/test_organization_searches.py
{ "start": 4244, "end": 12125 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-searches" method = "post" @cached_property def manager(self) -> User: user = self.create_user("test@test.com") self.create_member(organization=self.organization, user=user, role="manager") return user @cached_pr...
CreateOrganizationSearchesTest
python
facelessuser__pymdown-extensions
pymdownx/progressbar.py
{ "start": 6458, "end": 7580 }
class ____(Extension): """Add progress bar extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'level_class': [ True, "Include class that defines progress level - Default: True" ], ...
ProgressBarExtension
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py
{ "start": 26800, "end": 27842 }
class ____(GradientCheckpointingLayer): def __init__(self, config, attn_implementation: str = "sdpa") -> None: super().__init__() self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6) self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6) self.attn = Qwen3VLMoeVisionAttention(conf...
Qwen3VLMoeVisionBlock
python
streamlit__streamlit
lib/streamlit/components/v2/bidi_component/state.py
{ "start": 1100, "end": 3141 }
class ____(AttributeDictionary): """The schema for the custom component result object. The custom component result object is a dictionary-like object that supports both key and attribute notation. It contains all of the component's state and trigger values. Attributes ---------- <state_key...
BidiComponentResult
python
giampaolo__psutil
tests/test_heap.py
{ "start": 7963, "end": 9524 }
class ____(HeapTestCase): @retry_on_failure() def test_heap_used(self): """Test that HeapAlloc() without HeapFree() increases heap_used.""" size = HEAP_SIZE mem1 = psutil.heap_info() heap = GetProcessHeap() addr = HeapAlloc(heap, size) mem2 = psutil.heap_info() ...
TestHeapWindows
python
modin-project__modin
modin/core/dataframe/pandas/partitioning/partition_manager.py
{ "start": 3328, "end": 77428 }
class ____( ClassLogger, ABC, modin_layer="PARTITION-MANAGER", log_level=LogLevel.DEBUG ): """ Base class for managing the dataframe data layout and operators across the distribution of partitions. Partition class is the class to use for storing each partition. Each partition must extend the `Panda...
PandasDataframePartitionManager
python
jina-ai__jina
tests/integration/sparse_pipeline/test_sparse_pipeline.py
{ "start": 567, "end": 2072 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.docs = DocumentArray() @requests(on='/index') def encode(self, docs: DocumentArray, *args, **kwargs) -> Any: for i, doc in enumerate(docs): doc.embedding = sparse.coo_matrix...
DummyCSRSparseIndexEncoder
python
pytorch__pytorch
torch/distributed/optim/functional_adam.py
{ "start": 811, "end": 7391 }
class ____: def __init__( self, params: list[Tensor], lr: float = 1e-3, betas: tuple[float, float] = (0.9, 0.999), eps: float = 1e-8, weight_decay: float = 0.0, amsgrad: bool = False, maximize: bool = False, foreach: bool = False, fused...
_FunctionalAdam
python
walkccc__LeetCode
solutions/819. Most Common Word/819.py
{ "start": 0, "end": 268 }
class ____: def mostCommonWord(self, paragraph: str, banned: list[str]) -> str: banned = set(banned) words = re.findall(r'\w+', paragraph.lower()) return collections.Counter( word for word in words if word not in banned).most_common(1)[0][0]
Solution
python
sphinx-doc__sphinx
sphinx/search/it.py
{ "start": 193, "end": 596 }
class ____(SearchLanguage): lang = 'it' language_name = 'Italian' js_stemmer_rawcode = 'italian-stemmer.js' stopwords = ITALIAN_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('italian') def stem(se...
SearchItalian
python
rapidsai__cudf
python/cudf/cudf/core/udf/groupby_typing.py
{ "start": 10156, "end": 12894 }
class ____(AttributeTemplate): key = GroupType resolve_max = _make_unary_attr("max") resolve_min = _make_unary_attr("min") resolve_sum = _make_unary_attr("sum") resolve_mean = _make_unary_attr("mean") resolve_var = _make_unary_attr("var") resolve_std = _make_unary_attr("std") resolve_...
GroupAttr
python
pandas-dev__pandas
pandas/tests/reshape/test_melt.py
{ "start": 19650, "end": 25705 }
class ____: def test_pairs(self): data = { "birthdt": [ "08jan2009", "20dec2008", "30dec2008", "21dec2008", "11jan2009", ], "birthwt": [1766, 3301, 1454, 3139, 4133], "id": [101, 1...
TestLreshape
python
huggingface__transformers
examples/modular-transformers/modular_new_model.py
{ "start": 139, "end": 1006 }
class ____(GemmaConfig): def __init__( self, vocab_size=256030, hidden_size=64, intermediate_size=90, num_hidden_layers=28, num_attention_heads=16, num_key_value_heads=16, head_dim=256, hidden_act="gelu_pytorch_tanh", hidden_activation=...
NewModelConfig
python
encode__django-rest-framework
tests/schemas/test_coreapi.py
{ "start": 2214, "end": 2356 }
class ____(serializers.Serializer): c = serializers.CharField(required=True) d = serializers.CharField(required=False)
AnotherSerializer
python
weaviate__weaviate-python-client
weaviate/backup/backup.py
{ "start": 2215, "end": 2398 }
class ____(BackupStatusReturn): """Return type of the backup creation and restore methods.""" collections: List[str] = Field(default_factory=list, alias="classes")
BackupReturn
python
modin-project__modin
modin/pandas/indexing.py
{ "start": 22404, "end": 36313 }
class ____(_LocationIndexerBase): """ An indexer for modin_df.loc[] functionality. Parameters ---------- modin_df : Union[DataFrame, Series] DataFrame to operate on. """ _extensions: EXTENSION_DICT_TYPE = EXTENSION_DICT_TYPE(dict) def __getitem__(self, key): """ ...
_LocIndexer
python
pytorch__pytorch
test/inductor/test_padding.py
{ "start": 5562, "end": 8581 }
class ____(TestCaseBase): @unittest.skipIf(not DO_PERF_TEST, "Perf test not enabled") def test_nobias_LinearAndSoftmax_both_shapes(self): self.test_LinearAndSoftmax_both_shapes(bias=False) @unittest.skipIf(not DO_PERF_TEST, "Perf test not enabled") def test_LinearAndSoftmax_both_shapes(self, bi...
PerfTestBetweenGoodAndBadShape
python
run-llama__llama_index
llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/agent.py
{ "start": 1158, "end": 1295 }
class ____(Event): tool_call_id: str tool_name: str tool_kwargs: Dict[str, Any] tool_output: ToolOutput
ToolCallResultEvent
python
scipy__scipy
scipy/fftpack/tests/test_helper.py
{ "start": 993, "end": 1337 }
class ____: def test_definition(self): x = [0,1,2,3,4,-4,-3,-2,-1] assert_array_almost_equal(9*fftfreq(9),x) assert_array_almost_equal(9*pi*fftfreq(9,pi),x) x = [0,1,2,3,4,-5,-4,-3,-2,-1] assert_array_almost_equal(10*fftfreq(10),x) assert_array_almost_equal(10*pi*fft...
TestFFTFreq
python
kamyu104__LeetCode-Solutions
Python/determine-color-of-a-chessboard-square.py
{ "start": 29, "end": 255 }
class ____(object): def squareIsWhite(self, coordinates): """ :type coordinates: str :rtype: bool """ return (ord(coordinates[0])-ord('a'))%2 != (ord(coordinates[1])-ord('1'))%2
Solution
python
mitmproxy__pdoc
test/testdata/flavors_google.py
{ "start": 5030, "end": 6148 }
class ____(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document ...
ExampleError
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/dataset_generation.py
{ "start": 1438, "end": 3386 }
class ____(BaseModel): """ Query Response Dataset. The response can be empty if the dataset is generated from documents. Args: queries (Dict[str, str]): Query id -> query. responses (Dict[str, str]): Query id -> response. """ queries: Dict[str, str] = Field( default_f...
QueryResponseDataset
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py
{ "start": 173, "end": 665 }
class ____[T1 = str, T2 = T1](dict[T1, T2]): def method1(self) -> Self: return self reveal_type( ClassA[int].method1, expected_text="(self: ClassA[int, int]) -> ClassA[int, int]" ) reveal_type( ClassA.method1, expected_text="(self: ClassA[str, str]) -> ClassA[str, str]" ) a1 = ClassA[int]() revea...
ClassA
python
dagster-io__dagster
python_modules/dagster/dagster/_core/instance/types.py
{ "start": 949, "end": 2708 }
class ____(logging.Handler): def __init__(self, instance: "DagsterInstance"): self._instance = instance super().__init__() def emit(self, record: logging.LogRecord) -> None: from dagster._core.events import EngineEventData from dagster._core.events.log import StructuredLoggerMes...
_EventListenerLogHandler
python
pytorch__pytorch
test/fx/test_future.py
{ "start": 554, "end": 730 }
class ____(torch.nn.Module): def forward(self, x: list[torch.Tensor], a: A) -> torch.Tensor: return a(x[0]) # Non-torch annotation with internal forward references
M3
python
getsentry__sentry
tests/sentry/incidents/models/test_incidents.py
{ "start": 492, "end": 1898 }
class ____(TestCase): def test_empty(self) -> None: incidents = Incident.objects.fetch_for_organization(self.organization, [self.project]) assert [] == list(incidents) self.create_project() def test_simple(self) -> None: incident = self.create_incident() assert [inciden...
FetchForOrganizationTest
python
tensorflow__tensorflow
tensorflow/python/training/sync_replicas_optimizer_test.py
{ "start": 3281, "end": 10824 }
class ____(test.TestCase): def _run(self, train_op, sess): sess.run(train_op) @test_util.run_v1_only( "This exercises tensor lookup via names which is not supported in V2.") def test2Workers(self): num_workers = 2 replicas_to_aggregate = 2 num_ps = 2 workers, _ = create_local_cluster(n...
SyncReplicasOptimizerTest
python
django__django
tests/async/test_async_shortcuts.py
{ "start": 211, "end": 2432 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.s1 = SimpleModel.objects.create(field=0) cls.s2 = SimpleModel.objects.create(field=1) cls.r1 = RelatedModel.objects.create(simple=cls.s1) async def test_aget_object_or_404(self): self.assertEqual(await aget_objec...
GetListObjectOr404Test
python
getsentry__sentry
tests/sentry/integrations/source_code_management/test_commit_context.py
{ "start": 660, "end": 1133 }
class ____(CommitContextIntegration): """Mock implementation for testing""" integration_name = "mock_integration" def __init__(self) -> None: self.client = Mock() self.client.base_url = "https://example.com" def get_client(self) -> CommitContextClient: return self.client ...
MockCommitContextIntegration
python
sphinx-doc__sphinx
tests/utils.py
{ "start": 1665, "end": 4365 }
class ____(HttpServerThread): def __init__(self, handler: type[BaseRequestHandler], *, port: int = 0) -> None: super().__init__(handler, port=port) sslcontext = SSLContext(PROTOCOL_TLS_SERVER) sslcontext.load_cert_chain(CERT_FILE) self.server.socket = sslcontext.wrap_socket( ...
HttpsServerThread
python
pandas-dev__pandas
pandas/io/formats/format.py
{ "start": 50294, "end": 51028 }
class ____(_GenericArrayFormatter): values: DatetimeArray def __init__( self, values: DatetimeArray, nat_rep: str = "NaT", date_format: None = None, **kwargs, ) -> None: super().__init__(values, **kwargs) self.nat_rep = nat_rep self.date_forma...
_Datetime64Formatter
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/integration_aliases.py
{ "start": 932, "end": 16675 }
class ____(SanitySingleVersion): """Sanity test to evaluate integration test aliases.""" CI_YML = '.azure-pipelines/azure-pipelines.yml' TEST_ALIAS_PREFIX = 'shippable' # this will be changed at some point in the future DISABLED = 'disabled/' UNSTABLE = 'unstable/' UNSUPPORTED = 'unsupported/...
IntegrationAliasesTest
python
doocs__leetcode
solution/2300-2399/2363.Merge Similar Items/Solution.py
{ "start": 0, "end": 258 }
class ____: def mergeSimilarItems( self, items1: List[List[int]], items2: List[List[int]] ) -> List[List[int]]: cnt = Counter() for v, w in chain(items1, items2): cnt[v] += w return sorted(cnt.items())
Solution
python
wandb__wandb
wandb/sdk/data_types/table.py
{ "start": 40982, "end": 43667 }
class ____(Media): """A table which is composed of multiple sub-tables. Currently, PartitionedTable is designed to point to a directory within an artifact. """ _log_type = "partitioned-table" def __init__(self, parts_path): """Initialize a PartitionedTable. Args: ...
PartitionedTable
python
getsentry__sentry
src/sentry/users/services/user_option/impl.py
{ "start": 550, "end": 3834 }
class ____(UserOptionService): def serialize_many( self, *, filter: UserOptionFilterArgs, as_user: RpcUser | None = None, auth_context: AuthenticationContext | None = None, ) -> list[OpaqueSerializedResponse]: return self._FQ.serialize_many(filter, as_user, auth_c...
DatabaseBackedUserOptionService
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_data_validation06.py
{ "start": 315, "end": 2514 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("data_validation02.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file data validation.""" workbook = Wo...
TestCompareXLSXFiles
python
django__django
django/forms/widgets.py
{ "start": 14352, "end": 15741 }
class ____(Input): allow_multiple_selected = False input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def __init__(self, attrs=None): if ( attrs is not None and not self.allow_multiple_selected and attrs.get("...
FileInput
python
has2k1__plotnine
tests/test_layers.py
{ "start": 2718, "end": 3712 }
class ____: p = ggplot(larger_data, aes("x", "y")) def _assert_raster_smaller(self, p_no_raster, p_raster): # Plot and check that the file sizes are smaller when # rastering. Then delete the files. geom_name = p_raster.layers[0].geom.__class__.__name__ fn1 = Path(f"{geom_name}-n...
TestRasterizing
python
pandas-dev__pandas
pandas/tests/tslibs/test_np_datetime.py
{ "start": 4750, "end": 7889 }
class ____: def test_pass_non_dt64_array(self): # check that we raise, not segfault arr = np.arange(5) dtype = np.dtype("M8[ns]") msg = ( "astype_overflowsafe values.dtype and dtype must be either " "both-datetime64 or both-timedelta64" ) with...
TestAstypeOverflowSafe
python
huggingface__transformers
tests/models/rembert/test_modeling_rembert.py
{ "start": 17253, "end": 18382 }
class ____(unittest.TestCase): @slow def test_inference_model(self): # Test exact values at the last hidden layer model = RemBertModel.from_pretrained("google/rembert") input_ids = torch.tensor([[312, 56498, 313, 2125, 313]]) segment_ids = torch.tensor([[0, 0, 0, 1, 1]]) ...
RemBertModelIntegrationTest
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 12203, "end": 12263 }
class ____(Book): price = models.FloatField()
HardbackBook
python
automl__auto-sklearn
autosklearn/data/validation.py
{ "start": 1231, "end": 7425 }
class ____(BaseEstimator): """ Makes sure the input data complies with Auto-sklearn requirements. Categorical inputs are encoded via a Label Encoder, if the input is a dataframe. This class also perform checks for data integrity and flags the user via informative errors. Attributes ---...
InputValidator
python
numba__numba
numba/cuda/tests/cudapy/test_dispatcher.py
{ "start": 16983, "end": 26587 }
class ____(CUDATestCase): def test_get_regs_per_thread_unspecialized(self): # A kernel where the register usage per thread is likely to differ # between different specializations @cuda.jit def pi_sin_array(x, n): i = cuda.grid(1) if i < n: x[i]...
TestDispatcherKernelProperties
python
getsentry__sentry
tests/sentry/seer/fetch_issues/test_utils.py
{ "start": 7354, "end": 9545 }
class ____(TestCase): def test_get_latest_issue_event_success(self): data = load_data("python", timestamp=before_now(minutes=1)) event = self.store_event(data=data, project_id=self.project.id) group = event.group assert group is not None result = get_latest_issue_event(group...
TestGetLatestIssueEvent
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 195606, "end": 202258 }
class ____(MatmulCommon, TestCase): def setUp(self): self.matmul = np.matmul def test_out_arg(self): a = np.ones((5, 2), dtype=float) b = np.array([[1, 3], [5, 7]], dtype=float) tgt = np.dot(a, b) # test as positional argument msg = "out positional argument" ...
TestMatmul
python
numba__numba
numba/tests/parfors_cache_usecases.py
{ "start": 454, "end": 1778 }
class ____(TestCase): """ Tests for functionality of this module's functions. Note this does not define any "test_*" method, instead check_module() should be called by hand. """ def check_module(self, mod): total_cache_hits = 0 for fn in [mod.arrayexprs_case, mod.prange_case, mod...
_TestModule
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_pubsub.py
{ "start": 1893, "end": 6417 }
class ____: def test_async_pubsub_pull_trigger_serialization_should_execute_successfully(self, trigger): """ Asserts that the PubsubPullTrigger correctly serializes its arguments and classpath. """ classpath, kwargs = trigger.serialize() assert classpath == "airflow.p...
TestPubsubPullTrigger
python
Lightning-AI__lightning
src/lightning/fabric/strategies/strategy.py
{ "start": 1708, "end": 16359 }
class ____(ABC): """Base class for all strategies that change the behaviour of the training, validation and test- loop.""" def __init__( self, accelerator: Optional[Accelerator] = None, checkpoint_io: Optional[CheckpointIO] = None, precision: Optional[Precision] = None, ) ->...
Strategy
python
huggingface__transformers
src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py
{ "start": 21259, "end": 22775 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList( [RobertaPreLayerNormLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)] ) def forward( self, hidden_states: torch.T...
RobertaPreLayerNormEncoder
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/steps/bump_version.py
{ "start": 944, "end": 4501 }
class ____(StepModifyingFiles): context: ConnectorContext @property def title(self) -> str: return f"Set connector version to {self.new_version}" def __init__( self, context: ConnectorContext, connector_directory: dagger.Directory, new_version: str, ) -> Non...
SetConnectorVersion
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints/multiapi/main.py
{ "start": 1239, "end": 1661 }
class ____(remote.Service): @endpoints.method(Request, Response, path="bookmark") def get_bookmark(self, request): return Response() @endpoints.method(Request, Response) def best_sellers_list(self, request): return Response() # [END endpoints_books] # [END endpoints_multiclass] # [S...
Books
python
pytorch__pytorch
torch/utils/data/datapipes/iter/combinatorics.py
{ "start": 1988, "end": 6513 }
class ____(IterDataPipe[_T_co]): r""" Shuffle the input DataPipe with a buffer (functional name: ``shuffle``). The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then, each item will be yielded from the buffer by reservoir sampling via iterator. ``buffer_size`` is req...
ShufflerIterDataPipe
python
keon__algorithms
tests/test_sort.py
{ "start": 734, "end": 3449 }
class ____(unittest.TestCase): def test_bogo_sort(self): self.assertTrue(is_sorted(bogo_sort([1, 23, 5]))) def test_bitonic_sort(self): self.assertTrue(is_sorted(bitonic_sort([1, 3, 2, 5, 65, 23, 57, 1232]))) def test_bubble_sort(self): ...
TestSuite
python
django__django
tests/model_regress/models.py
{ "start": 1251, "end": 1413 }
class ____(models.Model): name = models.CharField(max_length=10, primary_key=True) # Chained foreign keys with to_field produce incorrect query #18432
NonAutoPK
python
allegroai__clearml
clearml/backend_api/session/session.py
{ "start": 1707, "end": 46551 }
class ____(TokenManager): """ClearML API Session class.""" _AUTHORIZATION_HEADER = "Authorization" _WORKER_HEADER = ( "X-ClearML-Worker", "X-Trains-Worker", ) _ASYNC_HEADER = ( "X-ClearML-Async", "X-Trains-Async", ) _CLIENT_HEADER = ( "X-ClearML-Clien...
Session
python
realpython__materials
geoshops/nearbyshops/migrations/0001_initial.py
{ "start": 135, "end": 837 }
class ____(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Shop', fields=[ ('id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbo...
Migration
python
getsentry__sentry
src/sentry/integrations/api/serializers/models/integration.py
{ "start": 7552, "end": 8410 }
class ____(Serializer): def serialize( self, obj: IntegrationProvider, attrs: Mapping[str, Any], user: User | RpcUser | AnonymousUser, **kwargs: Any, ) -> IntegrationProviderResponse: org_slug = kwargs.pop("organization").slug metadata: Any = obj.metadata ...
IntegrationProviderSerializer
python
crytic__slither
slither/detectors/compiler_bugs/enum_conversion.py
{ "start": 1047, "end": 2886 }
class ____(AbstractDetector): """ Detect dangerous conversion to enum """ ARGUMENT = "enum-conversion" HELP = "Detect dangerous enum conversion" IMPACT = DetectorClassification.MEDIUM CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Docum...
EnumConversion
python
doocs__leetcode
solution/1100-1199/1155.Number of Dice Rolls With Target Sum/Solution.py
{ "start": 0, "end": 414 }
class ____: def numRollsToTarget(self, n: int, k: int, target: int) -> int: f = [[0] * (target + 1) for _ in range(n + 1)] f[0][0] = 1 mod = 10**9 + 7 for i in range(1, n + 1): for j in range(1, min(i * k, target) + 1): for h in range(1, min(j, k) + 1): ...
Solution
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 123493, "end": 124012 }
class ____(Operation): def call(self, x): return backend.numpy.isneginf(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype="bool") @keras_export(["keras.ops.isneginf", "keras.ops.numpy.isneginf"]) def isneginf(x): """Test element-wise for negative infinity. Args: ...
Isneginf
python
falconry__falcon
falcon/util/time.py
{ "start": 359, "end": 1797 }
class ____(datetime.tzinfo): """GMT timezone class implementing the :class:`datetime.tzinfo` interface. .. deprecated:: 4.0 :class:`TimezoneGMT` is deprecated, use :attr:`datetime.timezone.utc` instead. (This class will be removed in Falcon 5.0.) """ GMT_ZERO = datetime.timedelta(hours...
TimezoneGMT
python
google__pytype
pytype/compare_test.py
{ "start": 9004, "end": 14257 }
class ____(CompareTestBase): def setUp(self): super().setUp() self._d = abstract.Dict(self._ctx) self._var = self._program.NewVariable() self._var.AddBinding(abstract.Unknown(self._ctx), [], self._node) def test_compatible_with__when_empty(self): self.assertFalsy(self._d) def test_compatibl...
DictTest
python
encode__starlette
starlette/middleware/httpsredirect.py
{ "start": 150, "end": 848 }
class ____: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): url = URL(scope=scope) redirect_scheme = {"...
HTTPSRedirectMiddleware
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 19758, "end": 21629 }
class ____(Constraint): """ Constraint functor that applies a sequence of constraints `cseq` at the submatrices at dimension `dim`, in a way compatible with :func:`torch.stack`. """ def __init__(self, cseq, dim=0): assert all(isinstance(c, Constraint) for c in cseq) self.cseq = ...
_Stack
python
doocs__leetcode
solution/1700-1799/1765.Map of Highest Peak/Solution.py
{ "start": 0, "end": 676 }
class ____: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m, n = len(isWater), len(isWater[0]) ans = [[-1] * n for _ in range(m)] q = deque() for i, row in enumerate(isWater): for j, v in enumerate(row): if v: q.ap...
Solution
python
wandb__wandb
tests/unit_tests/test_retry.py
{ "start": 3315, "end": 4252 }
class ____: def test_reraises_exc_failing_predicate(self): wrapped = mock.Mock(spec=retry.Backoff) filtered = retry.FilteredBackoff( filter=lambda e: False, wrapped=wrapped, ) with pytest.raises(MyError): filtered.next_sleep_or_reraise(MyError("do...
TestFilteredBackoff
python
pandas-dev__pandas
asv_bench/benchmarks/sparse.py
{ "start": 1844, "end": 2626 }
class ____: params = [True, False] param_names = ["sort_labels"] def setup(self, sort_labels): s = Series([np.nan] * 10000) s[0] = 3.0 s[100] = -1.0 s[999] = 12.1 s_mult_lvl = s.set_axis(MultiIndex.from_product([range(10)] * 4)) self.ss_mult_lvl = s_mult_lvl...
ToCoo
python
readthedocs__readthedocs.org
readthedocs/redirects/migrations/0001_initial.py
{ "start": 100, "end": 3449 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0002_add_importedfile_model"), ] operations = [ migrations.CreateModel( name="Redirect", fields=[ ( "id", models.Au...
Migration
python
lepture__authlib
authlib/integrations/flask_client/integration.py
{ "start": 217, "end": 806 }
class ____(FrameworkIntegration): def update_token(self, token, refresh_token=None, access_token=None): token_update.send( current_app, name=self.name, token=token, refresh_token=refresh_token, access_token=access_token, ) @staticmetho...
FlaskIntegration
python
sqlalchemy__sqlalchemy
test/sql/test_resultset.py
{ "start": 104187, "end": 120381 }
class ____(fixtures.TablesTest): __requires__ = ("sqlite",) @classmethod def setup_bind(cls): cls.engine = engine = engines.testing_engine( "sqlite://", options={"scope": "class"} ) return engine @classmethod def define_tables(cls, metadata): Table( ...
AlternateCursorResultTest
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/graphs/converter.py
{ "start": 276, "end": 2459 }
class ____(NamedTuple): node1: Node node2: Node @property def flip(self) -> "Edge": return Edge(self.node2, self.node1) @property def distance(self) -> float: return math.dist( (self.node1.row, self.node1.column), (self.node2.row, self.node2.column), ...
Edge
python
pandas-dev__pandas
pandas/tests/api/test_api.py
{ "start": 450, "end": 937 }
class ____: def check(self, namespace, expected, ignored=None): # see which names are in the namespace, minus optional # ignored ones # compare vs the expected result = sorted( f for f in dir(namespace) if not f.startswith("__") and f != "annotations" ) i...
Base
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/file_manager.py
{ "start": 1507, "end": 1965 }
class ____(FileHandle): """A reference to a file on a local filesystem.""" def __init__(self, path: str): self._path = check.str_param(path, "path") @public @property def path(self) -> str: """The file's path.""" return self._path @public @property def path_des...
LocalFileHandle