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
cython__cython
Cython/Compiler/Nodes.py
{ "start": 223691, "end": 234444 }
class ____(ClassDefNode): # A Python class definition. # # name EncodedString Name of the class # doc string or None The class docstring # body StatNode Attribute definition code # entry Symtab.Entry # scope PyClassScope # decorators [DecoratorNode]...
PyClassDefNode
python
sympy__sympy
sympy/stats/frv.py
{ "start": 1693, "end": 2359 }
class ____(RandomDomain): """ A domain with discrete finite support Represented using a FiniteSet. """ is_Finite = True @property def symbols(self): return FiniteSet(sym for sym, val in self.elements) @property def elements(self): return self.args[0] @property...
FiniteDomain
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 650058, "end": 650533 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node", "permission") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field(sgqlc.types.non_null("Repository"), gr...
TeamRepositoryEdge
python
pennersr__django-allauth
allauth/headless/mfa/response.py
{ "start": 1612, "end": 1910 }
class ____(APIResponse): def __init__(self, request, secret, totp_url): super().__init__( request, meta={ "secret": secret, "totp_url": totp_url, }, status=HTTPStatus.NOT_FOUND, )
TOTPNotFoundResponse
python
catalyst-team__catalyst
catalyst/contrib/datasets/imagewang.py
{ "start": 469, "end": 934 }
class ____(ImageClassificationDataset): """ `Imagewang <https://github.com/fastai/imagenette#image%E7%BD%91>`_ Dataset with images resized so that the shortest size is 160 px. .. note:: catalyst[cv] required for this dataset. """ name = "imagewang-160" resources = [ ( ...
Imagewang160
python
python-attrs__attrs
tests/dataclass_transform_example.py
{ "start": 613, "end": 795 }
class ____: _a: int = attrs.field(alias="_a") af = AliasedField(42) reveal_type(af.__init__) # noqa: F821 # unsafe_hash is accepted @attrs.define(unsafe_hash=True)
AliasedField
python
celery__celery
t/unit/backends/test_rpc.py
{ "start": 546, "end": 3692 }
class ____: def setup_method(self): self.b = RPCBackend(app=self.app) def test_oid(self): oid = self.b.oid oid2 = self.b.oid assert uuid.UUID(oid) assert oid == oid2 assert oid == self.app.thread_oid def test_oid_threads(self): # Verify that two RPC...
test_RPCBackend
python
pyca__cryptography
tests/hazmat/primitives/test_serialization.py
{ "start": 52143, "end": 52618 }
class ____: def test_non_bytes_password(self): with pytest.raises(ValueError): BestAvailableEncryption(object()) # type:ignore[arg-type] def test_encryption_with_zero_length_password(self): with pytest.raises(ValueError): BestAvailableEncryption(b"") @pytest.mark.supp...
TestKeySerializationEncryptionTypes
python
pytorch__pytorch
torch/export/graph_signature.py
{ "start": 1010, "end": 1141 }
class ____: name: str class_fqn: str fake_val: Optional[FakeScriptObject] = None @dataclasses.dataclass
CustomObjArgument
python
pytorch__pytorch
torch/_export/passes/add_runtime_assertions_for_constraints_pass.py
{ "start": 518, "end": 1129 }
class ____(NamedTuple): input_name: str dim: int def _convert_to_int(val): # Convert simple sympy Integers into concrete int if val in (sympy.oo, int_oo): return math.inf if val in (-sympy.oo, -int_oo): return -math.inf if isinstance(val, sympy.Integer): return int(val)...
InputDim
python
doocs__leetcode
solution/1400-1499/1410.HTML Entity Parser/Solution.py
{ "start": 0, "end": 607 }
class ____: def entityParser(self, text: str) -> str: d = { '&quot;': '"', '&apos;': "'", '&amp;': "&", "&gt;": '>', "&lt;": '<', "&frasl;": '/', } i, n = 0, len(text) ans = [] while i < n: fo...
Solution
python
ZoranPandovski__al-go-rithms
search/Traversal/Pre Order Traversal Binary Tree/Python/koffy.py
{ "start": 190, "end": 475 }
class ____: def preorderTraversal(self, root: TreeNode): result = [] if root: result.append(root.val) result += self.preorderTraversal(root.left) result += self.preorderTraversal(root.right) return result
Solution
python
numpy__numpy
numpy/polynomial/tests/test_printing.py
{ "start": 15003, "end": 18946 }
class ____: """Test the latex repr used by Jupyter""" @staticmethod def as_latex(obj): # right now we ignore the formatting of scalars in our tests, since # it makes them too verbose. Ideally, the formatting of scalars will # be fixed such that tests below continue to pass o...
TestLatexRepr
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/aioodbc.py
{ "start": 1809, "end": 2021 }
class ____(aiodbcConnector, MSDialect_pyodbc): driver = "aioodbc" supports_statement_cache = True execution_ctx_cls = MSExecutionContext_aioodbc dialect = MSDialectAsync_aioodbc
MSDialectAsync_aioodbc
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 2494, "end": 2568 }
class ____(Protocol): def m(self, x: Self) -> None: ...
Proto_ContraSelf
python
huggingface__transformers
tests/models/siglip/test_image_processing_siglip.py
{ "start": 1011, "end": 3040 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_rescale=True, rescale_factor=1 / 255, do_normalize=True, i...
SiglipImageProcessingTester
python
huggingface__transformers
src/transformers/models/big_bird/modeling_big_bird.py
{ "start": 100725, "end": 105486 }
class ____(BigBirdPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config self.bert = BigBirdModel(config) self.classifier = BigBirdClassificationHead(config) # Initialize weights and apply final...
BigBirdForSequenceClassification
python
psf__requests
src/requests/auth.py
{ "start": 2220, "end": 2851 }
class ____(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password def __eq__(self, other): return all( [ self.username == getattr(other, "...
HTTPBasicAuth
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 41137, "end": 63728 }
class ____(NonStrictDataModel): """ :param id: Task id :type id: str :param name: Task Name :type name: str :param user: Associated user id :type user: str :param company: Company ID :type company: str :param type: Type of task. Values: 'training', 'testing' :type type: TaskT...
Task
python
sympy__sympy
sympy/matrices/expressions/matexpr.py
{ "start": 20833, "end": 23055 }
class ____(MatrixExpr): """Symbolic representation of a Matrix object Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and can be included in Matrix Expressions Examples ======== >>> from sympy import MatrixSymbol, Identity >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 M...
MatrixSymbol
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 46264, "end": 50920 }
class ____(BaseModel, extra=Extra.forbid): """ Serve metadata with system-level info and details on all applications deployed to the Ray cluster. This is the response JSON schema for v2 REST API `GET /api/serve/applications`. """ controller_info: ServeActorDetails = Field( description=...
ServeInstanceDetails
python
sympy__sympy
sympy/integrals/heurisch.py
{ "start": 6832, "end": 7968 }
class ____: """ Derivatives of Bessel functions of orders n and n-1 in terms of each other. See the docstring of DiffCache. """ def __init__(self): self.table = {} self.n = Dummy('n') self.z = Dummy('z') self._create_table() def _create_table(t): ta...
BesselTable
python
modin-project__modin
modin/experimental/xgboost/utils.py
{ "start": 2494, "end": 3478 }
class ____: """ Context to connect a worker to a rabit tracker. Parameters ---------- actor_rank : int Rank of actor, connected to this context. args : list List with environment variables for Rabit Tracker. """ def __init__(self, actor_rank, args): self.args = ...
RabitContext
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 17010, "end": 17475 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_stat...
EsmOutput
python
getsentry__sentry
src/sentry/grouping/enhancer/parser.py
{ "start": 1527, "end": 5860 }
class ____(NodeVisitor[list[EnhancementRule]]): visit_comment = visit_empty = lambda *a: None unwrapped_exceptions = (InvalidEnhancerConfig,) def visit_enhancements( self, node: Node, children: list[EnhancementRule | None] ) -> list[EnhancementRule]: rules = [] for child in chil...
EnhancementsVisitor
python
tensorflow__tensorflow
tensorflow/python/framework/ops.py
{ "start": 228716, "end": 232549 }
class ____(enum.Enum): OFF: int = 0 LEGACY: int = 1 SAFE: int = 2 ALL: int = 3 _dtype_conversion_mode: PromoMode = PromoMode.OFF def get_dtype_conversion_mode() -> PromoMode: return _dtype_conversion_mode # TODO(b/289395872): Make sure all WeakTensor construction is guarded with this # check. def is_aut...
PromoMode
python
ansible__ansible
hacking/create-bulk-issues.py
{ "start": 3257, "end": 3936 }
class ____: title: str summary: str component: str labels: list[str] | None = None def create_issue(self, project: str) -> Issue: body = f''' ### Summary {self.summary} ### Issue Type Bug Report ### Component Name `{self.component}` ### Ansible Version {MAJOR_MINOR_VERSION} ### Conf...
BugReport
python
huggingface__transformers
src/transformers/models/glm4_moe/modeling_glm4_moe.py
{ "start": 22403, "end": 25633 }
class ____(Glm4MoePreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"model\.layers\.92.*", r"model\.layers\.46.*"] def __init__(self, config: Glm4MoeConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_to...
Glm4MoeModel
python
Lightning-AI__lightning
src/lightning/pytorch/strategies/launchers/xla.py
{ "start": 1257, "end": 7510 }
class ____(_MultiProcessingLauncher): r"""Launches processes that run a given function in parallel on XLA supported hardware, and joins them all at the end. The main process in which this launcher is invoked creates N so-called worker processes (using the `torch_xla` :func:`xmp.spawn`) that run the giv...
_XLALauncher
python
spyder-ide__spyder
spyder/plugins/remoteclient/api/manager/base.py
{ "start": 1003, "end": 1660 }
class ____(logging.Handler): def __init__(self, client, *args, **kwargs): self._client = client super().__init__(*args, **kwargs) log_format = "%(message)s &#8212; %(asctime)s" formatter = logging.Formatter(log_format, datefmt="%H:%M:%S %d/%m/%Y") self.setFormatter(formatter...
SpyderRemoteAPILoggerHandler
python
readthedocs__readthedocs.org
readthedocs/core/unresolver.py
{ "start": 1362, "end": 1571 }
class ____(UnresolverError): def __init__(self, project, version_slug, filename): self.project = project self.version_slug = version_slug self.filename = filename
VersionNotFoundError
python
walkccc__LeetCode
solutions/7. Reverse Integer/7.py
{ "start": 0, "end": 232 }
class ____: def reverse(self, x: int) -> int: ans = 0 sign = -1 if x < 0 else 1 x *= sign while x: ans = ans * 10 + x % 10 x //= 10 return 0 if ans < -2**31 or ans > 2**31 - 1 else sign * ans
Solution
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/extractors/base.py
{ "start": 1707, "end": 2055 }
class ____(Generic[DatasetSubclass, BaseFacetSubclass]): """Structure returned from lineage extraction.""" inputs: list[DatasetSubclass] = Factory(list) outputs: list[DatasetSubclass] = Factory(list) run_facets: dict[str, BaseFacetSubclass] = Factory(dict) job_facets: dict[str, BaseFacetSubclass] =...
OperatorLineage
python
getsentry__sentry
tests/sentry/releases/endpoints/test_release_deploys.py
{ "start": 4902, "end": 16915 }
class ____(APITestCase): def setUp(self) -> None: user = self.create_user(is_staff=False, is_superuser=False) self.org = self.create_organization() self.org.save() team = self.create_team(organization=self.org) self.project = self.create_project(name="foo", organization=self...
ReleaseDeploysCreateTest
python
huggingface__transformers
src/transformers/models/llava_onevision/modular_llava_onevision.py
{ "start": 1922, "end": 9127 }
class ____(LlavaNextImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"height": 384, "width": 384} crop_size = None default_to_square = False do_resize = True do_center_crop = None do_rescale = True do_nor...
LlavaOnevisionImageProcessorFast
python
huggingface__transformers
src/transformers/models/longformer/modeling_longformer.py
{ "start": 63096, "end": 63790 }
class ____(nn.Module): """Longformer Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = ...
LongformerLMHead
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v2_utils.py
{ "start": 61254, "end": 67942 }
class ____: """Configuration data for one embedding feature. This class holds the configuration data for a single embedding feature. The main use is to assign features to `tf.tpu.experimental.embedding.TableConfig`s via the table parameter: ```python table_config_one = tf.tpu.experimental.embedding.TableC...
FeatureConfig
python
sqlalchemy__sqlalchemy
test/orm/test_eager_relations.py
{ "start": 230169, "end": 232040 }
class ____(_fixtures.FixtureTest): """POC test for both #7153 and #7154""" run_inserts = "once" run_deletes = None __sparse_driver_backend__ = True @classmethod def setup_mappers(cls): cls._setup_stock_mapping() def test_limited_eager_w_null(self): User = self.classes.Use...
SingletonConstantSubqTest
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1180576, "end": 1180789 }
class ____(ColorScheme): """SequentialSingleHue schema wrapper.""" _schema = {"$ref": "#/definitions/SequentialSingleHue"} def __init__(self, *args): super().__init__(*args)
SequentialSingleHue
python
sqlalchemy__sqlalchemy
test/sql/test_compiler.py
{ "start": 7003, "end": 132891 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_compiler_column_element_is_slots(self): class SomeColThing(CompilerColumnElement): __slots__ = ("name",) __visit_name__ = "some_col_thing" def __init__(self, name): s...
SelectTest
python
bokeh__bokeh
tests/unit/bokeh/embed/test_bundle.py
{ "start": 3104, "end": 3522 }
class ____: def test_no_objs_all_resources_bundled(self) -> None: b = beb.bundle_for_objs_and_resources(None, ABSOLUTE) assert any('bokeh-widgets' in f.url for f in b.js_files) assert any('bokeh-gl' in f.url for f in b.js_files) assert any('bokeh-tables' in f.url for f in b.js_files...
Test_bundle_for_objs_and_resources
python
getsentry__sentry
src/sentry/analytics/events/user_removed.py
{ "start": 69, "end": 288 }
class ____(analytics.Event): user_id: int actor_id: int | None = None deletion_request_datetime: str | None = None deletion_datetime: str | None = None analytics.register(UserRemovedEvent)
UserRemovedEvent
python
neetcode-gh__leetcode
python/1523-count-odd-numbers-in-an-interval-range.py
{ "start": 0, "end": 168 }
class ____: def countOdds(self, low: int, high: int) -> int: if low%2!=0 or high%2!=0: return (high-low)//2 +1 return (high-low)//2
Solution
python
viewflow__viewflow
viewflow/workflow/flow/views/filters.py
{ "start": 2809, "end": 3019 }
class ____(FilterSet): created = DateRangeFilter() finished = NullDateRangeFilter() class Meta: model = Process fields = ["status", "created", "finished"]
DashboardProcessListViewFilter
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/responses.py
{ "start": 1646, "end": 2786 }
class ____(BaseModel): """ Solr response body. See `Solr documentation <https://solr.apache.org/guide/solr/latest/query-guide/response-writers.html#json-response-writer>`_ for details. """ docs: list[dict[str, Any]] """Documents returned by Solr for the query. Each document is a d...
SolrSelectResponseBody
python
python-visualization__folium
folium/plugins/fullscreen.py
{ "start": 161, "end": 1930 }
class ____(JSCSSMixin, MacroElement): """ Adds a fullscreen button to your map. Parameters ---------- position : str change the position of the button can be: 'topleft', 'topright', 'bottomright' or 'bottomleft' default: 'topleft' title : str change the title of ...
Fullscreen
python
PyCQA__pylint
tests/functional/u/unsupported/unsupported_version_for_final.py
{ "start": 374, "end": 611 }
class ____: @final # [using-final-decorator-in-unsupported-version] @final # [using-final-decorator-in-unsupported-version] def my_method(self): pass @myfinal # [using-final-decorator-in-unsupported-version]
MyClass1
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
{ "start": 1220, "end": 9092 }
class ____: def test_load_user(self): sm = EmptySecurityManager() sm.get_user_by_id = Mock() sm.load_user("123") sm.get_user_by_id.assert_called_once_with(123) @mock.patch("airflow.providers.fab.auth_manager.security_manager.override.g", spec={}) def test_load_user_jwt(sel...
TestFabAirflowSecurityManagerOverride
python
django__django
tests/prefetch_related/tests.py
{ "start": 68031, "end": 68864 }
class ____(TestCase): @classmethod def setUpTestData(cls): LessonEntry.objects.bulk_create( LessonEntry(id=id_, name1=name1, name2=name2) for id_, name1, name2 in [ (1, "einfach", "simple"), (2, "schwierig", "difficult"), ] ) ...
Ticket19607Tests
python
scipy__scipy
scipy/special/_generate_pyx.py
{ "start": 16388, "end": 28766 }
class ____(Func): """ Ufunc signature, restricted format suitable for special functions. Parameters ---------- name Name of the ufunc to create signature String of form 'func: fff*ff->f, func2: ddd->*i' describing the C-level functions and types of their input arguments ...
Ufunc
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
{ "start": 69341, "end": 134190 }
class ____(Sam3TrackerVideoPreTrainedModel): input_modalities = ("video", "text") _can_record_outputs = {"mask_decoder_attentions": OutputRecorder(Sam3TrackerVideoTwoWayAttentionBlock, index=2)} _keys_to_ignore_on_load_unexpected = [r"^detector_model."] _tied_weights_keys = {} _keys_to_ignore_on_loa...
Sam3TrackerVideoModel
python
pypa__pip
tests/unit/test_options.py
{ "start": 14799, "end": 19673 }
class ____(AddFakeCommandMixin): # the reason to specifically test general options is due to the # extra processing they receive, and the number of bugs we've had def test_cache_dir__default(self) -> None: # FakeCommand intentionally returns the wrong type. options, args = cast(tuple[Values...
TestGeneralOptions
python
pennersr__django-allauth
allauth/socialaccount/providers/trainingpeaks/provider.py
{ "start": 418, "end": 1478 }
class ____(OAuth2Provider): id = "trainingpeaks" name = "TrainingPeaks" account_class = TrainingPeaksAccount oauth2_adapter_class = TrainingPeaksOAuth2Adapter def extract_uid(self, data): return str(data["Id"]) def extract_common_fields(self, data): extra_common = super(Trainin...
TrainingPeaksProvider
python
doocs__leetcode
solution/1200-1299/1262.Greatest Sum Divisible by Three/Solution.py
{ "start": 0, "end": 323 }
class ____: def maxSumDivThree(self, nums: List[int]) -> int: n = len(nums) f = [[-inf] * 3 for _ in range(n + 1)] f[0][0] = 0 for i, x in enumerate(nums, 1): for j in range(3): f[i][j] = max(f[i - 1][j], f[i - 1][(j - x) % 3] + x) return f[n][0]
Solution
python
getsentry__sentry
src/sentry/codecov/endpoints/repositories/repositories.py
{ "start": 962, "end": 3640 }
class ____(CodecovEndpoint): owner = ApiOwner.CODECOV publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Retrieves list of repositories for a given owner", parameters=[ GlobalParams.ORG_ID_OR_SLUG, PreventParams.OWNER, ...
RepositoriesEndpoint
python
spyder-ide__spyder
spyder/plugins/completion/providers/languageserver/providers/document.py
{ "start": 730, "end": 12570 }
class ____: def register_file(self, filename, codeeditor): filename = path_as_uri(filename) if filename not in self.watched_files: self.watched_files[filename] = [] self.watched_files[filename].append(codeeditor) @handles(CompletionRequestTypes.DOCUMENT_PUBLISH_DIAGNOSTICS) ...
DocumentProvider
python
PrefectHQ__prefect
src/prefect/utilities/visualization.py
{ "start": 573, "end": 2663 }
class ____(Exception): pass def get_task_viz_tracker() -> Optional["TaskVizTracker"]: return TaskVizTrackerState.current @overload def track_viz_task( is_async: Literal[True], task_name: str, parameters: dict[str, Any], viz_return_value: Optional[Any] = None, ) -> Coroutine[Any, Any, Any]: ....
GraphvizExecutableNotFoundError
python
getsentry__sentry
tests/sentry_plugins/slack/test_plugin.py
{ "start": 502, "end": 6382 }
class ____(PluginTestCase): @cached_property def plugin(self) -> SlackPlugin: return SlackPlugin() @responses.activate def test_simple_notification(self) -> None: responses.add("POST", "http://example.com/slack") self.plugin.set_option("webhook", "http://example.com/slack", self...
SlackPluginTest
python
automl__auto-sklearn
autosklearn/ensembles/singlebest_ensemble.py
{ "start": 503, "end": 5339 }
class ____(AbstractEnsemble): """Ensemble consisting of a single model. Parameters ---------- task_type: int An identifier indicating which task is being performed. metrics: Sequence[Scorer] | Scorer The metrics used to evaluate the models. backend : Backend Gives acce...
AbstractSingleModelEnsemble
python
pypa__pipenv
pipenv/patched/pip/_internal/models/direct_url.py
{ "start": 4435, "end": 6576 }
class ____: url: str info: InfoType subdirectory: Optional[str] = None def _remove_auth_from_netloc(self, netloc: str) -> str: if "@" not in netloc: return netloc user_pass, netloc_no_user_pass = netloc.split("@", 1) if ( isinstance(self.info, VcsInfo) ...
DirectUrl
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 2369, "end": 2616 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a flow.""" tags: list[str] = Field( default_factory=list, description="A list of flow tags", examples=[["tag-1", "tag-2"]], )
FlowUpdate
python
giampaolo__psutil
tests/test_linux.py
{ "start": 27616, "end": 34147 }
class ____(PsutilTestCase): @pytest.mark.skipif(not HAS_CPU_FREQ, reason="not supported") @pytest.mark.skipif( AARCH64, reason="aarch64 does not always expose frequency" ) def test_emulate_use_second_file(self): # https://github.com/giampaolo/psutil/issues/981 def path_exists_moc...
TestSystemCPUFrequency
python
networkx__networkx
networkx/algorithms/assortativity/tests/test_connectivity.py
{ "start": 75, "end": 4978 }
class ____: def test_degree_p4(self): G = nx.path_graph(4) answer = {1: 2.0, 2: 1.5} nd = nx.average_degree_connectivity(G) assert nd == answer D = G.to_directed() answer = {2: 2.0, 4: 1.5} nd = nx.average_degree_connectivity(D) assert nd == answer ...
TestNeighborConnectivity
python
python-pillow__Pillow
src/PIL/Image.py
{ "start": 3350, "end": 3560 }
class ____(IntEnum): FLIP_LEFT_RIGHT = 0 FLIP_TOP_BOTTOM = 1 ROTATE_90 = 2 ROTATE_180 = 3 ROTATE_270 = 4 TRANSPOSE = 5 TRANSVERSE = 6 # transforms (also defined in Imaging.h)
Transpose
python
kamyu104__LeetCode-Solutions
Python/count-largest-group.py
{ "start": 54, "end": 403 }
class ____(object): def countLargestGroup(self, n): """ :type n: int :rtype: int """ count = collections.Counter() for x in xrange(1, n+1): count[sum(map(int, str(x)))] += 1 max_count = max(count.itervalues()) return sum(v == max_count for ...
Solution
python
openai__openai-python
src/openai/types/beta/realtime/session_updated_event.py
{ "start": 226, "end": 489 }
class ____(BaseModel): event_id: str """The unique ID of the server event.""" session: Session """Realtime session object configuration.""" type: Literal["session.updated"] """The event type, must be `session.updated`."""
SessionUpdatedEvent
python
ray-project__ray
python/ray/experimental/channel/common.py
{ "start": 3918, "end": 5625 }
class ____: serialization_context = _SerializationContext() _torch_available: Optional[bool] = None _torch_device: Optional["torch.device"] = None _current_stream: Optional["torch.cuda.Stream"] = None def __init__(self): # Used for the torch.Tensor accelerator transport. self.commun...
ChannelContext
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/lookup_ops_test.py
{ "start": 107639, "end": 112519 }
class ____(test.TestCase): def _createVocabFile(self, basename, values=("brain", "salad", "surgery")): vocabulary_file = os.path.join(self.get_temp_dir(), basename) with open(vocabulary_file, "w") as f: f.write("\n".join(values) + "\n") return vocabulary_file def test_index_to_string_table(self)...
IndexToStringTableFromFileTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsNone1.py
{ "start": 1405, "end": 2040 }
class ____(Protocol): def __bool__(self) -> Literal[False]: ... def func7(x: NoneProto | None): if x is None: reveal_type(x, expected_text="None") else: reveal_type(x, expected_text="NoneProto") _T3 = TypeVar("_T3", bound=None | int) def func8(x: _T3) -> _T3: if x is None: ...
NoneProto
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 71630, "end": 72377 }
class ____(FieldValues): """ Values for `FileField`. """ valid_inputs = [ (MockFile(name='example', size=10), MockFile(name='example', size=10)) ] invalid_inputs = [ ('invalid', ['The submitted data was not a file. Check the encoding type on the form.']), (MockFile(name='...
TestFileField
python
django__django
django/contrib/postgres/fields/array.py
{ "start": 10330, "end": 10429 }
class ____(ArrayRHSMixin, lookups.ContainedBy): pass @ArrayField.register_lookup
ArrayContainedBy
python
huggingface__transformers
tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py
{ "start": 8612, "end": 10725 }
class ____(VisionTextDualEncoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = VisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit", "hf-internal-testing/tiny-bert" ) batch_size = 13 pixel_values = fl...
ViTBertModelTest
python
scikit-learn__scikit-learn
sklearn/cross_decomposition/_pls.py
{ "start": 30685, "end": 37008 }
class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): """Partial Least Square SVD. This transformer simply performs a SVD on the cross-covariance matrix `X'y`. It is able to project both the training data `X` and the targets `y`. The training data `X` is projected on the left si...
PLSSVD
python
networkx__networkx
networkx/algorithms/tests/test_summarization.py
{ "start": 4884, "end": 7970 }
class ____: def build_original_graph(self): """ Builds graph shown in the original research paper """ original_matrix = [ ("1", "CB"), ("2", "ABC"), ("3", ["A", "B", "6"]), ("4", "ABC"), ("5", "AB"), ("6", ["5"])...
TestUnDirectedDedensification
python
numba__numba
numba/tests/test_ir_inlining.py
{ "start": 1330, "end": 4686 }
class ____(TestCase): _DEBUG = False inline_opt_as_bool = {'always': True, 'never': False} # -------------------------------------------------------------------------- # Example cost model def sentinel_17_cost_model(self, func_ir): # sentinel 17 cost model, this is a fake cost model that...
InliningBase
python
dask__distributed
distributed/deploy/old_ssh.py
{ "start": 10080, "end": 15189 }
class ____: def __init__( self, scheduler_addr, scheduler_port, worker_addrs, nthreads=0, n_workers=None, ssh_username=None, ssh_port=22, ssh_private_key=None, nohost=False, logdir=None, remote_python=None, memor...
SSHCluster
python
django__django
tests/update/models.py
{ "start": 876, "end": 1181 }
class ____(models.Model): foo = models.ForeignKey(Foo, models.CASCADE, to_field="target") o2o_foo = models.OneToOneField( Foo, models.CASCADE, related_name="o2o_bar", null=True ) m2m_foo = models.ManyToManyField(Foo, related_name="m2m_foo") x = models.IntegerField(default=0)
Bar
python
kamyu104__LeetCode-Solutions
Python/longest-palindromic-subsequence.py
{ "start": 31, "end": 607 }
class ____(object): def longestPalindromeSubseq(self, s): """ :type s: str :rtype: int """ if s == s[::-1]: # optional, to optimize special case return len(s) dp = [[1] * len(s) for _ in xrange(2)] for i in reversed(xrange(len(s))): f...
Solution
python
huggingface__transformers
src/transformers/models/falcon/modeling_falcon.py
{ "start": 4414, "end": 9756 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: FalconConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self....
FalconRotaryEmbedding
python
pennersr__django-allauth
allauth/socialaccount/views.py
{ "start": 883, "end": 2454 }
class ____( RedirectAuthenticatedUserMixin, CloseableSignupMixin, AjaxCapableProcessFormViewMixin, FormView, ): form_class = SignupForm template_name = "socialaccount/signup." + account_settings.TEMPLATE_EXTENSION def get_form_class(self): return get_form_class(app_settings.FORMS, "...
SignupView
python
tensorflow__tensorflow
tensorflow/python/data/experimental/benchmarks/csv_dataset_benchmark.py
{ "start": 1115, "end": 4788 }
class ____(benchmark_base.DatasetBenchmarkBase): """Benchmarks for `tf.data.experimental.CsvDataset`.""" FLOAT_VAL = '1.23456E12' STR_VAL = string.ascii_letters * 10 def _set_up(self, str_val): # Since this isn't test.TestCase, have to manually create a test dir gfile.MakeDirs(googletest.GetTempDir())...
CsvDatasetBenchmark
python
wandb__wandb
wandb/automations/_utils.py
{ "start": 1990, "end": 2465 }
class ____(Protocol): id: str def extract_id(obj: HasId | str) -> str: return obj.id if hasattr(obj, "id") else obj # --------------------------------------------------------------------------- ACTION_CONFIG_KEYS: dict[ActionType, str] = { ActionType.NOTIFICATION: "notification_action_input", Action...
HasId
python
pandas-dev__pandas
pandas/tests/arrays/categorical/test_indexing.py
{ "start": 3851, "end": 10237 }
class ____: def test_getitem_slice(self): cat = Categorical(["a", "b", "c", "d", "a", "b", "c"]) sliced = cat[3] assert sliced == "d" sliced = cat[3:5] expected = Categorical(["d", "a"], categories=["a", "b", "c", "d"]) tm.assert_categorical_equal(sliced, expected) ...
TestCategoricalIndexing
python
readthedocs__readthedocs.org
readthedocs/projects/tasks/search.py
{ "start": 4455, "end": 13456 }
class ____(Indexer): def __init__(self, version: Version, build: Build): self.version = version self.build = build self._hashes = {} def process(self, html_file: HTMLFile, sync_id: int): self._hashes[html_file.path] = html_file.processed_json["main_content_hash"] def collec...
FileManifestIndexer
python
plotly__plotly.py
plotly/graph_objs/scattergeo/hoverlabel/_font.py
{ "start": 233, "end": 17158 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergeo.hoverlabel" _path_str = "scattergeo.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", ...
Font
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 15274, "end": 15422 }
class ____(_DropBase["Table"]): def to_metadata(self, metadata: MetaData, table: Table) -> Self: raise NotImplementedError()
TableDropDDL
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1324564, "end": 1324727 }
class ____(sgqlc.types.Type, ProjectV2FieldCommon, Node): """A field inside a project.""" __schema__ = github_schema __field_names__ = ()
ProjectV2Field
python
getlogbook__logbook
benchmark/bench_noop_filter_on_handler.py
{ "start": 179, "end": 490 }
class ____(StreamHandler): def should_handle(self, record): return False def run(): out = StringIO() with NullHandler(): with CustomStreamHandler(out): for _ in range(500): log.warning("this is not handled") assert not out.getvalue()
CustomStreamHandler
python
spack__spack
lib/spack/spack/util/typing.py
{ "start": 206, "end": 764 }
class ____(Protocol): """Objects that support =, !=, <, <=, >, and >=.""" def __eq__(self, other: Any) -> bool: raise NotImplementedError def __ne__(self, other: Any) -> bool: raise NotImplementedError def __lt__(self, other: Any) -> bool: raise NotImplementedError def __...
SupportsRichComparison
python
Textualize__textual
tests/toggles/test_radiobutton.py
{ "start": 121, "end": 1955 }
class ____(App[None]): def __init__(self): super().__init__() self.events_received = [] def compose(self) -> ComposeResult: yield RadioButton("Test", id="rb1") yield RadioButton(id="rb2") yield RadioButton(value=True, id="rb3") def on_radio_button_changed(self, even...
RadioButtonApp
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
{ "start": 8798, "end": 11704 }
class ____(QAbstractTableModel): """Import wizard preview table model""" def __init__(self, data=None, parent=None): QAbstractTableModel.__init__(self, parent) data = [] if data is None else data self._data = data def rowCount(self, parent=QModelIndex()): """Return row coun...
PreviewTableModel
python
graphql-python__graphene
graphene/utils/orderedtype.py
{ "start": 55, "end": 1221 }
class ____: creation_counter = 1 def __init__(self, _creation_counter=None): self.creation_counter = _creation_counter or self.gen_counter() @staticmethod def gen_counter(): counter = OrderedType.creation_counter OrderedType.creation_counter += 1 return counter def...
OrderedType
python
getsentry__sentry
src/sentry/integrations/web/integration_extension_configuration.py
{ "start": 886, "end": 1770 }
class ____(IntegrationPipeline): def _dialog_success(self, _org_integration): assert self.organization, "Organization must exist to get slug" org_slug = self.organization.slug assert isinstance( self.provider, IntegrationProvider ), "Must be an IntegrationProvider to get...
ExternalIntegrationPipeline
python
pikepdf__pikepdf
tests/test_object.py
{ "start": 7114, "end": 8860 }
class ____: def test_name_equality(self): # Who needs transitivity? :P # While this is less than ideal ('/Foo' != b'/Foo') it allows for slightly # sloppy tests like if colorspace == '/Indexed' without requiring # Name('/Indexed') everywhere assert Name('/Foo') == '/Foo' ...
TestName
python
astropy__astropy
astropy/coordinates/representation/base.py
{ "start": 1384, "end": 4518 }
class ____(MixinInfo): """ Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ attrs_from_parent = {"unit"} # Indicates unit is read-only _...
BaseRepresentationOrDifferentialInfo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 1887, "end": 10297 }
class ____(HttpStream, ABC): primary_key = "id" # Detect streams with high API load large_stream = False max_retries: int = 5 stream_base_params = {} def __init__(self, api_url: str = "https://api.github.com", access_token_type: str = "", **kwargs): if kwargs.get("authenticator"): ...
GithubStreamABC
python
kubernetes-client__python
kubernetes/client/models/v1_watch_event.py
{ "start": 383, "end": 4740 }
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...
V1WatchEvent
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/optimizer_v2.py
{ "start": 3352, "end": 4028 }
class ____(object): def __init__(self, *args, **kwargs): pass def __enter__(self): pass def __exit__(self, type_arg, value_arg, traceback_arg): return False # False values do not suppress exceptions def name_scope_only_in_function_or_graph(name): """Internal-only entry point for `name_scope*`....
NullContextmanager
python
ansible__ansible
lib/ansible/modules/service_facts.py
{ "start": 14155, "end": 15438 }
class ____(BaseService): def gather_services(self): services = {} if platform.system() == 'AIX': lssrc_path = self.module.get_bin_path("lssrc") if lssrc_path: rc, stdout, stderr = self.module.run_command("%s -a" % lssrc_path) if rc != 0: ...
AIXScanService
python
getsentry__sentry
tests/sentry/integrations/source_code_management/test_commit_context.py
{ "start": 1133, "end": 8952 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.integration = MockCommitContextIntegration() self.repo = Repository.objects.create( organization_id=self.organization.id, name="example/repo", ) self.source_line = SourceLineInfo( ...
TestCommitContextIntegrationSLO