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
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 77132, "end": 81059 }
class ____: @mock.patch("google.cloud.aiplatform.datasets.VideoDataset") @mock.patch(VERTEX_AI_PATH.format("auto_ml.AutoMLHook")) def test_execute(self, mock_hook, mock_dataset): mock_hook.return_value.create_auto_ml_video_training_job.return_value = (None, "training_id") with pytest.warns(A...
TestVertexAICreateAutoMLVideoTrainingJobOperator
python
ipython__ipython
docs/autogen_shortcuts.py
{ "start": 3064, "end": 6792 }
class ____: """Used as a buffer to get prompt_toolkit bindings""" handle_return = None input_transformer_manager = None display_completions = None editing_mode = "emacs" auto_suggest = None def bindings_from_prompt_toolkit(prompt_bindings: KeyBindingsBase) -> List[Binding]: """Collect bin...
_DummyTerminal
python
davidhalter__parso
test/fuzz_diff_parser.py
{ "start": 3323, "end": 7799 }
class ____: @classmethod def generate(cls, code_lines, change_count, previous_file_modification=None): if previous_file_modification is not None and random.random() > 0.5: # We want to keep the previous modifications in some cases to make # more complex parser issues visible. ...
FileModification
python
pallets__jinja
src/jinja2/visitor.py
{ "start": 1733, "end": 3550 }
class ____(NodeVisitor): """Walks the abstract syntax tree and allows modifications of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor functions to replace or remove the old node. If the return value of the visitor function is `None` the node will be removed ...
NodeTransformer
python
tiangolo__fastapi
fastapi/middleware/asyncexitstack.py
{ "start": 209, "end": 637 }
class ____: def __init__( self, app: ASGIApp, context_name: str = "fastapi_middleware_astack" ) -> None: self.app = app self.context_name = context_name async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: async with AsyncExitStack() as stack: ...
AsyncExitStackMiddleware
python
scrapy__scrapy
scrapy/downloadermiddlewares/ajaxcrawl.py
{ "start": 565, "end": 3805 }
class ____: """ Handle 'AJAX crawlable' pages marked as crawlable via meta tag. """ def __init__(self, settings: BaseSettings): if not settings.getbool("AJAXCRAWL_ENABLED"): raise NotConfigured warn( "scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware is...
AjaxCrawlMiddleware
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/optional2.py
{ "start": 200, "end": 569 }
class ____: def __eq__(self, other: "Optional[Cmp]") -> bool: ... def __lt__(self, other: "Optional[Cmp]") -> bool: ... def __gt__(self, other: "Cmp") -> bool: ... def valid(value: Optional[Cmp], needed: Cmp): x = value > needed y = value == needed # This should generate an error if reportO...
Cmp
python
langchain-ai__langchain
libs/partners/huggingface/langchain_huggingface/chat_models/huggingface.py
{ "start": 2400, "end": 10862 }
class ____: """Message to send to the TextGenInference API.""" role: str content: str tool_calls: list[dict] def _lc_tool_call_to_hf_tool_call(tool_call: ToolCall) -> dict: return { "type": "function", "id": tool_call["id"], "function": { "name": tool_call["nam...
TGI_MESSAGE
python
doocs__leetcode
solution/0700-0799/0784.Letter Case Permutation/Solution.py
{ "start": 0, "end": 393 }
class ____: def letterCasePermutation(self, s: str) -> List[str]: def dfs(i: int) -> None: if i >= len(t): ans.append("".join(t)) return dfs(i + 1) if t[i].isalpha(): t[i] = chr(ord(t[i]) ^ 32) dfs(i + 1) ...
Solution
python
getsentry__sentry
src/sentry/analytics/events/rule_reenable.py
{ "start": 67, "end": 275 }
class ____(analytics.Event, abc.ABC): """Re-enable a rule that was disabled""" rule_id: int user_id: int | None organization_id: int @analytics.eventclass("rule_reenable.explicit")
RuleReenable
python
has2k1__plotnine
plotnine/scales/scale_size.py
{ "start": 871, "end": 1197 }
class ____(scale_size_ordinal): """ Discrete area size scale """ _aesthetics = ["size"] def __post_init__(self, range): warn( "Using size for a discrete variable is not advised.", PlotnineWarning, ) super().__post_init__(range) @dataclass
scale_size_discrete
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/handle.py
{ "start": 3163, "end": 4063 }
class ____: job_name: str repository_handle: RepositoryHandle def to_string(self): return f"{self.location_name}.{self.repository_name}.{self.job_name}" @property def repository_name(self): return self.repository_handle.repository_name @property def location_name(self): ...
JobHandle
python
python__mypy
mypyc/test/test_refcount.py
{ "start": 819, "end": 2052 }
class ____(MypycDataSuite): files = files base_path = test_temp_dir optional_out = True def run_case(self, testcase: DataDrivenTestCase) -> None: """Perform a runtime checking transformation test case.""" options = infer_ir_build_options_from_test_name(testcase.name) if options ...
TestRefCountTransform
python
viewflow__viewflow
viewflow/workflow/nodes/switch.py
{ "start": 307, "end": 1082 }
class ____(Activation): """Switch gateway activation.""" next_task = None @Activation.status.super() def activate(self): with transaction.atomic(savepoint=True), self.exception_guard(): for node, cond in self.flow_task._branches: if cond: if cond...
SwitchActivation
python
boto__boto3
tests/unit/resources/test_collection.py
{ "start": 4687, "end": 22027 }
class ____(BaseTestCase): def setUp(self): super().setUp() # Minimal definition so things like repr work self.collection_def = { 'request': {'operation': 'TestOperation'}, 'resource': {'type': 'Frob'}, } self.client = mock.Mock() self.client.c...
TestResourceCollection
python
Delgan__loguru
loguru/_file_sink.py
{ "start": 2039, "end": 2487 }
class ____: @staticmethod def retention_count(logs, number): def key_log(log): return (-os.stat(log).st_mtime, log) for log in sorted(logs, key=key_log)[number:]: os.remove(log) @staticmethod def retention_age(logs, seconds): t = datetime.datetime.now()....
Retention
python
astropy__astropy
astropy/modeling/tests/test_fitters.py
{ "start": 5725, "end": 7545 }
class ____: """ Tests the joint fitting routine using 2 gaussian models """ def setup_class(self): """ Create 2 gaussian models and some data with noise. Create a fitter for the two models keeping the amplitude parameter common for the two models. """ sel...
TestJointFitter
python
wandb__wandb
wandb/vendor/pygments/formatters/img.py
{ "start": 18817, "end": 19131 }
class ____(ImageFormatter): """ Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code. .. versionadded:: 1.0 """ name = 'img_gif' aliases = ['gif'] filenames = ['*.gif'] default_image_format = 'gif'
GifImageFormatter
python
mozilla__bleach
bleach/_vendor/html5lib/treewalkers/genshi.py
{ "start": 313, "end": 2309 }
class ____(base.TreeWalker): def __iter__(self): # Buffer the events so we can pass in the following one previous = None for event in self.tree: if previous is not None: for token in self.tokens(previous, event): yield token previou...
TreeWalker
python
imageio__imageio
imageio/plugins/dicom.py
{ "start": 3672, "end": 12621 }
class ____(Format): """See :mod:`imageio.plugins.dicom`""" def _can_read(self, request): # If user URI was a directory, we check whether it has a DICOM file if os.path.isdir(request.filename): files = os.listdir(request.filename) for fname in sorted(files): # Sorting ma...
DicomFormat
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/uninitializedVariable2.py
{ "start": 506, "end": 572 }
class ____(Abstract1): def __init__(self): self.x = ""
D
python
walkccc__LeetCode
solutions/2363. Merge Similar Items/2363.py
{ "start": 0, "end": 236 }
class ____: def mergeSimilarItems(self, items1: list[list[int]], items2: list[list[int]]) -> list[list[int]]: return sorted( (Counter(dict(items1)) + collections.Counter(dict(items2))).items())
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 110768, "end": 115953 }
class ____(TypedDict, total=False): """ :class:`altair.IntervalSelectionConfig` ``TypedDict`` wrapper. Parameters ---------- type Determines the default event processing and data query for the selection. Vega-Lite currently supports two selection types: * ``"point"`` -- to ...
IntervalSelectionConfigKwds
python
pypa__warehouse
tests/unit/admin/views/test_users.py
{ "start": 23053, "end": 45623 }
class ____: def test_user_recover_account_initiate(self, db_request, db_session): user = UserFactory.create( totp_secret=b"aaaaabbbbbcccccddddd", webauthn=[ WebAuthn( label="fake", credential_id="fake", public_key="extremely fake" )...
TestUserRecoverAccountInitiate
python
pandas-dev__pandas
asv_bench/benchmarks/frame_ctor.py
{ "start": 1927, "end": 2310 }
class ____: params = [Nano(1), Hour(1)] param_names = ["offset"] def setup(self, offset): N = 10**3 idx = date_range(Timestamp("1/1/1900"), freq=offset, periods=N) df = DataFrame(np.random.randn(N, 10), index=idx) self.d = df.to_dict() def time_dict_with_timestamp_offse...
FromDictwithTimestamp
python
geekcomputers__Python
Checker_game_by_dz/modules/pieces.py
{ "start": 81, "end": 1272 }
class ____: padding = 17 outline = 2 def __init__(self, row, col, color): self.row = row self.col = col self.color = color self.king = False """if (self.color == yellow): self.direction = -1 else: self.direction = 1""" self.x...
pieces
python
ray-project__ray
python/ray/serve/tests/unit/test_common.py
{ "start": 2376, "end": 4903 }
class ____: def test_name_required(self): with pytest.raises(TypeError): DeploymentStatusInfo( status=DeploymentStatus.HEALTHY, status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, ) def test_deployment_status_required(self): with...
TestDeploymentStatusInfo
python
huggingface__transformers
src/transformers/models/modernbert_decoder/modular_modernbert_decoder.py
{ "start": 1802, "end": 12726 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ModernBertDecoderModel`]. It is used to instantiate a ModernBert decoder model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will ...
ModernBertDecoderConfig
python
davidhalter__parso
parso/python/tree.py
{ "start": 22214, "end": 22545 }
class ____(Flow): type = 'for_stmt' __slots__ = () def get_testlist(self): """ Returns the input node ``y`` from: ``for x in y:``. """ return self.children[3] def get_defined_names(self, include_setitem=False): return _defined_names(self.children[1], include_set...
ForStmt
python
tensorflow__tensorflow
tensorflow/lite/python/lite_flex_test.py
{ "start": 12151, "end": 13808 }
class ____(test_util.TensorFlowTestCase): @test_util.run_v2_only def testFlexResourceVariables(self): class Model(tf.Module): def __init__(self): self.v = tf.Variable([[0.0, 0.0, 0.0, 0.0]]) @tf.function( input_signature=[tf.TensorSpec(shape=[1, 4], dtype=tf.float32)]) de...
FromSavedModelTest
python
huggingface__transformers
src/transformers/models/maskformer/image_processing_maskformer_fast.py
{ "start": 3100, "end": 31629 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD size = {"shortest_edge": 800, "longest_edge": 1333} default_to_square = False do_resize = True do_rescale = True rescale_factor = 1 / 255 do_...
MaskFormerImageProcessorFast
python
scipy__scipy
scipy/stats/tests/test_contingency.py
{ "start": 1766, "end": 10937 }
class ____: def test_chi2_contingency_trivial(self): # Some very simple tests for chi2_contingency. # A trivial case obs = np.array([[1, 2], [1, 2]]) chi2, p, dof, expected = chi2_contingency(obs, correction=False) assert_equal(chi2, 0.0) assert_equal(p, 1.0) ...
TestChi2Contingency
python
tensorflow__tensorflow
tensorflow/python/training/evaluation_test.py
{ "start": 1990, "end": 9224 }
class ____(test.TestCase): def setUp(self): super(EvaluateOnceTest, self).setUp() # Create an easy training set: np.random.seed(0) self._inputs = np.zeros((16, 4)) self._labels = np.random.randint(0, 2, size=(16, 1)).astype(np.float32) for i in range(16): j = int(2 * self._labels[i] ...
EvaluateOnceTest
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 42537, "end": 48242 }
class ____(nn.Module): def __init__(self, config: MMGroundingDinoConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = MMGroundingDinoMultiscaleDeformableAttention( config, num_heads=config.encoder_attention_heads, n_points=config.encoder_n_points )...
MMGroundingDinoDeformableLayer
python
neetcode-gh__leetcode
python/0745-prefix-and-suffix-search.py
{ "start": 0, "end": 171 }
class ____: def __init__(self): self.children = {} # Dictionary to store child nodes self.word = -1 # Store the index of the word at this node
TrieNode
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 50292, "end": 53717 }
class ____(VariableTracker): def __init__(self, method_wrapper, **kwargs) -> None: super().__init__(**kwargs) self.method_wrapper = method_wrapper self._builtin_fns = {} def call_function( self, tx: "InstructionTranslator", args: "list[VariableTracker]", ...
MethodWrapperVariable
python
google__pytype
pytype/tests/test_operators3.py
{ "start": 672, "end": 892 }
class ____(test_base.BaseTest, test_utils.OperatorsTestMixin): """Tests for in-place operators.""" def test_div(self): self.check_inplace("itruediv", "/=") if __name__ == "__main__": test_base.main()
InplaceTest
python
coleifer__peewee
tests/models.py
{ "start": 154200, "end": 154326 }
class ____(TestModel): user = ForeignKeyField(TUser, backref='transactions') amount = FloatField(default=0.)
Transaction
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-cassandra/llama_index/tools/cassandra/base.py
{ "start": 345, "end": 3086 }
class ____(BaseToolSpec): """Base tool for interacting with an Apache Cassandra database.""" db: CassandraDatabase = Field(exclude=True) spec_functions = [ "cassandra_db_query", "cassandra_db_schema", "cassandra_db_select_table_data", ] def __init__(self, db: CassandraData...
CassandraDatabaseToolSpec
python
huggingface__transformers
src/transformers/models/gpt_neox/modeling_gpt_neox.py
{ "start": 31488, "end": 33720 }
class ____(GPTNeoXPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.gpt_neox = GPTNeoXModel(config) self.qa_outputs = nn.Linear(config.hidden_size, 2) # Initialize weights and apply final processing self.p...
GPTNeoXForQuestionAnswering
python
pyca__cryptography
src/cryptography/hazmat/primitives/asymmetric/dh.py
{ "start": 1258, "end": 2422 }
class ____(metaclass=abc.ABCMeta): @property @abc.abstractmethod def key_size(self) -> int: """ The bit length of the prime modulus. """ @abc.abstractmethod def parameters(self) -> DHParameters: """ The DHParameters object associated with this public key. ...
DHPublicKey
python
pytest-dev__pytest
src/_pytest/config/exceptions.py
{ "start": 175, "end": 315 }
class ____(Exception): """Raised when pytest should print its help to skip the rest of the argument parsing and validation."""
PrintHelp
python
huggingface__transformers
src/transformers/models/llama4/modeling_llama4.py
{ "start": 33564, "end": 36216 }
class ____(nn.Module): def __init__(self, config: Llama4VisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = config.hidden_size // config.num_attention_heads self.num_key...
Llama4VisionAttention
python
kamyu104__LeetCode-Solutions
Python/decode-the-slanted-ciphertext.py
{ "start": 29, "end": 864 }
class ____(object): def decodeCiphertext(self, encodedText, rows): """ :type encodedText: str :type rows: int :rtype: str """ cols = len(encodedText)//rows k = len(encodedText) for i in reversed(xrange(cols)): for j in reversed(xrange(i, le...
Solution
python
python__mypy
mypy/checker.py
{ "start": 405183, "end": 419521 }
class ____(Generic[TKey, TValue]): """An variation of the union-find algorithm/data structure where instead of keeping track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint. This da...
DisjointDict
python
PyCQA__pylint
tests/functional/i/invalid/invalid_str_returned.py
{ "start": 413, "end": 522 }
class ____(type): def __str__(cls): return "some str" @six.add_metaclass(StrMetaclass)
StrMetaclass
python
weaviate__weaviate-python-client
weaviate/connect/integrations.py
{ "start": 93, "end": 458 }
class ____(BaseModel): model_config = ConfigDict(strict=True) def _to_header(self) -> Dict[str, str]: # headers have to be strings return_dict = cast(dict, self.model_dump(by_alias=True, exclude_none=True)) for key, value in return_dict.items(): return_dict[key] = str(value)...
_IntegrationConfig
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 32187, "end": 32570 }
class ____(str, Enum): """The current status of the proxy.""" STARTING = "STARTING" HEALTHY = "HEALTHY" UNHEALTHY = "UNHEALTHY" DRAINING = "DRAINING" # The DRAINED status is a momentary state # just before the proxy is removed # so this status won't show up on the dashboard. DRAINED...
ProxyStatus
python
kamyu104__LeetCode-Solutions
Python/prime-arrangements.py
{ "start": 145, "end": 1073 }
class ____(object): def numPrimeArrangements(self, n): """ :type n: int :rtype: int """ def count_primes(n): if n <= 1: return 0 is_prime = [True]*((n+1)//2) cnt = len(is_prime) for i in xrange(3, n+1, 2): ...
Solution
python
pydata__xarray
asv_bench/benchmarks/dataset_io.py
{ "start": 11875, "end": 13998 }
class ____(IOMultipleNetCDF): def setup(self): # TODO: Lazily skipped in CI as it is very demanding and slow. # Improve times and remove errors. _skip_slow() requires_dask() self.make_ds() self.format = "NETCDF4" xr.save_mfdataset(self.ds_list, self.filename...
IOReadMultipleNetCDF4Dask
python
jazzband__django-oauth-toolkit
oauth2_provider/views/oidc.py
{ "start": 1248, "end": 4784 }
class ____(OIDCOnlyMixin, View): """ View used to show oidc provider configuration information per `OpenID Provider Metadata <https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata>`_ """ def get(self, request, *args, **kwargs): issuer_url = oauth2_settings.OIDC_ISS_END...
ConnectDiscoveryInfoView
python
h5py__h5py
h5py/_hl/dataset.py
{ "start": 9131, "end": 10210 }
class ____(AbstractView): """Wrapper to decode strings on reading the dataset""" def __init__(self, dset, encoding, errors='strict'): super().__init__(dset) self.encoding = encoding self.errors = errors @property def dtype(self): return numpy.dtype(object) def __get...
AsStrView
python
huggingface__transformers
src/transformers/models/phi3/modular_phi3.py
{ "start": 9187, "end": 10725 }
class ____(MistralForCausalLM): def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, position_ids=None, use_cache=True, logits_to_keep=None, **kwargs, ...
Phi3ForCausalLM
python
django__django
django/utils/deprecation.py
{ "start": 10242, "end": 12328 }
class ____: sync_capable = True async_capable = True def __init__(self, get_response): if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response # If get_response is a coroutine function, turns us into async mode so ...
MiddlewareMixin
python
lazyprogrammer__machine_learning_examples
rl3/ddpg.py
{ "start": 1902, "end": 10969 }
class ____: def __init__(self, obs_dim, act_dim, size): self.obs1_buf = np.zeros([size, obs_dim], dtype=np.float32) self.obs2_buf = np.zeros([size, obs_dim], dtype=np.float32) self.acts_buf = np.zeros([size, act_dim], dtype=np.float32) self.rews_buf = np.zeros(size, dtype=np.float32) self.done_buf...
ReplayBuffer
python
pandas-dev__pandas
pandas/core/internals/blocks.py
{ "start": 74017, "end": 80782 }
class ____(NDArrayBackedExtensionBlock): """Block for datetime64[ns], timedelta64[ns].""" __slots__ = () is_numeric = False values: DatetimeArray | TimedeltaArray # ----------------------------------------------------------------- # Constructor Helpers def maybe_coerce_values(values: ArrayLike) -> ...
DatetimeLikeBlock
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 2051, "end": 2278 }
class ____(TypedDict): """A message sent from the external process to the orchestration process.""" __dagster_pipes_version: str method: str params: Optional[Mapping[str, Any]] ###### PIPES CONTEXT
PipesMessage
python
Textualize__textual
src/textual/widgets/_switch.py
{ "start": 492, "end": 5904 }
class ____(Widget, can_focus=True): """A switch widget that represents a boolean value. Can be toggled by clicking on it or through its [bindings][textual.widgets.Switch.BINDINGS]. The switch widget also contains [component classes][textual.widgets.Switch.COMPONENT_CLASSES] that enable more customizat...
Switch
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-move-all-balls-to-each-box.py
{ "start": 29, "end": 473 }
class ____(object): def minOperations(self, boxes): """ :type boxes: str :rtype: List[int] """ result = [0]*len(boxes) for direction in (lambda x:x, reversed): cnt = accu = 0 for i in direction(xrange(len(boxes))): result[i] += ...
Solution
python
google__jax
tests/pmap_test.py
{ "start": 129348, "end": 129465 }
class ____(EagerPmapMixin, VmapOfPmapTest): pass @jtu.pytest_mark_if_available('multiaccelerator')
VmapOfPmapEagerTest
python
scrapy__scrapy
scrapy/core/downloader/handlers/http11.py
{ "start": 22587, "end": 27621 }
class ____(Protocol): def __init__( self, finished: Deferred[_ResultT], txresponse: TxResponse, request: Request, maxsize: int, warnsize: int, fail_on_dataloss: bool, crawler: Crawler, ): self._finished: Deferred[_ResultT] = finished ...
_ResponseReader
python
django__django
tests/test_utils/tests.py
{ "start": 85509, "end": 86757 }
class ____(SimpleTestCase): def setUp(self): self.addCleanup(setattr, self.__class__, "databases", self.databases) def test_no_close_match(self): self.__class__.databases = {"void"} message = ( "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is " ...
DatabaseAliasTests
python
pypa__warehouse
warehouse/captcha/__init__.py
{ "start": 81, "end": 517 }
class ____(ValueError): pass def includeme(config): # Register our Captcha service captcha_class = config.maybe_dotted(config.registry.settings["captcha.backend"]) config.register_service_factory( captcha_class.create_service, ICaptchaService, # Service requires a name for look...
CaptchaError
python
django__django
tests/admin_views/models.py
{ "start": 28572, "end": 29159 }
class ____(models.Model): NORTH_AMERICA = "North America" SOUTH_AMERICA = "South America" EUROPE = "Europe" ASIA = "Asia" OCEANIA = "Oceania" ANTARCTICA = "Antarctica" CONTINENT_CHOICES = [ (NORTH_AMERICA, NORTH_AMERICA), (SOUTH_AMERICA, SOUTH_AMERICA), (EUROPE, EURO...
Country
python
huggingface__transformers
tests/models/vilt/test_image_processing_vilt.py
{ "start": 4629, "end": 7494 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = ViltImageProcessor if is_vision_available() else None fast_image_processing_class = ViltImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester =...
ViltImageProcessingTest
python
django__django
tests/m2m_through/models.py
{ "start": 2222, "end": 2512 }
class ____(models.Model): first = models.ForeignKey( PersonSelfRefM2M, models.CASCADE, related_name="rel_from_set" ) second = models.ForeignKey( PersonSelfRefM2M, models.CASCADE, related_name="rel_to_set" ) date_friended = models.DateTimeField()
Friendship
python
explosion__spaCy
spacy/lang/tl/__init__.py
{ "start": 172, "end": 320 }
class ____(BaseDefaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS
TagalogDefaults
python
dask__distributed
distributed/diagnostics/plugin.py
{ "start": 27551, "end": 29273 }
class ____(logging.Handler): """ Handler class that gets installed inside workers by :class:`ForwardLoggingPlugin`. Not intended to be instantiated by the user directly. In each affected worker, ``ForwardLoggingPlugin`` adds an instance of this handler to one or more loggers (possibly the root ...
_ForwardingLogHandler
python
pyinstaller__pyinstaller
PyInstaller/depend/imphook.py
{ "start": 9732, "end": 26690 }
class ____: """ Cached object encapsulating a lazy loadable hook script. This object exposes public attributes (e.g., `datas`) of the underlying hook script as attributes of the same name of this object. On the first access of any such attribute, this hook script is lazily loaded into an in-memory ...
ModuleHook
python
getsentry__sentry
src/sentry/auth/access.py
{ "start": 1949, "end": 5848 }
class ____(abc.ABC): @property @abc.abstractmethod def sso_is_valid(self) -> bool: pass @property @abc.abstractmethod def requires_sso(self) -> bool: pass @property @abc.abstractmethod def has_open_membership(self) -> bool: pass @property @abc.abstr...
Access
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called_py38.py
{ "start": 295, "end": 411 }
class ____(MyProtocol): """An implementation.""" def __init__(self) -> None: ...
ProtocolImplimentation
python
scrapy__scrapy
tests/test_loader.py
{ "start": 698, "end": 798 }
class ____: name: list = dataclasses.field(default_factory=list) # test item loaders
NameDataClass
python
huggingface__transformers
tests/quantization/eetq_integration/test_eetq.py
{ "start": 1158, "end": 2253 }
class ____(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = EetqConfig() config_to_dict = quantization_config.to_dict() for key ...
EetqConfigTest
python
anthropics__anthropic-sdk-python
src/anthropic/lib/bedrock/_client.py
{ "start": 4495, "end": 10172 }
class ____(BaseBedrockClient[httpx.Client, Stream[Any]], SyncAPIClient): messages: Messages completions: Completions beta: Beta def __init__( self, aws_secret_key: str | None = None, aws_access_key: str | None = None, aws_region: str | None = None, aws_profile: s...
AnthropicBedrock
python
arrow-py__arrow
tests/test_locales.py
{ "start": 105119, "end": 106742 }
class ____: def test_format_timeframe(self): assert self.locale._format_timeframe("now", 0) == "ابھی" assert self.locale._format_timeframe("second", -1) == "ایک سیکنڈ" assert self.locale._format_timeframe("second", 1) == "ایک سیکنڈ" assert self.locale._format_timeframe("seconds", -3)...
TestUrduLocale
python
numba__numba
numba/testing/main.py
{ "start": 3654, "end": 4356 }
class ____(object): """Simply list available tests rather than running them.""" def __init__(self, useslice): self.useslice = parse_slice(useslice) def run(self, test): result = runner.TextTestResult(sys.stderr, descriptions=True, verbosity=1) ...
TestLister
python
kamyu104__LeetCode-Solutions
Python/depth-of-bst-given-insertion-order.py
{ "start": 59, "end": 510 }
class ____(object): def maxDepthBST(self, order): """ :type order: List[int] :rtype: int """ depths = sortedcontainers.SortedDict({float("-inf"):0, float("inf"):0}) values_view = depths.values() result = 0 for x in order: i = depths.bisect_...
Solution
python
astropy__astropy
astropy/modeling/fitting.py
{ "start": 2560, "end": 4247 }
class ____: """Class for covariance matrix calculated by fitter.""" def __init__(self, cov_matrix, param_names): self.cov_matrix = cov_matrix self.param_names = param_names def pprint(self, max_lines, round_val): # Print and label lower triangle of covariance matrix # Print...
Covariance
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_shape_base_.py
{ "start": 19576, "end": 20296 }
class ____(TestCase): """Only testing for integer splits.""" def test_non_iterable(self): assert_raises(ValueError, hsplit, 1, 1) def test_0D_array(self): a = np.array(1) try: hsplit(a, 2) assert_(0) except ValueError: pass def test_...
TestHsplit
python
huggingface__transformers
src/transformers/models/dpr/modeling_dpr.py
{ "start": 8536, "end": 8989 }
class ____(DPRPreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config: DPRConfig base_model_prefix = "span_predictor" ############### # Actual Models ############### @auto_docstring( custom...
DPRPretrainedReader
python
PrefectHQ__prefect
tests/server/api/test_server.py
{ "start": 9844, "end": 14823 }
class ____: @pytest.fixture(autouse=True) def enable_memoization(self, tmp_path): with temporary_settings( { PREFECT_MEMOIZE_BLOCK_AUTO_REGISTRATION: True, PREFECT_MEMO_STORE_PATH: tmp_path / "memo_store.toml", } ): yield @...
TestMemoizeBlockAutoRegistration
python
sympy__sympy
sympy/matrices/expressions/factorizations.py
{ "start": 475, "end": 507 }
class ____(UofLU): pass
UofCholesky
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_quotes/docstring_singles_mixed_quotes_class_var_2.py
{ "start": 0, "end": 357 }
class ____(): 'Do not'" start with empty string" ' and lint docstring safely' ''' Not a docstring ''' def foo(self, bar='''not a docstring'''): 'Do not'" start with empty string" ' and lint docstring safely' pass class Nested(foo()[:]): 'Do not'" start with empty string" ' and lint doc...
SingleLineDocstrings
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/secrets/test_secrets_manager.py
{ "start": 978, "end": 10466 }
class ____: @mock.patch("airflow.providers.amazon.aws.secrets.secrets_manager.SecretsManagerBackend.get_conn_value") def test_aws_secrets_manager_get_connection(self, mock_get_value): mock_get_value.return_value = "scheme://user:pass@host:100" conn = SecretsManagerBackend().get_connection("fake_...
TestSecretsManagerBackend
python
networkx__networkx
networkx/classes/coreviews.py
{ "start": 506, "end": 1531 }
class ____(Mapping): """An AtlasView is a Read-only Mapping of Mappings. It is a View into a dict-of-dict data structure. The inner level of dict is read-write. But the outer level is read-only. See Also ======== AdjacencyView: View into dict-of-dict-of-dict MultiAdjacencyView: View in...
AtlasView
python
google__pytype
pytype/tests/test_utils.py
{ "start": 8037, "end": 8274 }
class ____: """Match a regex.""" def __init__(self, regex): self.regex = regex def match(self, message): return re.search(self.regex, message, flags=re.DOTALL) def __repr__(self): return repr(self.regex)
RegexMatcher
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 13966, "end": 14290 }
class ____(ArffException): '''Error raised when the layout of the ARFF file has something wrong.''' message = 'Invalid layout of the ARFF file, at line %d.' def __init__(self, msg=''): super().__init__() if msg: self.message = BadLayout.message + ' ' + msg.replace('%', '%%')
BadLayout
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 3805, "end": 3947 }
class ____(Status): id: str arguments: str name: str server_label: str type: str = "mcp_approval_request"
McpApprovalRequest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
{ "start": 27419, "end": 29991 }
class ____: def setup_method(self) -> None: self.cluster_name: str = CLUSTER_NAME self.fargate_profile_name: str = FARGATE_PROFILE_NAME self.delete_fargate_profile_operator = EksDeleteFargateProfileOperator( task_id=TASK_ID, cluster_name=self.cluster_name, fargate_profile_name=s...
TestEksDeleteFargateProfileOperator
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 11988, "end": 12423 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "InvalidSubsetError" pipeline = graphene.Field( graphene.NonNull("dagster_graphql.schema.pipelines.pipeline.GraphenePipeline") ) def __init__(self, message, pipeline): super().__init__() ...
GrapheneInvalidSubsetError
python
google__pytype
pytype/pyi/parser.py
{ "start": 10090, "end": 28981 }
class ____(visitor.BaseVisitor): """Converts an ast tree to a pytd tree.""" _NOOP_NODES = { # Expression contexts are ignored. astlib.Load, astlib.Store, astlib.Del, # Appears as an operator in `__all__ += ...`. astlib.Add, # These nodes are passed through unchanged and pr...
_GeneratePytdVisitor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/bigquery.py
{ "start": 92695, "end": 94020 }
class ____(GoogleBaseAsyncHook): """Async hook for BigQuery Table.""" sync_hook_class = BigQueryHook def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ): super().__init__( ...
BigQueryTableAsyncHook
python
getsentry__sentry
src/sentry/issue_detection/detectors/query_injection_detector.py
{ "start": 645, "end": 5721 }
class ____(PerformanceDetector): __slots__ = "stored_problems" type = DetectorType.QUERY_INJECTION settings_key = DetectorType.QUERY_INJECTION def __init__(self, settings: dict[DetectorType, Any], event: dict[str, Any]) -> None: super().__init__(settings, event) self.stored_problems =...
QueryInjectionDetector
python
getsentry__sentry
src/sentry/seer/breakpoints.py
{ "start": 1185, "end": 1453 }
class ____(TypedDict): data: "Mapping[str, BreakpointTransaction]" sort: NotRequired[str] allow_midpoint: NotRequired[str] validate_tail_hours: NotRequired[int] trend_percentage: NotRequired[float] min_change: NotRequired[float]
BreakpointRequest
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 13832, "end": 14716 }
class ____(BiffRecord): """ This record stores two Windows country identifiers. The first represents the user interface language of the Excel version that has saved the file, and the second represents the system regional settings at the time the file was saved. Record COUNTRY, BIF...
CountryRecord
python
pandas-dev__pandas
asv_bench/benchmarks/frame_ctor.py
{ "start": 1708, "end": 1927 }
class ____: def setup(self): mi = MultiIndex.from_product([range(100), range(100)]) self.s = Series(np.random.randn(10000), index=mi) def time_mi_series(self): DataFrame(self.s)
FromSeries
python
sqlalchemy__sqlalchemy
examples/generic_associations/table_per_related.py
{ "start": 1844, "end": 2427 }
class ____: """HasAddresses mixin, creates a new Address class for each parent. """ @declared_attr def addresses(cls): cls.Address = type( f"{cls.__name__}Address", (Address, Base), dict( __tablename__=f"{cls.__tablename__}_address", ...
HasAddresses
python
PyCQA__pylint
tests/functional/i/invalid/invalid_str_returned.py
{ "start": 1002, "end": 1097 }
class ____: """ Uninferable return value """ __str__ = lambda self: Missing
AmbiguousStr
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/cfg.py
{ "start": 21836, "end": 32351 }
class ____(gast.NodeVisitor): """Converts an AST to CFGs. A separate CFG will be constructed for each function. """ def __init__(self): super(AstToCfg, self).__init__() self.builder_stack = [] self.builder = None self.cfgs = {} self.lexical_scopes = [] def _enter_lexical_scope(self, n...
AstToCfg
python
dagster-io__dagster
integration_tests/python_modules/dagster-k8s-test-infra/dagster_k8s_test_infra/cluster.py
{ "start": 1173, "end": 9733 }
class ____(namedtuple("_ClusterConfig", "name kubeconfig_file")): """Used to represent a cluster, returned by the cluster_provider fixture below.""" def __new__(cls, name, kubeconfig_file): return super().__new__( cls, name=check.str_param(name, "name"), kubeconfig_f...
ClusterConfig