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
pytest-dev__pytest-django
pytest_django_test/db_helpers.py
{ "start": 1152, "end": 5790 }
class ____: def __init__(self, status_code: int, std_out: bytes, std_err: bytes) -> None: self.status_code = status_code self.std_out = std_out self.std_err = std_err def run_cmd(*args: str, env: Mapping[str, str] | None = None) -> CmdResult: r = subprocess.Popen( args, ...
CmdResult
python
graphql-python__graphene
graphene/types/unmountedtype.py
{ "start": 46, "end": 2344 }
class ____(OrderedType): """ This class acts a proxy for a Graphene Type, so it can be mounted dynamically as Field, InputField or Argument. Instead of writing: .. code:: python from graphene import ObjectType, Field, String class MyObjectType(ObjectType): my_field = ...
UnmountedType
python
PyCQA__pylint
tests/test_similar.py
{ "start": 711, "end": 10212 }
class ____: def _runtest(self, args: list[str], code: int) -> None: """Runs the tests and sees if output code is as expected.""" out = StringIO() pylint_code = self._run_pylint(args, out=out) output = out.getvalue() msg = f"expected output status {code}, got {pylint_code}" ...
TestSymilarCodeChecker
python
ray-project__ray
rllib/models/tf/tf_action_dist.py
{ "start": 21402, "end": 25231 }
class ____(TFActionDistribution): """Action distribution that operates on a set of actions. Args: inputs (Tensor list): A list of tensors from which to compute samples. """ def __init__( self, inputs, model, *, child_distributions, input_lens, action_space, **kwargs ): Acti...
MultiActionDistribution
python
django__django
tests/multiple_database/models.py
{ "start": 1101, "end": 1357 }
class ____(models.Manager): def create(self, *args, extra_arg=None, **kwargs): return super().create(*args, **kwargs) def get_or_create(self, *args, extra_arg=None, **kwargs): return super().get_or_create(*args, **kwargs)
BookManager
python
spyder-ide__spyder
spyder/plugins/switcher/widgets/item.py
{ "start": 403, "end": 2590 }
class ____(QStandardItem): """Base List Item.""" _PADDING = 5 _WIDTH = 400 _TEMPLATE = None def __init__(self, parent=None, styles=None, use_score=True): """Create basic List Item.""" super().__init__() # Style self._width = self._WIDTH self._padding = self...
SwitcherBaseItem
python
kamyu104__LeetCode-Solutions
Python/longer-contiguous-segments-of-ones-than-zeros.py
{ "start": 29, "end": 439 }
class ____(object): def checkZeroOnes(self, s): """ :type s: str :rtype: bool """ max_cnt = [0]*2 cnt = 0 for i in xrange(len(s)+1): if i == len(s) or (i >= 1 and s[i] != s[i-1]): max_cnt[int(s[i-1])] = max(max_cnt[int(s[i-1])], cnt...
Solution
python
pallets__jinja
src/jinja2/ext.py
{ "start": 21310, "end": 25702 }
class ____(Extension): """A ``{% debug %}`` tag that dumps the available variables, filters, and tests. .. code-block:: html+jinja <pre>{% debug %}</pre> .. code-block:: text {'context': {'cycler': <class 'jinja2.utils.Cycler'>, ..., 'namespa...
DebugExtension
python
pypa__warehouse
tests/unit/manage/views/test_teams.py
{ "start": 30645, "end": 36307 }
class ____: @pytest.fixture def organization(self, _enable_organizations, pyramid_user): organization = OrganizationFactory.create() OrganizationRoleFactory.create( organization=organization, user=pyramid_user, role_name=OrganizationRoleType.Owner, ) ...
TestDeleteTeamProjectRole
python
spyder-ide__spyder
spyder/plugins/projects/widgets/main_widget.py
{ "start": 2648, "end": 42228 }
class ____(PluginMainWidget): """Project explorer main widget.""" # ---- PluginMainWidget API # ------------------------------------------------------------------------- SHOW_MESSAGE_WHEN_EMPTY = True IMAGE_WHEN_EMPTY = "projects" MESSAGE_WHEN_EMPTY = _("No project opened") DESCRIPTION_WHEN...
ProjectExplorerWidget
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/_internal/setup_teardown.py
{ "start": 14126, "end": 14690 }
class ____(BaseSetupTeardownContext): """Context manager for setup and teardown tasks.""" @staticmethod def add_task(task: AbstractOperator | PlainXComArg): """Add task to context manager.""" from airflow.sdk.definitions.xcom_arg import PlainXComArg if not SetupTeardownContext.acti...
SetupTeardownContext
python
gevent__gevent
src/gevent/libev/watcher.py
{ "start": 6492, "end": 6809 }
class ____(_base.AsyncMixin, watcher): def send(self): libev.ev_async_send(self.loop._ptr, self._watcher) @property def pending(self): return self._watcher is not None and bool(libev.ev_async_pending(self._watcher)) # Provide BWC for those that have async locals()['async'] = async_
async_
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-coins-you-can-get.py
{ "start": 52, "end": 277 }
class ____(object): def maxCoins(self, piles): """ :type piles: List[int] :rtype: int """ piles.sort() return sum(itertools.islice(piles, len(piles)//3, len(piles), 2))
Solution
python
doocs__leetcode
solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/Solution.py
{ "start": 0, "end": 230 }
class ____: def replaceElements(self, arr: List[int]) -> List[int]: mx = -1 for i in reversed(range(len(arr))): x = arr[i] arr[i] = mx mx = max(mx, x) return arr
Solution
python
ipython__ipython
IPython/lib/demo.py
{ "start": 22608, "end": 22653 }
class ____(ClearMixin,Demo): pass
ClearDemo
python
MongoEngine__mongoengine
tests/queryset/test_queryset_aggregation.py
{ "start": 278, "end": 13477 }
class ____(MongoDBTestCase): def test_read_preference_aggregation_framework(self): class Bar(Document): txt = StringField() meta = {"indexes": ["txt"]} # Aggregates with read_preference pipeline = [] bars = Bar.objects.read_preference( ReadPrefer...
TestQuerysetAggregate
python
ray-project__ray
python/ray/serve/_private/deployment_state.py
{ "start": 7413, "end": 41461 }
class ____: """Wraps a Ray actor for a deployment replica. This is primarily defined so that we can mock out actual Ray operations for unit testing. *All Ray API calls should be made here, not in DeploymentState.* """ def __init__( self, replica_id: ReplicaID, version:...
ActorReplicaWrapper
python
getsentry__sentry
src/sentry/feedback/lib/utils.py
{ "start": 156, "end": 1147 }
class ____(Enum): NEW_FEEDBACK_ENVELOPE = "new_feedback_envelope" USER_REPORT_DJANGO_ENDPOINT = "user_report_sentry_django_endpoint" USER_REPORT_ENVELOPE = "user_report_envelope" CRASH_REPORT_EMBED_FORM = "crash_report_embed_form" UPDATE_USER_REPORTS_TASK = "update_user_reports_task" @classmeth...
FeedbackCreationSource
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py
{ "start": 435, "end": 507 }
class ____: with ...: def __eq__(self, other): ...
MaybeEqWith
python
huggingface__transformers
src/transformers/models/edgetam_video/modular_edgetam_video.py
{ "start": 30768, "end": 30850 }
class ____(Sam2VideoTwoWayAttentionBlock): pass
EdgeTamVideoTwoWayAttentionBlock
python
doocs__leetcode
solution/3000-3099/3034.Number of Subarrays That Match a Pattern I/Solution.py
{ "start": 0, "end": 401 }
class ____: def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int: def f(a: int, b: int) -> int: return 0 if a == b else (1 if a < b else -1) ans = 0 for i in range(len(nums) - len(pattern)): ans += all( f(nums[i + k], nums[i + ...
Solution
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 17424, "end": 24210 }
class ____(BaseModel): """ Describes one Serve application, and currently can also be used as a standalone config to deploy a single application to a Ray cluster. """ name: str = Field( default=SERVE_DEFAULT_APP_NAME, description=( "Application name, the name should be u...
ServeApplicationSchema
python
pytorch__pytorch
tools/experimental/torchfuzz/codegen.py
{ "start": 7703, "end": 10398 }
class ____(FuzzTemplate): def __init__(self): from torchfuzz.checks import EagerVsFullGraphDynamicCompileCheck super().__init__( supported_ops=[ # Basic arithmetic operations "torch.add", "torch.sub", "torch.mul", ...
DefaultFuzzTemplate
python
airbytehq__airbyte
airbyte-integrations/connectors/source-younium/components.py
{ "start": 601, "end": 3593 }
class ____(NoAuth): config: Config username: Union[InterpolatedString, str] password: Union[InterpolatedString, str] legal_entity: Union[InterpolatedString, str] grant_type: Union[InterpolatedString, str] client_id: Union[InterpolatedString, str] scope: Union[InterpolatedString, str] _...
CustomYouniumAuthenticator
python
ultrajson__ultrajson
tests/fuzz.py
{ "start": 1987, "end": 2316 }
class ____(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): values = re.findall("[^: ]+", values) if len(values) == 1: values = (int(values[0]),) else: values = range(*map(int, values)) setattr(namespace, self.dest, values) ...
RangeOption
python
getsentry__sentry
src/sentry_plugins/amazon_sqs/plugin.py
{ "start": 1690, "end": 8048 }
class ____(CorePluginMixin, DataForwardingPlugin): title = "Amazon SQS" slug = "amazon-sqs" description = DESCRIPTION conf_key = "amazon-sqs" required_field = "queue_url" feature_descriptions = [ FeatureDescription( """ Forward Sentry errors and events to Amazon S...
AmazonSQSPlugin
python
huggingface__transformers
src/transformers/models/ijepa/modular_ijepa.py
{ "start": 3670, "end": 4462 }
class ____(ViTPreTrainedModel): @torch.no_grad() def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None: """Initialize the weights""" if isinstance(module, (nn.Linear, nn.Conv2d)): init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_ran...
IJepaPreTrainedModel
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 90902, "end": 91837 }
class ____(TestCase): @parametrize("nd", [0, 1, 2]) def test_nd(self, nd): # get an nd array with multiple elements in every dimension x = np.empty((2,) * nd, dtype=bool) # none x[...] = False assert_equal(np.argwhere(x).shape, (0, nd)) # only one x[...]...
TestArgwhere
python
kubernetes-client__python
kubernetes/client/models/v1beta2_counter_set.py
{ "start": 383, "end": 4953 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1beta2CounterSet
python
viewflow__viewflow
tests/workflow/test_context.py
{ "start": 90, "end": 709 }
class ____(TestCase): def test_activation_context_scope(self): with Context(first_scope='first_scope'): with Context(second_scope='second_scope'): self.assertEqual(context.first_scope, 'first_scope') self.assertEqual(context.second_scope, 'second_scope') ...
Test
python
gevent__gevent
src/gevent/resolver/dnspython.py
{ "start": 12975, "end": 20706 }
class ____(AbstractResolver): """ An *experimental* resolver that uses `dnspython`_. This is typically slower than the default threaded resolver (unless there's a cache hit, in which case it can be much faster). It is usually much faster than the c-ares resolver. It tends to scale well as more ...
Resolver
python
openai__openai-python
src/openai/resources/audio/translations.py
{ "start": 7422, "end": 13727 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncTranslationsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://w...
AsyncTranslations
python
PrefectHQ__prefect
tests/server/utilities/test_text_search_parser.py
{ "start": 14813, "end": 15549 }
class ____: """Test query validation (character limits enforced at API layer)""" def test_handles_very_long_queries(self): # Parser should handle long queries (limits enforced in EventFilter/LogFilter) long_query = "a" * 500 result = parse_text_search_query(long_query) assert re...
TestQueryValidation
python
walkccc__LeetCode
solutions/758. Bold Words in String/758-2.py
{ "start": 108, "end": 1233 }
class ____: def boldWords(self, words: list[str], s: str) -> str: n = len(s) ans = [] # bold[i] := True if s[i] should be bolded bold = [0] * n root = TrieNode() def insert(word: str) -> None: node = root for c in word: if c not in node.children: node.children[c]...
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 116577, "end": 118441 }
class ____(BaseModel, extra="forbid"): """ Search request. Holds all conditions and parameters for the search of most similar points by vector similarity given the filtering restrictions. """ shard_key: Optional["ShardKeySelector"] = Field( default=None, description="Specify in which sh...
SearchRequest
python
sqlalchemy__sqlalchemy
test/orm/test_lazy_relations.py
{ "start": 46242, "end": 48605 }
class ____(fixtures.MappedTest): """Test [issue:3145]. This involves an object that refers to itself, which isn't entirely a supported use case. Here, we're able to fix it, but long term it's not clear if future needs will affect this. The use case is not super-critical. """ @classmetho...
RefersToSelfLazyLoadInterferenceTest
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 8859, "end": 16129 }
class ____(JitBackendTestCase): """ Tests for the selective lowering API. """ class OuterModule(torch.nn.Module): def __init__(self, sub1, sub2, other): super().__init__() self.sub1 = sub1 self.sub2 = sub2 self.other = other def forward(s...
SelectiveLoweringTest
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 73238, "end": 73544 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) permission_level: Optional[PermissionLevel] = None service_principal_name: Optional[ServicePrincipalName] = None
AccessControlRequestForServicePrincipal
python
h5py__h5py
h5py/tests/test_dtype.py
{ "start": 14487, "end": 18686 }
class ____(TestCase): """ Test H5T_NATIVE_B8 reading """ def test_b8_bool(self): arr1 = np.array([False, True], dtype=bool) self._test_b8( arr1, expected_default_cast_dtype=np.uint8 ) self._test_b8( arr1, expected_default_...
TestBitfield
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
{ "start": 20402, "end": 30239 }
class ____: """Test composition of multiple wrap_model_call middleware.""" def test_two_middleware_composition(self) -> None: """Test that two middleware compose correctly (outer wraps inner).""" execution_order = [] class OuterMiddleware(AgentMiddleware): def wrap_model_ca...
TestMiddlewareComposition
python
tensorflow__tensorflow
tensorflow/python/eager/core.py
{ "start": 1411, "end": 1848 }
class ____(Exception): """Exception class to handle not ok Status.""" def __init__(self, message, code, payloads): super(_NotOkStatusException, self).__init__() self.message = message self.code = code self.payloads = payloads def __str__(self): e = _status_to_exception(self) return "%s: ...
_NotOkStatusException
python
getsentry__sentry
src/sentry/core/endpoints/scim/schemas.py
{ "start": 7161, "end": 7643 }
class ____(SCIMEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = (OrganizationSCIMMemberPermission,) def get(self, request: Request, *args: Any, **kwds: Any) -> Response: query_params = self.get_query_parameters(request) return Response( ...
OrganizationSCIMSchemaIndex
python
django__django
django/contrib/admindocs/views.py
{ "start": 8333, "end": 8702 }
class ____(BaseAdminDocsView): template_name = "admin_doc/model_index.html" def get_context_data(self, **kwargs): m_list = [ m._meta for m in apps.get_models() if user_has_model_view_permission(self.request.user, m._meta) ] return super().get_context_...
ModelIndexView
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 270631, "end": 271226 }
class ____(sgqlc.types.Input): """Autogenerated input type of RegenerateEnterpriseIdentityProviderRecoveryCodes """ __schema__ = github_schema __field_names__ = ("enterprise_id", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId") "...
RegenerateEnterpriseIdentityProviderRecoveryCodesInput
python
scipy__scipy
scipy/optimize/tests/test_bracket.py
{ "start": 1681, "end": 16047 }
class ____: @pytest.mark.parametrize("seed", (615655101, 3141866013, 238075752)) @pytest.mark.parametrize("use_xmin", (False, True)) @pytest.mark.parametrize("other_side", (False, True)) @pytest.mark.parametrize("fix_one_side", (False, True)) def test_nfev_expected(self, seed, use_xmin, other_side, ...
TestBracketRoot
python
hyperopt__hyperopt
hyperopt/rdists.py
{ "start": 257, "end": 901 }
class ____(rv_continuous): """Stats for Y = e^X where X ~ U(low, high).""" def __init__(self, low=0, high=1): rv_continuous.__init__(self, a=np.exp(low), b=np.exp(high)) self._low = low self._high = high def _rvs(self, *args, size=None, random_state=None): rval = np.exp(mtr...
loguniform_gen
python
pdm-project__pdm
src/pdm/resolver/providers.py
{ "start": 19793, "end": 21820 }
class ____(ReusePinProvider): """A specialized provider to handle an "eager" upgrade strategy. An eager upgrade tries to upgrade not only packages specified, but also their dependencies (recursively). This contrasts to the "only-if-needed" default, which only promises to upgrade the specified package, ...
EagerUpdateProvider
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 40093, "end": 40571 }
class ____(str, Enum): """Tracks the type of API that an application originates from.""" UNKNOWN = "unknown" IMPERATIVE = "imperative" DECLARATIVE = "declarative" @classmethod def get_valid_user_values(cls): """Get list of valid APIType values that users can explicitly pass. E...
APIType
python
getsentry__sentry
src/sentry/seer/endpoints/project_seer_preferences.py
{ "start": 2799, "end": 6074 }
class ____(ProjectEndpoint): permission_classes = ( ProjectEventPermission, # Anyone in the org should be able to set preferences, follows event permissions. ) publish_status = { "POST": ApiPublishStatus.EXPERIMENTAL, "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner....
ProjectSeerPreferencesEndpoint
python
django-compressor__django-compressor
compressor/tests/test_parsers.py
{ "start": 674, "end": 840 }
class ____(ParserTestCase, CompressorTestCase): parser_cls = "compressor.parser.LxmlParser" @unittest.skipIf(html5lib is None, "html5lib not found")
LxmlParserTests
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/multiple_models/tutorial001.py
{ "start": 134, "end": 344 }
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)
Hero
python
apache__thrift
lib/py/src/protocol/TMultiplexedProtocol.py
{ "start": 891, "end": 1457 }
class ____(TProtocolDecorator.TProtocolDecorator): def __init__(self, protocol, serviceName): self.serviceName = serviceName def writeMessageBegin(self, name, type, seqid): if (type == TMessageType.CALL or type == TMessageType.ONEWAY): super(TMultiplexedProtocol, sel...
TMultiplexedProtocol
python
dask__distributed
distributed/pytest_resourceleaks.py
{ "start": 4987, "end": 5397 }
class ____(ResourceChecker, name="memory"): LEAK_THRESHOLD = 10 * 2**20 def measure(self) -> int: return psutil.Process().memory_info().rss def has_leak(self, before: int, after: int) -> bool: return after > before + self.LEAK_THRESHOLD def format(self, before: int, after: int) -> str...
RSSMemoryChecker
python
protocolbuffers__protobuf
python/google/protobuf/internal/reflection_test.py
{ "start": 1456, "end": 2877 }
class ____(object): """Decodes a stream of values from a string. Once upon a time we actually had a class called decoder.Decoder. Then we got rid of it during a redesign that made decoding much, much faster overall. But a couple tests in this file used it to check that the serialized form of a message was c...
_MiniDecoder
python
pytorch__pytorch
torch/jit/_trace.py
{ "start": 2358, "end": 10757 }
class ____(torch.nn.Module): def __init__( self, inner, strict=True, force_outplace=False, return_inputs=False, return_inputs_states=False, ): super().__init__() # inner may be a Module, or it may be an arbitrary callable # If it's a Module...
ONNXTracedModule
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 84992, "end": 85579 }
class ____(torch.nn.Module): r"""We can skip quantization by explicitly setting qconfig of a submodule to None """ def __init__(self, qengine): super().__init__() self.qconfig = torch.ao.quantization.get_default_qconfig(qengine) self.sub = QuantWrapper(InnerModule()) sel...
AnnotatedSkipQuantModel
python
doocs__leetcode
solution/2400-2499/2426.Number of Pairs Satisfying Inequality/Solution.py
{ "start": 445, "end": 766 }
class ____: def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int: tree = BinaryIndexedTree(10**5) ans = 0 for a, b in zip(nums1, nums2): v = a - b ans += tree.query(v + diff + 40000) tree.update(v + 40000, 1) return ans
Solution
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 94924, "end": 95008 }
class ____(_TestLinearFilter): dtype = np.dtype('g')
TestLinearFilterFloatExtended
python
huggingface__transformers
src/transformers/models/gpt_oss/modeling_gpt_oss.py
{ "start": 19729, "end": 21189 }
class ____(PreTrainedModel): config: GptOssConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["GptOssDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = False _supports_flex_attn = True ...
GptOssPreTrainedModel
python
giampaolo__psutil
tests/test_bsd.py
{ "start": 16913, "end": 17411 }
class ____(PsutilTestCase): def test_boot_time(self): s = sysctl('kern.boottime') sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y") psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time()) assert sys_bt == psutil_bt # ============================================...
OpenBSDTestCase
python
getsentry__sentry
tests/sentry/core/endpoints/test_team_time_to_resolution.py
{ "start": 377, "end": 5428 }
class ____(APITestCase): endpoint = "sentry-api-0-team-time-to-resolution" def test_simple(self) -> None: project1 = self.create_project(teams=[self.team], slug="foo") project2 = self.create_project(teams=[self.team], slug="bar") group1 = self.create_group(project=project1, times_seen=1...
TeamTimeToResolutionTest
python
realpython__materials
directory-tree-generator-python/source_code_final/rptree/rptree.py
{ "start": 168, "end": 826 }
class ____: def __init__(self, root_dir, dir_only=False, output_file=sys.stdout): self._output_file = output_file self._generator = _TreeGenerator(root_dir, dir_only) def generate(self): tree = self._generator.build_tree() if self._output_file != sys.stdout: # Wrap t...
DirectoryTree
python
Textualize__textual
src/textual/widgets/_link.py
{ "start": 147, "end": 1952 }
class ____(Static, can_focus=True): """A simple, clickable link that opens a URL.""" DEFAULT_CSS = """ Link { width: auto; height: auto; min-height: 1; color: $text-accent; text-style: underline; &:hover { color: $accent; } &:focus { text-style: bold ...
Link
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 2752, "end": 6200 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "parent", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), ) Table( "association", ...
AutoFlushTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/objects.py
{ "start": 5625, "end": 5836 }
class ____(NamedTuple("_StepSuccessData", [("duration_ms", float)])): def __new__(cls, duration_ms): return super().__new__(cls, duration_ms=check.float_param(duration_ms, "duration_ms"))
StepSuccessData
python
ray-project__ray
release/serve_tests/workloads/serve_resnet_benchmark.py
{ "start": 1503, "end": 2509 }
class ____: def __init__(self, handle: DeploymentHandle, device="cpu"): self.model = models.resnet50(pretrained=True) self.model.eval().to(device) self.device = device self.handle = handle async def predict(self, uris: List[str]): preprocessing_tasks = [] for ur...
ImageObjectioner
python
PyCQA__pylint
tests/functional/n/no/no_self_argument.py
{ "start": 1380, "end": 1738 }
class ____: def __class_getitem__(cls, params): # This is actually a special method which is always a class method. # See https://www.python.org/dev/peps/pep-0560/#class-getitem pass def __class_other__(cls, params): # [no-self-argument] # This is not a special case and as suc...
Toto
python
Textualize__textual
src/textual/demo/home.py
{ "start": 7009, "end": 7100 }
class ____(VerticalScroll, can_focus=False): """Non focusable vertical scroll."""
Content
python
kamyu104__LeetCode-Solutions
Python/minimum-penalty-for-a-shop.py
{ "start": 38, "end": 395 }
class ____(object): def bestClosingTime(self, customers): """ :type customers: str :rtype: int """ result = mx = curr = 0 for i, x in enumerate(customers): curr += 1 if x == 'Y' else -1 if curr > mx: mx = curr re...
Solution
python
simonw__datasette
datasette/utils/__init__.py
{ "start": 8065, "end": 25734 }
class ____(Exception): pass # Allow SQL to start with a /* */ or -- comment comment_re = ( # Start of string, then any amount of whitespace r"^\s*(" + # Comment that starts with -- and ends at a newline r"(?:\-\-.*?\n\s*)" + # Comment that starts with /* and ends with */ - but does not...
InvalidSql
python
PyCQA__pylint
tests/functional/u/useless/useless_parent_delegation.py
{ "start": 14748, "end": 14992 }
class ____(ReturnTypeAny): choices = ["a", "b"] def draw(self) -> Any: # [useless-parent-delegation] return super().draw() # Any number of positional arguments followed by one keyword argument with a default value
ReturnTypeSame
python
kamyu104__LeetCode-Solutions
Python/simple-bank-system.py
{ "start": 111, "end": 1181 }
class ____(object): def __init__(self, balance): """ :type balance: List[int] """ self.__balance = balance def transfer(self, account1, account2, money): """ :type account1: int :type account2: int :type money: int :rtype: bool ""...
Bank
python
getsentry__sentry
src/sentry/search/events/builder/metrics.py
{ "start": 71368, "end": 73040 }
class ____(MetricsQueryBuilder): base_function_acl = ["histogram"] def __init__( self, histogram_params: HistogramParams, *args: Any, **kwargs: Any, ): self.histogram_aliases: list[str] = [] self.num_buckets = histogram_params.num_buckets self.min_bin...
HistogramMetricQueryBuilder
python
django-guardian__django-guardian
example_project_custom_group/posts/migrations/0001_initial.py
{ "start": 93, "end": 940 }
class ____(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Post", fields=[ ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), ("title", mo...
Migration
python
pytorch__pytorch
torch/distributed/tensor/_shards_wrapper.py
{ "start": 555, "end": 13478 }
class ____(torch.Tensor): """ A wrapper class to hold local shards of a DTensor. This class is used largely for checkpointing purposes and implicitly subtypes the _Checkpointable protocol. """ __slots__ = ["_local_shards", "_storage_meta"] _local_shards: list[torch.Tensor] _storage_meta...
LocalShardsWrapper
python
facelessuser__pymdown-extensions
pymdownx/fancylists.py
{ "start": 16756, "end": 17084 }
class ____(FancyOListProcessor): """Process unordered list blocks.""" SIBLING_TAGS = ['ul'] TAG = 'ul' def __init__(self, parser, config): """Initialize.""" super().__init__(parser, config) self.list_re = re.compile(r'^[ ]{0,%d}[-+*][ ]+(.*)' % (self.tab_length - 1))
FancyUListProcessor
python
getsentry__sentry
tests/sentry/integrations/slack/test_message_builder.py
{ "start": 43380, "end": 44518 }
class ____(TestCase): @patch("sentry.models.group.Group.has_replays") def test_build_replay_issue(self, has_replays: MagicMock) -> None: replay1_id = "46eb3948be25448abd53fe36b5891ff2" self.project.flags.has_replays = True self.project.save() event = self.store_event( ...
BuildGroupAttachmentReplaysTest
python
sqlalchemy__sqlalchemy
test/orm/test_core_compilation.py
{ "start": 22464, "end": 25478 }
class ____(QueryTest, AssertsCompiledSQL): __dialect__ = "default" def test_exclude_eagerloads(self): User, Address = self.classes("User", "Address") stmt = select(User).options(joinedload(User.addresses)) froms = stmt.columns_clause_froms mapper = inspect(User) is_(f...
ColumnsClauseFromsTest
python
openai__openai-python
tests/test_transform.py
{ "start": 8911, "end": 10469 }
class ____(BaseModel): foo: str @parametrize @pytest.mark.asyncio async def test_pydantic_model_to_dictionary(use_async: bool) -> None: assert cast(Any, await transform(MyModel(foo="hi!"), Any, use_async)) == {"foo": "hi!"} assert cast(Any, await transform(MyModel.construct(foo="hi!"), Any, use_async)) ==...
MyModel
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 9088, "end": 13615 }
class ____: email = wtforms.fields.EmailField( validators=[ wtforms.validators.InputRequired(), PreventNullBytesValidator(), wtforms.validators.Email(), wtforms.validators.Length( max=254, message=_("The email address is too long. Try again.") ...
NewEmailMixin
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 30397, "end": 35011 }
class ____(TestCase): def test_valid_dir(self) -> None: for cls in c.Dir, c.FilesystemObject: with self.subTest(cls): d = os.path.dirname(__file__) class Schema(Config): option = cls(exists=True) conf = self.get_config(Schema,...
FilesystemObjectTest
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_algorithm.py
{ "start": 7995, "end": 9289 }
class ____(_CalibrationAlgorithmBase): """AverageMinMaxCalibrationAlgorithm for calculating min and max values of calibration result. AverageMinMax calibration calculates the average of min and max values. average of min = sum of min values / number of samples average of max = sum of max values / number of sam...
_AverageMinMax
python
spyder-ide__spyder
spyder/plugins/mainmenu/api.py
{ "start": 2533, "end": 2688 }
class ____: UndoRedo = 'undo_redo_section' Copy = 'copy_section' Editor = 'editor_section' Formatting = 'formatting_section'
EditMenuSections
python
getlogbook__logbook
tests/test_more.py
{ "start": 5142, "end": 7023 }
class ____: @require_module("riemann_client") def test_happy_path(self, logger): from logbook.more import RiemannHandler riemann_handler = RiemannHandler( "127.0.0.1", 5555, message_type="test", level=logbook.INFO ) null_handler = logbook.NullHandler() with n...
TestRiemannHandler
python
sphinx-doc__sphinx
sphinx/util/typing.py
{ "start": 5931, "end": 26694 }
class ____(typing.TypedDict, total=False): """The metadata returned by an extension's ``setup()`` function. See :ref:`ext-metadata`. """ version: str """The extension version (default: ``'unknown version'``).""" env_version: int """An integer that identifies the version of env data added b...
ExtensionMetadata
python
encode__django-rest-framework
tests/test_routers.py
{ "start": 620, "end": 746 }
class ____(models.Model): uuid = models.CharField(max_length=20) text = models.CharField(max_length=200)
RouterTestModel
python
django__django
tests/admin_scripts/tests.py
{ "start": 1656, "end": 7989 }
class ____(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.joi...
AdminScriptTestCase
python
davidhalter__jedi
jedi/api/classes.py
{ "start": 1905, "end": 20916 }
class ____: """ The base class for all definitions, completions and signatures. """ _mapping = { 'posixpath': 'os.path', 'riscospath': 'os.path', 'ntpath': 'os.path', 'os2emxpath': 'os.path', 'macpath': 'os.path', 'genericpath': 'os.path', 'posix':...
BaseName
python
ray-project__ray
python/ray/tune/search/sample.py
{ "start": 4928, "end": 5189 }
class ____(Sampler): def __init__(self, mean: float = 0.0, sd: float = 0.0): self.mean = mean self.sd = sd assert self.sd > 0, "SD has to be strictly greater than 0" def __str__(self): return "Normal" @DeveloperAPI
Normal
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1594384, "end": 1595428 }
class ____(sgqlc.types.Union): """An item in a pull request timeline""" __schema__ = github_schema __types__ = ( AssignedEvent, BaseRefDeletedEvent, BaseRefForcePushedEvent, ClosedEvent, Commit, CommitCommentThread, CrossReferencedEvent, Demil...
PullRequestTimelineItem
python
doocs__leetcode
solution/2300-2399/2333.Minimum Sum of Squared Difference/Solution.py
{ "start": 0, "end": 762 }
class ____: def minSumSquareDiff( self, nums1: List[int], nums2: List[int], k1: int, k2: int ) -> int: d = [abs(a - b) for a, b in zip(nums1, nums2)] k = k1 + k2 if sum(d) <= k: return 0 left, right = 0, max(d) while left < right: mid = (le...
Solution
python
python__mypy
mypy/nodes.py
{ "start": 84957, "end": 85384 }
class ____(Expression): """List comprehension (e.g. [x + 1 for x in a])""" __slots__ = ("generator",) __match_args__ = ("generator",) generator: GeneratorExpr def __init__(self, generator: GeneratorExpr) -> None: super().__init__() self.generator = generator def accept(self,...
ListComprehension
python
django__django
django/template/backends/django.py
{ "start": 446, "end": 3120 }
class ____(BaseEngine): app_dirname = "templates" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() options.setdefault("autoescape", True) options.setdefault("debug", settings.DEBUG) options.setdefault("file_charset", "utf-8") ...
DjangoTemplates
python
pikepdf__pikepdf
src/pikepdf/_methods.py
{ "start": 26244, "end": 27229 }
class ____: @property def creation_date(self) -> datetime.datetime | None: if not self._creation_date: return None return decode_pdf_date(self._creation_date) @creation_date.setter def creation_date(self, value: datetime.datetime): self._creation_date = encode_pdf_da...
Extend_AttachedFile
python
jamielennox__requests-mock
requests_mock/request.py
{ "start": 610, "end": 5059 }
class ____(object): """A wrapper around a requests.Request that gives some extra information. This will be important both for matching and so that when it's save into the request_history users will be able to access these properties. """ def __init__(self, request, **kwargs): self._request...
_RequestObjectProxy
python
pytorch__pytorch
test/onnx/pytorch_test_common.py
{ "start": 11582, "end": 11979 }
class ____(common_utils.TestCase): """Test case for ONNX export. Any test case that tests functionalities under torch.onnx should inherit from this class. """ def setUp(self): super().setUp() # TODO(#88264): Flaky test failures after changing seed. set_rng_seed(0) if to...
ExportTestCase
python
rq__rq
tests/test_fixtures.py
{ "start": 62, "end": 653 }
class ____(RQTestCase): def test_rpush_fixture(self): connection_kwargs = self.connection.connection_pool.connection_kwargs fixtures.rpush('foo', 'bar', connection_kwargs) assert self.connection.lrange('foo', 0, 0)[0].decode() == 'bar' def test_start_worker_fixture(self): queue ...
TestFixtures
python
kamyu104__LeetCode-Solutions
Python/longest-turbulent-subarray.py
{ "start": 29, "end": 423 }
class ____(object): def maxTurbulenceSize(self, A): """ :type A: List[int] :rtype: int """ result = 1 start = 0 for i in xrange(1, len(A)): if i == len(A)-1 or \ cmp(A[i-1], A[i]) * cmp(A[i], A[i+1]) != -1: result = m...
Solution
python
aio-libs__aiohttp
aiohttp/test_utils.py
{ "start": 14746, "end": 20883 }
class ____(IsolatedAsyncioTestCase, ABC): """A base class to allow for unittest web applications using aiohttp. Provides the following: * self.client (aiohttp.test_utils.TestClient): an aiohttp test client. * self.app (aiohttp.web.Application): the application returned by self.get_application(...
AioHTTPTestCase
python
matplotlib__matplotlib
galleries/examples/widgets/lasso_selector_demo_sgskip.py
{ "start": 429, "end": 3328 }
class ____: """ Select indices from a matplotlib collection using `LassoSelector`. Selected indices are saved in the `ind` attribute. This tool fades out the points that are not part of the selection (i.e., reduces their alpha values). If your collection has alpha < 1, this tool will permanently ...
SelectFromCollection