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
streamlit__streamlit
lib/tests/streamlit/runtime/runtime_util_test.py
{ "start": 984, "end": 2163 }
class ____(unittest.TestCase): def test_should_limit_msg_size(self): max_message_size_mb = 50 runtime_util._max_message_size_bytes = None # Reset cached value with patch_config_options({"server.maxMessageSize": max_message_size_mb}): # Set up a larger than limit ForwardMsg stri...
RuntimeUtilTest
python
docker__docker-py
tests/unit/dockertypes_test.py
{ "start": 12722, "end": 14370 }
class ____(unittest.TestCase): def test_replicated_simple(self): mode = ServiceMode('replicated') assert mode == {'replicated': {}} assert mode.mode == 'replicated' assert mode.replicas is None def test_global_simple(self): mode = ServiceMode('global') assert mod...
ServiceModeTest
python
numba__numba
numba/tests/test_listobject.py
{ "start": 26128, "end": 26884 }
class ____(MemoryLeakMixin, TestCase): """Test list extend. """ def test_list_extend_empty(self): @njit def foo(items): l = listobject.new_list(int32) l.extend(items) return len(l) self.assertEqual(foo((1,)), 1) self.assertEqual(foo((1,2)), 2...
TestExtend
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 2272, "end": 2748 }
class ____(BaseModel): model_config = ConfigDict(extra="allow") type: str @model_validator(mode="after") def check_type(self) -> "Content": if self.type == "output_text": ResponseOutputText(**self.model_dump()) elif self.type == "refusal": ResponseOutputRefusal(*...
Content
python
walkccc__LeetCode
solutions/2194. Cells in a Range on an Excel Sheet/2194.py
{ "start": 0, "end": 281 }
class ____: def cellsInRange(self, s: str) -> list[str]: ans = [] startCol, startRow, _, endCol, endRow = s for j in range(ord(startCol), ord(endCol) + 1): for i in range(int(startRow), int(endRow) + 1): ans.append(chr(j) + str(i)) return ans
Solution
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-clip/llama_index/embeddings/clip/base.py
{ "start": 452, "end": 4282 }
class ____(MultiModalEmbedding): """ CLIP embedding models for encoding text and image for Multi-Modal purpose. This class provides an interface to generate embeddings using a model deployed in OpenAI CLIP. At the initialization it requires a model name of CLIP. Note: Requires `clip` p...
ClipEmbedding
python
Pylons__pyramid
docs/tutorials/wiki2/src/authorization/tutorial/security.py
{ "start": 260, "end": 1898 }
class ____: def __init__(self, secret): self.authtkt = AuthTktCookieHelper(secret) self.identity_cache = RequestLocalCache(self.load_identity) self.acl = ACLHelper() def load_identity(self, request): identity = self.authtkt.identify(request) if identity is None: ...
MySecurityPolicy
python
urllib3__urllib3
test/with_dummyserver/test_socketlevel.py
{ "start": 68575, "end": 69292 }
class ____(SocketDummyServerTestCase): def test_bad_statusline(self) -> None: self.start_response_handler( b"HTTP/1.1 Omg What Is This?\r\n" b"Content-Length: 0\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: with pytest.raises(Pro...
TestErrorWrapping
python
doocs__leetcode
solution/0700-0799/0798.Smallest Rotation with Highest Score/Solution.py
{ "start": 0, "end": 423 }
class ____: def bestRotation(self, nums: List[int]) -> int: n = len(nums) mx, ans = -1, n d = [0] * n for i, v in enumerate(nums): l, r = (i + 1) % n, (n + i + 1 - v) % n d[l] += 1 d[r] -= 1 s = 0 for k, t in enumerate(d): ...
Solution
python
huggingface__transformers
src/transformers/models/deberta_v2/tokenization_deberta_v2.py
{ "start": 1144, "end": 7081 }
class ____(TokenizersBackend): """ Construct a DeBERTa-v2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on Unigram tokenization. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to this superclass for more information regar...
DebertaV2Tokenizer
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 17725, "end": 22634 }
class ____(TorchDistributionWrapper): """Action distribution that operates on multiple, possibly nested actions.""" def __init__(self, inputs, model, *, child_distributions, input_lens, action_space): """Initializes a TorchMultiActionDistribution object. Args: inputs (torch.Tensor)...
TorchMultiActionDistribution
python
pytorch__pytorch
torch/ao/quantization/fake_quantize.py
{ "start": 14231, "end": 23563 }
class ____(FakeQuantize): r"""Define a fused module to observe the tensor. Fused module that is used to observe the input tensor (compute min/max), compute scale/zero_point and fake_quantize the tensor. This module uses calculation similar MovingAverageMinMaxObserver for the inputs, to compute the ...
FusedMovingAvgObsFakeQuantize
python
PyCQA__pylint
doc/data/messages/i/invalid-class-object/good.py
{ "start": 24, "end": 86 }
class ____: pass Apple.__class__ = RedDelicious
RedDelicious
python
coleifer__peewee
tests/sqlite.py
{ "start": 3226, "end": 3397 }
class ____(FTS5Model): title = SearchField() data = SearchField() misc = SearchField(unindexed=True) class Meta: legacy_table_names = False
FTS5Test
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/errors.py
{ "start": 4127, "end": 4278 }
class ____(OAuth2Error): error = 'mismatching_state' description = 'CSRF Warning! State not equal in request and response.'
MismatchingStateError
python
ray-project__ray
doc/source/serve/doc_code/application_level_autoscaling.py
{ "start": 501, "end": 964 }
class ____: def __init__(self, preprocessor, model): self._preprocessor = preprocessor self._model = model async def __call__(self, input_data: str) -> str: # Coordinate preprocessing and model inference preprocessed = await self._preprocessor.remote(input_data) result =...
Driver
python
ray-project__ray
python/ray/tests/test_unavailable_actors.py
{ "start": 336, "end": 6363 }
class ____: def __init__( self, *, caller_pid: Optional[int] = None, init_signal: Optional[ray.actor.ActorHandle] = None, ): if init_signal is not None: ray.get(init_signal.wait.remote()) self._count = 0 self._caller_pid = caller_pid def ...
Counter
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 22950, "end": 23661 }
class ____(PipesBlobStoreMessageWriterChannel): """Message writer channel that periodically writes message chunks to an endpoint mounted on the filesystem. Args: interval (float): interval in seconds between chunk uploads """ def __init__(self, path: str, *, interval: float = 10): supe...
PipesBufferedFilesystemMessageWriterChannel
python
scipy__scipy
scipy/linalg/tests/test_decomp.py
{ "start": 78541, "end": 84082 }
class ____: def check_schur(self, a, t, u, rtol, atol): # Check that the Schur decomposition is correct. assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol, err_msg="Schur decomposition does not match 'a'") # The expected value of u @ u.H - I is all zeros, s...
TestSchur
python
joblib__joblib
joblib/backports.py
{ "start": 1280, "end": 5450 }
class ____(Version): """Backport from deprecated distutils We maintain this backport to avoid introducing a new dependency on `packaging`. We might rexplore this choice in the future if all major Python projects introduce a dependency on packaging anyway. """ component_re = re.compile(r"(...
LooseVersion
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 314, "end": 429 }
class ____(Abcd): """dummy""" def abcd(self): # [method-hidden] """test""" print(self)
Cdef
python
numpy__numpy
numpy/_core/tests/test_scalar_ctors.py
{ "start": 162, "end": 1317 }
class ____: def test_floating(self): # Ticket #640, floats from string fsingle = np.single('1.234') fdouble = np.double('1.234') flongdouble = np.longdouble('1.234') assert_almost_equal(fsingle, 1.234) assert_almost_equal(fdouble, 1.234) assert_almost_equal(fl...
TestFromString
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_delete_pending_with_fk_constraints_app/migrations/0001_initial.py
{ "start": 180, "end": 1303 }
class ____(CheckedMigration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="FkTable", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, ser...
Migration
python
dagster-io__dagster
python_modules/libraries/dagster-mysql/dagster_mysql/utils.py
{ "start": 869, "end": 5876 }
class ____(Exception): pass def get_conn(conn_string: str) -> MySQLConnectionUnion: parsed = urlparse(conn_string) conn = cast( "MySQLConnectionUnion", mysql.connect( user=parsed.username, passwd=parsed.password, host=parsed.hostname, databas...
DagsterMySQLException
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/pod.py
{ "start": 4181, "end": 4305 }
class ____(AirflowException): """When during reconnect more than one matching pod was found."""
FoundMoreThanOnePodFailure
python
numba__numba
numba/cuda/vector_types.py
{ "start": 830, "end": 6750 }
class ____(types.Type): def __init__(self, name, base_type, attr_names, user_facing_object): self._base_type = base_type self._attr_names = attr_names self._user_facing_object = user_facing_object super().__init__(name=name) @property def base_type(self): return self...
VectorType
python
prabhupant__python-ds
data_structures/binary_trees/sum_of_all_left_leaves.py
{ "start": 53, "end": 825 }
class ____: def __init__(self, val): self.val = val self.left = None self.right = None def is_leaf(root): if root is None: return False if root.left is None and root.right is None: return True return False def sum_left(root): s = 0 stack = [] whi...
Node
python
numba__numba
numba/cuda/tests/cudapy/test_blackscholes.py
{ "start": 1127, "end": 4023 }
class ____(CUDATestCase): def test_blackscholes(self): OPT_N = 400 iterations = 2 stockPrice = randfloat(np.random.random(OPT_N), 5.0, 30.0) optionStrike = randfloat(np.random.random(OPT_N), 1.0, 100.0) optionYears = randfloat(np.random.random(OPT_N), 0.25, 10.0) ca...
TestBlackScholes
python
getsentry__sentry
src/sentry/middleware/customer_domain.py
{ "start": 2528, "end": 4371 }
class ____: """ Set active organization from request.domain. """ def __init__(self, get_response: Callable[[HttpRequest], HttpResponseBase]) -> None: self.get_response = get_response def __call__(self, request: HttpRequest) -> HttpResponseBase: if ( request.method != "G...
CustomerDomainMiddleware
python
huggingface__transformers
src/transformers/models/llava_onevision/configuration_llava_onevision.py
{ "start": 802, "end": 8061 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`LlavaOnevisionForConditionalGeneration`]. It is used to instantiate an Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defau...
LlavaOnevisionConfig
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 165491, "end": 171629 }
class ____(Request): """ Get plot events for the requested amount of iterations per each task :param metrics: List of metrics and variants :type metrics: Sequence[TaskMetricVariants] :param iters: Max number of latest iterations for which to return plots :type iters: int :param navigate_ear...
PlotsRequest
python
facebook__pyre-check
client/log/log.py
{ "start": 1501, "end": 1542 }
class ____: LAMBDA: str = "ƛ"
Character
python
tensorflow__tensorflow
tensorflow/lite/python/util_test.py
{ "start": 12959, "end": 16289 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @classmethod def setUpClass(cls): super(UtilModifyIntegerQuantizedModelIOTypeTest, cls).setUpClass() cls.post_train_int8_model = _generate_integer_tflite_model() cls.post_train_int16_model ...
UtilModifyIntegerQuantizedModelIOTypeTest
python
getsentry__sentry
src/sentry/templatetags/sentry_features.py
{ "start": 695, "end": 1345 }
class ____(template.Node): def __init__(self, nodelist_true, nodelist_false, name, params): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false self.name = name self.params = [template.Variable(i) for i in params] def render(self, context): params = [...
FeatureNode
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/api/secret.py
{ "start": 441, "end": 2270 }
class ____: """Secret API operations.""" client: IGraphQLClient def list_secrets( self, location_name: Optional[str] = None, scope: Optional[str] = None, limit: Optional[int] = None, ) -> "DgApiSecretList": """List secrets with optional filtering. Args:...
DgApiSecretApi
python
openai__openai-python
src/openai/types/conversations/conversation_item.py
{ "start": 4908, "end": 5345 }
class ____(BaseModel): id: str """The unique ID of the approval response""" approval_request_id: str """The ID of the approval request being answered.""" approve: bool """Whether the request was approved.""" type: Literal["mcp_approval_response"] """The type of the item. Always `mcp_a...
McpApprovalResponse
python
pytest-dev__pytest
testing/test_terminal.py
{ "start": 49737, "end": 67825 }
class ____: """Test class which can be subclassed with a different option provider to run e.g. distributed tests.""" def test_collect_fail(self, pytester: Pytester, option) -> None: pytester.makepyfile("import xyz\n") result = pytester.runpytest(*option.args) result.stdout.fnmatch_l...
TestGenericReporting
python
ray-project__ray
python/ray/runtime_context.py
{ "start": 450, "end": 19883 }
class ____(object): """A class used for getting runtime context.""" def __init__(self, worker): assert worker is not None self.worker = worker @Deprecated( message="Use get_xxx_id() methods to get relevant ids instead", warning=True ) def get(self) -> Dict[str, Any]: ...
RuntimeContext
python
Textualize__textual
src/textual/messages.py
{ "start": 2748, "end": 3834 }
class ____(Message): """Reports if the in-band window resize protocol is supported. https://gist.github.com/rockorager/e695fb2924d36b2bcf1fff4a3704bd83""" def __init__(self, supported: bool, enabled: bool) -> None: """Initialize message. Args: supported: Is the protocol suppor...
InBandWindowResize
python
tensorflow__tensorflow
tensorflow/python/ops/math_grad_test.py
{ "start": 25993, "end": 26620 }
class ____(test.TestCase): def test_zero_grad_tf_gradients(self): if context.executing_eagerly(): self.skipTest("tf.gradients not supported in eager.") x = constant_op.constant([-1., 0., 1.]) g = self.evaluate(gradients.gradients(math_ops.pow(x, 2), x)[0]) self.assertAllClose([-2., 0., 2.], g)...
PowGradTest
python
huggingface__transformers
src/transformers/models/chinese_clip/modeling_chinese_clip.py
{ "start": 7040, "end": 11854 }
class ____(nn.Module): def __init__(self, config: ChineseCLIPVisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.class_embedding = nn.Parameter(torch.r...
ChineseCLIPVisionEmbeddings
python
pytorch__pytorch
test/test_overrides.py
{ "start": 50183, "end": 50790 }
class ____(TestCase): # Regression test for gh-64687 def test_parameter_does_not_prevent_dispatch(self): class MyTensor: @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): return "called" t1 = MyTensor() t2 = torch.nn.Par...
TestDisabledTorchFunction
python
huggingface__transformers
tests/models/vivit/test_modeling_vivit.py
{ "start": 1514, "end": 5736 }
class ____: def __init__( self, parent, batch_size=2, is_training=True, use_labels=True, num_labels=10, image_size=10, num_frames=8, # decreased, because default 32 takes too much RAM at inference tubelet_size=[2, 4, 4], num_channels=3...
VivitModelTester
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 31396, "end": 32058 }
class ____(BaseLinksSerializer): _self = serializers.SerializerMethodField() project = serializers.SerializerMethodField() def get__self(self, obj): path = reverse( "projects-redirects-detail", kwargs={ "parent_lookup_project__slug": obj.project.slug, ...
RedirectLinksSerializer
python
mozilla__bleach
bleach/_vendor/html5lib/treebuilders/base.py
{ "start": 4821, "end": 14565 }
class ____(object): """Base treebuilder implementation * documentClass - the class to use for the bottommost node of a document * elementClass - the class to use for HTML Elements * commentClass - the class to use for comments * doctypeClass - the class to use for doctypes """ # pylint:dis...
TreeBuilder
python
getsentry__sentry
tests/sentry/notifications/notifications/organization_request/test_integration_request.py
{ "start": 233, "end": 2452 }
class ____(TestCase): def test_get_context(self) -> None: owner = self.create_user("owner@example.com") org = self.create_organization(owner=owner) requester = self.create_user() self.create_member(user=requester, organization=org) message = "hello" notification = In...
TestIntegrationRequestNotification
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_dialect.py
{ "start": 4532, "end": 8672 }
class ____(fixtures.TestBase): __backend__ = True __requires__ = ("isolation_level",) def _get_non_default_isolation_level(self): levels = requirements.get_isolation_levels(config) default = levels["default"] supported = levels["supported"] s = set(supported).difference([...
IsolationLevelTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_decorators_2.py
{ "start": 246, "end": 289 }
class ____: x: pandas.DataFrame @frozen
B
python
pytorch__pytorch
torch/_dynamo/variables/user_defined.py
{ "start": 37007, "end": 37685 }
class ____: pass def call_random_fn(tx, fn, args, kwargs): from .builder import VariableBuilder args = [x.as_python_constant() for x in args] kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} random_call_index = len(tx.output.random_calls) example_value = fn(*args, **kwargs) ...
NO_SUCH_SUBOBJ
python
walkccc__LeetCode
solutions/3412. Find Mirror Score of a String/3412.py
{ "start": 0, "end": 347 }
class ____: def calculateScore(self, s: str) -> int: ans = 0 indices = [[] for _ in range(26)] for i, c in enumerate(s): index = ord(c) - ord('a') oppositeIndex = 25 - index if indices[oppositeIndex]: ans += i - indices[oppositeIndex].pop() else: indices[index].app...
Solution
python
huggingface__transformers
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
{ "start": 47495, "end": 50356 }
class ____(XLMRobertaPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout...
XLMRobertaForTokenClassification
python
urllib3__urllib3
src/urllib3/poolmanager.py
{ "start": 18453, "end": 23811 }
class ____(PoolManager): """ Behaves just like :class:`PoolManager`, but sends all requests through the defined proxy, using the CONNECT method for HTTPS URLs. :param proxy_url: The URL of the proxy to be used. :param proxy_headers: A dictionary containing headers that will be sent...
ProxyManager
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_freezing_weights.py
{ "start": 3324, "end": 3426 }
class ____(str, Enum): GradToNone = "grad_to_none" RequiresGrad = "requires_grad"
FreezingMethod
python
rq__rq
tests/test_worker.py
{ "start": 62437, "end": 63838 }
class ____(RQTestCase): def setUp(self): super().setUp() db_num = self.connection.connection_pool.connection_kwargs['db'] self.redis_url = 'redis://127.0.0.1:6379/%d' % db_num def test_run_empty_queue(self): """Run the worker in its own process with an empty queue""" sub...
TestWorkerSubprocess
python
doocs__leetcode
solution/2300-2399/2370.Longest Ideal Subsequence/Solution.py
{ "start": 0, "end": 441 }
class ____: def longestIdealString(self, s: str, k: int) -> int: n = len(s) ans = 1 dp = [1] * n d = {s[0]: 0} for i in range(1, n): a = ord(s[i]) for b in ascii_lowercase: if abs(a - ord(b)) > k: continue ...
Solution
python
django__django
django/core/exceptions.py
{ "start": 1184, "end": 1361 }
class ____(SuspiciousOperation): """ The number of fields in a GET or POST request exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. """ pass
TooManyFieldsSent
python
Textualize__textual
docs/examples/guide/workers/weather01.py
{ "start": 174, "end": 1262 }
class ____(App): """App to display the current weather.""" CSS_PATH = "weather.tcss" def compose(self) -> ComposeResult: yield Input(placeholder="Enter a City") with VerticalScroll(id="weather-container"): yield Static(id="weather") async def on_input_changed(self, message...
WeatherApp
python
django__django
tests/postgres_tests/__init__.py
{ "start": 1391, "end": 1470 }
class ____(WidgetTest, PostgreSQLSimpleTestCase): pass
PostgreSQLWidgetTestCase
python
huggingface__transformers
src/transformers/models/t5gemma/configuration_t5gemma.py
{ "start": 1336, "end": 10208 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`T5GemmaModuleModel`]. It is used to instantiate an T5GemmaModule model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a ...
T5GemmaModuleConfig
python
django__django
tests/model_fields/test_durationfield.py
{ "start": 2704, "end": 2945 }
class ____(SimpleTestCase): # Tests for forms.DurationField are in the forms_tests app. def test_formfield(self): field = models.DurationField() self.assertIsInstance(field.formfield(), forms.DurationField)
TestFormField
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator.py
{ "start": 3336, "end": 34550 }
class ____(object): """The worker context class. This context object provides configuration information for each task. One context manager with a worker context object will be created per invocation to the `worker_fn` where `get_current_worker_context` can be called to access the worker context object. """...
_WorkerContext
python
conda__conda
tests/shell/__init__.py
{ "start": 1493, "end": 2772 }
class ____: name: str | tuple[str, ...] # shell name path: str | None = None # $PATH style path to search for shell exe: str | None = None # shell executable path def __post_init__(self) -> None: if isinstance(self.name, str): pass elif isinstance(self.name, tuple) and al...
Shell
python
getsentry__sentry
tests/sentry/backup/test_imports.py
{ "start": 43388, "end": 49090 }
class ____(ImportTestCase): """ Ensures that decryption actually works. We only test one model for each scope, because it's extremely unlikely that a failed decryption will leave only part of the data unmangled. """ @staticmethod def encrypt_json_fixture(tmp_dir) -> tuple[Path, Path]: g...
DecryptionTests
python
spyder-ide__spyder
spyder/plugins/editor/extensions/manager.py
{ "start": 851, "end": 3186 }
class ____(Manager): """Manages the list of editor extensions of the CodeEdit widget.""" def __init__(self, editor): """Initialize and add a reference to the editor.""" super().__init__(editor) self._extensions = {} def add(self, extension): """ Add a extension to t...
EditorExtensionsManager
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 20943, "end": 21418 }
class ____(torch.nn.ModuleDict): def __init__( self, num_layers: int = 3, ) -> None: super().__init__() for i in range(num_layers): self.add_module(f"denselayer{i + 1:d}", _Block()) def forward(self, init_features): features = [init_features] for ...
EnumValues
python
getsentry__sentry
src/sentry/services/eventstore/models.py
{ "start": 28707, "end": 28797 }
class ____(string.Template): idpattern = r"(tag:)?[_a-z][_a-z0-9]*"
EventSubjectTemplate
python
keras-team__keras
integration_tests/dataset_tests/boston_housing_test.py
{ "start": 78, "end": 887 }
class ____(testing.TestCase): def test_load_data(self): (x_train, y_train), (x_test, y_test) = boston_housing.load_data() self.assertEqual(x_train.shape[1], 13) self.assertEqual(x_train.shape[0] + x_test.shape[0], 506) def test_seed_reproducibility(self): seed = 123 firs...
BostonHousingTest
python
doocs__leetcode
solution/3000-3099/3077.Maximum Strength of K Disjoint Subarrays/Solution.py
{ "start": 0, "end": 657 }
class ____: def maximumStrength(self, nums: List[int], k: int) -> int: n = len(nums) f = [[[-inf, -inf] for _ in range(k + 1)] for _ in range(n + 1)] f[0][0][0] = 0 for i, x in enumerate(nums, 1): for j in range(k + 1): sign = 1 if j & 1 else -1 ...
Solution
python
dagster-io__dagster
examples/docs_projects/project_ml/src/project_ml/defs/types.py
{ "start": 50, "end": 191 }
class ____(TypedDict): model: torch.nn.Module config: dict accuracy: float timestamp: str model_architecture: str
ModelData
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_definition.py
{ "start": 61, "end": 3002 }
class ____(util.MdCase): """Test Blocks admonitions cases.""" extension = ['pymdownx.blocks.definition', 'pymdownx.blocks.html'] def test_def(self): """Test definition.""" self.check_markdown( R''' /// define Apple - Pomaceous fruit of plan...
TestBlocksDefinition
python
pandas-dev__pandas
pandas/core/accessor.py
{ "start": 1339, "end": 5690 }
class ____: """ Abstract base class for delegating methods/properties. """ def _delegate_property_get(self, name: str, *args, **kwargs): raise TypeError(f"You cannot access the property {name}") def _delegate_property_set(self, name: str, value, *args, **kwargs) -> None: raise Type...
PandasDelegate
python
kamyu104__LeetCode-Solutions
Python/maximize-spanning-tree-stability-with-upgrades.py
{ "start": 808, "end": 1657 }
class ____(object): def maxStability(self, n, edges, k): """ :type n: int :type edges: List[List[int]] :type k: int :rtype: int """ uf = UnionFind(n) cnt = 0 result = float("inf") for u, v, s, m in edges: if not m: ...
Solution
python
dask__dask
dask/diagnostics/profile.py
{ "start": 6428, "end": 8507 }
class ____(Process): """Background process for tracking resource usage""" def __init__(self, dt=1): super().__init__() self.daemon = True self.dt = dt self.parent_pid = current_process().pid self.parent_conn, self.child_conn = Pipe() def shutdown(self): if n...
_Tracker
python
huggingface__transformers
src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py
{ "start": 54747, "end": 58611 }
class ____(RobertaPreLayerNormPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.roberta_prelayernorm = RobertaPreLayerNormModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_l...
RobertaPreLayerNormForQuestionAnswering
python
huggingface__transformers
src/transformers/modeling_gguf_pytorch_utils.py
{ "start": 8486, "end": 8866 }
class ____(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) # ref : https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L4666 def process(self, weights, name, **kwargs): if "norm.weight" in name: weights = weights - 1 ...
NemotronTensorProcessor
python
keon__algorithms
tests/test_map.py
{ "start": 4327, "end": 4668 }
class ____(unittest.TestCase): def test_word_pattern(self): self.assertTrue(word_pattern("abba", "dog cat cat dog")) self.assertFalse(word_pattern("abba", "dog cat cat fish")) self.assertFalse(word_pattern("abba", "dog dog dog dog")) self.assertFalse(word_pattern("aaaa", "dog cat cat...
TestWordPattern
python
mlflow__mlflow
mlflow/store/artifact/databricks_artifact_repo_resources.py
{ "start": 832, "end": 892 }
class ____: name: str value: str @dataclass
HttpHeader
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 2806, "end": 2973 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneRunEvent) name = "RunEnqueuedEvent"
GrapheneRunEnqueuedEvent
python
realpython__materials
python-script-structure/iris_summary.py
{ "start": 920, "end": 3889 }
class ____: data: pd.Series mean: float = field(init=False) median: float = field(init=False) mm_diff: float = field(init=False) def __post_init__(self): if not isinstance(self.data, pd.Series): raise TypeError( f"data must be a pandas Series, not {type(self.data...
DescriptiveStatistics
python
getsentry__sentry
src/sentry/api/endpoints/relay/register_response.py
{ "start": 845, "end": 976 }
class ____(RelayIdSerializer): token = serializers.CharField(required=True) @region_silo_endpoint
RelayRegisterResponseSerializer
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/unit_tests/test_component_decl.py
{ "start": 433, "end": 1045 }
class ____(ComponentTree): def set_root_decl(self, root_decl: ComponentDecl): setattr(self, "_root_decl", root_decl) def find_root_decl(self): if hasattr(self, "_root_decl"): return getattr(self, "_root_decl") return super().find_root_decl() @pytest.fixture def component_t...
MockComponentTree
python
airbytehq__airbyte
airbyte-integrations/connectors/source-twilio/unit_tests/test_streams.py
{ "start": 1267, "end": 3938 }
class ____: def test_next_page_token(self, requests_mock): accounts_page_1_json = { "accounts": [ { "sid": "AC123", "date_created": "2022-01-01T00:00:00Z", "subresource_uris": {"addresses": "/2010-04-01/Accounts/AC123/Ad...
TestTwilioStream
python
django__django
tests/view_tests/tests/test_debug.py
{ "start": 19529, "end": 21030 }
class ____(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.security", "WARNING"): response = self.client.get("/raises400/") self.assertContains(response, '<div class="context" id="', status_code=400) de...
NonDjangoTemplatesDebugViewTests
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/tests/test_completion_widget.py
{ "start": 272, "end": 852 }
class ____(object): """ Context manager for tempfile.mkdtemp(). This class is available in python +v3.2. See: https://gist.github.com/cpelley/10e2eeaf60dacc7956bb """ def __enter__(self): self.dir_name = tempfile.mkdtemp() return self.dir_name def __exit__(self, exc_type, e...
TemporaryDirectory
python
huggingface__transformers
src/transformers/models/pop2piano/feature_extraction_pop2piano.py
{ "start": 1388, "end": 19974 }
class ____(SequenceFeatureExtractor): r""" Constructs a Pop2Piano feature extractor. This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains most of the main methods. Users should refer to this superclass for more information regarding those m...
Pop2PianoFeatureExtractor
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/test_component_scaffolding.py
{ "start": 564, "end": 662 }
class ____(BaseModel): name: str age: int is_active: bool
TestParamsModelWithoutDefaults
python
openai__openai-python
src/openai/types/upload_create_params.py
{ "start": 273, "end": 1134 }
class ____(TypedDict, total=False): bytes: Required[int] """The number of bytes in the file you are uploading.""" filename: Required[str] """The name of the file to upload.""" mime_type: Required[str] """The MIME type of the file. This must fall within the supported MIME types for your fi...
UploadCreateParams
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 72637, "end": 76348 }
class ____(Operation): def __init__( self, strategy="greedy", beam_width=100, top_paths=1, merge_repeated=True, mask_index=0, *, name=None, ): super().__init__(name=name) self.strategy = strategy self.beam_width = beam_width...
CTCDecode
python
ansible__ansible
test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/action/plugin_lookup.py
{ "start": 119, "end": 1262 }
class ____(ActionBase): TRANSFERS_FILES = False _VALID_ARGS = frozenset(('type', 'name')) def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(None, task_vars) plugin_type = self._task.args.get('type')...
ActionModule
python
GoogleCloudPlatform__python-docs-samples
monitoring/snippets/v3/uptime-check-client/snippets_test.py
{ "start": 857, "end": 3277 }
class ____: """A test fixture that creates uptime check config.""" def __init__(self): self.project_id = snippets.project_id() self.project_name = snippets.project_name() def __enter__(self): # Create an uptime check config (GET request). self.config_get = snippets.create_u...
UptimeFixture
python
great-expectations__great_expectations
tests/expectations/fixtures/expect_column_values_to_equal_three.py
{ "start": 1346, "end": 3412 }
class ____(ExpectColumnValuesToEqualThree): """Expect values in this column to equal the number three.""" examples = [ { "dataset_name": "mostly_threes_second_iteration", "data": { "mostly_threes": [3, 3, 3, 3, 3, 3, 2, -1, None, None], }, ...
ExpectColumnValuesToEqualThree__SecondIteration
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_T.py
{ "start": 11344, "end": 12659 }
class ____(Benchmark): r""" Tripod objective function. This class defines the Tripod [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Tripod}}(x) = p(x_2) \left[1 + p(x_1) \right] + \lvert x_...
Tripod
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 238, "end": 1652 }
class ____(Benchmark): r""" CarromTable objective function. The CarromTable [1]_ global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{CarromTable}}(x) = - \frac{1}{30}\left(\cos(x_1) cos(x_2) e^{\left|1 - \frac{\sqrt{x_1^2 + x_2^2...
CarromTable
python
ray-project__ray
release/ray_release/exception.py
{ "start": 1910, "end": 2014 }
class ____(ClusterManagerError): exit_code = ExitCode.CLUSTER_ENV_BUILD_TIMEOUT
ClusterEnvBuildTimeout
python
python-pillow__Pillow
src/PIL/DdsImagePlugin.py
{ "start": 990, "end": 1258 }
class ____(IntFlag): CUBEMAP = 0x200 CUBEMAP_POSITIVEX = 0x400 CUBEMAP_NEGATIVEX = 0x800 CUBEMAP_POSITIVEY = 0x1000 CUBEMAP_NEGATIVEY = 0x2000 CUBEMAP_POSITIVEZ = 0x4000 CUBEMAP_NEGATIVEZ = 0x8000 VOLUME = 0x200000 # Pixel Format
DDSCAPS2
python
python-poetry__poetry
src/poetry/repositories/link_sources/html.py
{ "start": 460, "end": 2409 }
class ____(LinkSource): def __init__(self, url: str, content: str) -> None: super().__init__(url=url) parser = HTMLPageParser() parser.feed(content) self._parsed = parser.anchors self._base_url: str | None = parser.base_url @cached_property def _link_cache(self) -> ...
HTMLPage
python
doocs__leetcode
solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/Solution.py
{ "start": 0, "end": 255 }
class ____: def minimumRounds(self, tasks: List[int]) -> int: cnt = Counter(tasks) ans = 0 for v in cnt.values(): if v == 1: return -1 ans += v // 3 + (v % 3 != 0) return ans
Solution
python
altair-viz__altair
altair/vegalite/v6/api.py
{ "start": 24159, "end": 24813 }
class ____(TypedDict, t.Generic[_C], total=False): """ A dictionary representation of a conditional encoding or property. Parameters ---------- condition One or more (predicate, statement) pairs which each form a condition. value An optional default value, used when no predicate...
_Conditional
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 89177, "end": 92979 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, lwa_app_id: str, lwa_client_secret: str, refresh_token: str, aws_access_key: str, aws_secret_key: str, role_arn: str, replication_start_date: str, aws_enviro...
AmazonSellerPartnerSource
python
encode__django-rest-framework
tests/test_reverse.py
{ "start": 374, "end": 708 }
class ____(BaseVersioning): def __init__(self, raise_error=False): self.raise_error = raise_error def reverse(self, *args, **kwargs): if self.raise_error: raise NoReverseMatch() return 'http://scheme-reversed/view' @override_settings(ROOT_URLCONF='tests.test_reverse')
MockVersioningScheme