language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
getsentry__sentry
src/sentry/releases/endpoints/organization_release_files.py
{ "start": 604, "end": 4341 }
class ____(OrganizationReleasesBaseEndpoint, ReleaseFilesMixin): publish_status = { "GET": ApiPublishStatus.UNKNOWN, "POST": ApiPublishStatus.UNKNOWN, } rate_limits = RateLimitConfig( limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=40, wi...
OrganizationReleaseFilesEndpoint
python
huggingface__transformers
src/transformers/models/nemotron/configuration_nemotron.py
{ "start": 923, "end": 7851 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`NemotronModel`]. It is used to instantiate an Nemotron model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar co...
NemotronConfig
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 466099, "end": 467041 }
class ____(UnopNode): # 'not' operator # # operand ExprNode operator = '!' type = PyrexTypes.c_bint_type def calculate_constant_result(self): self.constant_result = not self.operand.constant_result def compile_time_value(self, denv): operand = self.operand.compile_time...
NotNode
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py
{ "start": 2554, "end": 3782 }
class ____(BetterPandasIOManager): def load_input(self, context: dg.InputContext) -> np.ndarray: # pyright: ignore[reportIncompatibleMethodOverride] file_path = self._get_path(context.upstream_output) array = np.genfromtxt(file_path, delimiter=",", dtype=None) return array @dg.op(ins={"np...
MyBetterNumpyLoader
python
readthedocs__readthedocs.org
readthedocs/api/v3/views.py
{ "start": 17901, "end": 18677 }
class ____( APIv3Settings, NestedViewSetMixin, ProjectQuerySetMixin, FlexFieldsMixin, ListModelMixin, RetrieveModelMixin, UpdateMixin, UpdateModelMixin, GenericViewSet, ): model = Notification lookup_field = "pk" lookup_url_kwarg = "notification_pk" serializer_class =...
NotificationsBuildViewSet
python
django__django
tests/unmanaged_models/models.py
{ "start": 2560, "end": 2651 }
class ____(models.Model): class Meta: db_table = "unmanaged_models_proxy2"
Proxy2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 130755, "end": 131522 }
class ____(sgqlc.types.Input): """Autogenerated input type of AddProjectCard""" __schema__ = github_schema __field_names__ = ("project_column_id", "content_id", "note", "client_mutation_id") project_column_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectColumnId") """The Node ...
AddProjectCardInput
python
conda__conda
conda/exceptions.py
{ "start": 19133, "end": 19279 }
class ____(CondaError, ImportError): def __init__(self, message: str): msg = f"{message}" super().__init__(msg)
CondaImportError
python
pola-rs__polars
py-polars/src/polars/datatypes/classes.py
{ "start": 2779, "end": 7837 }
class ____(metaclass=DataTypeClass): """Base class for all Polars data types.""" def _string_repr(self) -> str: return _dtype_str_repr(self) @overload # type: ignore[override] def __eq__(self, other: pl.DataTypeExpr) -> pl.Expr: ... @overload def __eq__(self, other: PolarsDataType) -...
DataType
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/side_channel/incoming_message.py
{ "start": 40, "end": 3366 }
class ____: """ Utility class for reading the message written to a SideChannel. Values must be read in the order they were written. """ def __init__(self, buffer: bytes, offset: int = 0): """ Create a new IncomingMessage from the bytes. """ self.buffer = buffer ...
IncomingMessage
python
PyCQA__bandit
tests/unit/core/test_issue.py
{ "start": 226, "end": 4728 }
class ____(testtools.TestCase): def test_issue_create(self): new_issue = _get_issue_instance() self.assertIsInstance(new_issue, issue.Issue) def test_issue_str(self): test_issue = _get_issue_instance() expect = ( "Issue: 'Test issue' from B999:bandit_plugin:" ...
IssueTests
python
wepe__MachineLearning
DeepLearning Tutorials/FaceRecognition_CNN(olivettifaces)/use_CNN_olivettifaces.py
{ "start": 1408, "end": 2213 }
class ____(object): def __init__(self, input, params_W,params_b,n_in, n_out): self.W = params_W self.b = params_b self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) self.y_pred = T.argmax(self.p_y_given_x, axis=1) self.params = [self.W, self.b] def negative...
LogisticRegression
python
ray-project__ray
rllib/examples/envs/classes/transformed_action_space_env.py
{ "start": 51, "end": 2044 }
class ____(gym.ActionWrapper): def __init__(self, env, low, high): super().__init__(env) self._low = low self._high = high self.action_space = type(env.action_space)( self._low, self._high, env.action_space.shape, env.action_space.dtype ) def action(self, act...
ActionTransform
python
scrapy__scrapy
tests/test_request_left.py
{ "start": 226, "end": 733 }
class ____(Spider): name = "signal_catcher" def __init__(self, crawler, url, *args, **kwargs): super().__init__(*args, **kwargs) crawler.signals.connect(self.on_request_left, signal=request_left_downloader) self.caught_times = 0 self.start_urls = [url] @classmethod def ...
SignalCatcherSpider
python
facebook__pyre-check
tools/upgrade/commands/command.py
{ "start": 1817, "end": 6683 }
class ____(Command): def __init__( self, command_arguments: CommandArguments, repository: Repository ) -> None: super().__init__(repository) self._command_arguments: CommandArguments = command_arguments self._comment: Optional[str] = command_arguments.comment self._max_li...
ErrorSuppressingCommand
python
gawel__pyquery
tests/test_pyquery.py
{ "start": 11870, "end": 12005 }
class ____(TestCase): def test_typeerror_on_invalid_value(self): self.assertRaises(TypeError, pq, object())
TestConstruction
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-measurespace/llama_index/tools/measurespace/base.py
{ "start": 173, "end": 7777 }
class ____(BaseToolSpec): """Measure Space tool spec.""" spec_functions = [ "get_hourly_weather_forecast", "get_daily_weather_forecast", "get_daily_climate_forecast", "get_daily_air_quality_forecast", "get_latitude_longitude_from_location", "get_location_from_lat...
MeasureSpaceToolSpec
python
tensorflow__tensorflow
tensorflow/python/distribute/mirrored_strategy_test.py
{ "start": 46749, "end": 49285 }
class ____(test.TestCase): def testAssignReplicaLocalVarSumAggregation(self, distribution): def model_fn(): v_sum = variable_v1.VariableV1( 1.0, synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.SUM) return v_s...
SyncOnReadVariableAssignTest
python
django-import-export__django-import-export
tests/core/tests/resources.py
{ "start": 1695, "end": 1820 }
class ____(resources.ModelResource): class Meta: model = WithDefault fields = ("name",)
WithDefaultResource
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/files.py
{ "start": 12668, "end": 24157 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: """ 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://www.gith...
AsyncFiles
python
scrapy__scrapy
tests/test_http2_client_protocol.py
{ "start": 5205, "end": 5970 }
class ____(LeafResource): """Sends all the headers received as a response""" def render_GET(self, request: TxRequest): request.setHeader("Content-Type", "application/json; charset=UTF-8") request.setHeader("Content-Encoding", "UTF-8") headers = {} for k, v in request.requestHead...
RequestHeaders
python
numba__numba
numba/tests/test_struct_ref.py
{ "start": 2979, "end": 7579 }
class ____(MemoryLeakMixin, TestCase): def test_structref_type(self): sr = types.StructRef([('a', types.int64)]) self.assertEqual(sr.field_dict['a'], types.int64) sr = types.StructRef([('a', types.int64), ('b', types.float64)]) self.assertEqual(sr.field_dict['a'], types.int64) ...
TestStructRefBasic
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/dagrun.py
{ "start": 1026, "end": 1245 }
class ____(StrictBaseModel): """Schema for Trigger DAG Run API request.""" logical_date: UtcDateTime | None = None conf: dict = Field(default_factory=dict) reset_dag_run: bool = False
TriggerDAGRunPayload
python
sqlalchemy__sqlalchemy
test/orm/test_dataclasses.py
{ "start": 774, "end": 7235 }
class ____(fixtures.MappedTest, testing.AssertsCompiledSQL): @classmethod def define_tables(cls, metadata): Table( "accounts", metadata, Column("account_id", Integer, primary_key=True), Column("widget_count", Integer, nullable=False), ) Tab...
DataclassesTest
python
conda__conda
conda/auxlib/entity.py
{ "start": 25516, "end": 31357 }
class ____(metaclass=EntityType): __fields__ = odict() _lazy_validate = False def __init__(self, **kwargs): for key, field in self.__fields__.items(): try: setattr(self, key, kwargs[key]) except KeyError: alias = next((ls for ls in field._alia...
Entity
python
viewflow__viewflow
tests/json/test_json__basics.py
{ "start": 2578, "end": 2747 }
class ____(models.Model): data = models.JSONField() name = jsonstore.CharField(max_length=250) address = jsonstore.CharField(max_length=250, blank=True)
Person
python
great-expectations__great_expectations
great_expectations/compatibility/bigquery.py
{ "start": 2093, "end": 2723 }
class ____: """Namespace for Bigquery dialect types""" INTEGER = INTEGER NUMERIC = NUMERIC STRING = STRING BIGNUMERIC = BIGNUMERIC BYTES = BYTES BOOL = BOOL BOOLEAN = BOOLEAN TIMESTAMP = TIMESTAMP TIME = TIME FLOAT = FLOAT DATE = DATE DATETIME = DATETIME try: f...
BIGQUERY_TYPES
python
wandb__wandb
tests/unit_tests/test_launch/test_runner/test_kubernetes.py
{ "start": 8551, "end": 48640 }
class ____: def __init__(self): self.jobs = dict() async def create_namespaced_custom_object( self, group, version, namespace, plural, body ): self.jobs[body["metadata"]["name"]] = body return body async def delete_namespaced_custom_object( self, group, version,...
MockCustomObjectsApi
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 6436, "end": 6780 }
class ____(AnsibleError): """Invalid options were passed.""" # FIXME: This exception is used for many non-CLI related errors. # The few cases which are CLI related should really be handled by argparse instead, at which point the exit code here can be removed. _exit_code = ExitCode.INVALID_CLI_...
AnsibleOptionsError
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 11857, "end": 12000 }
class ____(models.Model): library = models.ForeignKey("Library", on_delete=models.CASCADE, null=True) history = HistoricalRecords()
State
python
getsentry__sentry
tests/flagpole/test_conditions.py
{ "start": 6672, "end": 8526 }
class ____: def test_is_equal_string(self) -> None: value = "foo" condition = EqualsCondition(property="foo", value=value) assert condition.match(context=EvaluationContext({"foo": "foo"}), segment_name="test") not_condition = NotEqualsCondition(property="foo", value=value) a...
TestEqualsConditions
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table02.py
{ "start": 315, "end": 1111 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 15471, "end": 15892 }
class ____(LocalizableStreamlitException): """Exception raised when an invalid ID component is provided.""" def __init__(self, part: str, delimiter: str) -> None: super().__init__( "The `{part}` of a bidirectional component's ID must not contain " "the delimiter sequence `{delim...
BidiComponentInvalidIdError
python
pyca__cryptography
tests/hazmat/primitives/test_scrypt.py
{ "start": 1850, "end": 7780 }
class ____: @pytest.mark.parametrize("params", vectors) def test_derive(self, backend, params): _skip_if_memory_limited(_MEM_LIMIT, params) password = params["password"] work_factor = int(params["n"]) block_size = int(params["r"]) parallelization_factor = int(params["p"])...
TestScrypt
python
doocs__leetcode
solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/Solution2.py
{ "start": 0, "end": 421 }
class ____: def stringCount(self, n: int) -> int: mod = 10**9 + 7 a = b = pow(25, n, mod) c = pow(25, n, mod) + n * pow(25, n - 1, mod) ab = pow(24, n, mod) ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) %...
Solution
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 88729, "end": 93358 }
class ____: def setup_method(self): self.rng = np.random.default_rng(8638464332) # Expected cdf values were computed with mpmath. For given x and c, # x = mpmath.mpf(x) # c = mpmath.mpf(c) # cdf = mpmath.gammainc(c, 0, mpmath.exp(x), # regularized=T...
TestLoggamma
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 578554, "end": 579145 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("ReleaseEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.t...
ReleaseConnection
python
coleifer__peewee
peewee.py
{ "start": 46627, "end": 49140 }
class ____(ColumnBase): no_coerce_functions = set(('sum', 'count', 'avg', 'cast', 'array_agg')) def __init__(self, name, arguments, coerce=True, python_value=None): self.name = name self.arguments = arguments self._filter = None self._order_by = None self._python_value =...
Function
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 64103, "end": 64603 }
class ____(sgqlc.types.Enum): """The possible roles of a collaborator on a project. Enumeration Choices: * `ADMIN`: The collaborator can view, edit, and maange the settings of the project * `NONE`: The collaborator has no direct access to the project * `READER`: The collaborator can view the...
ProjectV2Roles
python
sympy__sympy
sympy/plotting/series.py
{ "start": 69280, "end": 71877 }
class ____(BaseSeries): """A base class for 3D surfaces.""" is_3Dsurface = True def __init__(self, *args, **kwargs): super().__init__(**kwargs) self.use_cm = kwargs.get("use_cm", False) # NOTE: why should SurfaceOver2DRangeSeries support is polar? # After all, the same resu...
SurfaceBaseSeries
python
gevent__gevent
src/greentest/3.10/test_httplib.py
{ "start": 61830, "end": 71253 }
class ____(TestCase): def setUp(self): if not hasattr(client, 'HTTPSConnection'): self.skipTest('ssl support required') def make_server(self, certfile): from test.ssl_servers import make_https_server return make_https_server(self, certfile=certfile) def test_attributes...
HTTPSTest
python
django__django
django/tasks/exceptions.py
{ "start": 241, "end": 339 }
class ____(ImproperlyConfigured): """The provided Task backend is invalid."""
InvalidTaskBackend
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image02.py
{ "start": 315, "end": 1110 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image02.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_c...
TestCompareXLSXFiles
python
wandb__wandb
tests/system_tests/test_launch/test_launch_add.py
{ "start": 360, "end": 18546 }
class ____: def __init__(self, name): self.name = name @pytest.fixture def push_to_run_queue_by_name_spy(wandb_backend_spy): gql = wandb_backend_spy.gql responder = gql.Capture() wandb_backend_spy.stub_gql( gql.Matcher(operation="pushToRunQueueByName"), responder, ) ret...
MockBranch
python
GoogleCloudPlatform__python-docs-samples
functions/v2/ocr/main_test.py
{ "start": 725, "end": 3870 }
class ____: @mock.patch.object(main, "publisher") @mock.patch.object(main, "translate_client") @mock.patch.object(main, "vision_client") def test_detect_text( self, mock_vision_client, mock_translate_client, mock_publisher ): mock_annotation = mock.MagicMock() mock_annotation...
TestGCFPyOCRSample
python
google__jax
jax/_src/dtypes.py
{ "start": 1948, "end": 2302 }
class ____(extended): """Scalar class for PRNG Key dtypes. This is an abstract class that should never be instantiated, but rather exists for the sake of `jnp.issubdtype`. Examples: >>> from jax import random >>> from jax import dtypes >>> key = random.key(0) >>> jnp.issubdtype(key.dtype, dtyp...
prng_key
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 798033, "end": 806040 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "app", "company_url", "configuration_resource_path", "configuration_url", "documentation_url", "extended_description", "...
MarketplaceListing
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess4.py
{ "start": 359, "end": 395 }
class ____(Mixin1): item = "hi"
B1
python
pytorch__pytorch
torch/testing/_internal/common_fsdp.py
{ "start": 2427, "end": 2620 }
class ____(Enum): # No FSDP wrapping NO_FSDP = auto() # FSDP recursive wrapping RECURSIVE = auto() # TODO: FSDP non-recursive wrapping # NONRECURSIVE = auto()
FSDPInitMode
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/table.py
{ "start": 1577, "end": 1806 }
class ____(graphene.ObjectType): schema = graphene.NonNull(GrapheneTableSchema) records = non_null_list(graphene.String) # each element is one record serialized as JSON class Meta: name = "Table"
GrapheneTable
python
great-expectations__great_expectations
great_expectations/datasource/fluent/snowflake_datasource.py
{ "start": 13351, "end": 33846 }
class ____(SQLDatasource): """Adds a Snowflake datasource to the data context. Args: name: The name of this Snowflake datasource. connection_string: The SQLAlchemy connection string used to connect to the Snowflake database. For example: "snowflake://<user_login_name>:<password>@<ac...
SnowflakeDatasource
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed6.py
{ "start": 746, "end": 1025 }
class ____(TypedDict, extra_items=int): num: int def func4(p1: IntDict2): # This should generate an error. d1: dict[str, int] = p1 # This should generate an error. m1: MutableMapping[str, int] = p1 # This should generate an error. func1(p1)
IntDict2
python
HypothesisWorks__hypothesis
hypothesis-python/tests/typing_extensions/test_backported_types.py
{ "start": 6697, "end": 6751 }
class ____(TypedDict, total=True): author: str
Story
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_indexing.py
{ "start": 546, "end": 3606 }
class ____: def test_getitem_slice_keeps_name(self): # GH4226 st = Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles") et = Timestamp("2013-07-02 00:00:00", tz="America/Los_Angeles") dr = date_range(st, et, freq="h", name="timebucket") assert dr[1:].name == dr.name ...
TestGetItem
python
doocs__leetcode
solution/0800-0899/0893.Groups of Special-Equivalent Strings/Solution.py
{ "start": 0, "end": 180 }
class ____: def numSpecialEquivGroups(self, words: List[str]) -> int: s = {''.join(sorted(word[::2]) + sorted(word[1::2])) for word in words} return len(s)
Solution
python
pytorch__pytorch
test/inductor/test_minifier.py
{ "start": 7476, "end": 10901 }
class ____(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(10, 16) self.relu = torch.nn.ReLU() self.sigmoid = torch.nn.Sigmoid() def forward(self, inp, *, k): x = inp["x"] y = inp["y"] x = self.fc1(x) y = self.f...
Model
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/schemas/test_user_schema.py
{ "start": 1815, "end": 2328 }
class ____: @pytest.fixture(autouse=True) def setup_attrs(self, configured_app) -> None: self.app = configured_app self.client = self.app.test_client() self.role = self.app.appbuilder.sm.find_role("TestRole") self.session = self.app.appbuilder.session def teardown_method(sel...
TestUserBase
python
run-llama__llama_index
llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py
{ "start": 2180, "end": 2275 }
class ____(RunErrorEvent, Event): type: EventType = EventType.RUN_ERROR
RunErrorWorkflowEvent
python
celery__celery
t/unit/tasks/test_tasks.py
{ "start": 1225, "end": 1456 }
class ____(Task): autoretry_for = (Exception,) dont_autoretry_for = (TypeError,) retry_kwargs = {'max_retries': 5} retry_backoff = True retry_backoff_max = 700 retry_jitter = False
TaskWithRetryButForTypeError
python
tornadoweb__tornado
tornado/test/websocket_test.py
{ "start": 6001, "end": 6103 }
class ____(TestWebSocketHandler): def open(self): raise Exception("boom")
ErrorInOpenHandler
python
tensorflow__tensorflow
tensorflow/core/platform/ram_file_system_test.py
{ "start": 1175, "end": 4248 }
class ____(test_util.TensorFlowTestCase): def test_create_and_delete_directory(self): file_io.create_dir_v2('ram://testdirectory') file_io.delete_recursively_v2('ram://testdirectory') def test_create_and_delete_directory_tree_recursive(self): file_io.create_dir_v2('ram://testdirectory') file_io.cr...
RamFilesystemTest
python
doocs__leetcode
lcof2/剑指 Offer II 032. 有效的变位词/Solution.py
{ "start": 0, "end": 169 }
class ____: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t) or s == t: return False return Counter(s) == Counter(t)
Solution
python
django__django
tests/check_framework/test_model_checks.py
{ "start": 9243, "end": 13556 }
class ____(TestCase): def test_collision_in_same_model(self): class Model(models.Model): class Meta: constraints = [ models.CheckConstraint(condition=models.Q(id__gt=0), name="foo"), models.CheckConstraint(condition=models.Q(id__lt=100), na...
ConstraintNameTests
python
pytorch__pytorch
test/dynamo/test_functions.py
{ "start": 73320, "end": 73710 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3]"): l_x_ = L_x_ sum_1: "f32[]" = l_x_.sum(); l_x_ = None gt: "b8[]" = sum_1 > 0; sum_1 = None return (gt,) """, ) else: self.assertExpectedInline( normalize_gm(backend.graph...
GraphModule
python
Textualize__textual
src/textual/widgets/_rich_log.py
{ "start": 1445, "end": 12192 }
class ____(ScrollView, can_focus=True): """A widget for logging Rich renderables and text.""" DEFAULT_CSS = """ RichLog{ background: $surface; color: $foreground; overflow-y: scroll; &:focus { background-tint: $foreground 5%; } } """ max_line...
RichLog
python
doocs__leetcode
solution/1300-1399/1377.Frog Position After T Seconds/Solution.py
{ "start": 0, "end": 731 }
class ____: def frogPosition( self, n: int, edges: List[List[int]], t: int, target: int ) -> float: g = defaultdict(list) for u, v in edges: g[u].append(v) g[v].append(u) q = deque([(1, 1.0)]) vis = [False] * (n + 1) vis[1] = True w...
Solution
python
doocs__leetcode
lcof2/剑指 Offer II 067. 最大的异或/Solution2.py
{ "start": 0, "end": 649 }
class ____: def __init__(self): self.children = [None] * 2 def insert(self, x): node = self for i in range(30, -1, -1): v = (x >> i) & 1 if node.children[v] is None: node.children[v] = Trie() node = node.children[v] def search(sel...
Trie
python
Farama-Foundation__Gymnasium
gymnasium/envs/tabular/blackjack.py
{ "start": 16473, "end": 17769 }
class ____(FunctionalJaxEnv, EzPickle): """A Gymnasium Env wrapper for the functional blackjack env.""" metadata = {"render_modes": ["rgb_array"], "render_fps": 50, "jax": True} def __init__(self, render_mode: str | None = None, **kwargs): """Initializes Gym wrapper for blackjack functional env.""...
BlackJackJaxEnv
python
numba__numba
numba/cpython/hashing.py
{ "start": 13826, "end": 13929 }
class ____(Structure): _fields_ = [ ('k0', c_uint64), ('k1', c_uint64), ]
SIPHASH
python
astropy__astropy
astropy/coordinates/tests/test_representation_arithmetic.py
{ "start": 36984, "end": 38681 }
class ____: def setup_method(self): s = SphericalRepresentation( lon=[0.0, 6.0, 21.0] * u.hourangle, lat=[0.0, -30.0, 85.0] * u.deg, distance=[1, 2, 3] * u.kpc, ) self.s = s self.r = s.represent_as(RadialRepresentation) self.e = s.unit_vect...
TestRadialDifferential
python
kamyu104__LeetCode-Solutions
Python/generate-tag-for-video-caption.py
{ "start": 604, "end": 877 }
class ____(object): def generateTag(self, caption): """ :type caption: str :rtype: str """ L = 100 return ('#'+"".join(x.lower() if i == 0 else x[0].upper()+x[1:].lower() for i, x in enumerate(caption.split())))[:L]
Solution2
python
prabhupant__python-ds
data_structures/binary_trees/check_if_path_exists.py
{ "start": 80, "end": 538 }
class ____: def __init__(self, val): self.val = val self.right = None self.left = None def check_path(root, arr, n, index): if root is None: return n == 0 if root.left == None and root.right == None and root.val == arr[index] and index == n -1: return True re...
Node
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/common.py
{ "start": 3645, "end": 6827 }
class ____(VersionCheck): context: ConnectorContext title = "Connector version increment check" BYPASS_CHECK_FOR = [ METADATA_FILE_NAME, "acceptance-test-config.yml", "README.md", "bootstrap.md", ".dockerignore", "unit_tests", "integration_tests", ...
VersionIncrementCheck
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes5.py
{ "start": 5724, "end": 5997 }
class ____: test1: int = 1 test2: int | None = None test3: int @property def test4(self) -> int: return 3 test5: int test6: Any test7: int # This should generate 4 errors if reportIncompatibleVariableOverride # is enabled.
PeerClass2
python
getsentry__sentry
tests/sentry/issues/auto_source_code_config/test_process_event.py
{ "start": 23603, "end": 24803 }
class ____(LanguageSpecificDeriveCodeMappings): platform = "go" def test_auto_source_code_config_go_abs_filename(self) -> None: self._process_and_assert_configuration_changes( repo_trees={REPO1: ["sentry/capybara.go"]}, frames=[self.frame("/Users/JohnDoe/code/sentry/capybara.go"...
TestGoDeriveCodeMappings
python
django__django
django/template/defaulttags.py
{ "start": 13806, "end": 14332 }
class ____(Node): def __init__(self, partial_name, partial_mapping): # Defer lookup in `partial_mapping` and nodelist to runtime. self.partial_name = partial_name self.partial_mapping = partial_mapping def render(self, context): try: return self.partial_mapping[self....
PartialNode
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 57684, "end": 59259 }
class ____(ConstNode): type = PyrexTypes.c_bint_type # The constant value True or False def __init__(self, pos, value: bool, type=None): assert value is True or value is False, repr(value) super().__init__(pos, value=value, constant_result=value) if type is not None and type is not...
BoolNode
python
pytorch__pytorch
test/inductor/test_external_callables.py
{ "start": 1005, "end": 3240 }
class ____(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls._saved_config = config.save_config() def tearDown(self): super().tearDown() config.load_config(self._saved_config) def test_matmul_cpu(self): # 2I + 2I == (2I)(2I) x = torch...
TestInductorExternalCallable
python
joblib__joblib
joblib/logger.py
{ "start": 1459, "end": 2558 }
class ____(object): """Base class for logging messages.""" def __init__(self, depth=3, name=None): """ Parameters ---------- depth: int, optional The depth of objects printed. name: str, optional The namespace to log to. If None, defaults to jobli...
Logger
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/externaltool/package.py
{ "start": 217, "end": 399 }
class ____(Package): homepage = "http://somewhere.com" has_code = False version("1.0") version("0.9") version("0.8.1") depends_on("externalprereq")
Externaltool
python
apache__airflow
airflow-core/tests/unit/models/test_dag_version.py
{ "start": 1136, "end": 3188 }
class ____: def setup_method(self): clear_db_dags() def teardown_method(self): clear_db_dags() @pytest.mark.need_serialized_dag def test_writing_dag_version(self, dag_maker, session): with dag_maker("test_writing_dag_version") as dag: pass latest_version = ...
TestDagVersion
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 15905, "end": 16223 }
class ____(BaseModel): root: JsonValue type: Literal["XComSequenceIndexResult"] = "XComSequenceIndexResult" @classmethod def from_response(cls, response: XComSequenceIndexResponse) -> XComSequenceIndexResult: return cls(root=response.root, type="XComSequenceIndexResult")
XComSequenceIndexResult
python
nryoung__algorithms
tests/test_sorting.py
{ "start": 2010, "end": 2271 }
class ____(SortingAlgorithmTestCase): """ Tests Insertion sort on a small range from 0-9 """ def test_insertionsort(self): self.output = insertion_sort.sort(self.input) self.assertEqual(self.correct, self.output)
TestInsertionSort
python
numba__numba
numba/tests/test_lists.py
{ "start": 22680, "end": 24915 }
class ____(MemoryLeakMixin, TestCase): """ Test reflection of native Numba lists on Python list objects. """ def check_reflection(self, pyfunc): cfunc = jit(nopython=True)(pyfunc) samples = [([1., 2., 3., 4.], [0.]), ([1., 2., 3., 4.], [5., 6., 7., 8., 9.]), ...
TestListReflection
python
django__django
tests/model_formsets/models.py
{ "start": 299, "end": 696 }
class ____(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) class Meta: unique_together = (("author", "title"),) ordering = ["id"] def __str__(self): return self.title def clean(self): # Ensure author is alw...
Book
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 163355, "end": 163434 }
class ____(RecvmsgIntoTests, SendrecvmsgUDPTestBase): pass
RecvmsgIntoUDPTest
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/deployment.py
{ "start": 246, "end": 501 }
class ____(BaseModel): """Deployment resource model.""" id: int # Deployment IDs are integers in the GraphQL schema name: str type: DeploymentType class Config: from_attributes = True # For future ORM compatibility
Deployment
python
huggingface__transformers
src/transformers/models/mixtral/modular_mixtral.py
{ "start": 18587, "end": 18666 }
class ____(MistralForTokenClassification): pass
MixtralForTokenClassification
python
pytest-dev__pytest
src/_pytest/cacheprovider.py
{ "start": 15733, "end": 23149 }
class ____: """Plugin which implements the --nf (run new-first) option.""" def __init__(self, config: Config) -> None: self.config = config self.active = config.option.newfirst assert config.cache is not None self.cached_nodeids = set(config.cache.get("cache/nodeids", [])) ...
NFPlugin
python
numba__numba
numba/core/types/scalars.py
{ "start": 5072, "end": 5138 }
class ____(_NPDatetimeBase): type_name = 'datetime64'
NPDatetime
python
pypa__warehouse
tests/unit/admin/views/test_projects.py
{ "start": 38094, "end": 41803 }
class ____: def test_archive(self, db_request): project = ProjectFactory.create(name="foo") user = UserFactory.create(username="testuser") db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/the-redirect") db_request.method = "POST" db_request.user = user ...
TestProjectArchival
python
ray-project__ray
python/ray/data/tests/unit/test_datatype.py
{ "start": 20568, "end": 26672 }
class ____: """Test type predicate methods (is_list_type, is_struct_type, etc.).""" @pytest.mark.parametrize( "datatype,expected_result", [ # List types (DataType.list(DataType.int64()), True), (DataType.large_list(DataType.string()), True), (Data...
TestTypePredicates
python
ansible__ansible
lib/ansible/_internal/_templating/_jinja_plugins.py
{ "start": 6246, "end": 7249 }
class ____: """Functions/methods marked `_DirectCall` bypass Jinja Environment checks for `Marker`.""" _marker_attr: t.Final[str] = "_directcall" @classmethod def mark[T: t.Callable](cls, src: T) -> T: setattr(src, cls._marker_attr, True) return src @classmethod def is_marked(...
_DirectCall
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-of-buying-candies-with-discount.py
{ "start": 42, "end": 267 }
class ____(object): def minimumCost(self, cost): """ :type cost: List[int] :rtype: int """ cost.sort(reverse=True) return sum(x for i, x in enumerate(cost) if i%3 != 2)
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 84161, "end": 103054 }
class ____(test.TestCase): def setUp(self): self._test_precision_at_k = functools.partial( _test_precision_at_k, test_case=self) self._test_precision_at_top_k = functools.partial( _test_precision_at_top_k, test_case=self) self._test_average_precision_at_k = functools.partial( _tes...
MultiLabelPrecisionAtKTest
python
scikit-learn__scikit-learn
sklearn/externals/array_api_compat/common/_linalg.py
{ "start": 875, "end": 930 }
class ____(NamedTuple): Q: Array R: Array
QRResult
python
run-llama__llama_index
llama-index-core/llama_index/core/base/response/schema.py
{ "start": 3601, "end": 5673 }
class ____: """ StreamingResponse object. Returned if streaming=True. Attributes: response_gen: The response generator. """ response_gen: TokenGen source_nodes: List[NodeWithScore] = field(default_factory=list) metadata: Optional[Dict[str, Any]] = None response_txt: Optio...
StreamingResponse
python
encode__django-rest-framework
rest_framework/authentication.py
{ "start": 866, "end": 1488 }
class ____: """ All authentication classes should extend BaseAuthentication. """ def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ raise NotImplementedError(".authenticate() must be overridden.") def authentic...
BaseAuthentication
python
walkccc__LeetCode
solutions/2615. Sum of Distances/2615.py
{ "start": 0, "end": 584 }
class ____: def distance(self, nums: list[int]) -> list[int]: ans = [0] * len(nums) numToIndices = collections.defaultdict(list) for i, num in enumerate(nums): numToIndices[num].append(i) for indices in numToIndices.values(): n = len(indices) if n == 1: continue sumSo...
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/context.py
{ "start": 1158, "end": 13020 }
class ____(PipelineContext): """The connector context is used to store configuration for a specific connector pipeline run.""" DEFAULT_CONNECTOR_ACCEPTANCE_TEST_IMAGE = "airbyte/connector-acceptance-test:dev" def __init__( self, pipeline_name: str, connector: ConnectorWithModifiedF...
ConnectorContext