language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
getsentry__sentry
src/sentry/integrations/vsts/issues.py
{ "start": 2076, "end": 17660 }
class ____(IssueSyncIntegration, SourceCodeIssueIntegration, ABC): description = "Integrate Azure DevOps work items by linking a project." slug = IntegrationProviderSlug.AZURE_DEVOPS.value conf_key = slug issue_fields = frozenset(["id", "title", "url"]) done_categories = frozenset(["Resolved", "Com...
VstsIssuesSpec
python
Pylons__pyramid
docs/tutorials/wiki/src/authorization/tutorial/models/__init__.py
{ "start": 148, "end": 321 }
class ____(PersistentMapping): __name__ = None __parent__ = None __acl__ = [ (Allow, Everyone, 'view'), (Allow, 'group:editors', 'edit'), ]
Wiki
python
huggingface__transformers
tests/models/nanochat/test_modeling_nanochat.py
{ "start": 1408, "end": 8687 }
class ____(unittest.TestCase): """Integration tests for NanoChat models using real checkpoints.""" def setUp(self): cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @slow def test_model_d20_logits(self): """Test that d20 mod...
NanoChatIntegrationTest
python
pytorch__pytorch
test/test_mps.py
{ "start": 428415, "end": 430862 }
class ____(TorchDispatchMode): """ TorchDispatchMode which intercepts the _scaled_dot_product_attention_math_for_mps aten operator to check that the meta kernel is correct. """ def __init__(self, test): self.test = test super().__init__() def __torch_dispatch__(self, func, ...
TestSDPAMetaDispatchMode
python
kamyu104__LeetCode-Solutions
Python/triples-with-bitwise-and-equal-to-zero.py
{ "start": 159, "end": 882 }
class ____(object): def countTriplets(self, A): """ :type A: List[int] :rtype: int """ def FWT(A, v): B = A[:] d = 1 while d < len(B): for i in xrange(0, len(B), d << 1): for j in xrange(d): ...
Solution
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_modelresource/test_resource_postgres.py
{ "start": 1559, "end": 7346 }
class ____(TransactionTestCase): # Make sure to start the sequences back at 1 reset_sequences = True def test_create_object_after_importing_dataset_with_id(self): dataset = tablib.Dataset(headers=["id", "name"]) dataset.append([1, "Some book"]) resource = BookResource() resu...
PostgresTests
python
tensorflow__tensorflow
tensorflow/python/data/ops/multi_device_iterator_ops.py
{ "start": 7199, "end": 9461 }
class ____(dataset_ops.DatasetV2): """Creates a _PerDeviceGenerator-like dataset with a new incarnation_id. Re-uses the functions from the provided per_device_dataset and just switches out the function argument corresponding to the incarnation_id. """ def __init__(self, per_device_dataset, incarnation_id): ...
_ReincarnatedPerDeviceGenerator
python
getsentry__sentry
src/sentry/apidocs/examples/scim_examples.py
{ "start": 51, "end": 5046 }
class ____: LIST_ORG_MEMBERS = [ OpenApiExample( "List an Organization's Members", value={ "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 1, "startIndex": 1, "itemsPerPage": 1, ...
SCIMExamples
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 195457, "end": 197116 }
class ____(Binding): """ BindRadioSelect schema wrapper. Parameters ---------- input : Literal['radio', 'select'] options : Sequence[Any] An array of options to select from. debounce : float If defined, delays event handling until the specified milliseconds have elapsed ...
BindRadioSelect
python
kamyu104__LeetCode-Solutions
Python/jump-game-vii.py
{ "start": 59, "end": 614 }
class ____(object): def canReach(self, s, minJump, maxJump): """ :type s: str :type minJump: int :type maxJump: int :rtype: bool """ dp = [False]*len(s) dp[0] = True cnt = 0 for i in xrange(1, len(s)): if i >= minJump: ...
Solution
python
PrefectHQ__prefect
src/prefect/client/orchestration/base.py
{ "start": 386, "end": 954 }
class ____: server_type: "ServerType" def __init__(self, client: "Client"): self._client = client def request( self, method: HTTP_METHODS, path: "ServerRoutes", params: dict[str, Any] | None = None, path_params: dict[str, Any] | None = None, **kwargs...
BaseClient
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/enums.py
{ "start": 3863, "end": 3968 }
class ____(_SunderMissingInEnumMixin, enum.Enum): """this is enum class"""
EnumSunderMissingInEnumMixin
python
huggingface__transformers
tests/models/emu3/test_modeling_emu3.py
{ "start": 11303, "end": 20611 }
class ____(unittest.TestCase): @slow @require_bitsandbytes def test_model_generation(self): model = Emu3ForConditionalGeneration.from_pretrained( "BAAI/Emu3-Chat-hf", quantization_config=BitsAndBytesConfig(load_in_4bit=True) ) processor = Emu3Processor.from_pretrained("BA...
Emu3IntegrationTest
python
python-pillow__Pillow
src/PIL/IcoImagePlugin.py
{ "start": 4629, "end": 4849 }
class ____(NamedTuple): width: int height: int nb_color: int reserved: int planes: int bpp: int size: int offset: int dim: tuple[int, int] square: int color_depth: int
IconHeader
python
mlflow__mlflow
mlflow/deployments/databricks/__init__.py
{ "start": 716, "end": 1308 }
class ____(AttrDict): """ A dictionary-like object representing a Databricks serving endpoint. .. code-block:: python endpoint = DatabricksEndpoint( { "name": "chat", "creator": "alice@company.com", "creation_timestamp": 0, ...
DatabricksEndpoint
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 8845, "end": 9231 }
class ____(_Permission[BackupsAction]): collection: str def _to_weaviate(self) -> List[WeaviatePermission]: return [ { "action": action, "backups": { "collection": _capitalize_first_letter(self.collection), }, }...
_BackupsPermission
python
huggingface__transformers
src/transformers/models/phi3/modeling_phi3.py
{ "start": 12827, "end": 13548 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Phi3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_d...
Phi3RMSNorm
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 39180, "end": 40273 }
class ____(TestCase): def test_db_comment(self): class Model(models.Model): field = models.IntegerField(db_comment="Column comment") errors = Model._meta.get_field("field").check(databases=self.databases) expected = ( [] if connection.features.supports_co...
DbCommentTests
python
realpython__materials
arcade-platformer/arcade_platformer/arcade_platformer.py
{ "start": 1689, "end": 4159 }
class ____(arcade.View): """Displays a title screen and prompts the user to begin the game. Provides a way to show instructions and start the game. """ def __init__(self) -> None: super().__init__() # Find the title image in the images folder title_image_path = ASSETS_PATH / "i...
TitleView
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/typehints.py
{ "start": 1243, "end": 1342 }
class ____: def __new__(cls, i: int) -> NewAnnotation: # NoQA: PYI034 pass
NewAnnotation
python
h5py__h5py
h5py/tests/test_h5p.py
{ "start": 358, "end": 2651 }
class ____(TestCase): """ Feature: Setting/getting lib ver bounds """ def test_libver(self): """ Test libver bounds set/get """ plist = h5p.create(h5p.FILE_ACCESS) plist.set_libver_bounds(h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST) self.assertEqual((h5f.LIBVER_EARLIEST,...
TestLibver
python
pandas-dev__pandas
pandas/tests/indexes/period/test_period.py
{ "start": 245, "end": 7921 }
class ____: def test_view_asi8(self): idx = PeriodIndex([], freq="M") exp = np.array([], dtype=np.int64) tm.assert_numpy_array_equal(idx.view("i8"), exp) tm.assert_numpy_array_equal(idx.asi8, exp) idx = PeriodIndex(["2011-01", NaT], freq="M") exp = np.array([492, -...
TestPeriodIndex
python
Pylons__pyramid
tests/test_path.py
{ "start": 19537, "end": 19843 }
class ____: """Has no __file__ attribute.""" def __init__(self, real_package_or_module): self.__name__ = real_package_or_module.__name__ import os self.package_path = os.path.dirname( os.path.abspath(real_package_or_module.__file__) )
DummyNamespacePackage
python
yandexdataschool__Practical_RL
week09_policy_II/mujoco_wrappers.py
{ "start": 1949, "end": 3760 }
class ____(gym.Wrapper): """ A vectorized wrapper that normalizes the observations and returns from an environment. """ # pylint: disable=too-many-arguments def __init__(self, env, obs=True, ret=True, clipobs=10., cliprew=10., gamma=0.99, eps=1e-8): super().__init__(env...
Normalize
python
python-visualization__folium
folium/plugins/encoded.py
{ "start": 2652, "end": 3733 }
class ____(_BaseFromEncoded): """Create Polygons directly from the encoded string. Parameters ---------- encoded: str The raw encoded string from the Polyline Encoding Algorithm. See: https://developers.google.com/maps/documentation/utilities/polylinealgorithm **kwargs: Poly...
PolygonFromEncoded
python
walkccc__LeetCode
solutions/1525. Number of Good Ways to Split a String/1525.py
{ "start": 0, "end": 412 }
class ____: def numSplits(self, s: str) -> int: n = len(s) ans = 0 seen = set() prefix = [0] * n suffix = [0] * n for i in range(n): seen.add(s[i]) prefix[i] = len(seen) seen.clear() for i in reversed(range(n)): seen.add(s[i]) suffix[i] = len(seen) for i...
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_neptune.py
{ "start": 8070, "end": 15304 }
class ____: @mock.patch.object(NeptuneHook, "conn") @mock.patch.object(NeptuneHook, "get_cluster_status") @mock.patch.object(NeptuneHook, "get_waiter") def test_stop_cluster_wait_for_completion(self, mock_hook_get_waiter, mock_get_cluster_status, mock_conn): '''Test the waiter is only once when ...
TestNeptuneStopClusterOperator
python
django__django
tests/generic_views/views.py
{ "start": 3974, "end": 4299 }
class ____(generic.UpdateView): get_form_called_count = 0 # Used to ensure get_form() is called once. model = Author success_url = "/list/authors/" fields = "__all__" def get_form(self, *args, **kwargs): self.get_form_called_count += 1 return super().get_form(*args, **kwargs)
AuthorUpdate
python
python__mypy
mypy/test/teststubtest.py
{ "start": 2668, "end": 2775 }
class ____: __module__: str def __init__(self) -> None: pass def __repr__(self) -> str: pass
object
python
jazzband__django-formtools
tests/wizard/wizardtests/tests.py
{ "start": 590, "end": 10670 }
class ____: def setUp(self): self.testuser, created = User.objects.get_or_create(username='testuser1') # Get new step data, since we modify it during the tests. self.wizard_step_data = copy.deepcopy(self.wizard_step_data) self.wizard_step_data[0]['form1-user'] = self.testuser.pk ...
WizardTests
python
tensorflow__tensorflow
tensorflow/compiler/tests/sort_ops_test.py
{ "start": 1465, "end": 14737 }
class ____(xla_test.XLATestCase, parameterized.TestCase): def _assertOpOutputMatchesExpected(self, op, args, expected): """Tests that op(*args) == expected.""" with self.session() as session: with self.test_scope(): placeholders = [ array_ops.placeholder(dtypes.as_dtype(arg.dtype), ...
XlaSortOpTest
python
plotly__plotly.py
plotly/figure_factory/_candlestick.py
{ "start": 7816, "end": 10038 }
class ____(object): """ Refer to FigureFactory.create_candlestick() for docstring. """ def __init__(self, open, high, low, close, dates, **kwargs): self.open = open self.high = high self.low = low self.close = close if dates is not None: self.x = date...
_Candlestick
python
apache__airflow
providers/mysql/src/airflow/providers/mysql/transfers/presto_to_mysql.py
{ "start": 1155, "end": 3331 }
class ____(BaseOperator): """ Moves data from Presto to MySQL. Note that for now the data is loaded into memory before being pushed to MySQL, so this operator should be used for smallish amount of data. :param sql: SQL query to execute against Presto. (templated) :param mysql_table: target MyS...
PrestoToMySqlOperator
python
getsentry__sentry
tests/sentry/notifications/utils/test_participants.py
{ "start": 2740, "end": 4927 }
class ____(_ParticipantsTest): def get_send_to_member( self, project: Project | None = None, user_id: int | None = None ) -> Mapping[ExternalProviders, set[Actor]]: return get_send_to( project=project or self.project, target_type=ActionTargetType.MEMBER, targe...
GetSendToMemberTest
python
miyuchina__mistletoe
mistletoe/contrib/scheme.py
{ "start": 377, "end": 905 }
class ____(span_token.SpanToken): @classmethod def find(cls, string): matches = [] start = [] for i, c in enumerate(string): if c == '(': start.append(i) elif c == ')': pos = start.pop() end_pos = i + 1 ...
Expr
python
huggingface__transformers
src/transformers/models/aimv2/modeling_aimv2.py
{ "start": 3924, "end": 4647 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Aimv2RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_...
Aimv2RMSNorm
python
joke2k__faker
faker/providers/address/fi_FI/__init__.py
{ "start": 45, "end": 16654 }
class ____(AddressProvider): building_number_formats = ("###", "##", "#") postcode_formats = ("#####",) city_formats = ("{{city_name}}",) street_name_formats = ("{{street_prefix}}{{street_suffix}}",) street_address_formats = ("{{street_name}} {{building_number}}",) address_formats = ("{{str...
Provider
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/response_model/tutorial001_py39.py
{ "start": 128, "end": 1085 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thr...
Hero
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 9181, "end": 9317 }
class ____(PipError): """Raised when the most up-to-date version of a package is already installed."""
BestVersionAlreadyInstalled
python
readthedocs__readthedocs.org
readthedocs/doc_builder/backends/sphinx.py
{ "start": 7034, "end": 7200 }
class ____(HtmlBuilder): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sphinx_builder = "singlehtml"
SingleHtmlBuilder
python
sympy__sympy
sympy/physics/vector/printing.py
{ "start": 552, "end": 1417 }
class ____(StrPrinter): """String Printer for vector expressions. """ def _print_Derivative(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t if (bool(sum(i == t for i in e.variables)) & isinstance(type(e.args[0]), UndefinedFunctio...
VectorStrPrinter
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/definition_metadata.py
{ "start": 606, "end": 708 }
class ____: name: str description: Optional[str] source: Optional[str] @record
DgJobMetadata
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 136109, "end": 137545 }
class ____: def test_fancy_indexing_ndarray(self): IandJ = [ (np.array([[1], [2], [3]]), np.array([3, 4, 2])), (np.array([[1], [2], [3]]), np.array([[3, 4, 2]])), (np.array([[1, 2, 3]]), np.array([[3], [4], [2]])), (np.array([1, 2, 3]), np.array([[3], [4], [2]...
_TestFancyMultidim
python
doocs__leetcode
solution/2100-2199/2195.Append K Integers With Minimal Sum/Solution.py
{ "start": 0, "end": 307 }
class ____: def minimalKSum(self, nums: List[int], k: int) -> int: nums.extend([0, 2 * 10**9]) nums.sort() ans = 0 for a, b in pairwise(nums): m = max(0, min(k, b - a - 1)) ans += (a + 1 + a + m) * m // 2 k -= m return ans
Solution
python
wandb__wandb
wandb/vendor/pygments/styles/friendly.py
{ "start": 402, "end": 2515 }
class ____(Style): """ A modern style based on the VIM pyte theme. """ background_color = "#f0f0f0" default_style = "" styles = { Whitespace: "#bbbbbb", Comment: "italic #60a0b0", Comment.Preproc: "noitalic #007020", Co...
FriendlyStyle
python
pytorch__pytorch
torch/distributed/checkpoint/planner.py
{ "start": 2586, "end": 10408 }
class ____(abc.ABC): """ Abstract class defining the protocol used by save_state_dict to plan the save process. SavePlanners are stateful objects that can be used to customize the whole save process. SavePlanner acts as an access proxy to the state_dict, so any transformation done to it will be vi...
SavePlanner
python
django__django
django/db/models/sql/where.py
{ "start": 11689, "end": 11898 }
class ____: """A node that matches nothing.""" contains_aggregate = False contains_over_clause = False def as_sql(self, compiler=None, connection=None): raise EmptyResultSet
NothingNode
python
yandexdataschool__Practical_RL
week09_policy_II/mujoco_wrappers.py
{ "start": 125, "end": 1949 }
class ____: """ Computes running mean and variance. Args: eps (float): a small constant used to initialize mean to zero and variance to 1. shape tuple(int): shape of the statistics. """ # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm def _...
RunningMeanVar
python
ray-project__ray
python/ray/_private/runtime_env/agent/runtime_env_agent.py
{ "start": 2201, "end": 6659 }
class ____: """ The URI reference table which is used for GC. When the reference count is decreased to zero, the URI should be removed from this table and added to cache if needed. """ def __init__( self, uris_parser: Callable[[RuntimeEnv], Tuple[str, UriType]], unus...
ReferenceTable
python
pytorch__pytorch
torch/ao/quantization/quantizer/quantizer.py
{ "start": 2857, "end": 3158 }
class ____(QuantizationSpecBase): """ Quantization spec for the Tensors whose quantization parameters are shared with other Tensors """ # the edge or node to share observer or fake quant instances with edge_or_node: EdgeOrNode @dataclass(eq=True, frozen=True)
SharedQuantizationSpec
python
aio-libs__aiohttp
aiohttp/streams.py
{ "start": 443, "end": 506 }
class ____(Exception): """eof stream indication."""
EofStream
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_scatter09.py
{ "start": 315, "end": 1589 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_scatter09.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.g...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/distribute/packed_distributed_variable_test.py
{ "start": 1944, "end": 6447 }
class ____(test.TestCase): def setUp(self): super(PackedDistributedVariableTest, self).setUp() cpus = config.list_physical_devices('CPU') # Set 2 virtual CPUs config.set_logical_device_configuration(cpus[0], [ context.LogicalDeviceConfiguration(), context.LogicalDeviceConfiguration(),...
PackedDistributedVariableTest
python
getsentry__sentry-python
tests/profiler/test_transaction_profiler.py
{ "start": 19503, "end": 24414 }
class ____(Scheduler): def setup(self): # type: () -> None pass def teardown(self): # type: () -> None pass def ensure_running(self): # type: () -> None pass current_thread = threading.current_thread() thread_metadata = { str(current_thread.ident): { ...
NoopScheduler
python
getsentry__sentry
src/sentry/integrations/slack/webhooks/event.py
{ "start": 1817, "end": 13187 }
class ____(SlackDMEndpoint): owner = ApiOwner.ECOSYSTEM publish_status = { "POST": ApiPublishStatus.PRIVATE, } """ XXX(dcramer): a lot of this is copied from sentry-plugins right now, and will need refactoring """ authentication_classes = () permission_classes = () slack_req...
SlackEventEndpoint
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 51604, "end": 56577 }
class ____(_TestNormBase): # Define the part for 2d arrays separately, so we can subclass this # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg. def test_matrix_empty(self): assert_equal(norm(np.array([[]], dtype=self.dt)), 0.0) def test_matrix_return_type(self): ...
_TestNorm2D
python
sphinx-doc__sphinx
sphinx/roles.py
{ "start": 14364, "end": 16155 }
class ____(SphinxRole): parens_re = re.compile(r'(\\\\|\\{|\\}|{|})') def run(self) -> tuple[list[Node], list[system_message]]: children = self.parse(self.text) node = nodes.literal( self.rawtext, '', *children, role=self.name.lower(), classes=[self.name] ) return [...
EmphasizedLiteral
python
huggingface__transformers
tests/models/deformable_detr/test_modeling_deformable_detr.py
{ "start": 7118, "end": 26515 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (DeformableDetrModel, DeformableDetrForObjectDetection) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": DeformableDetrModel, "object-detection": DeformableDetrForObjectDetect...
DeformableDetrModelTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callbackProtocol5.py
{ "start": 289, "end": 968 }
class ____(Protocol[P, R]): __name__: str other_attribute: int def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... def decorator1(f: Callable[P, R]) -> CallbackProto1[P, R]: converted = cast(CallbackProto1, f) print(converted.__name__) converted.other_attribute = 1 # This ...
CallbackProto1
python
streamlit__streamlit
lib/streamlit/testing/v1/local_script_runner.py
{ "start": 1596, "end": 6624 }
class ____(ScriptRunner): """Subclasses ScriptRunner to provide some testing features.""" def __init__( self, script_path: str, session_state: SafeSessionState, pages_manager: PagesManager, args: Any = None, kwargs: Any = None, ) -> None: """Initializ...
LocalScriptRunner
python
google__jax
tests/lax_numpy_test.py
{ "start": 5892, "end": 238540 }
class ____(jtu.JaxTestCase): """Tests for LAX-backed Numpy implementation.""" def _GetArgsMaker(self, rng, shapes, dtypes, np_arrays=True): def f(): out = [rng(shape, dtype or jnp.float_) for shape, dtype in zip(shapes, dtypes)] if np_arrays: return out return [jnp.asarra...
LaxBackedNumpyTests
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/processing_sam3_tracker_video.py
{ "start": 1640, "end": 38113 }
class ____(ProcessorMixin): r""" Constructs a SAM2 processor which wraps a SAM2 image processor and an 2D points & Bounding boxes processor into a single processor. [`Sam3TrackerVideoProcessor`] offers all the functionalities of [`Sam2ImageProcessorFast`] and [`Sam3TrackerVideoProcessor`]. See the docs...
Sam3TrackerVideoProcessor
python
tiangolo__fastapi
docs_src/extra_models/tutorial001_py310.py
{ "start": 88, "end": 204 }
class ____(BaseModel): username: str password: str email: EmailStr full_name: str | None = None
UserIn
python
laurentluce__python-algorithms
algorithms/tests/test_list.py
{ "start": 50, "end": 1742 }
class ____(unittest.TestCase): def setUp(self): pass def test_find_max_sub(self): bounds, m = [e for e in list.find_max_sub([-2, 3, -4, 5, 1, -5])] self.assertEqual(bounds, (3, 4)) self.assertEqual(m, 6) def test_find_int_first_half(self): idx = list.find_int(4, [1...
List
python
numba__numba
numba/tests/npyufunc/test_gufunc.py
{ "start": 5424, "end": 11613 }
class ____(MemoryLeakMixin, TestCase): target = 'cpu' def test_dynamic_matmul(self): def check_matmul_gufunc(gufunc, A, B, C): Gold = np.matmul(A, B) gufunc(A, B, C) np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8) gufunc = GUVectorize(matmulcore, ...
TestDynamicGUFunc
python
ipython__ipython
IPython/core/inputtransformer2.py
{ "start": 20701, "end": 28498 }
class ____: """Applies various transformations to a cell or code block. The key methods for external use are ``transform_cell()`` and ``check_complete()``. """ def __init__(self): self.cleanup_transforms = [ leading_empty_lines, leading_indent, classic_pr...
TransformerManager
python
pydata__xarray
asv_bench/benchmarks/groupby.py
{ "start": 5562, "end": 6419 }
class ____: def setup(self, use_cftime, use_flox): arr = np.random.randn(10, 10, 365 * 30) time = xr.date_range("2000", periods=30 * 365, use_cftime=use_cftime) # GH9426 - deep-copying CFTime object arrays is weirdly slow asda = xr.DataArray(time) labeled_time = [] f...
GroupByLongTime
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 95008, "end": 95086 }
class ____(_TestLinearFilter): dtype = 'complex64'
TestLinearFilterComplex64
python
PyCQA__pylint
doc/data/messages/n/non-parent-init-called/good.py
{ "start": 190, "end": 296 }
class ____(Vertebrate): def __init__(self): super().__init__() self.is_adorable = True
Cat
python
coleifer__peewee
peewee.py
{ "start": 166490, "end": 169649 }
class ____(object): def __init__(self, instance, name): self.instance = instance self.name = name value = self.instance.__data__.get(self.name) if not value: value = bytearray() elif not isinstance(value, bytearray): value = bytearray(value) se...
BigBitFieldData
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v3.py
{ "start": 8243, "end": 18180 }
class ____( tpu_values.TPUVariableMixin, values.DistributedVariable ): """A ShardedVariable class for Embedding tables on TPU.""" def _is_mirrored(self) -> bool: return False # Only support sharding on the first dimension. @property def shard_dim(self) -> int: return 0 @property def shape(s...
TPUEmbeddingShardedVariable
python
vyperlang__vyper
vyper/venom/memory_allocator.py
{ "start": 162, "end": 1831 }
class ____: # global state: # all allocated mems, mem_id => (ptr, size) allocated: dict[int, tuple[int, int]] # function => set of memlocs in that function # (free vars + union of all mems_used is equivalent to `allocated`) mems_used: dict[IRFunction, OrderedSet[IRAbstractMemLoc]] # mem...
MemoryAllocator
python
vyperlang__vyper
vyper/venom/passes/sccp/sccp.py
{ "start": 692, "end": 752 }
class ____: inst: IRInstruction @dataclass
SSAWorkListItem
python
paramiko__paramiko
paramiko/kex_gss.py
{ "start": 24217, "end": 24562 }
class ____: """ This class represents the Null Host Key for GSS-API Key Exchange as defined in `RFC 4462 Section 5 <https://tools.ietf.org/html/rfc4462.html#section-5>`_ """ def __init__(self): self.key = "" def __str__(self): return self.key def get_name(self): ...
NullHostKey
python
pytorch__pytorch
torch/_inductor/cudagraph_trees.py
{ "start": 27898, "end": 28174 }
class ____(OutputAliasInfo): "Marks that the graph output aliases an index in the new, returned outputs" __slots__ = ["index"] index: int def __init__(self, index: int) -> None: assert isinstance(index, int) self.index = index
AliasesNewOutput
python
getsentry__sentry
tests/sentry/notifications/utils/test_participants.py
{ "start": 4927, "end": 8512 }
class ____(_ParticipantsTest): def setUp(self) -> None: super().setUp() with assume_test_silo_mode(SiloMode.CONTROL): NotificationSettingProvider.objects.create( team_id=self.team.id, scope_type="team", scope_identifier=self.team.id, ...
GetSendToTeamTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 119603, "end": 119779 }
class ____(Float[_N]): """The SQL FLOAT type. .. seealso:: :class:`_types.Float` - documentation for the base type. """ __visit_name__ = "FLOAT"
FLOAT
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_bytes.py
{ "start": 207, "end": 299 }
class ____: def __bytes__(self): return "some bytes" # [invalid-bytes-return]
Str
python
langchain-ai__langchain
libs/cli/langchain_cli/integration_template/integration_template/chat_models.py
{ "start": 466, "end": 13999 }
class ____(BaseChatModel): # TODO: Replace all TODOs in docstring. See example docstring: # https://github.com/langchain-ai/langchain/blob/7ff05357bac6eaedf5058a2af88f23a1817d40fe/libs/partners/openai/langchain_openai/chat_models/base.py#L1120 """__ModuleName__ chat model integration. The default imple...
Chat__ModuleName__
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 222457, "end": 222768 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field(CheckStep, graphql_name="node")
CheckStepEdge
python
kamyu104__LeetCode-Solutions
Python/special-binary-string.py
{ "start": 169, "end": 628 }
class ____(object): def makeLargestSpecial(self, S): """ :type S: str :rtype: str """ result = [] anchor = count = 0 for i, v in enumerate(S): count += 1 if v == '1' else -1 if count == 0: result.append("1{}0".format(sel...
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/c_api_util_test.py
{ "start": 1869, "end": 3650 }
class ____(test_util.TensorFlowTestCase): def setUp(self): super(UniquePtrTest, self).setUp() class MockClass: def __init__(self): self.deleted = False def deleter(obj): obj.deleted = True self.obj = MockClass() self.deleter = deleter def testLifeCycle(self): self....
UniquePtrTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/events/__init__.py
{ "start": 72190, "end": 73194 }
class ____( NamedTuple( "_JobFailureData", [ ("error", Optional[SerializableErrorInfo]), ("failure_reason", Optional[RunFailureReason]), ("first_step_failure_event", Optional["DagsterEvent"]), ], ) ): def __new__( cls, error: Option...
JobFailureData
python
pandas-dev__pandas
pandas/plotting/_matplotlib/converter.py
{ "start": 10867, "end": 11079 }
class ____(mdates.AutoDateFormatter): def __init__(self, locator, tz=None, defaultfmt: str = "%Y-%m-%d") -> None: mdates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt)
PandasAutoDateFormatter
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 22361, "end": 22676 }
class ____(DifferentiableAOTOutput): """The mutated value of an input tensor, returned so we can appropriately propagate autograd.""" mutated_input: AOTInput def expr(self) -> str: return f"__input_mutation({self.mutated_input.expr()})" @dataclasses.dataclass(frozen=True)
InputMutationAOTOutput
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/types.py
{ "start": 2130, "end": 8930 }
class ____: """Model request information for the agent.""" model: BaseChatModel messages: list[AnyMessage] # excluding system message system_message: SystemMessage | None tool_choice: Any | None tools: list[BaseTool | dict] response_format: ResponseFormat | None state: AgentState r...
ModelRequest
python
ansible__ansible
test/units/module_utils/basic/test_set_cwd.py
{ "start": 351, "end": 5543 }
class ____: def test_set_cwd(self, monkeypatch): """make sure /tmp is used""" def mock_getcwd(): return '/tmp' def mock_access(path, perm): return True def mock_chdir(path): pass monkeypatch.setattr(os, 'getcwd', mock_getcwd) ...
TestAnsibleModuleSetCwd
python
sympy__sympy
sympy/polys/matrices/domainscalar.py
{ "start": 392, "end": 3778 }
class ____: r""" docstring """ def __new__(cls, element, domain): if not isinstance(domain, Domain): raise TypeError("domain should be of type Domain") if not domain.of_type(element): raise TypeError("element %s should be in domain %s" % (element, domain)) ...
DomainScalar
python
huggingface__transformers
src/transformers/models/donut/modeling_donut_swin.py
{ "start": 39883, "end": 42254 }
class ____(DonutSwinPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.donut = DonutSwinModel(config) # Classifier head self.classifier = ( nn.Linear(self.donut.num_features, config.num_labels) if conf...
DonutSwinForImageClassification
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/aiomysql.py
{ "start": 2232, "end": 2568 }
class ____( AsyncAdapt_dbapi_ss_cursor, AsyncAdapt_aiomysql_cursor ): __slots__ = () def _make_new_cursor( self, connection: AsyncIODBAPIConnection ) -> AsyncIODBAPICursor: return connection.cursor( self._adapt_connection.dbapi.aiomysql.cursors.SSCursor )
AsyncAdapt_aiomysql_ss_cursor
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/envs/unity_gym_env.py
{ "start": 12449, "end": 14060 }
class ____: """ Flattens branched discrete action spaces into single-branch discrete action spaces. """ def __init__(self, branched_action_space): """ Initialize the flattener. :param branched_action_space: A List containing the sizes of each branch of the action space, ...
ActionFlattener
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-reinitialize-a-permutation.py
{ "start": 41, "end": 841 }
class ____(object): def reinitializePermutation(self, n): """ :type n: int :rtype: int """ # reference: https://cp-algorithms.com/algebra/discrete-log.html def discrete_log(a, b, m): a %= m b %= m n = int(m**0.5)+1 an = ...
Solution
python
readthedocs__readthedocs.org
readthedocs/api/v2/permissions.py
{ "start": 554, "end": 785 }
class ____(permissions.BasePermission): """Allow read-only access to authenticated and anonymous users.""" def has_permission(self, request, view): return request.method in permissions.SAFE_METHODS
ReadOnlyPermission
python
numba__numba
numba/core/generators.py
{ "start": 1489, "end": 7985 }
class ____(object): """ Base support class for lowering generators. """ def __init__(self, lower): self.context = lower.context self.fndesc = lower.fndesc self.library = lower.library self.func_ir = lower.func_ir self.lower = lower self.geninfo = lower.g...
BaseGeneratorLower
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/decl_api.py
{ "start": 15576, "end": 19907 }
class ____(declared_attr[_T]): kw: Dict[str, Any] def __init__(self, **kw: Any): self.kw = kw @hybridmethod def _stateful(self, **kw: Any) -> _stateful_declared_attr[_T]: new_kw = self.kw.copy() new_kw.update(kw) return _stateful_declared_attr(**new_kw) def __call_...
_stateful_declared_attr
python
joke2k__faker
tests/providers/test_credit_card.py
{ "start": 248, "end": 3532 }
class ____: """Test credit card provider methods""" mastercard_pattern: Pattern = re.compile( r"(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}", ) visa_pattern: Pattern = re.compile(r"4[0-9]{12}([0-9]{3}){0,2}") discover_pattern: Pattern = re.compile(r"6(?...
TestCreditCardProvider
python
coleifer__peewee
tests/libs/mock.py
{ "start": 9546, "end": 10535 }
class ____: pass ClassType = type(OldStyleClass) def _copy(value): if type(value) in (dict, list, tuple, set): return type(value)(value) return value ClassTypes = (type,) if not inPy3k: ClassTypes = (type, ClassType) _allowed_names = set( [ 'return_value', '_mock_return_value', ...
OldStyleClass
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 4350, "end": 5731 }
class ____: key: str pattern: str def matches_frame( self, frames: list[MatchFrame], idx: int, exception_data: dict[str, Any], cache: ReturnValueCache, ) -> bool: raise NotImplementedError() @property def description(self) -> str: raise N...
EnhancementMatch
python
tensorflow__tensorflow
tensorflow/python/distribute/one_device_strategy_test.py
{ "start": 1496, "end": 6539 }
class ____( strategy_test_lib.DistributionTestBase, strategy_test_lib.OneDeviceDistributionTestBase): def testMinimizeLoss(self, distribution): if context.executing_eagerly(): self._test_minimize_loss_eager(distribution) else: self._test_minimize_loss_graph(distribution) def testReplic...
OneDeviceStrategyTest
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/package_entry.py
{ "start": 4119, "end": 5033 }
class ____: """A manifest of all components in a package. This is used to generate the component registry and to validate that the package entry point is valid. """ modules: Sequence[str] # List of modules scanned objects: Sequence[EnvRegistryObjectSnap] def merge(self, other: "EnvRegist...
EnvRegistryManifest