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
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 3665, "end": 3830 }
class ____(Rule, ABC): """A simple rule that does not depend on other rules""" def contains_dont_know(self) -> bool: return False @dataclass
AtomicRule
python
kamyu104__LeetCode-Solutions
Python/n-queens.py
{ "start": 36, "end": 1293 }
class ____(object): def solveNQueens(self, n): """ :type n: int :rtype: List[List[str]] """ def dfs(row): if row == n: result.append(map(lambda x: '.'*x + "Q" + '.'*(n-x-1), curr)) return for i in xrange(n): ...
Solution
python
py-pdf__pypdf
pypdf/annotations/_markup_annotations.py
{ "start": 4647, "end": 5890 }
class ____(MarkupAnnotation): def __init__( self, p1: Vertex, p2: Vertex, rect: Union[RectangleObject, tuple[float, float, float, float]], text: str = "", **kwargs: Any, ) -> None: super().__init__(**kwargs) self.update( { ...
Line
python
pytransitions__transitions
tests/test_experimental.py
{ "start": 735, "end": 9022 }
class ____(TestCase): def setUp(self) -> None: self.machine_cls = Machine # type: Type[Machine] self.create_trigger_class() def create_trigger_class(self): @with_model_definitions class TriggerMachine(self.machine_cls): # type: ignore pass self.trigger_ma...
TestExperimental
python
pdm-project__pdm
src/pdm/_types.py
{ "start": 3569, "end": 4259 }
class ____(NamedTuple): name: str version: str summary: str SearchResults = list[SearchResult] if TYPE_CHECKING: from typing import Required, TypedDict class Comparable(Protocol): def __lt__(self, __other: Any) -> bool: ... SpinnerT = TypeVar("SpinnerT", bound="Spinner") class...
SearchResult
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 55228, "end": 55762 }
class ____(PyConstNode): # The constant value None is_none = 1 value = "Py_None" constant_result = None def compile_time_value(self, denv): return None def may_be_none(self): return True def coerce_to(self, dst_type, env): if not (dst_type.is_pyobject or dst_typ...
NoneNode
python
ray-project__ray
rllib/examples/rl_modules/classes/autoregressive_actions_rlm.py
{ "start": 666, "end": 4697 }
class ____(TorchRLModule, ValueFunctionAPI): """An RLModule that uses an autoregressive action distribution. Actions are sampled in two steps. The first (prior) action component is sampled from a categorical distribution. Then, the second (posterior) action component is sampled from a posterior distrib...
AutoregressiveActionsRLM
python
PrefectHQ__prefect
src/prefect/input/run_input.py
{ "start": 8657, "end": 9910 }
class ____(BaseRunInput): @classmethod def receive( cls, timeout: Optional[float] = 3600, poll_interval: float = 10, raise_timeout_error: bool = False, exclude_keys: Optional[Set[str]] = None, key_prefix: Optional[str] = None, flow_run_id: Optional[UUID] =...
RunInput
python
getsentry__sentry
src/sentry/middleware/auth.py
{ "start": 2179, "end": 3860 }
class ____(MiddlewareMixin): def process_request(self, request: HttpRequest) -> None: if request.path.startswith("/api/0/internal/rpc/"): # Avoid doing RPC authentication when we're already # in an RPC request. request.user, request.auth = AnonymousUser(), None ...
AuthenticationMiddleware
python
realpython__materials
python-callable-instances/cumulative_average.py
{ "start": 159, "end": 351 }
class ____: def __init__(self): self.data = [] def __call__(self, new_value): self.data.append(new_value) return sum(self.data) / len(self.data)
CumulativeAverager
python
great-expectations__great_expectations
great_expectations/expectations/metrics/query_metric_provider.py
{ "start": 1125, "end": 1329 }
class ____(TypeError): def __init__(self, parameter_name: str, expected_type: type): super().__init__(f"`{parameter_name}` must be provided as type `{expected_type}`.")
InvalidParameterTypeError
python
getsentry__sentry
tests/sentry/deletions/test_apiapplication.py
{ "start": 766, "end": 2664 }
class ____(TransactionTestCase, HybridCloudTestMixin): def test_simple(self) -> None: app = ApiApplication.objects.create( owner=self.user, status=ApiApplicationStatus.pending_deletion ) ApiToken.objects.create(application=app, user=self.user, scopes=0) ApiGrant.objects.c...
DeleteApiApplicationTest
python
mlflow__mlflow
tests/utils/test_gorilla.py
{ "start": 50, "end": 5386 }
class ____: def __init__(self, delegated_fn): self.delegated_fn = delegated_fn def __get__(self, instance, owner): return self.delegated_fn def delegate(delegated_fn): return lambda fn: Delegator(delegated_fn) def gen_class_A_B(): class A: def f1(self): pass ...
Delegator
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 55185, "end": 55902 }
class ____(Block): type: str = field(repr=False) proto: BlockProto.Expandable = field(repr=False) icon: str label: str def __init__(self, proto: BlockProto.Expandable, root: ElementTree) -> None: self.children = {} self.proto = proto self.root = root self.type = "sta...
Status
python
getsentry__sentry
src/sentry/apidocs/hooks.py
{ "start": 813, "end": 3253 }
class ____(TypedDict): methods: HTTP_METHODS_SET PUBLIC_ENDPOINTS: dict[str, EndpointRegistryType] = {} _DEFINED_TAG_SET = {t["name"] for t in OPENAPI_TAGS} _OWNERSHIP_FILE = "api_ownership_stats_dont_modify.json" # path prefixes to exclude # this is useful if we're duplicating an endpoint for legacy purposes #...
EndpointRegistryType
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_oklahoma_zip.py
{ "start": 747, "end": 1751 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_oklahoma_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pand...
ColumnValuesToBeValidOklahomaZip
python
getsentry__sentry
src/sentry/auth/services/auth/impl.py
{ "start": 1034, "end": 8185 }
class ____(AuthService): def get_organization_api_keys(self, *, organization_id: int) -> list[RpcApiKey]: return [ serialize_api_key(k) for k in ApiKey.objects.filter(organization_id=organization_id) ] def get_organization_key(self, *, key: str) -> RpcApiKey | None: try: ...
DatabaseBackedAuthService
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_integration_features.py
{ "start": 242, "end": 1434 }
class ____(APITestCase): endpoint = "sentry-api-0-integration-features" method = "GET" def setUp(self) -> None: self.user = self.create_user(email="cynthia@poke.mon") self.login_as(self.user) def test_returns_all_features(self) -> None: """ Tests that all of the default...
IntegrationFeaturesTest
python
huggingface__transformers
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
{ "start": 24266, "end": 29722 }
class ____(XLMRobertaPreTrainedModel): _no_split_modules = ["XLMRobertaEmbeddings", "XLMRobertaLayer"] def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init...
XLMRobertaModel
python
crytic__slither
slither/slithir/operations/internal_dynamic_call.py
{ "start": 648, "end": 2815 }
class ____( Call, OperationWithLValue ): # pylint: disable=too-many-instance-attributes def __init__( self, lvalue: Optional[Union[TemporaryVariableSSA, TemporaryVariable]], function: Union[LocalVariable, LocalIRVariable], function_type: FunctionType, ) -> None: asse...
InternalDynamicCall
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 401, "end": 480 }
class ____(NamedModel): line = models.LineStringField(srid=4269)
Interstate2D
python
celery__celery
t/unit/utils/test_local.py
{ "start": 170, "end": 394 }
class ____: def test_imports(self): assert try_import(__name__) def test_when_default(self): default = object() assert try_import('foobar.awqewqe.asdwqewq', default) is default
test_try_import
python
scipy__scipy
scipy/stats/_resampling.py
{ "start": 101934, "end": 106090 }
class ____(ResamplingMethod): """Configuration information for a bootstrap confidence interval. Instances of this class can be passed into the `method` parameter of some confidence interval methods to generate a bootstrap confidence interval. Attributes ---------- n_resamples : int, optional ...
BootstrapMethod
python
allegroai__clearml
clearml/backend_api/services/v2_23/projects.py
{ "start": 117730, "end": 119953 }
class ____(Response): """ Response of projects.get_project_tags endpoint. :param tags: The list of unique tag values :type tags: Sequence[str] :param system_tags: The list of unique system tag values. Returned only if 'include_system' is set to 'true' in the request :type system_tags: S...
GetProjectTagsResponse
python
cython__cython
Cython/Compiler/TypeSlots.py
{ "start": 16544, "end": 18915 }
class ____(InternalMethodSlot): # Descriptor for tp_new and tp_dealloc. def __init__(self, slot_name, method=None, **kargs): InternalMethodSlot.__init__(self, slot_name, **kargs) self.method = method def _needs_own(self, scope): if (scope.parent_type.base_type and ...
ConstructorSlot
python
langchain-ai__langchain
libs/core/langchain_core/tools/base.py
{ "start": 45715, "end": 52107 }
class ____(InjectedToolArg): """Annotation for injecting the tool call ID. This annotation is used to mark a tool parameter that should receive the tool call ID at runtime. ```python from typing import Annotated from langchain_core.messages import ToolMessage from langchain_core.tools impo...
InjectedToolCallId
python
encode__django-rest-framework
tests/test_testing.py
{ "start": 1522, "end": 2469 }
class ____(serializers.Serializer): flag = fields.BooleanField(default=lambda: True) @api_view(['POST']) @parser_classes((parsers.JSONParser,)) def post_json_view(request): return Response(request.data) @api_view(['DELETE']) @renderer_classes((renderers.JSONRenderer, )) def delete_json_view(request): re...
BasicSerializer
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_comm_hooks.py
{ "start": 1202, "end": 2302 }
class ____(nn.Module): def __init__(self, has_wrapping, sharding_strategy, mixed_precision=None): # to ensure determinism torch.manual_seed(0) torch.get_device_module(device_type).manual_seed(0) super().__init__() if has_wrapping: self.net = FSDP( ...
Net
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws_tests/ecs_tests/stubbed_ecs.py
{ "start": 2763, "end": 20924 }
class ____: """A class that stubs ECS responses using botocore's Stubber: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/stubber.html. Stubs are minimally sufficient for testing existing Dagster ECS behavior; consequently, not all endpoints are stubbed and not all stubbed endpoint...
StubbedEcs
python
numpy__numpy
numpy/ma/tests/test_core.py
{ "start": 40852, "end": 79127 }
class ____: # Base test class for MaskedArrays. def _create_data(self): # Base data definition. x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1...
TestMaskedArrayArithmetic
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 694703, "end": 695103 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("MarketplaceListing", grap...
MarketplaceListingEdge
python
pdm-project__pdm
src/pdm/pytest.py
{ "start": 1580, "end": 1712 }
class ____(IteratorByteStream): def close(self) -> None: self._stream.close() # type: ignore[attr-defined]
FileByteStream
python
coleifer__peewee
playhouse/reflection.py
{ "start": 5006, "end": 7357 }
class ____(object): column_map = {} extension_import = '' def __init__(self, database): self.database = database self.requires_extension = False def execute(self, sql, *params): return self.database.execute_sql(sql, params) def get_columns(self, table, schema=None): ...
Metadata
python
coleifer__peewee
tests/models.py
{ "start": 162474, "end": 162717 }
class ____(TestModel): heading = ForeignKeyField('self', backref='tasks', null=True) project = ForeignKeyField('self', backref='projects', null=True) title = TextField() type = IntegerField() PROJECT = 1 HEADING = 2
Task
python
ray-project__ray
python/ray/data/_internal/iterator/stream_split_iterator.py
{ "start": 952, "end": 4448 }
class ____(DataIterator): """Implements a collection of iterators over a shared data stream.""" @staticmethod def create( base_dataset: "Dataset", n: int, locality_hints: Optional[List[NodeIdStr]], ) -> List["StreamSplitDataIterator"]: """Create a split iterator from the...
StreamSplitDataIterator
python
walkccc__LeetCode
solutions/139. Word Break/139-4.py
{ "start": 0, "end": 557 }
class ____: def wordBreak(self, s: str, wordDict: list[str]) -> bool: n = len(s) maxLength = len(max(wordDict, key=len)) wordSet = set(wordDict) # dp[i] := True if s[0..i) can be segmented dp = [True] + [False] * n for i in range(1, n + 1): for j in range(i - 1, -1, -1): if i - ...
Solution
python
ansible__ansible
test/units/cli/test_galaxy.py
{ "start": 1675, "end": 10956 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): """creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested.""" # class data for easy viewing: role_dir, role_tar, role_name, role_req, role_path cls.temp_dir = tem...
TestGalaxy
python
scipy__scipy
scipy/signal/tests/test_waveforms.py
{ "start": 7956, "end": 10292 }
class ____: def test_sweep_poly_quad1(self): p = np.poly1d([1.0, 0.0, 1.0]) t = np.linspace(0, 3.0, 10000) phase = waveforms._sweep_poly_phase(t, p) tf, f = compute_frequency(t, phase) expected = p(tf) abserr = np.max(np.abs(f - expected)) assert abserr < 1e-...
TestSweepPoly
python
Textualize__textual
src/textual/widgets/_progress_bar.py
{ "start": 5173, "end": 5791 }
class ____(Label): """A label to display the percentage status of the progress bar.""" DEFAULT_CSS = """ PercentageStatus { width: 5; content-align-horizontal: right; } """ percentage: reactive[int | None] = reactive[Optional[int]](None) """The percentage of progress that h...
PercentageStatus
python
Netflix__metaflow
metaflow/plugins/env_escape/configurations/test_lib_impl/test_lib.py
{ "start": 3046, "end": 3570 }
class ____(object): def __init__(self, value, stride, count): self._mylist = [value + stride * i for i in range(count)] def something(self, val): return "Test2:Something:%s" % val def __iter__(self): self._pos = 0 return self def __next__(self): if self._pos < ...
TestClass2
python
kamyu104__LeetCode-Solutions
Python/cinema-seat-allocation.py
{ "start": 819, "end": 1734 }
class ____(object): def maxNumberOfFamilies(self, n, reservedSeats): """ :type n: int :type reservedSeats: List[List[int]] :rtype: int """ reservedSeats.sort() result, i = 2*n, 0 while i < len(reservedSeats): reserved = [False]*3 ...
Solution2
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_square_free_number.py
{ "start": 1831, "end": 4145 }
class ____(ColumnMapExpectation): """Expect column values to be valid square-free numbers.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_square_free_numb...
ExpectColumnValuesToBeValidSquareFreeNumber
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 874696, "end": 875965 }
class ____(VegaLiteSchema): """ Position schema wrapper. A Position is an array of coordinates. https://tools.ietf.org/html/rfc7946#section-3.1.1 Array should contain between two and three elements. The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M v...
Position
python
tensorflow__tensorflow
tensorflow/python/util/tf_stack.py
{ "start": 3168, "end": 3623 }
class ____(StackTraceTransform): """Allows filtering traceback information by removing superfluous frames.""" _stack_dict = _source_filter_stacks def __init__(self): self.internal_set = _tf_stack.PyBindFileSet() def update(self): self.internal_set.update_to(set(self.get_filtered_filenames())) def g...
StackTraceFilter
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_one_hot_op_test.py
{ "start": 1329, "end": 7727 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ # 2D Indices (ragged_rank=1) dict(indices=[[0, 2, -1], [3]], depth=4, expected=[[[1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]], [[0, 0, 0, 1]]]), dict(indices=[[0, 2,...
RaggedOneHotTest
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called.py
{ "start": 906, "end": 1122 }
class ____(ParentWithoutInit, GrandParentWithInit): """Since ParentWithoutInit calls GrandParentWithInit it doesn't need to be called.""" def __init__(self): GrandParentWithInit.__init__(self)
ChildOne
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 916, "end": 12745 }
class ____(MaskedArraySetup): @pytest.mark.parametrize( "ufunc", (np.add, np.subtract, np.divide, np.arctan2, np.minimum) ) @pytest.mark.parametrize("a, b", [("ma", "mb"), ("ma", "b"), ("a", "mb")]) def test_2op_ufunc(self, ufunc, a, b): a, b = getattr(self, a), getattr(self, b) ...
MaskedUfuncTests
python
getsentry__sentry
tests/apidocs/endpoints/events/test_group_events.py
{ "start": 926, "end": 1309 }
class ____(ProjectGroupEventBase): def setUp(self) -> None: super().setUp() self.url = f"/api/0/organizations/{self.organization.slug}/issues/{self.group_id}/events/" def test_get(self) -> None: response = self.client.get(self.url) request = RequestFactory().get(self.url) ...
ProjectGroupEventsDocs
python
huggingface__transformers
src/transformers/models/bart/modeling_bart.py
{ "start": 70952, "end": 75749 }
class ____(BartPreTrainedModel, GenerationMixin): _tied_weights_keys = { "lm_head.weight": "model.decoder.embed_tokens.weight", } def __init__(self, config): config.is_decoder = True config.is_encoder_decoder = False super().__init__(config) self.model = BartDecoderW...
BartForCausalLM
python
scipy__scipy
scipy/linalg/tests/test_special_matrices.py
{ "start": 17897, "end": 22181 }
class ____: cases = [ (1, array([[1]]), array([[1]])), (2, array([[1, 1], [1, 2]]), array([[1, 0], [1, 1]])), (3, array([[1, 1, 1], [1, 2, 3], [1, 3, 6]]), array([[1, 0, 0], ...
TestPascal
python
pypa__pip
src/pip/_vendor/distlib/resources.py
{ "start": 498, "end": 2035 }
class ____(Cache): def __init__(self, base=None): if base is None: # Use native string to avoid issues on 2.x: see Python #20140. base = os.path.join(get_cache_base(), str('resource-cache')) super(ResourceCache, self).__init__(base) def is_stale(self, resource, path): ...
ResourceCache
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/skip_analysis.py
{ "start": 262, "end": 558 }
class ____: def taint_here(self, x): _test_sink(x) def tito_here(self, x): return x def no_issue_due_to_skip(): x = _test_source() skip = SkipMe() skip.taint_here(x) _test_sink(skip.tito_here(x)) # No issue in top level _test_sink(_test_source())
SkipMe
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 35087, "end": 35154 }
class ____(RedirectSerializerBase): pass
RedirectCreateSerializer
python
pandas-dev__pandas
asv_bench/benchmarks/stat_ops.py
{ "start": 4380, "end": 4685 }
class ____: params = [] param_names = [] def setup(self): self.s = pd.Series(np.random.randn(100000)) self.s2 = pd.Series(np.random.randn(100000)) def time_cov_series(self): self.s.cov(self.s2) from .pandas_vb_common import setup # noqa: F401 isort:skip
Covariance
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 454316, "end": 456090 }
class ____(sgqlc.types.Interface): """Things that can be starred.""" __schema__ = github_schema __field_names__ = ("id", "stargazer_count", "stargazers", "viewer_has_starred") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") stargazer_count = sgqlc.types.Field(sgqlc.types.non_nu...
Starrable
python
numpy__numpy
numpy/distutils/tests/test_exec_command.py
{ "start": 3357, "end": 7381 }
class ____: def setup_method(self): self.pyexe = get_pythonexe() def check_nt(self, **kws): s, o = exec_command.exec_command('cmd /C echo path=%path%') assert_(s == 0) assert_(o != '') s, o = exec_command.exec_command( '"%s" -c "import sys;sys.stderr.write(sys....
TestExecCommand
python
coleifer__peewee
tests/manytomany.py
{ "start": 276, "end": 452 }
class ____(TestModel): text = TextField() users = ManyToManyField(User) NoteUserThrough = Note.users.get_through_model() AltThroughDeferred = DeferredThroughModel()
Note
python
cython__cython
tests/run/withstat_py27.py
{ "start": 1924, "end": 2404 }
class ____(object): def __init__(self, value=None, gobble=False): if value is None: value = self self.value = value self.gobble = gobble self.enter_called = False self.exit_called = False def __enter__(self): self.enter_called = True return se...
Dummy
python
pypa__pip
src/pip/_vendor/rich/highlighter.py
{ "start": 1975, "end": 3543 }
class ____(RegexHighlighter): """Highlights the text typically produced from ``__repr__`` methods.""" base_style = "repr." highlights = [ r"(?P<tag_start><)(?P<tag_name>[-\w.:|]*)(?P<tag_contents>[\w\W]*)(?P<tag_end>>)", r'(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>"?[\w_]+"?)?', ...
ReprHighlighter
python
django__django
django/db/models/query_utils.py
{ "start": 10672, "end": 11199 }
class ____: """ Hook used in RegisterLookupMixin to return partial functions depending on the caller type (instance or class of models.Field). """ def __init__(self, class_method, instance_method): self.class_method = class_method self.instance_method = instance_method def __ge...
class_or_instance_method
python
getsentry__sentry
tests/sentry/releases/endpoints/test_project_release_commits.py
{ "start": 275, "end": 4365 }
class ____(APITestCase): endpoint = "sentry-api-0-project-release-commits" def setUp(self) -> None: super().setUp() self.project = self.create_project(name="foo") self.release = Release.objects.create( organization_id=self.project.organization_id, version="1" ) ...
ReleaseCommitsListTest
python
huggingface__transformers
src/transformers/models/idefics/modeling_idefics.py
{ "start": 3782, "end": 7667 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the lan...
IdeficsCausalLMOutputWithPast
python
encode__django-rest-framework
rest_framework/utils/formatting.py
{ "start": 2267, "end": 3015 }
class ____: """ Delay formatting until it's actually needed. Useful when the format string or one of the arguments is lazy. Not using Django's lazy because it is too slow. """ __slots__ = ('format_string', 'args', 'kwargs', 'result') def __init__(self, format_string, *args, **kwargs): ...
lazy_format
python
huggingface__transformers
src/transformers/models/longformer/modeling_longformer.py
{ "start": 62430, "end": 63096 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden stat...
LongformerPooler
python
huggingface__transformers
src/transformers/models/glm4v_moe/modeling_glm4v_moe.py
{ "start": 32444, "end": 37018 }
class ____(nn.Module): def __init__(self, config: Glm4vMoeVisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.num_patches = (self.image_size // self.pa...
Glm4vMoeVisionEmbeddings
python
TheAlgorithms__Python
data_structures/binary_tree/avl_tree.py
{ "start": 250, "end": 885 }
class ____: def __init__(self) -> None: self.data: list[Any] = [] self.head: int = 0 self.tail: int = 0 def is_empty(self) -> bool: return self.head == self.tail def push(self, data: Any) -> None: self.data.append(data) self.tail = self.tail + 1 def pop...
MyQueue
python
pytorch__pytorch
test/dynamo/test_structured_trace.py
{ "start": 1832, "end": 2357 }
class ____(logging.Filter): def __init__(self, match_name=None): self.match_name = match_name def filter(self, record): if "str" in record.metadata: return False if self.match_name is not None: if "artifact" in record.metadata: if self.match_name ...
StructuredTraceTestingFilter
python
pennersr__django-allauth
tests/apps/socialaccount/providers/shopify/tests.py
{ "start": 490, "end": 2303 }
class ____(OAuth2TestsMixin, TestCase): provider_id = ShopifyProvider.id def _complete_shopify_login(self, q, resp, resp_mock, with_refresh_token): complete_url = reverse(self.provider.id + "_callback") self.assertGreater(q["redirect_uri"][0].find(complete_url), 0) response_json = self....
ShopifyTests
python
jazzband__django-oauth-toolkit
tests/test_token_view.py
{ "start": 386, "end": 1093 }
class ____(TestCase): """ TestCase superclass for Authorized Token Views" Test Cases """ @classmethod def setUpTestData(cls): cls.foo_user = UserModel.objects.create_user("foo_user", "test@example.com", "123456") cls.bar_user = UserModel.objects.create_user("bar_user", "dev@example....
TestAuthorizedTokenViews
python
falconry__falcon
tests/test_httperror.py
{ "start": 4240, "end": 4366 }
class ____: def on_get(self, req, resp): raise falcon.HTTPNotFound(description='Not Found')
NotFoundResourceWithBody
python
astropy__astropy
astropy/io/fits/card.py
{ "start": 734, "end": 916 }
class ____: """Undefined value.""" def __init__(self): # This __init__ is required to be here for Sphinx documentation pass UNDEFINED = Undefined()
Undefined
python
sphinx-doc__sphinx
sphinx/util/cfamily.py
{ "start": 2811, "end": 2929 }
class ____(Exception): # Used to avoid implementing unneeded id generation for old id schemes. pass
NoOldIdError
python
kamyu104__LeetCode-Solutions
Python/flower-planting-with-no-adjacent.py
{ "start": 29, "end": 469 }
class ____(object): def gardenNoAdj(self, N, paths): """ :type N: int :type paths: List[List[int]] :rtype: List[int] """ result = [0]*N G = [[] for i in xrange(N)] for x, y in paths: G[x-1].append(y-1) G[y-1].append(x-1) ...
Solution
python
bokeh__bokeh
tests/unit/bokeh/document/test_document.py
{ "start": 2355, "end": 2609 }
class ____(SomeDataModel): prop3 = Int() prop4 = Int(default=112) prop5 = List(Int, default=[1, 2, 3, 4]) prop6 = Instance(SomeDataModel) prop7 = Nullable(Instance(SomeDataModel)) prop2 = Override(default=[4, 5, 6])
DerivedDataModel
python
mlflow__mlflow
dev/clint/src/clint/rules/test_name_typo.py
{ "start": 36, "end": 185 }
class ____(Rule): def _message(self) -> str: return "This function looks like a test, but its name does not start with 'test_'."
TestNameTypo
python
gevent__gevent
src/gevent/tests/test__threadpool.py
{ "start": 3210, "end": 3689 }
class ____(object): def __init__(self, the_func): self.func = the_func self.elapsed = None def __call__(self, *args, **kwds): t = time() try: return self.func(*args, **kwds) finally: self.elapsed = time() - t def sqr(x, wait=0.0): sleep(wai...
TimingWrapper
python
run-llama__llama_index
llama-index-core/llama_index/core/tools/query_engine.py
{ "start": 491, "end": 3668 }
class ____(AsyncBaseTool): """ Query engine tool. A tool making use of a query engine. Args: query_engine (BaseQueryEngine): A query engine. metadata (ToolMetadata): The associated metadata of the query engine. """ def __init__( self, query_engine: BaseQueryEn...
QueryEngineTool
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/teams.py
{ "start": 902, "end": 999 }
class ____(BaseModel): """Base serializer for Team.""" id: UUID name: str
TeamResponse
python
bokeh__bokeh
src/bokeh/models/renderers/tile_renderer.py
{ "start": 1466, "end": 2719 }
class ____(Renderer): ''' ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) tile_source = Instance(TileSource, default=InstanceDefault(WMTSTileSource), help=""" Local data source to use when rend...
TileRenderer
python
keras-team__keras
keras/src/layers/rnn/rnn_test.py
{ "start": 2077, "end": 16022 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basics(self): self.run_layer_test( layers.RNN, init_kwargs={"cell": OneStateRNNCell(5, state_size=5)}, input_shape=(3, 2, 4), expected_output_shape=(3, 5), expected_...
RNNTest
python
ansible__ansible
test/units/plugins/connection/test_ssh.py
{ "start": 13091, "end": 14898 }
class ____(object): def __init__(self): self.files_watched = 0 self.register = MagicMock(side_effect=self._register) self.unregister = MagicMock(side_effect=self._unregister) self.close = MagicMock() self.get_map = MagicMock() self.select = MagicMock() def _regis...
MockSelector
python
getsentry__sentry
src/sentry/migrations/0962_json_fields_too_big.py
{ "start": 628, "end": 2476 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
numba__numba
numba/tests/test_sysinfo.py
{ "start": 4925, "end": 5890 }
class ____(TestCase): def setUp(self): self.plat_spec_info = { 'Linux': { str: (nsi._libc_version,), }, 'Windows': { str: (nsi._os_spec_version,), }, 'Darwin': { str: (nsi._os_spec_version,), ...
TestPlatformSpecificInfo
python
numpy__numpy
numpy/_typing/_nested_sequence.py
{ "start": 289, "end": 2505 }
class ____(Protocol[_T_co]): """A protocol for representing nested sequences. Warning ------- `_NestedSequence` currently does not work in combination with typevars, *e.g.* ``def func(a: _NestedSequnce[T]) -> T: ...``. See Also -------- collections.abc.Sequence ABCs for read-on...
_NestedSequence
python
chroma-core__chroma
chromadb/api/rust.py
{ "start": 2102, "end": 22054 }
class ____(ServerAPI): bindings: chromadb_rust_bindings.Bindings hnsw_cache_size: int product_telemetry_client: ProductTelemetryClient def __init__(self, system: System): super().__init__(system) self.product_telemetry_client = self.require(ProductTelemetryClient) if platform.s...
RustBindingsAPI
python
facebook__pyre-check
client/configuration/configuration.py
{ "start": 2800, "end": 24740 }
class ____: binary: Optional[str] = None buck_mode: Optional[platform_aware.PlatformAware[str]] = field( default=None, metadata={"merge_policy": platform_aware.PlatformAware.merge_optional}, ) bxl_builder: Optional[str] = None only_check_paths: Sequence[str] = field( default_...
PartialConfiguration
python
kamyu104__LeetCode-Solutions
Python/partition-list.py
{ "start": 29, "end": 233 }
class ____(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next))
ListNode
python
huggingface__transformers
src/transformers/models/deepseek_vl/modular_deepseek_vl.py
{ "start": 5854, "end": 6254 }
class ____(JanusForConditionalGeneration): output_modalities = ("text",) def prepare_embeddings_for_image_generation(self): raise AttributeError("Not needed for DeepseekVL") def decode_image_tokens(self): raise AttributeError("Not needed for DeepseekVL") def generate(self): ra...
DeepseekVLForConditionalGeneration
python
jazzband__django-pipeline
pipeline/forms.py
{ "start": 292, "end": 3010 }
class ____: """A property that converts Pipeline packages to lists of files. This is used behind the scenes for any Media classes that subclass :py:class:`PipelineFormMedia`. When accessed, it converts any Pipeline packages into lists of media files and returns or forwards on lookups to that list. ...
PipelineFormMediaProperty
python
numba__numba
numba/core/byteflow.py
{ "start": 82391, "end": 82548 }
class ____(object): def __init__(self, blockinfo, offset): self.offset = offset self.body = tuple(i for i, _ in blockinfo.insts)
AdaptCFBlock
python
pydata__xarray
xarray/coding/variables.py
{ "start": 25102, "end": 25573 }
class ____(VariableCoder): # Convert Numpy 2 StringDType arrays to object arrays for backwards compatibility # TODO: remove this if / when we decide to allow StringDType arrays in Xarray def encode(self): raise NotImplementedError def decode(self, variable: Variable, name: T_Name = None) -> Var...
Numpy2StringDTypeCoder
python
crytic__slither
slither/utils/loc.py
{ "start": 404, "end": 3288 }
class ____: src: LoCInfo = field(default_factory=LoCInfo) dep: LoCInfo = field(default_factory=LoCInfo) test: LoCInfo = field(default_factory=LoCInfo) def to_pretty_table(self) -> MyPrettyTable: table = MyPrettyTable(["", "src", "dep", "test"]) table.add_row(["loc", str(self.src.loc), ...
LoC
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 25387, "end": 26064 }
class ____(RequestHandler): def get(self): # tests the validity of web.RequestHandler._VALID_HEADER_CHARS illegal_chars = [chr(o) for o in range(0, 0x20)] illegal_chars.append(chr(0x7F)) illegal_chars.remove("\t") for char in illegal_chars: try: se...
SetHeaderHandler
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_sequence.py
{ "start": 447, "end": 2645 }
class ____(fixtures.TablesTest): __only_on__ = "mssql" __backend__ = True @classmethod def define_tables(cls, metadata): Table( "int_seq_t", metadata, Column( "id", Integer, default=Sequence("int_seq", data_type=Integer()) ), ...
SequenceTest
python
tensorflow__tensorflow
tensorflow/python/distribute/tpu_values.py
{ "start": 1638, "end": 5529 }
class ____(object): """Mixin for TPU variables.""" def __init__(self, *args, **kwargs): super(TPUVariableMixin, self).__init__(*args, **kwargs) # Handle ID is needed for `get_replicated_var_handle` to cache the variables # correctly since in eager mode different variables can have the same name. i...
TPUVariableMixin
python
openai__gym
gym/wrappers/env_checker.py
{ "start": 377, "end": 2306 }
class ____(gym.Wrapper): """A passive environment checker wrapper that surrounds the step, reset and render functions to check they follow the gym API.""" def __init__(self, env): """Initialises the wrapper with the environments, run the observation and action space tests.""" super().__init__(e...
PassiveEnvChecker
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 150254, "end": 150744 }
class ____(AtomicExprNode): # Node created during analyse_types phase # of an ExceptClauseNode to fetch the current # exception value. def __init__(self, pos, type=py_object_type): AtomicExprNode.__init__(self, pos, type=type) def set_var(self, var): self.var = var def calc...
ExcValueNode
python
sympy__sympy
sympy/codegen/cfunctions.py
{ "start": 3976, "end": 5074 }
class ____(Function): """ Represents the exponential function with base two. Explanation =========== The benefit of using ``exp2(x)`` over ``2**x`` is that the latter is not as efficient under finite precision arithmetic. Examples ======== >>> from sympy.abc import x >>> ...
exp2
python
fastai__fastai
fastai/fp16_utils.py
{ "start": 2150, "end": 6957 }
class ____(nn.Module): """ Convert model to half precision in a batchnorm-safe way. """ def __init__(self, network): super(FP16Model, self).__init__() self.network = convert_network(network, dtype=torch.half) def forward(self, *inputs): inputs = tuple(t.half() for t in inpu...
FP16Model
python
pytorch__pytorch
torch/nn/parallel/_functions.py
{ "start": 174, "end": 1233 }
class ____(Function): @staticmethod def forward(ctx, target_gpus, *inputs): assert all(i.device.type != "cpu" for i in inputs), ( "Broadcast function not implemented for CPU tensors" ) target_gpus = [_get_device_index(x, True) for x in target_gpus] ctx.target_gpus = t...
Broadcast