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 | bottlepy__bottle | test/test_exc.py | {
"start": 87,
"end": 1135
} | class ____(ServerTestBase):
def test_no_exc(self):
@bottle.route('/')
def test(): return 'test'
self.assertBody('test', '/')
def test_memory_error(self):
@bottle.route('/')
def test(): raise MemoryError
with self.assertRaises(MemoryError):
self.urlop... | TestAppException |
python | getsentry__sentry | src/sentry/users/services/user/model.py | {
"start": 4607,
"end": 4807
} | class ____(TypedDict, total=False):
avatar_url: str
avatar_type: int
actor_id: int # TODO(hybrid-cloud): Remove this after the actor migration is complete
is_active: bool
| UserUpdateArgs |
python | getsentry__sentry | src/sentry/api/endpoints/organization_ai_conversations.py | {
"start": 1770,
"end": 11631
} | class ____(OrganizationEventsV2EndpointBase):
"""Endpoint for fetching AI agent conversation traces."""
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.DATA_BROWSING
def get(self, request: Request, organization: Organization) -> Response:
"""
Retrieve... | OrganizationAIConversationsEndpoint |
python | encode__django-rest-framework | tests/test_response.py | {
"start": 9267,
"end": 10766
} | class ____(TestCase):
"""
Covers #807
"""
def test_does_not_append_charset_by_default(self):
"""
Renderers don't include a charset unless set explicitly.
"""
headers = {"HTTP_ACCEPT": RendererA.media_type}
resp = self.client.get('/', **headers)
expected = ... | Issue807Tests |
python | getsentry__sentry | tests/sentry/tasks/test_daily_summary.py | {
"start": 1453,
"end": 44186
} | class ____(
OutcomesSnubaTest, SnubaTestCase, PerformanceIssueTestCase, SlackActivityNotificationTest
):
def store_event_and_outcomes(
self,
project_id,
timestamp,
fingerprint,
category,
release=None,
resolve=True,
level="error",
):
if ... | DailySummaryTest |
python | ray-project__ray | python/ray/autoscaler/node_launch_exception.py | {
"start": 103,
"end": 1238
} | class ____(Exception):
"""A structured exception that can be thrown by a node provider during a
`create_node` call to pass additional information for observability.
"""
def __init__(
self,
category: str,
description: str,
src_exc_info: Optional[Tuple[Any, Any, Any]], # ... | NodeLaunchException |
python | tox-dev__tox | src/tox/config/loader/ini/__init__.py | {
"start": 773,
"end": 4119
} | class ____(StrConvert, Loader[str]):
"""Load configuration from an ini section (ini file is a string to string dictionary)."""
def __init__(
self,
section: Section,
parser: ConfigParser,
overrides: list[Override],
core_section: Section,
section_key: str | None = ... | IniLoader |
python | apache__airflow | providers/yandex/src/airflow/providers/yandex/utils/credentials.py | {
"start": 914,
"end": 3487
} | class ____(TypedDict, total=False):
"""Credentials dict description."""
token: str
service_account_key: dict[str, str]
def get_credentials(
oauth_token: str | None = None,
service_account_json: dict | str | None = None,
service_account_json_path: str | None = None,
) -> CredentialsType:
"... | CredentialsType |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1179006,
"end": 1179567
} | class ____(Generator):
"""
SequenceGenerator schema wrapper.
Parameters
----------
sequence : dict, :class:`SequenceParams`
Generate a sequence of numbers.
name : str
Provide a placeholder name and bind data at runtime.
"""
_schema = {"$ref": "#/definitions/SequenceGene... | SequenceGenerator |
python | astropy__astropy | astropy/units/core.py | {
"start": 74351,
"end": 78288
} | class ____(NamedUnit, metaclass=_UnitMetaClass):
"""
The main unit class.
There are a number of different ways to construct a Unit, but
always returns a `UnitBase` instance. If the arguments refer to
an already-existing unit, that existing unit instance is returned,
rather than a new one.
... | Unit |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 4573,
"end": 5470
} | class ____(dg.ConfigurableIOManager):
def handle_output(self, context: dg.OutputContext, obj):
table_name = context.name
write_dataframe_to_table(name=table_name, dataframe=obj)
def load_input(self, context: dg.InputContext):
if context.upstream_output:
return read_dataframe... | MyIOManager |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ComboBox.py | {
"start": 108,
"end": 7773
} | class ____(QtWidgets.QComboBox):
"""Extends QComboBox to add extra functionality.
* Handles dict mappings -- user selects a text key, and the ComboBox indicates
the selected value.
* Requires item strings to be unique
* Remembers selected value if list is cleared and subsequently repopula... | ComboBox |
python | zarr-developers__zarr-python | src/zarr/core/indexing.py | {
"start": 36727,
"end": 39958
} | class ____(Indexer):
dim_indexers: list[SliceDimIndexer]
shape: tuple[int, ...]
drop_axes: tuple[int, ...]
def __init__(
self, selection: BasicSelection, shape: tuple[int, ...], chunk_grid: ChunkGrid
) -> None:
chunk_shape = get_chunk_shape(chunk_grid)
# handle ellipsis
... | BlockIndexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/asyncio/session.py | {
"start": 59738,
"end": 60464
} | class ____(Generic[_AS]):
__slots__ = ("async_session", "trans")
async_session: _AS
trans: AsyncSessionTransaction
def __init__(self, async_session: _AS):
self.async_session = async_session
async def __aenter__(self) -> _AS:
self.trans = self.async_session.begin()
await se... | _AsyncSessionContextManager |
python | ray-project__ray | rllib/core/learner/tests/test_learner_group.py | {
"start": 9375,
"end": 14661
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_restore_from_path_multi_rl_module_and_individual_modules(self):
"""Tests whether MultiRLModule- and single RLModule state... | TestLearnerGroupCheckpointRestore |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1010084,
"end": 1010410
} | class ____(
sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, TeamAuditEntryData
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("is_ldap_mapped",)
is_ldap_mapped = sgqlc.types.Field(Boolean, graphql_name="isLdapMapped")
| TeamAddMemberAuditEntry |
python | psf__black | tests/data/cases/type_aliases.py | {
"start": 393,
"end": 458
} | class ____:
type InClass = int
type = aliased
print(type(42))
| X |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 76092,
"end": 79618
} | class ____(Request):
"""
Get 'plot' events for the given tasks
:param tasks: List of task IDs
:type tasks: Sequence[str]
:param iters: Max number of latest iterations for which to return debug images
:type iters: int
:param scroll_id: Scroll ID of previous call (used for getting more result... | GetMultiTaskPlotsRequest |
python | plotly__plotly.py | plotly/graph_objs/box/marker/_line.py | {
"start": 233,
"end": 5612
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "box.marker"
_path_str = "box.marker.line"
_valid_props = {"color", "outliercolor", "outlierwidth", "width"}
@property
def color(self):
"""
Sets the marker.line color. It accepts either a specific color
or an array of n... | Line |
python | python-poetry__poetry | tests/repositories/fixtures/pypi.org/generate.py | {
"start": 5982,
"end": 8300
} | class ____:
sha256: str = ""
md5: str = ""
KNOWN_DISTRIBUTION_HASHES = {{
{text},
}}
@pytest.fixture
def dist_hash_getter() -> DistributionHashGetter:
def get_hash(name: str) -> DistributionHash:
return KNOWN_DISTRIBUTION_HASHES.get(name, DistributionHash())
return get_hash
""",
enc... | DistributionHash |
python | pypa__pipenv | pipenv/patched/pip/_internal/index/sources.py | {
"start": 1409,
"end": 2974
} | class ____:
"""Scans directory and caches results"""
def __init__(self, path: str) -> None:
self._path = path
self._page_candidates: List[str] = []
self._project_name_to_urls: Dict[str, List[str]] = defaultdict(list)
self._scanned_directory = False
def _scan_directory(self)... | _FlatDirectoryToUrls |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 11259,
"end": 11364
} | class ____(OpcodeWithArg): # Arg: Number of list items
_FLAGS = HAS_ARGUMENT
__slots__ = ()
| BUILD_LIST |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/view/primitives.py | {
"start": 1300,
"end": 1599
} | class ____:
top_left: Point | None = None
def draw(self, **attributes) -> str:
if self.top_left:
attrs = attributes | {"x": self.top_left.x, "y": self.top_left.y}
else:
attrs = attributes
return tag("rect", **attrs)
@dataclass(frozen=True)
| Rect |
python | python__mypy | mypyc/test/test_run.py | {
"start": 15265,
"end": 15619
} | class ____(TestRun):
"""Run the main multi-module tests in multi-file compilation mode.
In multi-file mode each module gets compiled into a separate C file,
but all modules (C files) are compiled together.
"""
multi_file = True
test_name_suffix = "_multi"
files = ["run-multimodule.test", "... | TestRunMultiFile |
python | simplejson__simplejson | simplejson/tests/test_subclass.py | {
"start": 86,
"end": 190
} | class ____(int):
def __repr__(self):
return 'invalid json'
__str__ = __repr__
| AlternateInt |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverlap1.py | {
"start": 5394,
"end": 5471
} | class ____(Protocol):
def __radd__(self, other: Any, /) -> Any: ...
| DProto1 |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 15639,
"end": 16471
} | class ____(ProjectForm):
"""Form used when importing a project."""
class Meta:
model = Project
fields = ("name", "repo", "default_branch", "language", "remote_repository")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["repo"].widget.attr... | ProjectBasicsForm |
python | huggingface__transformers | src/transformers/models/cohere/modular_cohere.py | {
"start": 11669,
"end": 12026
} | class ____(LlamaModel):
def __init__(self, config: CohereConfig):
super().__init__(config)
self.layers = nn.ModuleList(
[CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = CohereLayerNorm(hidden_size=(config.hidden_size),... | CohereModel |
python | pytorch__pytorch | test/onnx/exporter/test_capture_strategies.py | {
"start": 290,
"end": 2202
} | class ____(common_utils.TestCase):
@common_utils.parametrize(
"strategy_cls",
[
_capture_strategies.TorchExportStrictStrategy,
_capture_strategies.TorchExportNonStrictStrategy,
_capture_strategies.TorchExportDraftExportStrategy,
],
name_fn=lambda s... | ExportStrategiesTest |
python | getsentry__sentry-python | sentry_sdk/profiler/continuous_profiler.py | {
"start": 18276,
"end": 20175
} | class ____:
def __init__(self, options, sdk_info, buffer_size, capture_func):
# type: (Dict[str, Any], SDKInfo, int, Callable[[Envelope], None]) -> None
self.options = options
self.sdk_info = sdk_info
self.buffer_size = buffer_size
self.capture_func = capture_func
se... | ProfileBuffer |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_responses.py | {
"start": 491,
"end": 601
} | class ____(BaseModel):
# No custom docstring, should have no description in tool
data: str
| EmptyDocModel |
python | readthedocs__readthedocs.org | readthedocs/projects/tasks/mixins.py | {
"start": 386,
"end": 3423
} | class ____:
"""Mixin that handles the VCS sync/update."""
def get_version(self, version_pk):
"""
Retrieve version data from the API.
:param version_pk: version pk to sync
:type version_pk: int
:returns: a data-complete version object
:rtype: builds.models.APIVer... | SyncRepositoryMixin |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 440,
"end": 645
} | class ____(ShowFieldTypeAndContent, PolymorphicModel):
"""UUID as primary key example"""
uuid_primary_key = models.UUIDField(primary_key=True)
field1 = models.CharField(max_length=10)
| UUIDModelA |
python | getsentry__sentry | src/sentry/identity/vsts/provider.py | {
"start": 8728,
"end": 9197
} | class ____(OAuth2LoginView):
def get_authorize_params(self, state, redirect_uri):
params = {
"client_id": self.client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"response_mode": "query",
"scope": self.get_scope(),
"state... | VSTSOAuth2LoginView |
python | coleifer__peewee | tests/reflection.py | {
"start": 1835,
"end": 15509
} | class ____(BaseReflectionTestCase):
requires = [ColTypes, Nullable, RelModel, FKPK, Underscores, Category,
Nugget]
def test_generate_models(self):
models = self.introspector.generate_models()
self.assertTrue(set((
'category',
'col_types',
'fkp... | TestReflection |
python | huggingface__transformers | src/transformers/models/arcee/configuration_arcee.py | {
"start": 1299,
"end": 8927
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ArceeModel`]. It is used to instantiate an Arcee
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configur... | ArceeConfig |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 53534,
"end": 54460
} | class ____(atlas_info):
_lib_names = ['f77blas', 'cblas']
def calc_info(self):
lib_dirs = self.get_lib_dirs()
info = {}
opt = self.get_option_single('atlas_libs', 'libraries')
atlas_libs = self.get_libs(opt, self._lib_names + self._lib_atlas)
atlas = self.check_libs2(lib... | atlas_blas_info |
python | doocs__leetcode | solution/0100-0199/0130.Surrounded Regions/Solution2.py | {
"start": 0,
"end": 905
} | class ____:
def solve(self, board: List[List[str]]) -> None:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
m, n = len(board), len(board[0])
p = list(range(m * n + 1))
for i in range(m):
for j in range(n):
... | Solution |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/exception.py | {
"start": 632,
"end": 748
} | class ____(UnityException):
"""
Related to errors with sending actions.
"""
pass
| UnityActionException |
python | huggingface__transformers | src/transformers/models/grounding_dino/processing_grounding_dino.py | {
"start": 2826,
"end": 3433
} | class ____(dict):
message = (
"The key `labels` is will return integer ids in `GroundingDinoProcessor.post_process_grounded_object_detection` "
"output since v4.51.0. Use `text_labels` instead to retrieve string object names."
)
def __getitem__(self, key):
if key == "labels":
... | DictWithDeprecationWarning |
python | walkccc__LeetCode | solutions/2970. Count the Number of Incremovable Subarrays I/2970.py | {
"start": 0,
"end": 1149
} | class ____:
def incremovableSubarrayCount(self, nums: list[int]) -> int:
n = len(nums)
startIndex = self._getStartIndexOfSuffix(nums)
# If the complete array is strictly increasing, the total number of ways we
# can remove elements equals the total number of possible subarrays.
if startIndex == 0:... | Solution |
python | ray-project__ray | python/ray/serve/_private/request_router/common.py | {
"start": 1812,
"end": 1890
} | class ____:
queue_len: int
timestamp: float
| ReplicaQueueLengthCacheEntry |
python | walkccc__LeetCode | solutions/806. Number of Lines To Write String/806.py | {
"start": 0,
"end": 346
} | class ____:
def numberOfLines(self, widths: list[int], s: str) -> list[int]:
numLines = 1
runningWidth = 0
for c in s:
width = widths[ord(c) - ord('a')]
if runningWidth + width <= 100:
runningWidth += width
else:
numLines += 1
runningWidth = width
return [nu... | Solution |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 2824,
"end": 3743
} | class ____:
"""
Shared context for all Actions in a Checkpoint run.
Note that order matters in the Action list, as the context is updated with each Action's result.
"""
def __init__(self) -> None:
self._data: list[tuple[ValidationAction, dict]] = []
@property
def data(self) -> list... | ActionContext |
python | walkccc__LeetCode | solutions/2430. Maximum Deletions on a String/2430.py | {
"start": 0,
"end": 509
} | class ____:
def deleteString(self, s: str) -> int:
n = len(s)
# lcs[i][j] := the number of the same letters of s[i..n) and s[j..n)
lcs = [[0] * (n + 1) for _ in range(n + 1)]
# dp[i] := the maximum number of operations needed to delete s[i..n)
dp = [1] * n
for i in range(n - 1, -1, -1):
... | Solution |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/rolling.py | {
"start": 882,
"end": 2474
} | class ____(DefaultMethod):
"""Builder for default-to-pandas aggregation on a rolling window functions."""
OBJECT_TYPE = "Rolling"
@classmethod
def _build_rolling(cls, func):
"""
Build function that creates a rolling window and executes `func` on it.
Parameters
--------... | RollingDefault |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 21613,
"end": 21942
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MobileBertLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
| MobileBertOnlyMLMHead |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 8191,
"end": 10134
} | class ____(TestBaseAsyncSpiderMiddleware):
"""process_spider_output tests for simple callbacks"""
ITEM_TYPE = dict
MW_SIMPLE = ProcessSpiderOutputSimpleMiddleware
MW_ASYNCGEN = ProcessSpiderOutputAsyncGenMiddleware
MW_UNIVERSAL = ProcessSpiderOutputUniversalMiddleware
@deferred_f_from_coro_f
... | TestProcessSpiderOutputSimple |
python | getsentry__sentry | tests/sentry/dynamic_sampling/tasks/test_tasks.py | {
"start": 1774,
"end": 3932
} | class ____(BaseMetricsLayerTestCase, TestCase, SnubaTestCase):
@staticmethod
def old_date():
return timezone.now() - timedelta(minutes=NEW_MODEL_THRESHOLD_IN_MINUTES + 1)
@staticmethod
def disable_all_biases(project):
project.update_option(
"sentry:dynamic_sampling_biases",
... | TasksTestCase |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/runnables/test_openai_functions.py | {
"start": 490,
"end": 3007
} | class ____(BaseChatModel):
@property
def _llm_type(self) -> str:
return "fake-openai-chat-model"
@override
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,... | FakeChatOpenAI |
python | langchain-ai__langchain | libs/langchain/langchain_classic/memory/vectorstore.py | {
"start": 604,
"end": 4247
} | class ____(BaseMemory):
"""Vector Store Retriever Memory.
Store the conversation history in a vector store and retrieves the relevant
parts of past conversation based on the input.
"""
retriever: VectorStoreRetriever = Field(exclude=True)
"""VectorStoreRetriever object to connect to."""
m... | VectorStoreRetrieverMemory |
python | tensorflow__tensorflow | tensorflow/python/autograph/lang/special_functions_test.py | {
"start": 1055,
"end": 4357
} | class ____(test.TestCase):
def test_match_staging_level(self):
some_tensor = constant_op.constant(0)
tensor_one = special_functions.match_staging_level(1, some_tensor)
python_one = special_functions.match_staging_level(1, 1)
with self.cached_session() as sess:
self.assertTrue(tensor_util.is_tf_... | SpecialFunctionsTest |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 955,
"end": 1231
} | class ____(Interface):
"""An event type that is emitted whenever :app:`Pyramid`
begins to process a new request. See the documentation attached
to :class:`pyramid.events.NewRequest` for more information."""
request = Attribute('The request object')
| INewRequest |
python | docker__docker-py | tests/integration/models_images_test.py | {
"start": 4964,
"end": 5807
} | class ____(BaseIntegrationTest):
def test_tag_and_remove(self):
repo = 'dockersdk.tests.images.test_tag'
tag = 'some-tag'
identifier = f'{repo}:{tag}'
client = docker.from_env(version=TEST_API_VERSION)
image = client.images.pull('alpine:latest')
result = image.tag(... | ImageTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-distance-between-unequal-words-in-array-i.py | {
"start": 41,
"end": 332
} | class ____(object):
def maxDistance(self, words):
"""
:type words: List[str]
:rtype: int
"""
for i in xrange(len(words)//2+1):
if words[~i] != words[0] or words[i] != words[-1]:
return len(words)-i
return 0
| Solution |
python | pydata__xarray | xarray/groupers.py | {
"start": 31006,
"end": 39714
} | class ____(Resampler):
"""Allows grouping using a custom definition of seasons.
Parameters
----------
seasons: Sequence[str]
An ordered list of seasons.
drop_incomplete: bool
Whether to drop seasons that are not completely included in the data.
For example, if a time series ... | SeasonResampler |
python | apache__airflow | providers/apache/kafka/tests/integration/apache/kafka/hooks/test_admin_client.py | {
"start": 1108,
"end": 1837
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="kafka_d",
conn_type="kafka",
extra=json.dumps(client_config),
)
)
d... | TestKafkaAdminClientHook |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_itertools.py | {
"start": 110485,
"end": 111089
} | class ____(__TestCase):
def test_repeat(self):
self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
self.assertEqual(operator.length_hint(repeat(None), 12), 12)
def test_repeat_with_negative_times(self):
self.as... | LengthTransparency |
python | huggingface__transformers | src/transformers/models/afmoe/modeling_afmoe.py | {
"start": 5904,
"end": 6651
} | class ____(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.L... | AfmoeMLP |
python | great-expectations__great_expectations | great_expectations/core/configuration.py | {
"start": 416,
"end": 1237
} | class ____(ABC, SerializableDictDot):
"""Abstract base class for Config objects. Sets the fields that must be included on a Config."""
def __init__(self, id: Optional[str] = None, name: Optional[str] = None) -> None:
self.id = id
self.name = name
super().__init__()
@override
de... | AbstractConfig |
python | python-excel__xlwt | tests/test_easyxf.py | {
"start": 841,
"end": 2255
} | class ____(unittest.TestCase):
def create_example_xls(self, filename):
mkd = datetime.date
hdngs = ['Date', 'Stock Code', 'Quantity', 'Unit Price', 'Value', 'Message']
kinds = 'date text int price money text'.split()
data = [
[mkd(2007, 7, ... | TestUnicode0 |
python | justquick__django-activity-stream | actstream/templatetags/activity_tags.py | {
"start": 2999,
"end": 3861
} | class ____(AsNode):
def render_result(self, context):
action_instance = context['action'] = self.args[0].resolve(context)
templates = [
'actstream/%s/action.html' % action_instance.verb.replace(' ', '_'),
'actstream/action.html',
]
return render_to_string(tem... | DisplayAction |
python | bokeh__bokeh | src/bokeh/models/axes.py | {
"start": 9552,
"end": 12262
} | class ____(Axis):
''' An axis that displays ticks and labels for categorical ranges.
The ``CategoricalAxis`` can handle factor ranges with up to two levels of
nesting, including drawing a separator line between top-level groups of
factors.
'''
# explicit __init__ to support Init signatures
... | CategoricalAxis |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 207600,
"end": 215799
} | class ____(
DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefGradientstringnull
):
"""
FillDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be posit... | FillDatum |
python | numba__numba | numba/cuda/tests/cudadrv/test_cuda_devicerecord.py | {
"start": 3502,
"end": 3808
} | class ____(TestCudaDeviceRecord):
"""
Tests the DeviceRecord class with np.record host types
"""
def setUp(self):
CUDATestCase.setUp(self)
self._create_data(np.recarray)
@skip_on_cudasim('Structured array attr access not supported in simulator')
| TestCudaDeviceRecordWithRecord |
python | ray-project__ray | python/ray/_private/external_storage.py | {
"start": 21417,
"end": 24748
} | class ____(FileSystemStorage):
"""This class is for testing slow object spilling."""
def __init__(self, node_id: str, **kwargs):
super().__init__(node_id, **kwargs)
self._min_delay = 1
self._max_delay = 2
def spill_objects(self, object_refs, owner_addresses) -> List[str]:
d... | SlowFileStorage |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 12694,
"end": 12982
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
self.mode = "some_string"
def forward(self, x):
if self.mode == "some_string":
return F.relu(self.linear1(x))
| StringMember |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 37184,
"end": 37610
} | class ____:
params = [get_benchmark_shapes("TimeReplace")]
param_names = ["shape"]
def setup(self, shape):
rows, cols = shape
self.to_replace = {i: getattr(IMPL, "Timestamp")(i) for i in range(rows)}
self.df = IMPL.DataFrame(np.random.randint(rows, size=(rows, cols)))
execut... | TimeReplace |
python | great-expectations__great_expectations | scripts/cleanup/cleanup_snowflake.py | {
"start": 299,
"end": 2220
} | class ____(BaseSettings):
"""Environment variables for Snowflake connection.
These are injected in via CI, but when running locally, you may use your own credentials.
"""
SNOWFLAKE_CI_USER_PASSWORD: str
SNOWFLAKE_CI_ACCOUNT: str
@property
def connection_string(self) -> str:
return ... | SnowflakeConnectionConfig |
python | getsentry__sentry | tests/sentry/db/models/fields/bitfield/test_bitfield.py | {
"start": 13697,
"end": 14343
} | class ____(unittest.TestCase):
def test_can_unserialize_bithandler(self) -> None:
bf = BitFieldTestModel()
bf.flags.FLAG_0 = True
bf.flags.FLAG_1 = False
data = pickle.dumps(bf)
inst = pickle.loads(data)
self.assertTrue(inst.flags.FLAG_0)
self.assertFalse(inst... | BitFieldSerializationTest |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-maximize-last-elements-in-arrays.py | {
"start": 61,
"end": 688
} | class ____(object):
def minOperations(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
cnt = [0]*2
for x, y in itertools.izip(nums1, nums2):
if not (min(x, y) <= min(nums1[-1], nums2[-1]) and max(x, y) <= max(n... | Solution |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 23127,
"end": 23784
} | class ____(
APIv3Settings,
GenericViewSet,
):
# TODO: migrate code from corporate here.
# NOTE: this viewset is only useful for nested URLs required for notifications:
# /api/v3/organizations/<slug>/notifications/
# However, accessing to /api/v3/organizations/ or /api/v3/organizations/<slug>/ wi... | OrganizationsViewSetBase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-kyve/source_kyve/source.py | {
"start": 279,
"end": 1839
} | class ____(AbstractSource):
def check_connection(self, logger, config: Mapping[str, Any]) -> Tuple[bool, any]:
# check that pools and bundles are the same length
pools = config.get("pool_ids").split(",")
start_ids = config.get("start_ids").split(",")
if not len(pools) == len(start_i... | SourceKyve |
python | getsentry__sentry | src/sentry/api/serializers/models/userreport.py | {
"start": 1012,
"end": 3033
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
attrs: dict[str, _EventUser] = {}
project = Project.objects.get(id=item_list[0].project_id)
retention = quotas.backend.get_event_retention(organization=project.organization)
events = eventstore.backend.get_even... | UserReportSerializer |
python | django__django | tests/inspectdb/tests.py | {
"start": 21049,
"end": 27271
} | class ____(TransactionTestCase):
available_apps = ["inspectdb"]
def test_include_views(self):
"""inspectdb --include-views creates models for database views."""
cursor_execute(
"CREATE VIEW inspectdb_people_view AS "
"SELECT id, name FROM inspectdb_people"
)
... | InspectDBTransactionalTests |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 5480,
"end": 12643
} | class ____(SocketDummyServerTestCase):
"""
Tests for client certificate support.
"""
@classmethod
def setup_class(cls) -> None:
cls.tmpdir = tempfile.mkdtemp()
ca = trustme.CA()
cert = ca.issue_cert("localhost")
encrypted_key = encrypt_key_pem(cert.private_key_pem, b... | TestClientCerts |
python | Netflix__metaflow | metaflow/cmd/develop/__init__.py | {
"start": 113,
"end": 689
} | class ____:
def __init__(self):
pass
@click.group()
@click.pass_context
def cli(ctx):
pass
@cli.group(help="Metaflow develop commands")
@click.option(
"--quiet/--no-quiet",
show_default=True,
default=False,
help="Suppress unnecessary messages",
)
@click.pass_context
def develop(
... | CommandObj |
python | tensorflow__tensorflow | tensorflow/python/framework/type_spec.py | {
"start": 30376,
"end": 40985
} | class ____(TypeSpec, metaclass=abc.ABCMeta):
"""TypeSpec with a batchable tensor encoding.
The batchable tensor encoding is a list of `tf.Tensor`s that supports
batching and unbatching. In particular, stacking (or unstacking)
values with the same `TypeSpec` must be equivalent to stacking (or
unstacking) eac... | BatchableTypeSpec |
python | django__django | tests/queries/tests.py | {
"start": 162789,
"end": 163432
} | class ____(TestCase):
def test_ticket_20101(self):
"""
Tests QuerySet ORed combining in exclude subquery case.
"""
t = Tag.objects.create(name="foo")
a1 = Annotation.objects.create(tag=t, name="a1")
a2 = Annotation.objects.create(tag=t, name="a2")
a3 = Annotat... | Ticket20101Tests |
python | openai__openai-python | src/openai/resources/files.py | {
"start": 1171,
"end": 14032
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> FilesWithRawResponse:
"""
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.github.com... | Files |
python | doocs__leetcode | lcci/01.07.Rotate Matrix/Solution.py | {
"start": 0,
"end": 376
} | class ____:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n >> 1):
for j in range(n):
matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j]
for i in range(n):
for j in range(i):
matr... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-snowflake-cortex/destination_snowflake_cortex/cortex_processor.py | {
"start": 3877,
"end": 15716
} | class ____(SqlProcessorBase):
"""A Snowflake implementation for use with Cortex functions."""
supports_merge_insert = False
"""We use the emulated merge code path because each primary key has multiple rows (chunks)."""
sql_config: SnowflakeCortexConfig
"""The configuration for the Snowflake proces... | SnowflakeCortexSqlProcessor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1409589,
"end": 1409970
} | class ____(sgqlc.types.Type, Node, AuditEntry, RepositoryAuditEntryData, OrganizationAuditEntryData):
"""Audit log entry for a repo.destroy event."""
__schema__ = github_schema
__field_names__ = ("visibility",)
visibility = sgqlc.types.Field(RepoDestroyAuditEntryVisibility, graphql_name="visibility")
... | RepoDestroyAuditEntry |
python | PyCQA__pylint | pylint/checkers/utils.py | {
"start": 15801,
"end": 80376
} | class ____(Exception):
"""A format character in a format string is not one of the supported
format characters.
"""
def __init__(self, index: int) -> None:
super().__init__(index)
self.index = index
def parse_format_string(
format_string: str,
) -> tuple[set[str], int, dict[str, st... | UnsupportedFormatCharacter |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 6166,
"end": 6776
} | class ____(scale_continuous[None]):
"""
Base class for continuous position scales
"""
guide: None = None
def map(self, x, limits=None):
# Position aesthetics don't map, because the coordinate
# system takes care of it.
# But the continuous scale has to deal with out of boun... | scale_position_continuous |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 103692,
"end": 103991
} | class ____(FromGrouping, NamedFromClause):
"""represent a grouping of a named FROM clause
.. versionadded:: 2.0
"""
inherit_cache = True
if TYPE_CHECKING:
def self_group(
self, against: Optional[OperatorType] = None
) -> Self: ...
| NamedFromGrouping |
python | wandb__wandb | wandb/sdk/artifacts/exceptions.py | {
"start": 1524,
"end": 1903
} | class ____(ArtifactStatusError):
"""Raised for Artifact methods or attributes that can't be changed after logging."""
def __init__(self, fullname: str, obj: ArtifactT):
*_, name = fullname.split(".")
msg = f"{fullname!r} used on logged artifact. Can't modify finalized artifact."
super()... | ArtifactFinalizedError |
python | walkccc__LeetCode | solutions/3365. Rearrange K Substrings to Form Target String/3365.py | {
"start": 0,
"end": 258
} | class ____:
def isPossibleToRearrange(self, s: str, t: str, k: int) -> bool:
n = len(s)
return (collections.Counter(s[i:i + n // k] for i in range(0, n, n // k)) ==
collections.Counter(t[i:i + n // k] for i in range(0, n, n // k)))
| Solution |
python | kamyu104__LeetCode-Solutions | Python/linked-list-cycle.py | {
"start": 127,
"end": 431
} | class ____(object):
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
return True
return False
| Solution |
python | getsentry__sentry-python | sentry_sdk/integrations/pure_eval.py | {
"start": 794,
"end": 4605
} | class ____(Integration):
identifier = "pure_eval"
@staticmethod
def setup_once():
# type: () -> None
@add_global_event_processor
def add_executing_info(event, hint):
# type: (Event, Optional[Hint]) -> Optional[Event]
if sentry_sdk.get_client().get_integratio... | PureEvalIntegration |
python | walkccc__LeetCode | solutions/2582. Pass the Pillow/2582.py | {
"start": 0,
"end": 249
} | class ____:
def passThePillow(self, n: int, time: int) -> int:
# Repeat every (n - 1) * 2 seconds.
time %= (n - 1) * 2
if time < n: # Go forward from 1.
return 1 + time
return n - (time - (n - 1)) # Go backward from n.
| Solution |
python | huggingface__transformers | tests/models/mbart/test_tokenization_mbart.py | {
"start": 2974,
"end": 8726
} | class ____(unittest.TestCase):
checkpoint_name = "facebook/mbart-large-en-ro"
src_text = [
" UN Chief Says There Is No Military Solution in Syria",
""" Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the... | MBartEnroIntegrationTest |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_v2_test.py | {
"start": 202167,
"end": 205520
} | class ____(lite_v2_test_util.ModelTest):
@test_util.run_v2_only
def testCOncreteFunctionFloat(self):
root = self._getSimpleVariableModel()
input_data = tf.constant(1.0, shape=[1])
concrete_func = root.f.get_concrete_function(input_data)
# Convert model.
converter = lite.TFLiteConverterV2.from_... | BufferOffsetTest |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 1928,
"end": 2131
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
name: str
is_annotated: bool
location: Location
contains_explicit_any: bool
@dataclasses.dataclass(frozen=True)
| ParameterAnnotationInfo |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_validators.py | {
"start": 2129,
"end": 2563
} | class ____(BaseDataSourceValidator[MockModel]):
field1 = serializers.CharField()
field2 = serializers.IntegerField()
data_source_type_handler = QuerySubscriptionDataSourceHandler
class Meta:
model = MockModel
fields = [
"field1",
"field2",
]
def crea... | MockDataSourceValidator |
python | eth-brownie__brownie | brownie/convert/datatypes.py | {
"start": 10660,
"end": 15996
} | class ____(tuple):
"""Tuple subclass with dict-like functionality, used for iterable return values."""
_abi: Optional[List[ABIComponent]] = None
_dict: Dict[str, Any] = {}
def __new__(
cls,
values: Iterable[Any],
abi: Optional[Sequence[ABIComponent]] = None,
) -> "ReturnVal... | ReturnValue |
python | scipy__scipy | scipy/sparse/tests/test_minmax1d.py | {
"start": 652,
"end": 2643
} | class ____:
def test_minmax(self, spcreator):
D = np.arange(5)
X = spcreator(D)
assert_equal(X.min(), 0)
assert_equal(X.max(), 4)
assert_equal((-X).min(), -4)
assert_equal((-X).max(), 0)
def test_minmax_axis(self, spcreator):
D = np.arange(50)
X ... | Test_MinMaxMixin1D |
python | getsentry__sentry | src/sentry/replays/usecases/ingest/__init__.py | {
"start": 3687,
"end": 3882
} | class ____(TypedDict):
context: EventContext
payload_compressed: bytes
payload: bytes
replay_event: dict[str, Any] | None
replay_video: bytes | None
@dataclasses.dataclass
| Event |
python | nmslib__hnswlib | examples/python/pyw_hnswlib.py | {
"start": 150,
"end": 1948
} | class ____():
def __init__(self, space, dim):
self.index = hnswlib.Index(space, dim)
self.lock = threading.Lock()
self.dict_labels = {}
self.cur_ind = 0
def init_index(self, max_elements, ef_construction=200, M=16):
self.index.init_index(max_elements=max_elements, ef_con... | Index |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 55165,
"end": 59888
} | class ____:
def test_ticket1441(self, xp):
"""Regression test for ticket 1441."""
# Because freqz previously used arange instead of linspace,
# when N was large, it would return one more point than
# requested.
N = 100000
w, h = freqz_zpk(xp.asarray([0.5]), xp.asarra... | TestFreqz_zpk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.