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
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/mirror_sourceforge_broken/package.py
{ "start": 309, "end": 623 }
class ____(AutotoolsPackage, SourceforgePackage): """Simple sourceforge.net package""" homepage = "http://www.tcl.tk" url = "http://prdownloads.sourceforge.net/tcl/tcl8.6.5-src.tar.gz" version("8.6.8", sha256="c43cb0c1518ce42b00e7c8f6eaddd5195c53a98f94adc717234a65cbcfd3f96a")
MirrorSourceforgeBroken
python
apache__airflow
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/models/test_secret.py
{ "start": 1121, "end": 5465 }
class ____: def test_to_env_secret(self): secret = Secret("env", "name", "secret", "key") assert secret.to_env_secret() == k8s.V1EnvVar( name="NAME", value_from=k8s.V1EnvVarSource(secret_key_ref=k8s.V1SecretKeySelector(name="secret", key="key")), ) def test_to_en...
TestSecret
python
openai__openai-python
src/openai/_base_client.py
{ "start": 46702, "end": 47023 }
class ____(DefaultAsyncHttpxClient): def __del__(self) -> None: if self.is_closed: return try: # TODO(someday): support non asyncio runtimes here asyncio.get_running_loop().create_task(self.aclose()) except Exception: pass
AsyncHttpxClientWrapper
python
facebookresearch__faiss
tests/test_search_params.py
{ "start": 387, "end": 13308 }
class ____(unittest.TestCase): """ Test the IDSelector filtering for as many (index class, id selector class) combinations as possible. """ def do_test_id_selector( self, index_key, id_selector_type="batch", mt=faiss.METRIC_L2, k=10, use_heap=True ...
TestSelector
python
pytorch__pytorch
test/quantization/core/experimental/test_floatx.py
{ "start": 7330, "end": 13956 }
class ____(TestCase): @dtypes(*FLOAT8_DTYPES) @dtypesIfCUDA(*CUDA_FLOAT8_DTYPES) def test_creation_with_zeros(self, dtype, device): """Sanity test, round-trip casting of zeros.""" x8 = torch.zeros(8, dtype=dtype, device=device) if dtype is torch.float8_e8m0fnu: # zeros ar...
TestFloat8Dtype
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 489876, "end": 490621 }
class ____(ValueChannelMixin, core.PositionValueDef): """ Radius2Value schema wrapper. Definition object for a constant value (primitive value or gradient definition) of an encoding channel. Parameters ---------- value : dict, float, :class:`ExprRef`, Literal['height', 'width'] A c...
Radius2Value
python
pallets__jinja
tests/test_tests.py
{ "start": 191, "end": 7851 }
class ____: def test_defined(self, env): tmpl = env.from_string("{{ missing is defined }}|{{ true is defined }}") assert tmpl.render() == "False|True" def test_even(self, env): tmpl = env.from_string("""{{ 1 is even }}|{{ 2 is even }}""") assert tmpl.render() == "False|True" ...
TestTestsCase
python
ray-project__ray
python/ray/data/_internal/datasource/parquet_datasource.py
{ "start": 3529, "end": 5724 }
class ____: """This wrapper class is created to avoid utilizing `ParquetFileFragment` original serialization protocol that actually does network RPCs during serialization (to fetch actual parquet metadata)""" def __init__(self, f: "ParquetFileFragment", file_size: int): self._fragment = f ...
_ParquetFragment
python
ansible__ansible
test/units/modules/mount_facts_data.py
{ "start": 226, "end": 416 }
class ____: fstab: str fstab_parsed: list[dict[str, str]] mtab: str mtab_parsed: list[dict[str, str]] mount: str mount_parsed: list[dict[str, str]] @dataclass
LinuxData
python
Textualize__textual
src/textual/widgets/_rule.py
{ "start": 1544, "end": 1945 }
class ____: """Renders a horizontal rule.""" def __init__(self, character: str, style: Style, width: int): self.character = character self.style = style self.width = width def __rich_console__( self, console: Console, options: ConsoleOptions ) -> Iterable[Segment]: ...
HorizontalRuleRenderable
python
wandb__wandb
wandb/vendor/pygments/lexers/graphics.py
{ "start": 19613, "end": 25836 }
class ____(RegexLexer): """ For `Persistence of Vision Raytracer <http://www.povray.org/>`_ files. .. versionadded:: 0.11 """ name = 'POVRay' aliases = ['pov'] filenames = ['*.pov', '*.inc'] mimetypes = ['text/x-povray'] tokens = { 'root': [ (r'/\*[\w\W]*?\*/', ...
PovrayLexer
python
python-visualization__folium
folium/plugins/scroll_zoom_toggler.py
{ "start": 80, "end": 1761 }
class ____(MacroElement): """Creates a button for enabling/disabling scroll on the Map.""" _template = Template( """ {% macro header(this,kwargs) %} <style> #{{ this.get_name() }} { position:absolute; width:35px; ...
ScrollZoomToggler
python
pytorch__pytorch
test/test_fx_experimental.py
{ "start": 2669, "end": 67483 }
class ____(JitTestCase): def test_find_single_partition(self): class TestModule(torch.nn.Module): def forward(self, a, b): return a + b m = TestModule() traced = symbolic_trace(m) a = torch.rand(1) b = torch.rand(1) graph_manipulation.get_...
TestFXExperimental
python
scikit-learn__scikit-learn
sklearn/feature_selection/_univariate_selection.py
{ "start": 31023, "end": 34099 }
class ____(_BaseFilter): """Filter: Select the p-values for an estimated false discovery rate. This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound on the expected false discovery rate. Read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ----------...
SelectFdr
python
walkccc__LeetCode
solutions/356. Line Reflection/356.py
{ "start": 0, "end": 432 }
class ____: def isReflected(self, points: list[list[int]]) -> bool: minX = math.inf maxX = -math.inf seen = set() for x, y in points: minX = min(minX, x) maxX = max(maxX, x) seen.add((x, y)) summ = minX + maxX # (leftX + rightX) / 2 = (minX + maxX) / 2 # leftX = minX +...
Solution
python
Textualize__textual
docs/examples/styles/link_style.py
{ "start": 64, "end": 747 }
class ____(App): CSS_PATH = "link_style.tcss" def compose(self): yield Label( "Visit the [link='https://textualize.io']Textualize[/link] website.", id="lbl1", # (1)! ) yield Label( "Click [@click=app.bell]here[/] for the bell sound.", id=...
LinkStyleApp
python
getsentry__sentry
tests/sentry/tasks/test_delete_seer_grouping_records.py
{ "start": 382, "end": 6938 }
class ____(TestCase): def setUp(self) -> None: super().setUp() # Needed for may_schedule_task_to_delete_hashes_from_seer to allow the task to be scheduled self.project.update_option("sentry:similarity_backfill_completed", int(time())) def _setup_groups_and_hashes(self, number_of_groups:...
TestDeleteSeerGroupingRecordsByHash
python
django__django
django/db/models/base.py
{ "start": 18164, "end": 18798 }
class ____: """Store model instance state.""" db = None # If true, uniqueness validation checks will consider this a new, unsaved # object. Necessary for correct validation of new instances of objects with # explicit (non-auto) PKs. This impacts validation only; it has no effect # on the actual...
ModelState
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 40727, "end": 64847 }
class ____: async def test_repeated_task_call_within_flow_is_cached_by_default(self): @task(persist_result=True) def foo(x): return x @flow def bar(): return foo(1, return_state=True), foo(1, return_state=True) first_state, second_state = bar() ...
TestTaskCaching
python
pypa__packaging
src/packaging/pylock.py
{ "start": 7258, "end": 8076 }
class ____(Exception): """Raised when when input data is not spec-compliant.""" context: str | None = None message: str def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, PylockValidationError): ...
PylockValidationError
python
doocs__leetcode
solution/2500-2599/2517.Maximum Tastiness of Candy Basket/Solution.py
{ "start": 0, "end": 528 }
class ____: def maximumTastiness(self, price: List[int], k: int) -> int: def check(x: int) -> bool: cnt, pre = 0, -x for cur in price: if cur - pre >= x: pre = cur cnt += 1 return cnt >= k price.sort() ...
Solution
python
getsentry__sentry
src/sentry/notifications/platform/registry.py
{ "start": 330, "end": 1424 }
class ____(Registry[type[NotificationProvider[Any]]]): """ A registry for notification providers. Adds `get_all` and `get_available` methods to the base registry. """ def get_all(self) -> list[type[NotificationProvider[Any]]]: """ Returns every NotificationProvider that has been registe...
NotificationProviderRegistry
python
ray-project__ray
python/ray/data/_internal/issue_detection/detectors/hanging_detector.py
{ "start": 871, "end": 1004 }
class ____: operator_id: str task_idx: int bytes_output: int start_time_hanging: float @dataclass
HangingExecutionState
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 21968, "end": 25071 }
class ____(SinglePatternODESolver): r""" Solves an almost-linear differential equation. The general form of an almost linear differential equation is .. math:: a(x) g'(f(x)) f'(x) + b(x) g(f(x)) + c(x) Here `f(x)` is the function to be solved for (the dependent variable). The substitution `g(...
AlmostLinear
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 11932, "end": 19865 }
class ____(test.TestCase): def setUp(self): ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.mean_tensor(array_ops.ones([4, 3])) _assert_metric_variables(self, ('mean/total_tensor:0', 'mean/count_tensor:0')) @test_util.run_deprecated_...
MeanTensorTest
python
getsentry__sentry
src/sentry/apidocs/parameters.py
{ "start": 3686, "end": 4179 }
class ____: ENVIRONMENT = OpenApiParameter( name="environment", location="path", required=True, type=str, description="The name of the environment.", ) VISIBILITY = OpenApiParameter( name="visibility", location="query", required=False, ...
EnvironmentParams
python
spyder-ide__spyder
spyder/plugins/projects/widgets/main_widget.py
{ "start": 2453, "end": 2648 }
class ____: SearchInSwitcher = "search_in_switcher" # ---- Main widget # ----------------------------------------------------------------------------- @class_register
ProjectsOptionsMenuActions
python
getsentry__sentry
tests/sentry/integrations/vsts/test_notify_action.py
{ "start": 785, "end": 8116 }
class ____(RuleTestCase, VstsIssueBase): rule_cls = AzureDevopsCreateTicketAction def setUp(self) -> None: integration, _, _, _ = self.create_identity_integration( user=self.user, organization=self.organization, integration_params={ "provider": "vsts"...
AzureDevopsCreateTicketActionTest
python
tensorflow__tensorflow
tensorflow/python/training/adam_test.py
{ "start": 1966, "end": 18994 }
class ____(test.TestCase): def doTestSparse(self, use_resource=False): for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with self.cached_session(): # Initialize variables for numpy implementation. m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 var0_np = np.array([1.0, 2.0], dtype=dt...
AdamOptimizerTest
python
getsentry__sentry
src/sentry/utils/meta.py
{ "start": 340, "end": 6351 }
class ____: """ A lazy view to detached validation and normalization meta data. It allows to safely traverse the meta tree and create a deep path lazily. Use ``enter`` to get a view to the meta data inside a specific key. The ``Meta`` object is a shallow view onto the top-level meta structure and ...
Meta
python
ray-project__ray
python/ray/train/v2/api/config.py
{ "start": 9231, "end": 13840 }
class ____: """Runtime configuration for training runs. Args: name: Name of the trial or experiment. If not provided, will be deduced from the Trainable. storage_path: Path where all results and checkpoints are persisted. Can be a local directory or a destination on clou...
RunConfig
python
ray-project__ray
rllib/models/catalog.py
{ "start": 3840, "end": 36145 }
class ____: """Registry of models, preprocessors, and action distributions for envs. .. testcode:: :skipif: True prep = ModelCatalog.get_preprocessor(env) observation = prep.transform(raw_observation) dist_class, dist_dim = ModelCatalog.get_action_dist( env.action_...
ModelCatalog
python
huggingface__transformers
src/transformers/models/mixtral/modeling_mixtral.py
{ "start": 30938, "end": 31239 }
class ____(GenericForQuestionAnswering, MixtralPreTrainedModel): pass __all__ = [ "MixtralForCausalLM", "MixtralForQuestionAnswering", "MixtralModel", "MixtralPreTrainedModel", "MixtralForSequenceClassification", "MixtralForTokenClassification", ]
MixtralForQuestionAnswering
python
google__jax
tests/pallas/mosaic_gpu_test.py
{ "start": 172140, "end": 193301 }
class ____(PallasTest): @parameterized.product(m=[512], n=[512], repeats=[1, 10], manual_consumed_barriers=[False, True], max_concurrent_steps=[2, 3]) def test_pipelined_copy( self, m, n, repeats, manual_consumed_barriers, max_concurrent_steps ): x = ja...
WarpSpecializedPipelineTest
python
ray-project__ray
rllib/algorithms/ppo/default_ppo_rl_module.py
{ "start": 413, "end": 2543 }
class ____(RLModule, InferenceOnlyAPI, ValueFunctionAPI, abc.ABC): """Default RLModule used by PPO, if user does not specify a custom RLModule. Users who want to train their RLModules with PPO may implement any RLModule (or TorchRLModule) subclass as long as the custom class also implements the `ValueF...
DefaultPPORLModule
python
davidhalter__jedi
test/completion/dynamic_params.py
{ "start": 1294, "end": 1368 }
class ____(): def __init__(self, a): #? str() a A("s")
A
python
pytest-dev__pytest
testing/code/test_code.py
{ "start": 4690, "end": 5562 }
class ____: def test_not_raise_exception_with_mixed_encoding(self, tw_mock) -> None: args = [("unicode_string", "São Paulo"), ("utf8_string", b"S\xc3\xa3o Paulo")] r = ReprFuncArgs(args) r.toterminal(tw_mock) assert ( tw_mock.lines[0] == r"unicode_string = S...
TestReprFuncArgs
python
kamyu104__LeetCode-Solutions
Python/evaluate-valid-expressions.py
{ "start": 37, "end": 932 }
class ____(object): def evaluateExpression(self, expression): """ :type expression: str :rtype: int """ LOOKUP = { "add":lambda a, b: a+b, "sub":lambda a, b: a-b, "mul":lambda a, b: a*b, "div":lambda a, b: a//b } ...
Solution
python
scipy__scipy
scipy/linalg/tests/test_solvers.py
{ "start": 30854, "end": 34598 }
class ____: cases = [ # empty cases (np.empty((0, 0)), np.empty((0, 0)), np.empty((0, 0))), (np.empty((0, 0)), np.empty((2, 2)), np.empty((0, 2))), (np.empty((2, 2)), np.empty((0, 0)), np.empty((2, 0))), # a, b, c all re...
TestSolveSylvester
python
redis__redis-py
tests/test_asyncio/test_pipeline.py
{ "start": 218, "end": 15961 }
class ____: async def test_pipeline_is_true(self, r): """Ensure pipeline instances are not false-y""" async with r.pipeline() as pipe: assert pipe async def test_pipeline(self, r): async with r.pipeline() as pipe: ( pipe.set("a", "a1") ...
TestPipeline
python
huggingface__transformers
tests/quantization/hqq/test_hqq.py
{ "start": 3225, "end": 5289 }
class ____(unittest.TestCase): def tearDown(self): cleanup() def test_fp16_quantized_model(self): """ Simple LLM model testing fp16 """ quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_...
HQQTest
python
django__django
tests/model_forms/tests.py
{ "start": 121345, "end": 121428 }
class ____(forms.Field): queryset = 42
CustomFieldWithQuerysetButNoLimitChoicesTo
python
MongoEngine__mongoengine
tests/document/test_instance.py
{ "start": 124184, "end": 125954 }
class ____(MongoDBTestCase): def test_object_key_simple_document(self): class Book(Document): title = StringField() book = Book(title="Whatever") assert book._object_key == {"pk": None} book.pk = ObjectId() assert book._object_key == {"pk": book.pk} def tes...
ObjectKeyTestCase
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 174984, "end": 175478 }
class ____(_MatrixMixin, TestCSR): @classmethod def spcreator(cls, *args, **kwargs): with warnings.catch_warnings(): warnings.filterwarnings("ignore", WMSG, SparseEfficiencyWarning) return csr_matrix(*args, **kwargs) def test_spmatrix_subscriptable(): result = csr_matrix[np....
TestCSRMatrix
python
plotly__plotly.py
plotly/graph_objs/barpolar/selected/_textfont.py
{ "start": 233, "end": 2425 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "barpolar.selected" _path_str = "barpolar.selected.textfont" _valid_props = {"color"} @property def color(self): """ Sets the text font color of selected points. The 'color' property is a color and may be specified as:...
Textfont
python
milvus-io__pymilvus
tests/test_connections.py
{ "start": 12942, "end": 18533 }
class ____: def test_issue_1196(self): """ >>> connections.connect(alias="default11", host="xxx.com", port=19541, user="root", password="12345", secure=True) >>> connections.add_connection(default={"host": "xxx.com", "port": 19541}) >>> connections.connect("default", user="root", pas...
TestIssues
python
django__django
tests/admin_scripts/tests.py
{ "start": 91270, "end": 92228 }
class ____(SimpleTestCase): def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ with self.settings( INSTALLED_APPS=[ "admin_scripts.complex_app", "admin_scripts.simple_app", "django.contri...
Discovery
python
networkx__networkx
networkx/algorithms/tests/test_euler.py
{ "start": 9603, "end": 11209 }
class ____: def test_disconnected(self): with pytest.raises(nx.NetworkXError): G = nx.from_edgelist([(0, 1), (2, 3)]) nx.eulerize(G) def test_null_graph(self): with pytest.raises(nx.NetworkXPointlessConcept): nx.eulerize(nx.Graph()) def test_null_multigr...
TestEulerize
python
wandb__wandb
wandb/vendor/pygments/lexers/parsers.py
{ "start": 23668, "end": 25866 }
class ____(RegexLexer): """ A base lexer for `Treetop <http://treetop.rubyforge.org/>`_ grammars. Not for direct use; use TreetopLexer instead. .. versionadded:: 1.6 """ tokens = { 'root': [ include('space'), (r'require[ \t]+[^\n\r]+[\n\r]', Other), ...
TreetopBaseLexer
python
jazzband__django-simple-history
simple_history/tests/tests/test_signals.py
{ "start": 345, "end": 4113 }
class ____(TestCase): def setUp(self): self.signal_was_called = False self.signal_instance = None self.signal_history_instance = None self.signal_sender = None self.field = None self.rows = None def test_pre_create_historical_record_signal(self): def hand...
PrePostCreateHistoricalRecordSignalTest
python
takluyver__flit
tests/test_install.py
{ "start": 538, "end": 15849 }
class ____(TestCase): def setUp(self): td = tempfile.TemporaryDirectory() self.addCleanup(td.cleanup) self.get_dirs_patch = patch('flit.install.get_dirs', return_value={ 'scripts': os.path.join(td.name, 'scripts'), 'purelib': os.path.jo...
InstallTests
python
Lightning-AI__lightning
src/lightning/pytorch/callbacks/timer.py
{ "start": 1203, "end": 8283 }
class ____(Callback): """The Timer callback tracks the time spent in the training, validation, and test loops and interrupts the Trainer if the given time limit for the training loop is reached. Args: duration: A string in the format DD:HH:MM:SS (days, hours, minutes seconds), or a :class:`datetime...
Timer
python
pytorch__pytorch
torch/_inductor/select_algorithm.py
{ "start": 11655, "end": 59634 }
class ____(TritonKernel): """ A specialized kernel class for Triton templates that handles code generation for templated Triton kernels. This class extends TritonKernel to provide additional functionality for template-based kernel generation, including support for subgraphs, workspace arguments...
TritonTemplateKernel
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 20162, "end": 20532 }
class ____(DagsterError): def __init__(self, *args, **kwargs): from dagster._utils.error import SerializableErrorInfo self.load_error_infos = check.list_param( kwargs.pop("load_error_infos"), "load_error_infos", SerializableErrorInfo, ) super().__...
DagsterCodeLocationLoadError
python
django__django
tests/admin_inlines/models.py
{ "start": 6769, "end": 6983 }
class ____(models.Model): name = models.CharField(max_length=100, help_text="Help text for ReadOnlyInline") capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE) # Models for #18433
ReadOnlyInline
python
readthedocs__readthedocs.org
readthedocs/api/v2/views/model_views.py
{ "start": 3519, "end": 5452 }
class ____: """ Helper to disable APIv2 listing endpoint. We are disablng the listing endpoint because it could cause DOS without using any type of filtering. This class disables these endpoints except: - version resource when passing ``?project__slug=`` - build resource when using ``?c...
DisableListEndpoint
python
instagram__MonkeyType
tests/test_util.py
{ "start": 2738, "end": 3148 }
class ____: @pytest.mark.parametrize( 'input_string, expected', [ ("foo", "Foo"), ("foo_bar", "FooBar"), ("fooBar", "FooBar"), ("FooBar", "FooBar"), ("_foo___bar_baz__", "FooBarBaz"), ], ) def test_pascal_case(self, input_st...
TestPascalCase
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 150775, "end": 151533 }
class ____(PositionToken): """Matches if current position is at the end of a line within the parse string """ def __init__(self) -> None: super().__init__() self.whiteChars.discard("\n") self.set_whitespace_chars(self.whiteChars, copy_defaults=False) self.set_name("end o...
LineEnd
python
Pylons__pyramid
src/pyramid/i18n.py
{ "start": 545, "end": 8435 }
class ____: """ An object providing translation and pluralizations related to the current request's locale name. A :class:`pyramid.i18n.Localizer` object is created using the :func:`pyramid.i18n.get_localizer` function. """ def __init__(self, locale_name, translations): self.locale...
Localizer
python
fastai__fastai
fastai/callback/fp16.py
{ "start": 6619, "end": 6990 }
class ____(Callback): "Use with NonNativeMixedPrecision callback (but it needs to run at the very beginning)" order=-50 def before_fit(self): self.learn.model = convert_network(self.model, dtype=torch.float16) def after_fit (self): self.learn.model = convert_network(self.model, dtype=torch.float32) # %...
ModelToHalf
python
tensorflow__tensorflow
tensorflow/python/ops/sparse_ops_test.py
{ "start": 1735, "end": 11169 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testSparseEye(self): def test_one(n, m, as_tensors): expected = np.eye(n, m) if as_tensors: m = constant_op.constant(m) n = constant_op.constant(n) s = sparse_ops.sparse_eye(n, m) d = sparse_ops.sparse_t...
SparseOpsTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/eks.py
{ "start": 38092, "end": 42456 }
class ____(AwsBaseOperator[EksHook]): """ Deletes an Amazon EKS managed node group from an Amazon EKS Cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:EksDeleteNodegroupOperator` :param cluster_name: The name of the ...
EksDeleteNodegroupOperator
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/errors.py
{ "start": 798, "end": 937 }
class ____(PyCTError, NotImplementedError): """Raised for code patterns that AutoGraph does not support."""
UnsupportedLanguageElementError
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 47474, "end": 47792 }
class ____(sympy.Function): is_real = True @classmethod def eval(cls, number, ndigits): # assert number.is_integer is not True, number if isinstance(number, sympy.Number) and isinstance(ndigits, sympy.Integer): return sympy.Float(round(float(number), int(ndigits)))
RoundDecimal
python
Textualize__textual
src/textual/_spatial_map.py
{ "start": 316, "end": 3764 }
class ____(Generic[ValueType]): """A spatial map allows for data to be associated with rectangular regions in Euclidean space, and efficiently queried. When the SpatialMap is populated, a reference to each value is placed into one or more buckets associated with a regular grid that covers 2D space. ...
SpatialMap
python
protocolbuffers__protobuf
upb/bazel/amalgamate.py
{ "start": 1835, "end": 5021 }
class ____: def __init__(self, h_out, c_out): self.include_paths = ["."] self.included = set() self.output_h = open(h_out, "w") self.output_c = open(c_out, "w") self.h_out = h_out.split("/")[-1] def amalgamate(self, h_files, c_files): self.h_files = set(h_files) self.output_c.write("/* ...
Amalgamator
python
encode__django-rest-framework
tests/test_validators.py
{ "start": 35754, "end": 35904 }
class ____(models.Model): slug = models.CharField(max_length=100, unique_for_year='published') published = models.DateField()
UniqueForYearModel
python
chroma-core__chroma
chromadb/utils/data_loaders.py
{ "start": 222, "end": 1021 }
class ____(DataLoader[List[Optional[Image]]]): def __init__(self, max_workers: int = multiprocessing.cpu_count()) -> None: try: self._PILImage = importlib.import_module("PIL.Image") self._max_workers = max_workers except ImportError: raise ValueError( ...
ImageLoader
python
django__django
tests/test_utils/tests.py
{ "start": 51860, "end": 54090 }
class ____(SimpleTestCase): def test_equal(self): valid_tests = ( ("http://example.com/?", "http://example.com/"), ("http://example.com/?x=1&", "http://example.com/?x=1"), ("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), ("http://example.com/?x=...
AssertURLEqualTests
python
huggingface__transformers
src/transformers/models/tvp/modeling_tvp.py
{ "start": 7107, "end": 12778 }
class ____(nn.Module): """ Takes input of both image and video (multi-frame) """ def __init__(self, config): super().__init__() # sequence embedding self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.row_position_embeddings =...
TvpVisualInputEmbedding
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/strings_ops/string_to_hash_bucket_op_test.py
{ "start": 1028, "end": 4128 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testStringToOneHashBucketFast(self): with self.cached_session(): input_string = array_ops.placeholder(dtypes.string) output = string_ops.string_to_hash_bucket_fast(input_string, 1) result = output.eval(feed_dict={input_string: ['a', ...
StringToHashBucketOpTest
python
getsentry__sentry
src/sentry/rules/conditions/new_high_priority_issue.py
{ "start": 387, "end": 1595 }
class ____(EventCondition): id = "sentry.rules.conditions.high_priority_issue.NewHighPriorityIssueCondition" label = "Sentry marks a new issue as high priority" def is_new(self, state: EventState) -> bool: if not self.rule or self.rule.environment_id is None: return state.is_new ...
NewHighPriorityIssueCondition
python
numba__numba
numba/core/callwrapper.py
{ "start": 112, "end": 2435 }
class ____(object): """ A utility class to handle argument unboxing and cleanup """ def __init__(self, context, builder, api, env_manager, endblk, nargs): self.context = context self.builder = builder self.api = api self.env_manager = env_manager self.arg_count = ...
_ArgManager
python
joke2k__faker
faker/providers/person/en_NZ/__init__.py
{ "start": 105, "end": 40961 }
class ____(PersonProvider): formats = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}-{{last_name}}", "{{first_name_female}} {{last...
Provider
python
encode__django-rest-framework
tests/test_response.py
{ "start": 7761, "end": 8436 }
class ____(TestCase): def test_should_allow_posting_json(self): response = self.client.post('/json', data='{"test": 123}', content_type='application/json') self.assertEqual(response.status_code, 200) def test_should_not_allow_posting_xml(self): response = self.client.post('/json', data...
UnsupportedMediaTypeTests
python
doocs__leetcode
solution/0400-0499/0438.Find All Anagrams in a String/Solution.py
{ "start": 0, "end": 406 }
class ____: def findAnagrams(self, s: str, p: str) -> List[int]: m, n = len(s), len(p) ans = [] if m < n: return ans cnt1 = Counter(p) cnt2 = Counter(s[: n - 1]) for i in range(n - 1, m): cnt2[s[i]] += 1 if cnt1 == cnt2: ...
Solution
python
Pylons__pyramid
src/pyramid/authentication.py
{ "start": 40771, "end": 42497 }
class ____(CallbackAuthenticationPolicy): """A :app:`Pyramid` authentication policy which gets its data from the configured :term:`session`. For this authentication policy to work, you will have to follow the instructions in the :ref:`sessions_chapter` to configure a :term:`session factory`. Const...
SessionAuthenticationPolicy
python
chroma-core__chroma
chromadb/db/migrations.py
{ "start": 1008, "end": 1390 }
class ____(Exception): def __init__(self, dir: str, db_version: int, source_version: int): super().__init__( f"Inconsistent migration versions in {dir}:" + f"db version was {db_version}, source version was {source_version}." + " Has the migration sequence been modified si...
InconsistentVersionError
python
sphinx-doc__sphinx
tests/roots/test-add_enumerable_node/enumerable_node.py
{ "start": 242, "end": 527 }
class ____(Directive): required_arguments = 1 has_content = True def run(self): figure_node = my_figure() figure_node += nodes.image(uri=self.arguments[0]) figure_node += nodes.caption(text=''.join(self.content)) return [figure_node]
MyFigure
python
huggingface__transformers
examples/modular-transformers/modeling_super.py
{ "start": 7742, "end": 10820 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: SuperConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size /...
SuperAttention
python
pypa__pip
tests/unit/test_options.py
{ "start": 8507, "end": 14799 }
class ____(AddFakeCommandMixin): @pytest.mark.parametrize("option", ["verbose", "quiet"]) @pytest.mark.parametrize("value", range(4)) def test_cli_long(self, option: str, value: int) -> None: flags = [f"--{option}"] * value # FakeCommand intentionally returns the wrong type. opt1, ar...
TestCountOptions
python
kamyu104__LeetCode-Solutions
Python/word-ladder.py
{ "start": 1283, "end": 2150 }
class ____(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ lookup = set(wordList) if endWord not in lookup: return 0 ladder = 2 ...
Solution2
python
pyparsing__pyparsing
tests/test_unit.py
{ "start": 4512, "end": 5234 }
class ____(TestCase): def runTest(self): print( "Beginning test of pyparsing, version", pp.__version__, pp.__version_time__, ) config_options = [] if PYTHON_JIT_ENABLED: config_options.append("JIT enabled") if PYTHON_FREE_THREAD...
Test01_PyparsingTestInit
python
kamyu104__LeetCode-Solutions
Python/intersection-of-two-arrays-ii.py
{ "start": 2512, "end": 3266 }
class ____(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. res = [] it1, it2 = 0, 0 while it1 < l...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 30354, "end": 30448 }
class ____(_Deannotate, _ReturnsStringKey, RoleImpl): __slots__ = ()
DDLConstraintColumnImpl
python
matplotlib__matplotlib
lib/matplotlib/dates.py
{ "start": 33172, "end": 37519 }
class ____: """ A simple wrapper around a `dateutil.rrule` allowing flexible date tick specifications. """ def __init__(self, freq, tzinfo=None, **kwargs): """ Parameters ---------- freq : {YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY} Tick f...
rrulewrapper
python
neetcode-gh__leetcode
python/0143-reorder-list.py
{ "start": 0, "end": 682 }
class ____: def reorderList(self, head: ListNode) -> None: # find middle slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next # reverse second half second = slow.next prev = slow.next = None whi...
Solution
python
astropy__astropy
astropy/extern/configobj/configobj.py
{ "start": 5919, "end": 6018 }
class ____(ConfigObjError): """Base class for the two interpolation errors."""
InterpolationError
python
apache__airflow
airflow-core/src/airflow/dag_processing/dagbag.py
{ "start": 7174, "end": 29485 }
class ____(LoggingMixin): """ A dagbag is a collection of dags, parsed out of a folder tree and has high level configuration settings. Some possible setting are database to use as a backend and what executor to use to fire off tasks. This makes it easier to run distinct environments for say product...
DagBag
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 144378, "end": 144495 }
class ____(BaseModel, extra="forbid"): upsert: "PointInsertOperations" = Field(..., description="")
UpsertOperation
python
hynek__structlog
tests/test_stdlib.py
{ "start": 44837, "end": 49125 }
class ____: def test_sync_bl(self, abl, cl): """ AsyncBoungLogger.sync_bl works outside of loops. """ abl.sync_bl.info("test") assert [ CapturedCall(method_name="info", args=(), kwargs={"event": "test"}) ] == cl.calls @pytest.mark.asyncio async d...
TestAsyncBoundLogger
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 20172, "end": 20386 }
class ____(GatherDepDoneEvent): """:class:`GatherDep` instruction terminated: network failure while trying to communicate with remote worker """ __slots__ = () @dataclass
GatherDepNetworkFailureEvent
python
Pylons__pyramid
docs/conf.py
{ "start": 11117, "end": 13690 }
class ____(Directive): def run(self): return [nodes.raw( '', format='latex')] def app_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """custom role for :app: marker, does nothing in particular except allow :app:`Pyramid` to work (for later search and re...
BackMatter
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_build.py
{ "start": 2212, "end": 5637 }
class ____(GoogleCloudBaseOperator): """ Cancels a build in progress. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudBuildCancelBuildOperator` :param id_: The ID of the build. :param project_id: Optional, Google Cl...
CloudBuildCancelBuildOperator
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001.py
{ "start": 1334, "end": 5078 }
class ____(TeamPublic): heroes: List[HeroPublic] = [] sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(e...
TeamPublicWithHeroes
python
kamyu104__LeetCode-Solutions
Python/convert-to-base-2.py
{ "start": 32, "end": 380 }
class ____(object): def baseNeg2(self, N): """ :type N: int :rtype: str """ result = [] while N: result.append(str(-N & 1)) # N % -2 N = -(N >> 1) # N //= -2 result.reverse() return "".join(result) if result else "0" # Time:...
Solution
python
ApeWorX__ape
src/ape_pm/dependency.py
{ "start": 12916, "end": 19618 }
class ____(DependencyAPI): """ A dependency installed from Python tooling, such as `pip`. """ site_package: Optional[str] = None """ The Python site-package name, such as ``"snekmate"``. Cannot use with ``pypi:``. Requires the dependency to have been installed either via ``pip`` or some...
PythonDependency
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 532976, "end": 533427 }
class ____(sgqlc.types.Type): """Autogenerated return type of CopyProjectV2""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "project_v2") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutat...
CopyProjectV2Payload
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1593086, "end": 1593249 }
class ____(sgqlc.types.Union): """Types that can be inside Project Cards.""" __schema__ = github_schema __types__ = (Issue, PullRequest)
ProjectCardItem
python
walkccc__LeetCode
solutions/2049. Count Nodes With the Highest Score/2049.py
{ "start": 0, "end": 701 }
class ____: def countHighestScoreNodes(self, parents: list[int]) -> int: tree = [[] for _ in range(len(parents))] for i, parent in enumerate(parents): if parent == -1: continue tree[parent].append(i) ans = 0 maxScore = 0 def dfs(u: int) -> int: # Returns node count no...
Solution