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
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/shuffle_ops.py
{ "start": 1367, "end": 11707 }
class ____(dataset_ops.UnaryUnchangedStructureDataset): """A `Dataset` that fuses `shuffle` and `repeat`.""" def __init__(self, input_dataset, buffer_size, count=None, seed=None): self._input_dataset = input_dataset self._buffer_size = ops.convert_to_tensor( buffer_size, dtype=dtypes.int64, name="b...
_ShuffleAndRepeatDataset
python
doocs__leetcode
solution/0700-0799/0742.Closest Leaf in a Binary Tree/Solution.py
{ "start": 192, "end": 952 }
class ____: def findClosestLeaf(self, root: Optional[TreeNode], k: int) -> int: def dfs(root: Optional[TreeNode], fa: Optional[TreeNode]): if root: g[root].append(fa) g[fa].append(root) dfs(root.left, root) dfs(root.right, root) ...
Solution
python
SmileyChris__easy-thumbnails
easy_thumbnails/VIL/ImageDraw.py
{ "start": 226, "end": 566 }
class ____: def __init__(self, im): self.im = im def rectangle(self, xy, fill=None, outline=None, width=1): if fill: self.im.canvas.setFillColor(fill) if outline: self.im.canvas.setStrokeColor(outline) self.im.canvas.setLineWidth(width) self.im.ca...
ImageDraw
python
huggingface__transformers
src/transformers/models/openai/modeling_openai.py
{ "start": 1469, "end": 3968 }
class ____(nn.Module): def __init__(self, nx, n_positions, config, scale=False): super().__init__() n_state = nx # in Attention: n_state=768 (nx=n_embd) if n_state % config.n_head != 0: raise ValueError(f"Attention n_state shape: {n_state} must be divisible by config.n_head {con...
Attention
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 5300, "end": 6331 }
class ____(CompositeTrigger): """A composite trigger that requires some number of triggers to have fired within the given time period""" type: Literal["compound"] = "compound" require: Union[int, Literal["any", "all"]] @property def num_expected_firings(self) -> int: if self.require ==...
CompoundTrigger
python
pytorch__pytorch
test/test_python_dispatch.py
{ "start": 98668, "end": 99178 }
class ____(TestCase): def test_basic(self): x = torch.randn(2, requires_grad=True) r = torch._C._EnablePythonDispatcher() torch.add(x, x) def test_lstsq(self): a = torch.randn(4, 3) b = torch.rand(4, 3) expected_shape = torch.linalg.lstsq(a, b).solution.shape ...
TestPythonDispatcher
python
readthedocs__readthedocs.org
readthedocs/organizations/tests/test_orgs.py
{ "start": 3880, "end": 6680 }
class ____(OrganizationTestCase): def test_owner_add(self): """Test owner add form.""" self.assertEqual(self.organization.owners.count(), 1) self.add_owner(username="tester") self.assertEqual(self.organization.owners.count(), 1) invitation = Invitation.objects.for_object(self...
OrganizationOwnerTests
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/docs/base.py
{ "start": 3001, "end": 3887 }
class ____(BaseReader): """Docx parser.""" def load_data( self, file: Path, extra_info: Optional[Dict] = None, fs: Optional[AbstractFileSystem] = None, ) -> List[Document]: """Parse file.""" if not isinstance(file, Path): file = Path(file) ...
DocxReader
python
walkccc__LeetCode
solutions/89. Gray Code/89.py
{ "start": 0, "end": 191 }
class ____: def grayCode(self, n: int) -> list[int]: ans = [0] for i in range(n): for j in reversed(range(len(ans))): ans.append(ans[j] | 1 << i) return ans
Solution
python
Textualize__textual
src/textual/widgets/_rule.py
{ "start": 1345, "end": 1448 }
class ____(Exception): """Exception raised for an invalid rule orientation."""
InvalidRuleOrientation
python
scipy__scipy
scipy/linalg/tests/test_blas.py
{ "start": 5732, "end": 26635 }
class ____: @parametrize_blas(fblas, "gemv", "sdcz") def test_gemv(self, f, dtype): assert_array_almost_equal(f(3, [[3]], [-4]), [-36]) assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21]) if dtype in COMPLEX_DTYPES: assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-4...
TestFBLAS2Simple
python
keras-team__keras
keras/src/saving/saving_lib_test.py
{ "start": 35056, "end": 35612 }
class ____(keras.layers.Layer): def __init__(self, factor, **kwargs): super().__init__(**kwargs) self.factor = factor def call(self, x): return x * self.factor def get_config(self): return {"factor": self.factor} # This custom model does not explicitly deserialize the lay...
FactorLayer
python
kamyu104__LeetCode-Solutions
Python/sum-of-scores-of-built-strings.py
{ "start": 42, "end": 704 }
class ____(object): def sumScores(self, s): """ :type s: str :rtype: int """ # Template: https://cp-algorithms.com/string/z-function.html def z_function(s): # Time: O(n), Space: O(n) z = [0]*len(s) l, r = 0, 0 for i in xrange(1, le...
Solution
python
huggingface__transformers
src/transformers/utils/quantization_config.py
{ "start": 68407, "end": 72990 }
class ____(QuantizationConfigMixin): """ FPQuantConfig is a configuration class for quantization using the FPQuant method. Args: forward_dtype (`str`, *optional*, defaults to `"nvfp4"`): The dtype to use for the forward pass. forward_method (`str`, *optional*, defaults to `"abs_...
FPQuantConfig
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/from_list_test.py
{ "start": 1542, "end": 4999 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(elements=[ combinations.NamedObject("empty_input", []), combinations.NamedObject("non-list_input...
FromListTest
python
openai__openai-python
tests/api_resources/test_evals.py
{ "start": 10385, "end": 20928 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: eval = await async_client.evals.create( ...
TestAsyncEvals
python
pydantic__pydantic
pydantic-core/tests/serializers/test_serialize_as_any.py
{ "start": 203, "end": 235 }
class ____: x: int
ParentModel
python
huggingface__transformers
src/transformers/utils/notebook.py
{ "start": 11487, "end": 15711 }
class ____(TrainerCallback): """ A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or Google colab. """ def __init__(self): self.training_tracker = None self.prediction_bar = None self._force_next_update = False ...
NotebookProgressCallback
python
networkx__networkx
networkx/algorithms/tests/test_cuts.py
{ "start": 2191, "end": 3035 }
class ____: """Unit tests for the :func:`~networkx.normalized_cut_size` function.""" def test_graph(self): G = nx.path_graph(4) S = {1, 2} T = set(G) - S size = nx.normalized_cut_size(G, S, T) # The cut looks like this: o-{-o--o-}-o expected = 2 * ((1 / 4) + (1 /...
TestNormalizedCutSize
python
kamyu104__LeetCode-Solutions
Python/smallest-value-after-replacing-with-sum-of-prime-factors.py
{ "start": 537, "end": 1055 }
class ____(object): def smallestValue(self, n): """ :type n: int :rtype: int """ while True: curr, new_n = n, 0 for p in PRIMES: if p**2 > curr: break while curr%p == 0: curr //= p...
Solution
python
nryoung__algorithms
tests/test_random.py
{ "start": 66, "end": 1961 }
class ____(unittest.TestCase): """ Tests Mersenne Twister values for several seeds comparing against expected values from C++ STL's Mersenne Twister implementation """ def test_mersenne_twister(self): mt = mersenne_twister.MersenneTwister() # Test seed 1 mt.seed(1) ...
TestMersenneTwister
python
django__django
django/forms/models.py
{ "start": 50090, "end": 51610 }
class ____(Field): """ A basic integer field that deals with validating the given value to a given parent instance in an inline. """ widget = HiddenInput default_error_messages = { "invalid_choice": _("The inline value did not match the parent instance."), } def __init__(self, ...
InlineForeignKeyField
python
pytorch__pytorch
test/distributed/pipelining/model_registry.py
{ "start": 5946, "end": 6696 }
class ____(torch.nn.Module): def __init__(self, d_hid: int, n_layers: int = 2): super().__init__() self.layers = torch.nn.ModuleList( [MLPKWargModule(d_hid, i) for i in range(n_layers)] ) # For testing purpose only, this should be defined by user self.split_spec =...
MultiMLPKwargs
python
PyCQA__pylint
tests/functional/a/alternative/alternative_union_syntax_regession_8119.py
{ "start": 325, "end": 459 }
class ____(Generic[T]): def __init__(self, update_interval=None) -> None: self.update_interval = update_interval
Coordinator
python
apache__thrift
test/py.tornado/test_suite.py
{ "start": 1496, "end": 3045 }
class ____(object): def __init__(self, test_instance): self.test_instance = test_instance def testVoid(self): pass def testString(self, s): if s == 'unexpected_error': raise Exception(s) return s def testByte(self, b): return b def testI16(self...
TestHandler
python
facelessuser__pymdown-extensions
pymdownx/blocks/__init__.py
{ "start": 4601, "end": 18291 }
class ____(BlockProcessor): """Generic block processor.""" def __init__(self, parser: BlockParser, md: Markdown) -> None: """Initialization.""" self.md = md # The Block classes indexable by name self.blocks: dict[str, type[Block]] = {} self.config: dict[str, dict[str, ...
BlocksProcessor
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 9824, "end": 10196 }
class ____(BiffRecord): """ This record is part of the worksheet/workbook protection. It determines whether the window configuration of this document is protected. Window protection is not active, if this record is omitted. """ _REC_ID = 0x0019 def __init__(self, wndprotect): self....
WindowProtectRecord
python
PyCQA__isort
tests/unit/test_exceptions.py
{ "start": 1232, "end": 1481 }
class ____(TestISortError): def setup_class(self): self.instance: exceptions.FileSkipComment = exceptions.FileSkipComment("file_path") def test_variables(self): assert self.instance.file_path == "file_path"
TestFileSkipComment
python
getsentry__sentry
src/sentry/integrations/utils/metrics.py
{ "start": 14879, "end": 15045 }
class ____(StrEnum): # OAuth identity NO_CODE_PROVIDED = "no_code_provided" # VSTS NO_ACCOUNTS = "no_accounts" @dataclass
IntegrationPipelineHaltReason
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py
{ "start": 1773, "end": 12947 }
class ____(AwsBaseOperator[GlueJobHook]): """ Create an AWS Glue Job. AWS Glue is a serverless Spark ETL service for running Spark Jobs on the AWS cloud. Language support: Python and Scala. .. seealso:: For more information on how to use this operator, take a look at the guide: :re...
GlueJobOperator
python
ray-project__ray
python/ray/train/v2/_internal/data_integration/interfaces.py
{ "start": 439, "end": 969 }
class ____(Protocol): def get_dataset_shard(self, dataset_info: DatasetShardMetadata) -> DataIterator: """Get the dataset shard for the given dataset info. Args: dataset_info: The metadata of the shard to retrieve, including the dataset name. Returns: ...
DatasetShardProvider
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_crypto_ticker.py
{ "start": 680, "end": 1687 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_crypto_ticker" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pan...
ColumnValuesToBeValidCryptoTicker
python
huggingface__transformers
tests/models/florence2/test_modeling_florence2.py
{ "start": 8917, "end": 33756 }
class ____(unittest.TestCase): def setUp(self): self.image1 = Image.open( requests.get( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg?download=true", stream=True, ).raw ) ...
Florence2ForConditionalGenerationIntegrationTest
python
PyCQA__pylint
tests/functional/r/regression_02/regression_5030.py
{ "start": 603, "end": 870 }
class ____(SomeData): """A subclass of a dataclass.""" def __init__(self, **kwargs: Dict[str, Any]) -> None: """Subclass init func.""" super().__init__(**kwargs) if "test" in self.a_dict: print(self.a_dict["test"])
SubSomeData
python
lxml__lxml
src/lxml/tests/test_incremental_xmlfile.py
{ "start": 15063, "end": 17508 }
class ____(_XmlFileTestCaseBase): class SimpleFileLike: def __init__(self, target): self._target = target self.write = target.write self.tell = target.tell self.seek = target.seek self.closed = False def close(self): assert not...
SimpleFileLikeXmlFileTestCase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 242296, "end": 242777 }
class ____(sgqlc.types.Input): """Ordering options for IP allow list entry connections.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(IpAllowListEntryOrderField), graphql_name="field") """The field to order IP allow list entrie...
IpAllowListEntryOrder
python
Textualize__textual
examples/markdown.py
{ "start": 248, "end": 2476 }
class ____(App): """A simple Markdown viewer application.""" BINDINGS = [ Binding( "t", "toggle_table_of_contents", "TOC", tooltip="Toggle the Table of Contents Panel", ), Binding("b", "back", "Back", tooltip="Navigate back"), Bind...
MarkdownApp
python
getlogbook__logbook
src/logbook/notifiers.py
{ "start": 7357, "end": 8953 }
class ____(NotificationBaseHandler): """Sends notifications to boxcar.io. Can be forwarded to your iPhone or other compatible device. .. deprecated:: 1.9 """ api_url = "https://boxcar.io/notifications/" def __init__( self, email, password, record_limit=None, ...
BoxcarHandler
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ012.py
{ "start": 1161, "end": 1409 }
class ____(Model): """Model with `get_absolute_url` method before `save` method. Subclass this directly using the `Model` class. """ def get_absolute_url(self): pass def save(self): pass
GetAbsoluteUrlBeforeSave
python
astropy__astropy
astropy/units/tests/test_quantity_ufuncs.py
{ "start": 40943, "end": 44214 }
class ____: """Test the clip ufunc. In numpy, this is hidden behind a function that does not backwards compatibility checks. We explicitly test the ufunc here. """ def setup_method(self): self.clip = np_umath.clip def test_clip_simple(self): q = np.arange(-1.0, 10.0) * u.m ...
TestClip
python
networkx__networkx
networkx/classes/tests/test_digraph.py
{ "start": 7319, "end": 11231 }
class ____(BaseAttrDiGraphTester, _TestGraph): """Tests specific to dict-of-dict-of-dict digraph data structure""" def setup_method(self): self.Graph = nx.DiGraph # build dict-of-dict-of-dict K3 ed1, ed2, ed3, ed4, ed5, ed6 = ({}, {}, {}, {}, {}, {}) self.k3adj = {0: {1: ed1, 2:...
TestDiGraph
python
dagster-io__dagster
python_modules/dagster/dagster_tests/utils_tests/test_dataloader.py
{ "start": 3854, "end": 4187 }
class ____(LoadingContext): def __init__(self): from unittest import mock self._loaders = {} self._instance = mock.MagicMock() @property def loaders(self): return self._loaders @property def instance(self): return self._instance @record(kw_only=False)
MockedLoadingContext
python
celery__celery
t/unit/security/test_security.py
{ "start": 1001, "end": 6219 }
class ____(SecurityCase): def teardown_method(self): registry._disabled_content_types.clear() registry._set_default_serializer('json') try: registry.unregister('auth') except SerializerNotInstalled: pass def test_disable_insecure_serializers(self): ...
test_security
python
streamlit__streamlit
lib/streamlit/elements/deck_gl_json_chart.py
{ "start": 7000, "end": 7697 }
class ____(TypedDict, total=False): """ The schema for the PyDeck event state. The event state is stored in a dictionary-like object that supports both key and attribute notation. Event states cannot be programmatically changed or set through Session State. Only selection events are supported ...
PydeckState
python
huggingface__transformers
src/transformers/loss/loss_rt_detr.py
{ "start": 1303, "end": 5496 }
class ____(nn.Module): """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predict...
RTDetrHungarianMatcher
python
pallets__werkzeug
src/werkzeug/serving.py
{ "start": 4787, "end": 24821 }
class ____(BaseHTTPRequestHandler): """A request handler that implements WSGI dispatching.""" server: BaseWSGIServer @property def server_version(self) -> str: # type: ignore return self.server._server_version def make_environ(self) -> WSGIEnvironment: request_url = urlsplit(self...
WSGIRequestHandler
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 481, "end": 545 }
class ____(AbcdMixin, Abcd): def abcd(self): pass
Dabc
python
huggingface__transformers
examples/pytorch/multiple-choice/run_swag.py
{ "start": 1747, "end": 3642 }
class ____: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=No...
ModelArguments
python
chroma-core__chroma
chromadb/api/types.py
{ "start": 50981, "end": 51142 }
class ____(BaseModel): """Configuration for Full-Text Search index. No parameters required.""" model_config = {"extra": "forbid"} pass
FtsIndexConfig
python
pytorch__pytorch
torch/fx/experimental/symbolic_shapes.py
{ "start": 68196, "end": 68260 }
class ____: warn_only: bool @dataclass(frozen=True)
Constraint
python
pytorch__pytorch
test/functorch/test_memory_efficient_fusion.py
{ "start": 8080, "end": 9757 }
class ____(TestCase): def test_nochange(self): def f(x): a = x + 1 b = x + a a = x d = x + a return b + d t = torch.randn(2, 2) check(f, t, 0) def test_empty(self): def f(x): pass t = torch.randn(2...
NoChangeTestCase
python
RaRe-Technologies__gensim
gensim/test/test_corpora_dictionary.py
{ "start": 492, "end": 15536 }
class ____(unittest.TestCase): def setUp(self): self.texts = common_texts def test_doc_freq_one_doc(self): texts = [['human', 'interface', 'computer']] d = Dictionary(texts) expected = {0: 1, 1: 1, 2: 1} self.assertEqual(d.dfs, expected) def test_doc_freq_and_token2...
TestDictionary
python
langchain-ai__langchain
libs/core/langchain_core/callbacks/base.py
{ "start": 10890, "end": 12631 }
class ____: """Mixin for run manager.""" def on_text( self, text: str, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any, ) -> Any: """Run on an arbitrary text. Args: text: The text. run_id: The run ID....
RunManagerMixin
python
kamyu104__LeetCode-Solutions
Python/confusing-number-ii.py
{ "start": 2785, "end": 5591 }
class ____(object): def confusingNumberII(self, n): """ :type n: int :rtype: int """ lookup = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"} centers = {"0":"0", "1":"1", "8":"8"} def totalCount(n): # count all numbers in the pattern of [01689]{1,len(n)} in the...
Solution2
python
pypa__pipenv
pipenv/patched/pip/_internal/commands/check.py
{ "start": 613, "end": 2358 }
class ____(Command): """Verify installed packages have compatible dependencies.""" ignore_require_venv = True usage = """ %prog [options]""" def run(self, options: Values, args: List[str]) -> int: package_set, parsing_probs = create_package_set_from_installed() missing, conflicti...
CheckCommand
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/models.py
{ "start": 1871, "end": 1973 }
class ____(models.Model): a = models.ForeignKey("LoopA", null=True, on_delete=models.SET_NULL)
LoopB
python
huggingface__transformers
src/transformers/models/swiftformer/modeling_swiftformer.py
{ "start": 6542, "end": 7800 }
class ____(nn.Module): """ Efficient Additive Attention module for SwiftFormer. Input: tensor of shape `[batch_size, channels, height, width]` Output: tensor of shape `[batch_size, channels, height, width]` """ def __init__(self, config: SwiftFormerConfig, dim: int = 512): super().__i...
SwiftFormerEfficientAdditiveAttention
python
getsentry__sentry
src/sentry/api/endpoints/organization_on_demand_metrics_estimation_stats.py
{ "start": 937, "end": 1170 }
class ____(TypedDict): count: float | None # Type returned by get_events_stats_data is actually a [int, List[CountResult]] where the first # param is the timestamp MetricVolumeRow = list[Union[int, list[CountResult]]]
CountResult
python
Textualize__textual
docs/examples/widgets/pretty.py
{ "start": 388, "end": 547 }
class ____(App): def compose(self) -> ComposeResult: yield Pretty(DATA) app = PrettyExample() if __name__ == "__main__": app.run()
PrettyExample
python
getsentry__sentry
src/sentry/replays/lib/new_query/fields.py
{ "start": 5563, "end": 6116 }
class ____(BaseField[T]): """Column fields target one column.""" def __init__( self, column_name: str, parse_fn: Callable[[str], T], query_type: type[GenericBase] ) -> None: self.column_name = column_name self.parse = parse_fn self.query = query_type def apply(self, sea...
ColumnField
python
gevent__gevent
src/greentest/3.10/test_ftplib.py
{ "start": 2391, "end": 3571 }
class ____(asynchat.async_chat): dtp_conn_closed = False def __init__(self, conn, baseclass): asynchat.async_chat.__init__(self, conn) self.baseclass = baseclass self.baseclass.last_received_data = '' self.encoding = baseclass.encoding def handle_read(self): new_dat...
DummyDTPHandler
python
PyCQA__pylint
tests/functional/n/no/no_member_dataclasses.py
{ "start": 731, "end": 1082 }
class ____(DeploymentState): blue: Any green: Any candidate: Any def to_dict(self) -> Dict: return { 'type': self.type, # No error here 'blue': asdict(self.blue), 'green': asdict(self.green), 'candidate': self.candidate.value, } @datacl...
DeploymentStateEcs
python
has2k1__plotnine
plotnine/layer.py
{ "start": 970, "end": 13293 }
class ____: """ Layer When a `geom` or `stat` is added to a [](`~plotnine.ggplot`) object, it creates a single layer. This class is a representation of that layer. Parameters ---------- geom : geom to used to draw this layer. stat : stat used for the statistical transfo...
layer
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 87500, "end": 87764 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING AutoModelForUniversalSegmentation = auto_class_update( AutoModelForUniversalSegmentation, head_doc="universal image segmentation" )
AutoModelForUniversalSegmentation
python
django__django
tests/admin_docs/test_views.py
{ "start": 8048, "end": 8977 }
class ____(TestDataMixin, AdminDocsTestCase): def setUp(self): self.client.force_login(self.superuser) def test_template_detail_path_traversal(self): cases = ["/etc/passwd", "../passwd"] for fpath in cases: with self.subTest(path=fpath): response = self.clien...
AdminDocViewDefaultEngineOnly
python
huggingface__transformers
src/transformers/models/mra/modeling_mra.py
{ "start": 42895, "end": 47726 }
class ____(MraPreTrainedModel): def __init__(self, config): super().__init__(config) self.mra = MraModel(config) self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size) self.classifier = nn.Linear(config.hidden_size, 1) # Initialize weights and apply final p...
MraForMultipleChoice
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_sagemaker_pipeline.py
{ "start": 1376, "end": 2917 }
class ____: @mock.patch.object(SageMakerHook, "start_pipeline") @mock.patch.object(SageMakerHook, "check_status") def test_execute(self, check_status, start_pipeline): op = SageMakerStartPipelineOperator( task_id="test_sagemaker_operator", pipeline_name="my_pipeline", ...
TestSageMakerStartPipelineOperator
python
rapidsai__cudf
python/dask_cudf/dask_cudf/_expr/collection.py
{ "start": 4770, "end": 5453 }
class ____(DXSeries, CudfFrameBase): def groupby(self, by, **kwargs): from dask_cudf._expr.groupby import SeriesGroupBy return SeriesGroupBy(self, by, **kwargs) @cached_property def list(self): from dask_cudf._expr.accessors import ListMethods return ListMethods(self) ...
Series
python
pypa__setuptools
setuptools/_distutils/compilers/C/zos.py
{ "start": 2317, "end": 6586 }
class ____(unix.Compiler): src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s'] _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C'] _asm_extensions = ['.s'] def _get_zos_compiler_name(self): zos_compiler_names = [ os.path.basename(binary) for envvar in ('CC', 'CX...
Compiler
python
keras-team__keras
keras/src/losses/losses_test.py
{ "start": 3889, "end": 7404 }
class ____(testing.TestCase): def test_config(self): self.run_class_serialization_test( losses.MeanAbsoluteError(name="myname") ) def test_all_correct_unweighted(self): mae_obj = losses.MeanAbsoluteError() y_true = np.array([[4, 8, 12], [8, 1, 3]]) loss = mae...
MeanAbsoluteErrorTest
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/view/renderer_extras.py
{ "start": 470, "end": 4440 }
class ____(SVGRenderer): square_size: int = 100 line_width: int = 6 show_grid: bool = True show_obstacles: bool = True show_solution: bool = True show_roles: bool = True show_borders: bool = True show_nodes: bool = True show_edges: bool = True include_corners: bool = True de...
ExtendedSVGRenderer
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/trigger.py
{ "start": 989, "end": 1258 }
class ____(BaseModel): """Trigger serializer for responses.""" model_config = ConfigDict(populate_by_name=True) id: int classpath: str kwargs: Annotated[str, BeforeValidator(str)] created_date: datetime triggerer_id: int | None
TriggerResponse
python
getsentry__sentry
tests/sentry/deletions/test_organizationmember.py
{ "start": 266, "end": 770 }
class ____(APITestCase, TransactionTestCase, HybridCloudTestMixin): def test_simple(self) -> None: organization = self.create_organization(name="test") user = self.create_user() member = self.create_member(organization=organization, user=user) self.ScheduledDeletion.schedule(instance...
DeleteOrganizationMemberTest
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 42518, "end": 42709 }
class ____(Callback): def on_validation_start(self, trainer, pl_module): if not trainer.sanity_checking: raise RuntimeError("Trouble!")
TroubledCallbackOnValidationStart
python
pypa__packaging
src/packaging/metadata.py
{ "start": 1781, "end": 9608 }
class ____(TypedDict, total=False): """A dictionary of raw core metadata. Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that ...
RawMetadata
python
pypa__warehouse
warehouse/accounts/services.py
{ "start": 31582, "end": 32386 }
class ____: def __init__(self, name, service_class=TokenService): self.name = name self.service_class = service_class def __call__(self, context, request): secret = request.registry.settings[f"token.{self.name}.secret"] salt = self.name # Use the service name as the unique salt...
TokenServiceFactory
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 19929, "end": 20329 }
class ____(HTTPError): """ base class for the 400s, where the client is in error This is an error condition in which the client is presumed to be in-error. This is an expected problem, and thus is not considered a bug. A server-side traceback is not warranted. Unless specialized, this is a '...
HTTPClientError
python
python-pillow__Pillow
src/PIL/ImageFilter.py
{ "start": 8036, "end": 8215 }
class ____(BuiltinFilter): name = "Detail" # fmt: off filterargs = (3, 3), 6, 0, ( 0, -1, 0, -1, 10, -1, 0, -1, 0, ) # fmt: on
DETAIL
python
dask__dask
dask/local.py
{ "start": 17887, "end": 18724 }
class ____(Executor): _max_workers = 1 def submit(self, fn, *args, **kwargs): fut = Future() try: fut.set_result(fn(*args, **kwargs)) except BaseException as e: fut.set_exception(e) return fut synchronous_executor = SynchronousExecutor() def get_sync(...
SynchronousExecutor
python
joke2k__faker
tests/providers/test_person.py
{ "start": 31369, "end": 31556 }
class ____(TestEnIE): """Tests person in the ga-IE locale""" def setUp(self): self.fake = Faker("ga-ie") self.provider = GaIEProvider Faker.seed(0)
TestGaIE
python
ray-project__ray
python/ray/serve/_private/config.py
{ "start": 18097, "end": 34922 }
class ____: """Internal datastructure wrapping config options for a deployment's replicas. Provides five main properties (see property docstrings for more info): deployment_def: the code, or a reference to the code, that this replica should run. init_args: the deployment_def's init_...
ReplicaConfig
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/strings.py
{ "start": 5906, "end": 13823 }
class ____(ListStrategy[str]): def do_draw(self, data): # if our element strategy is OneCharStringStrategy, we can skip the # ListStrategy draw and jump right to data.draw_string. # Doing so for user-provided element strategies is not correct in # general, as they may define a differ...
TextStrategy
python
getsentry__sentry
src/sentry/integrations/mixins/issues.py
{ "start": 15189, "end": 18088 }
class ____(IssueBasicIntegration, ABC): comment_key: ClassVar[str | None] = None outbound_status_key: ClassVar[str | None] = None inbound_status_key: ClassVar[str | None] = None outbound_assignee_key: ClassVar[str | None] = None inbound_assignee_key: ClassVar[str | None] = None def should_sync(...
IssueSyncIntegration
python
crytic__slither
slither/core/expressions/binary_operation.py
{ "start": 224, "end": 5082 }
class ____(Enum): POWER = 0 # ** MULTIPLICATION = 1 # * DIVISION = 2 # / MODULO = 3 # % ADDITION = 4 # + SUBTRACTION = 5 # - LEFT_SHIFT = 6 # << RIGHT_SHIFT = 7 # >>> AND = 8 # & CARET = 9 # ^ OR = 10 # | LESS = 11 # < GREATER = 12 # > LESS_EQUAL = 13...
BinaryOperationType
python
django__django
tests/staticfiles_tests/test_liveserver.py
{ "start": 2019, "end": 2653 }
class ____(LiveServerBase): def urlopen(self, url): return urlopen(self.live_server_url + url) # The test is going to access a static file stored in this application. @modify_settings(INSTALLED_APPS={"append": "staticfiles_tests.apps.test"}) def test_collectstatic_emulation(self): """ ...
StaticLiveServerView
python
django__django
tests/logging_tests/logconfig.py
{ "start": 160, "end": 298 }
class ____(logging.Handler): def __init__(self): logging.Handler.__init__(self) self.config = settings.LOGGING
MyHandler
python
kamyu104__LeetCode-Solutions
Python/longest-path-with-different-adjacent-characters.py
{ "start": 1427, "end": 3018 }
class ____(object): def longestPath(self, parent, s): """ :type parent: List[int] :type s: str :rtype: int """ def iter_dfs(s, adj): result = 0 stk = [(1, (0, [0]))] while stk: step, args = stk.pop() ...
Solution2
python
walkccc__LeetCode
solutions/3310. Remove Methods From Project/3310.py
{ "start": 0, "end": 616 }
class ____: def remainingMethods( self, n: int, k: int, invocations: list[list[int]] ) -> list[int]: ans = [] graph = [[] for _ in range(n)] for u, v in invocations: graph[u].append(v) q = collections.deque([k]) seen = {k} while q: for _ in range(len(q)...
Solution
python
scikit-learn__scikit-learn
sklearn/svm/_classes.py
{ "start": 45314, "end": 52030 }
class ____(RegressorMixin, BaseLibSVM): """Epsilon-Support Vector Regression. The free parameters in the model are C and epsilon. The implementation is based on libsvm. The fit time complexity is more than quadratic with the number of samples which makes it hard to scale to datasets with more than...
SVR
python
huggingface__transformers
src/transformers/data/datasets/squad.py
{ "start": 3750, "end": 3807 }
class ____(Enum): train = "train" dev = "dev"
Split
python
kamyu104__LeetCode-Solutions
Python/maximum-prime-difference.py
{ "start": 511, "end": 844 }
class ____(object): def maximumPrimeDifference(self, nums): """ :type nums: List[int] :rtype: int """ left = next(i for i in xrange(len(nums)) if SPF[nums[i]] == nums[i]) right = next(i for i in reversed(xrange(len(nums))) if SPF[nums[i]] == nums[i]) return ri...
Solution
python
mwaskom__seaborn
seaborn/_core/plot.py
{ "start": 33453, "end": 68574 }
class ____: """ Engine for compiling a :class:`Plot` spec into a Matplotlib figure. This class is not intended to be instantiated directly by users. """ # TODO decide if we ever want these (Plot.plot(debug=True))? _data: PlotData _layers: list[Layer] _figure: Figure def __init__(s...
Plotter
python
pennersr__django-allauth
allauth/socialaccount/providers/authentiq/provider.py
{ "start": 974, "end": 1187 }
class ____(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get("profile") def get_avatar_url(self): return self.account.extra_data.get("picture")
AuthentiqAccount
python
sympy__sympy
sympy/utilities/exceptions.py
{ "start": 113, "end": 10570 }
class ____(DeprecationWarning): r""" A warning for deprecated features of SymPy. See the :ref:`deprecation-policy` document for details on when and how things should be deprecated in SymPy. Note that simply constructing this class will not cause a warning to be issued. To do that, you must cal...
SymPyDeprecationWarning
python
pytorch__pytorch
torch/testing/_internal/distributed/multi_threaded_pg.py
{ "start": 2939, "end": 3429 }
class ____: @torch.no_grad() def work(self, data): world_size = len(data) for dest_rank in range(world_size): output_tensor_list, _ = data[dest_rank] for src_rank in range(world_size): _, input_tensor_list = data[src_rank] # See Note [Hide ...
AllToAll
python
kamyu104__LeetCode-Solutions
Python/smallest-divisible-digit-product-ii.py
{ "start": 84, "end": 2232 }
class ____(object): def smallestNumber(self, num, t): """ :type num: str :type t: int :rtype: str """ LOOKUP = [[(0, 0, 0, 0), (0, 1, 0, 0)], [(1, 0, 0, 0), (0, 0, 0, 1)], [(0, 0, 1, 0), (1, 0, 0, 1)]] def count(x): ...
Solution
python
getsentry__sentry
tests/sentry/integrations/vsts/test_integration.py
{ "start": 21968, "end": 31239 }
class ____(VstsIntegrationTestCase): def test_get_organization_config(self) -> None: self.assert_installation() integration, installation = self._get_integration_and_install() fields = installation.get_organization_config() assert [field["name"] for field in fields] == [ ...
VstsIntegrationTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/dml.py
{ "start": 6727, "end": 8118 }
class ____(SyntaxExtension, ClauseElement): stringify_dialect = "sqlite" inferred_target_elements: Optional[List[Union[str, schema.Column[Any]]]] inferred_target_whereclause: Optional[ Union[ColumnElement[Any], TextClause] ] _traverse_internals = [ ("inferred_target_elements", Inte...
OnConflictClause
python
sanic-org__sanic
sanic/models/protocol_types.py
{ "start": 421, "end": 562 }
class ____(Protocol): start: Optional[int] end: Optional[int] size: Optional[int] total: Optional[int] __slots__ = ()
Range
python
pytorch__pytorch
test/quantization/core/test_workflow_module.py
{ "start": 27066, "end": 28787 }
class ____(QuantizationTestCase): # TODO: move this to quantize.py def test_record_observer(self): for qengine in supported_qengines: with override_quantized_engine(qengine): model = AnnotatedSingleLayerLinearModel() model.qconfig = default_debug_qconfig ...
TestRecordHistogramObserver