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 | openai__openai-python | src/openai/resources/vector_stores/file_batches.py | {
"start": 33628,
"end": 34196
} | class ____:
def __init__(self, file_batches: AsyncFileBatches) -> None:
self._file_batches = file_batches
self.create = async_to_streamed_response_wrapper(
file_batches.create,
)
self.retrieve = async_to_streamed_response_wrapper(
file_batches.retrieve,
... | AsyncFileBatchesWithStreamingResponse |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 21301,
"end": 22647
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self, name: str, key_id: str, private_key: str, issuer_id: str, vendor: str, start_date: str
):
"""Airbyte Source for Appstore Singer.
Documentation can be found at https://docs.airbyte.com/integrations/sources/appstore
... | AppstoreSingerSource |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 73584,
"end": 77456
} | class ____(_ValidatorFunctionSchema, total=False):
type: Required[Literal['function-after']]
def no_info_after_validator_function(
function: NoInfoValidatorFunction,
schema: CoreSchema,
*,
ref: str | None = None,
json_schema_input_schema: CoreSchema | None = None,
metadata: dict[str, Any] ... | AfterValidatorFunctionSchema |
python | dagster-io__dagster | examples/docs_projects/project_dspy/dspy_modules/puzzle.py | {
"start": 377,
"end": 514
} | class ____:
"""Represents a group in a Connections puzzle."""
name: str
color: str
words: List[str]
@dataclass
| PuzzleGroup |
python | readthedocs__readthedocs.org | readthedocs/redirects/querysets.py | {
"start": 668,
"end": 6754
} | class ____(NoReprQuerySet, models.QuerySet):
"""Redirects take into account their own privacy_level setting."""
use_for_related_fields = True
def _add_from_user_projects(self, queryset, user):
if user.is_authenticated:
projects_pk = AdminPermission.projects(
user=user,
... | RedirectQuerySet |
python | kubernetes-client__python | kubernetes/client/models/v1_node.py | {
"start": 383,
"end": 7016
} | 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... | V1Node |
python | pytest-dev__pytest | testing/code/test_source.py | {
"start": 13690,
"end": 14111
} | class ____:
def setup_class(self) -> None:
self.source = """\
try:
raise ValueError
finally:
raise IndexError(1)
"""
def test_body(self) -> None:
source = getstatement(1, self.source)
assert str(source) == " raise ValueError"
def test_finally(self) -> None:
sourc... | TestTryFinally |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-buy-pens-and-pencils.py | {
"start": 223,
"end": 1577
} | class ____(object):
def waysToBuyPensPencils(self, total, cost1, cost2):
"""
:type total: int
:type cost1: int
:type cost2: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def ceil_div... | Solution |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 8243,
"end": 8356
} | class ____(nodes.Part, nodes.Inline, nodes.FixedTextElement):
"""Node for a single parameter."""
| desc_parameter |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/virtual_with_abi/package.py | {
"start": 188,
"end": 403
} | class ____(Package):
"""Virtual package for mocking an interface with stable ABI ."""
homepage = "https://www.abi.org/"
virtual = True
def test_hello(self):
print("Hello there!")
| VirtualWithAbi |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 38913,
"end": 42264
} | class ____(
collections.namedtuple("InputOptions", [
"experimental_fetch_to_device",
"experimental_replication_mode",
"experimental_place_dataset_on_device",
"experimental_per_replica_buffer_size",
])):
"""Run options for `experimental_distribute_dataset(s_from_function)`.
T... | InputOptions |
python | pytorch__pytorch | torch/_dynamo/variables/tensor.py | {
"start": 65149,
"end": 66002
} | class ____(TensorVariable):
"""
This is a 1-element tensor represents unspecialized python float/int.
"""
_nonvar_fields = {
"raw_value",
"need_unwrap",
*TensorVariable._nonvar_fields,
}
def __init__(
self, proxy: torch.fx.Proxy, *, raw_value=None, need_unwrap=T... | UnspecializedPythonVariable |
python | apache__airflow | providers/docker/tests/unit/docker/test_exceptions.py | {
"start": 1741,
"end": 3226
} | class ____:
@pytest.fixture(autouse=True)
def setup_patchers(self, docker_api_client_patcher):
self.client_mock = mock.MagicMock(spec=APIClient)
self.client_mock.wait.return_value = {"StatusCode": 0}
self.log_messages = ["container log 😁 ", b"byte string container log"]
self.... | TestDockerContainerExceptions |
python | django__django | tests/admin_widgets/tests.py | {
"start": 21774,
"end": 26401
} | class ____(TestDataMixin, TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
band = Band.objects.create(name="Linkin Park")
cls.album = band.album_set.create(
name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg"
)
def test_render(self)... | AdminFileWidgetTests |
python | getsentry__sentry | src/sentry/integrations/jira_server/integration.py | {
"start": 53014,
"end": 56050
} | class ____(IntegrationProvider):
key = IntegrationProviderSlug.JIRA_SERVER.value
name = "Jira Server"
metadata = metadata
integration_cls = JiraServerIntegration
needs_default_identity = True
features = frozenset(
[
IntegrationFeatures.ISSUE_BASIC,
IntegrationFe... | JiraServerIntegrationProvider |
python | walkccc__LeetCode | solutions/2095. Delete the Middle Node of a Linked List/2095.py | {
"start": 0,
"end": 324
} | class ____:
def deleteMiddle(self, head: ListNode | None) -> ListNode | None:
dummy = ListNode(0, head)
slow = dummy
fast = dummy
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# Delete the middle node.
slow.next = slow.next.next
return dummy.next
| Solution |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_synapse_pipeline.py | {
"start": 1537,
"end": 7592
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_mock_connections):
create_mock_connections(
# connection_client_secret
Connection(
conn_id=DEFAULT_CONNECTION_CLIENT_SECRET,
conn_type="azure_synapse",
hos... | TestAzureSynapsePipelineHook |
python | pytorch__pytorch | torch/_dynamo/variables/dicts.py | {
"start": 36741,
"end": 40010
} | class ____(VariableTracker):
# proxies to the original dict_vt
def __init__(self, dv_dict: ConstDictVariable, **kwargs: Any) -> None:
super().__init__(**kwargs)
assert isinstance(dv_dict, ConstDictVariable)
self.dv_dict = dv_dict
def python_type(self) -> type:
return types.M... | MappingProxyVariable |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modeling_lfm2_moe.py | {
"start": 6075,
"end": 6706
} | class ____(nn.Module):
def __init__(self, config: Lfm2MoeConfig, intermediate_size: Optional[int] = None):
super().__init__()
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.w1 = nn.Linea... | Lfm2MoeMLP |
python | getsentry__sentry | src/sentry/auth/providers/saml2/generic/views.py | {
"start": 1850,
"end": 2772
} | class ____(AuthView):
def handle(self, request: HttpRequest, pipeline: AuthHelper) -> HttpResponseBase:
op = "url"
forms: dict[str, Form | None] = {
"url": URLMetadataForm(),
"xml": XMLMetadataForm(),
"idp": SAMLForm(),
}
if "action_save" in requ... | SelectIdP |
python | scikit-learn__scikit-learn | sklearn/manifold/_t_sne.py | {
"start": 19039,
"end": 44044
} | class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
"""T-distributed Stochastic Neighbor Embedding.
t-SNE [1] is a tool to visualize high-dimensional data. It converts
similarities between data points to joint probabilities and tries
to minimize the Kullback-Leibler divergence... | TSNE |
python | numba__numba | numba/tests/test_random.py | {
"start": 39099,
"end": 47337
} | class ____(BaseTest):
"""
Test array-producing variants of np.random.* functions.
"""
def _compile_array_dist(self, funcname, nargs):
qualname = "np.random.%s" % (funcname,)
argstring = ', '.join('abcd'[:nargs])
return jit_with_args(qualname, argstring)
def _check_array_dis... | TestRandomArrays |
python | wandb__wandb | wandb/sdk/launch/agent/run_queue_item_file_saver.py | {
"start": 175,
"end": 1308
} | class ____:
def __init__(
self,
agent_run: Optional["wandb.Run"],
run_queue_item_id: str,
):
self.run_queue_item_id = run_queue_item_id
self.run = agent_run
def save_contents(
self, contents: str, fname: str, file_sub_type: FileSubtypes
) -> Optional[List... | RunQueueItemFileSaver |
python | langchain-ai__langchain | libs/langchain/langchain_classic/output_parsers/retry.py | {
"start": 1106,
"end": 1247
} | class ____(TypedDict):
"""Retry chain input for RetryOutputParser."""
prompt: str
completion: str
| RetryOutputParserRetryChainInput |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classVar2.py | {
"start": 282,
"end": 630
} | class ____:
var1 = ""
def __init__(self) -> None:
self.var2 = ""
# This should generate an error because var2
# is not a class variable.
a: Proto = ProtoImpl()
def func1(x: Proto):
reveal_type(x.var1, expected_text="str")
reveal_type(x.var2, expected_text="str")
reveal_type(x.var3, expe... | ProtoImpl |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py | {
"start": 28859,
"end": 33439
} | class ____(LearningRateSchedule):
"""A LearningRateSchedule that uses a linear cosine decay schedule.
See [Bello et al., ICML2017] Neural Optimizer Search with RL.
https://arxiv.org/abs/1709.07417
For the idea of warm starts here controlled by `num_periods`,
see [Loshchilov & Hutter, ICLR2016] SGDR: Stochas... | LinearCosineDecay |
python | modin-project__modin | modin/tests/pandas/native_df_interoperability/test_compiler_caster.py | {
"start": 8420,
"end": 10178
} | class ____(BaseTestAutoMover):
"""Represents a cloud-hosted query compiler that prefers to stay on the cloud only for big data"""
# Operations are more costly on this engine, even though it can handle larger datasets
_MAX_SIZE_THIS_ENGINE_CAN_HANDLE = BIG_DATA_CLOUD_MIN_NUM_ROWS * 10
_OPERATION_INITIAL... | CloudForBigDataQC |
python | astropy__astropy | astropy/utils/metadata/tests/test_metadata.py | {
"start": 1930,
"end": 2027
} | class ____(MetaBaseTest):
test_class = ExampleData
args = ()
@dataclass
| TestMetaExampleData |
python | getsentry__sentry | tests/sentry/api/endpoints/test_dif_assemble.py | {
"start": 764,
"end": 10180
} | class ____(APITestCase):
def setUp(self) -> None:
self.organization = self.create_organization(owner=self.user)
with assume_test_silo_mode(SiloMode.CONTROL):
self.token = ApiToken.objects.create(user=self.user, scope_list=["project:write"])
self.team = self.create_team(organizati... | DifAssembleEndpoint |
python | walkccc__LeetCode | solutions/2875. Minimum Size Subarray in Infinite Array/2875.py | {
"start": 0,
"end": 687
} | class ____:
def minSizeSubarray(self, nums: list[int], target: int) -> int:
summ = sum(nums)
n = len(nums)
remainingTarget = target % summ
repeatLength = (target // summ) * n
if remainingTarget == 0:
return repeatLength
suffixPlusPrefixLength = n
prefix = 0
prefixToIndex = {0: -... | Solution |
python | ray-project__ray | python/ray/serve/_private/build_app.py | {
"start": 494,
"end": 1330
} | class ____(dict, Generic[K, V]):
"""Dictionary that uses id() for keys instead of hash().
This is necessary because Application objects aren't hashable and we want each
instance to map to a unique key.
"""
def __getitem__(self, key: K) -> V:
if not isinstance(key, int):
key = i... | IDDict |
python | getsentry__sentry | tests/acceptance/test_organization_dashboards.py | {
"start": 1107,
"end": 26995
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
min_ago = before_now(minutes=1).isoformat()
self.store_event(
data={"event_id": "a" * 32, "message": "oh no", "timestamp": min_ago},
project_id=self.project.id,
)
self.dashboard =... | OrganizationDashboardsAcceptanceTest |
python | palantir__python-language-server | pyls/workspace.py | {
"start": 591,
"end": 4300
} | class ____(object):
M_PUBLISH_DIAGNOSTICS = 'textDocument/publishDiagnostics'
M_APPLY_EDIT = 'workspace/applyEdit'
M_SHOW_MESSAGE = 'window/showMessage'
def __init__(self, root_uri, endpoint, config=None):
self._config = config
self._root_uri = root_uri
self._endpoint = endpoin... | Workspace |
python | getsentry__sentry | tests/sentry/api/bases/test_project.py | {
"start": 12359,
"end": 21913
} | class ____(ProjectPermissionBase):
def setUp(self) -> None:
super().setUp()
self.organization.flags.allow_joinleave = False
self.organization.save()
self.team = self.create_team(organization=self.organization)
self.project = self.create_project(organization=self.organization)... | ProjectPermissionNoJoinLeaveTest |
python | great-expectations__great_expectations | great_expectations/data_context/store/gx_cloud_store_backend.py | {
"start": 1113,
"end": 1176
} | class ____(TypedDict):
errors: List[ErrorDetail]
| ErrorPayload |
python | kamyu104__LeetCode-Solutions | Python/find-the-longest-substring-containing-vowels-in-even-counts.py | {
"start": 29,
"end": 529
} | class ____(object):
def findTheLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
VOWELS = "aeiou"
result, mask, lookup = 0, 0, [-2]*(2**len(VOWELS))
lookup[0] = -1
for i, c in enumerate(s):
index = VOWELS.find(c)
mask ... | Solution |
python | django__django | tests/m2m_signals/tests.py | {
"start": 174,
"end": 19116
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.vw = Car.objects.create(name="VW")
cls.bmw = Car.objects.create(name="BMW")
cls.toyota = Car.objects.create(name="Toyota")
cls.wheelset = Part.objects.create(name="Wheelset")
cls.doors = Part.objects.create(n... | ManyToManySignalsTest |
python | realpython__materials | python-property/circle_v6.py | {
"start": 63,
"end": 267
} | class ____:
def __init__(self, radius):
self.radius = radius
@cached_property
def diameter(self):
sleep(0.5) # Simulate a costly computation
return self.radius * 2
| Circle |
python | huggingface__transformers | src/transformers/models/seed_oss/modeling_seed_oss.py | {
"start": 15700,
"end": 18839
} | class ____(SeedOssPreTrainedModel):
def __init__(self, config: SeedOssConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.l... | SeedOssModel |
python | google__flatbuffers | grpc/examples/python/greeter/models/greeter_grpc_fb.py | {
"start": 530,
"end": 1423
} | class ____(object):
'''Interface exported by the server.'''
def SayHello(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def SayManyHellos(self, request, context):
context... | GreeterServicer |
python | django__django | tests/model_enums/tests.py | {
"start": 8126,
"end": 8485
} | class ____(datetime.date, models.Choices):
APOLLO_11 = 1969, 7, 20, "Apollo 11 (Eagle)"
APOLLO_12 = 1969, 11, 19, "Apollo 12 (Intrepid)"
APOLLO_14 = 1971, 2, 5, "Apollo 14 (Antares)"
APOLLO_15 = 1971, 7, 30, "Apollo 15 (Falcon)"
APOLLO_16 = 1972, 4, 21, "Apollo 16 (Orion)"
APOLLO_17 = 1972, 12, ... | MoonLandings |
python | doocs__leetcode | solution/2500-2599/2567.Minimum Score by Changing Two Elements/Solution.py | {
"start": 0,
"end": 166
} | class ____:
def minimizeSum(self, nums: List[int]) -> int:
nums.sort()
return min(nums[-1] - nums[2], nums[-2] - nums[1], nums[-3] - nums[0])
| Solution |
python | numba__numba | numba/tests/test_extending.py | {
"start": 10326,
"end": 10708
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert isinstance(args[0], types.MakeFunctionLiteral)
return signature(types.none, *args)
def mk_func_test_impl():
mk_func_input(lambda a: a)
# -----------------------------------------------------------------------
# Define a types... | MkFuncTyping |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_selection.py | {
"start": 45214,
"end": 47326
} | class ____(AssetSelection):
selected_keys: Sequence[AssetKey]
def resolve_inner(
self, asset_graph: BaseAssetGraph, allow_missing: bool
) -> AbstractSet[AssetKey]:
specified_keys = set(self.selected_keys)
missing_keys = {key for key in specified_keys if not asset_graph.has(key)}
... | KeysAssetSelection |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 2127,
"end": 4390
} | class ____(SyncAPIResource):
@cached_property
def sessions(self) -> Sessions:
return Sessions(self._client)
@cached_property
def transcription_sessions(self) -> TranscriptionSessions:
return TranscriptionSessions(self._client)
@cached_property
def with_raw_response(self) -> Rea... | Realtime |
python | kamyu104__LeetCode-Solutions | Python/find-the-minimum-cost-array-permutation.py | {
"start": 77,
"end": 1033
} | class ____(object):
def findPermutation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
INF = float("inf")
n = len(nums)
dp = [[(INF, -1) for _ in xrange(n-1)] for _ in xrange(1<<(n-1))]
for i in xrange(n-1):
dp[1<<i][i] = (abs... | Solution |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_http_status_code.py | {
"start": 666,
"end": 1681
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_http_status_code"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _... | ColumnValuesToBeValidHttpStatusCode |
python | ray-project__ray | rllib/utils/actor_manager.py | {
"start": 439,
"end": 1612
} | class ____:
"""A wrapper around a result or a RayError thrown during remote task/actor calls.
This is used to return data from `FaultTolerantActorManager` that allows us to
distinguish between RayErrors (remote actor related) and valid results.
"""
def __init__(self, result: Any = None, error: Exc... | ResultOrError |
python | TheAlgorithms__Python | graphs/greedy_best_first.py | {
"start": 1975,
"end": 5389
} | class ____:
"""
>>> grid = TEST_GRIDS[2]
>>> gbf = GreedyBestFirst(grid, (0, 0), (len(grid) - 1, len(grid[0]) - 1))
>>> [x.pos for x in gbf.get_successors(gbf.start)]
[(1, 0), (0, 1)]
>>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1])
(0, 1)
>>> (gbf.start.pos_y + delta[2... | GreedyBestFirst |
python | MongoEngine__mongoengine | tests/utils.py | {
"start": 2955,
"end": 3259
} | class ____(query_counter):
def get_ops(self):
ignore_query = dict(self._ignored_query)
ignore_query["command.count"] = {
"$ne": "system.profile"
} # Ignore the query issued by query_counter
return list(self.db.system.profile.find(ignore_query))
| db_ops_tracker |
python | qdrant__qdrant-client | qdrant_client/async_client_base.py | {
"start": 385,
"end": 12533
} | class ____:
def __init__(self, **kwargs: Any):
pass
async def search_matrix_offsets(
self,
collection_name: str,
query_filter: Optional[types.Filter] = None,
limit: int = 3,
sample: int = 10,
using: Optional[str] = None,
**kwargs: Any,
) -> ty... | AsyncQdrantBase |
python | tensorflow__tensorflow | tensorflow/python/distribute/values.py | {
"start": 18002,
"end": 43644
} | class ____(DistributedDelegate, variables_lib.Variable,
core.Tensor):
"""Holds a map from replica to variables."""
def __init__(self, strategy, values, aggregation, var_policy=None):
if (aggregation == variables_lib.VariableAggregation.MEAN and
not values[0].dtype.is_floating)... | DistributedVariable |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_run.py | {
"start": 2271,
"end": 3111
} | class ____:
def test_template_fields(self):
operator = CloudRunCreateJobOperator(
task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, job=JOB
)
_assert_common_template_fields(operator.template_fields)
assert "job_name" in operator.template_fields
... | TestCloudRunCreateJobOperator |
python | ansible__ansible | lib/ansible/plugins/strategy/host_pinned.py | {
"start": 1720,
"end": 1875
} | class ____(FreeStrategyModule):
def __init__(self, tqm):
super(StrategyModule, self).__init__(tqm)
self._host_pinned = True
| StrategyModule |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 751578,
"end": 756799
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"avatar_url",
"billing_info",
"created_at",
"database_id",
"description",
"description_html",
"location",
"membe... | Enterprise |
python | walkccc__LeetCode | solutions/3044. Most Frequent Prime/3044.py | {
"start": 0,
"end": 774
} | class ____:
def mostFrequentPrime(self, mat: list[list[int]]) -> int:
DIRS = ((1, 0), (1, -1), (0, -1), (-1, -1),
(-1, 0), (-1, 1), (0, 1), (1, 1))
m = len(mat)
n = len(mat[0])
count = collections.Counter()
def isPrime(num: int) -> bool:
return not any(num % i == 0 for i in rang... | Solution |
python | modin-project__modin | modin/db_conn.py | {
"start": 1553,
"end": 5904
} | class ____:
"""
Creates a SQL database connection.
Parameters
----------
lib : str
The library for the SQL connection.
*args : iterable
Positional arguments to pass when creating the connection.
**kwargs : dict
Keyword arguments to pass when creating the connection.
... | ModinDatabaseConnection |
python | getsentry__sentry | src/sentry/migrations/0990_groupowner_json_field.py | {
"start": 188,
"end": 1515
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | ApeWorX__ape | src/ape/plugins/account.py | {
"start": 167,
"end": 1028
} | class ____(PluginType):
"""
An account-related plugin. The plugin must register both
an :class:`ape.api.accounts.AccountContainerAPI` as well as an
:class:`ape.api.accounts.AccountAPI`.
"""
@hookspec
def account_types( # type: ignore[empty-body]
self,
) -> tuple[type["AccountCo... | AccountPlugin |
python | Pylons__pyramid | tests/test_exceptions.py | {
"start": 1797,
"end": 2438
} | class ____(unittest.TestCase):
def _makeOne(self, message):
from pyramid.exceptions import Forbidden
return Forbidden(message)
def test_it(self):
from pyramid.interfaces import IExceptionResponse
e = self._makeOne('forbidden')
self.assertTrue(IExceptionResponse.provide... | TestForbidden |
python | dask__distributed | distributed/collections.py | {
"start": 943,
"end": 7099
} | class ____(MutableSet[T]):
"""A set-like where the `pop` method returns the smallest item, as sorted by an
arbitrary key function. Ties are broken by oldest first.
Values must be compatible with :mod:`weakref`.
Parameters
----------
key: Callable
A function that takes a single element ... | HeapSet |
python | huggingface__transformers | src/transformers/models/moshi/modeling_moshi.py | {
"start": 11714,
"end": 13992
} | class ____(nn.Module):
def __init__(self, input_size, output_size, num_layers):
super().__init__()
# Stack the weights for N layers into a single tensor (num_layers, output_size, input_size)
self.weight = nn.Parameter(torch.randn(num_layers, output_size, input_size))
def forward(self, x... | MoshiFlexibleLinear |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 5952,
"end": 6078
} | class ____(ArgsMismatchError):
"""
Internal error from cond() due to arguments mismatch.
"""
| CondOpArgsMismatchError |
python | kamyu104__LeetCode-Solutions | Python/optimal-partition-of-string.py | {
"start": 42,
"end": 398
} | class ____(object):
def partitionString(self, s):
"""
:type s: str
:rtype: int
"""
result, left = 1, 0
lookup = {}
for i, x in enumerate(s):
if x in lookup and lookup[x] >= left:
left = i
result += 1
look... | Solution |
python | altair-viz__altair | tests/utils/test_plugin_registry.py | {
"start": 96,
"end": 179
} | class ____(PluginRegistry[Callable[[int], int], int]):
pass
| TypedCallableRegistry |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 71957,
"end": 72084
} | class ____(NameError):
pass
# Base class for inline _ModuleStackTracer.__init__.AttrProxy
| _ModuleNotInstalledAsSubmoduleError |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 4031,
"end": 8533
} | class ____(ManagedKafkaBaseOperator):
"""
Create a new Apache Kafka cluster.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param cluster: Required. Configuration... | ManagedKafkaCreateClusterOperator |
python | sqlalchemy__sqlalchemy | examples/generic_associations/discriminator_on_association.py | {
"start": 1415,
"end": 1825
} | class ____(Base):
"""Associates a collection of Address objects
with a particular parent.
"""
__tablename__ = "address_association"
discriminator: Mapped[str] = mapped_column()
"""Refers to the type of parent."""
addresses: Mapped[list["Address"]] = relationship(
back_populates="as... | AddressAssociation |
python | joke2k__faker | faker/providers/automotive/ar_JO/__init__.py | {
"start": 48,
"end": 1567
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``ar_JO`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Jordan
"""
license_formats = (
"{{initials}}-####",
"{{initials}}-#####",
)
def initials(self) -> str:
""... | Provider |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 5899,
"end": 16240
} | class ____(nn.Module):
def __init__(
self,
config: T5Config,
has_relative_attention_bias=False,
layer_idx: Optional[int] = None,
):
super().__init__()
self.is_decoder = config.is_decoder
self.has_relative_attention_bias = has_relative_attention_bias
... | T5Attention |
python | google__pytype | pytype/pyi/definitions.py | {
"start": 7194,
"end": 8957
} | class ____(visitors.Visitor):
"""Visitor for verifying TypeParameters used in mutations are in scope."""
def __init__(self):
super().__init__()
# A stack of type parameters introduced into the scope. The top of the stack
# contains the currently accessible parameter set.
self.type_params_in_scope =... | _VerifyMutators |
python | redis__redis-py | redis/asyncio/cluster.py | {
"start": 72659,
"end": 74770
} | class ____(ABC):
@abstractmethod
async def initialize(self) -> "ClusterPipeline":
"""
Initialize the execution strategy.
See ClusterPipeline.initialize()
"""
pass
@abstractmethod
def execute_command(
self, *args: Union[KeyT, EncodableT], **kwargs: Any
... | ExecutionStrategy |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/redshift_cluster.py | {
"start": 1693,
"end": 16104
} | class ____(AwsBaseOperator[RedshiftHook]):
"""
Creates a new cluster with the specified parameters.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:RedshiftCreateClusterOperator`
:param cluster_identifier: A unique identifi... | RedshiftCreateClusterOperator |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/fabric.py | {
"start": 7416,
"end": 7634
} | class ____(_PowerBIAsset):
"""Microsoft PowerBI DAX."""
_reader_method: ClassVar[FabricReaderMethods] = "evaluate_dax"
type: Literal["powerbi_dax"] = "powerbi_dax"
dax_string: str
@public_api
| PowerBIDax |
python | mlflow__mlflow | mlflow/tracing/constant.py | {
"start": 1843,
"end": 2103
} | class ____:
TOTAL_SIZE_BYTES = "total_size_bytes"
NUM_SPANS = "num_spans"
MAX_SPAN_SIZE_BYTES = "max"
P25_SPAN_SIZE_BYTES = "p25"
P50_SPAN_SIZE_BYTES = "p50"
P75_SPAN_SIZE_BYTES = "p75"
# A set of reserved attribute keys
| TraceSizeStatsKey |
python | apache__airflow | providers/google/tests/unit/google/ads/transfers/test_ads_to_gcs.py | {
"start": 1150,
"end": 2441
} | class ____:
@mock.patch("airflow.providers.google.ads.transfers.ads_to_gcs.GoogleAdsHook")
@mock.patch("airflow.providers.google.ads.transfers.ads_to_gcs.GCSHook")
def test_execute(self, mock_gcs_hook, mock_ads_hook):
op = GoogleAdsToGcsOperator(
gcp_conn_id=gcp_conn_id,
goog... | TestGoogleAdsToGcsOperator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 5680,
"end": 6441
} | class ____:
"""Demo."""
@overload
def bar(self, x: int) -> int: ...
@overload
def bar(self, x: str) -> str:
...
def bar(self, x: int | str) -> int | str:
return x
# end
# E302
"""Main module."""
def fn():
pass
# end
# E302
import sys
def get_sys_path():
return sys.pa... | Foo |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 28218,
"end": 30283
} | class ____(greentest.TestCase):
def test_simple(self):
with gevent.spawn(gevent.sleep, timing.SMALL_TICK) as g:
self.assert_greenlet_spawned(g)
# It is completed after the suite
self.assert_greenlet_finished(g)
def test_wait_in_suite(self):
with gevent.spawn(self._r... | TestContextManager |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes7.py | {
"start": 114,
"end": 265
} | class ____(Generic[T]):
pass
IntBaseClass = BaseClass[float]
# This should generate an error because the same
# base class is used twice.
| BaseClass |
python | sympy__sympy | sympy/polys/domains/domain.py | {
"start": 3070,
"end": 3775
} | class ____(AbsElement, Protocol):
"""An element that can be compared to other elements.
Must support ``<``, ``<=``, ``>``, ``>=``.
"""
def __lt__(self, other: Self, /) -> bool: ...
def __le__(self, other: Self, /) -> bool: ...
def __gt__(self, other: Self, /) -> bool: ...
def __ge__(self, o... | OrderedElement |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 91198,
"end": 97570
} | class ____:
"""Object representing an advertised importable object"""
def __init__(
self,
name: str,
module_name: str,
attrs: Iterable[str] = (),
extras: Iterable[str] = (),
dist: Distribution | None = None,
) -> None:
if not MODULE(module_name):
... | EntryPoint |
python | django__django | tests/model_fields/test_durationfield.py | {
"start": 2204,
"end": 2704
} | class ____(SimpleTestCase):
def test_invalid_string(self):
field = models.DurationField()
with self.assertRaises(exceptions.ValidationError) as cm:
field.clean("not a datetime", None)
self.assertEqual(cm.exception.code, "invalid")
self.assertEqual(
cm.exceptio... | TestValidation |
python | celery__celery | celery/beat.py | {
"start": 6520,
"end": 16356
} | class ____:
"""Scheduler for periodic tasks.
The :program:`celery beat` program may instantiate this class
multiple times for introspection purposes, but then with the
``lazy`` argument set. It's important for subclasses to
be idempotent when this argument is set.
Arguments:
schedule ... | Scheduler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 41842,
"end": 44649
} | class ____(_AbstractRelationshipLoader):
"""A relationship loader that emits a second SELECT statement."""
__slots__ = ()
def _setup_for_recursion(self, context, path, loadopt, join_depth=None):
effective_path = (
context.compile_state.current_path or orm_util.PathRegistry.root
... | _PostLoader |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 23718,
"end": 25547
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch... | BertForPreTrainingOutput |
python | pytorch__pytorch | torch/multiprocessing/queue.py | {
"start": 1123,
"end": 1477
} | class ____(multiprocessing.queues.SimpleQueue):
def _make_methods(self):
if not isinstance(self._reader, ConnectionWrapper):
self._reader: ConnectionWrapper = ConnectionWrapper(self._reader)
self._writer: ConnectionWrapper = ConnectionWrapper(self._writer)
super()._make_metho... | SimpleQueue |
python | matplotlib__matplotlib | galleries/examples/specialty_plots/skewt.py | {
"start": 1185,
"end": 2602
} | class ____(maxis.XTick):
def draw(self, renderer):
# When adding the callbacks with `stack.callback`, we fetch the current
# visibility state of the artist with `get_visible`; the ExitStack will
# restore these states (`set_visible`) at the end of the block (after
# the draw).
... | SkewXTick |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/breakpoint_table_view.py | {
"start": 1123,
"end": 1416
} | class ____:
# Triggers
ClearAllBreakpoints = 'clear_all_breakpoints_action'
ClearBreakpoint = 'clear_breakpoint_action'
EditBreakpoint = 'edit_breakpoint_action'
# --- Model
# ----------------------------------------------------------------------------
| BreakpointTableViewActions |
python | sympy__sympy | sympy/polys/polyoptions.py | {
"start": 9814,
"end": 10071
} | class ____(BooleanOption, metaclass=OptionType):
"""``greedy`` option to polynomial manipulation functions. """
option = 'greedy'
requires: list[str] = []
excludes = ['domain', 'split', 'gaussian', 'extension', 'modulus', 'symmetric']
| Greedy |
python | fluentpython__example-code-2e | 17-it-generator/sentence_iter2.py | {
"start": 222,
"end": 501
} | class ____:
def __init__(self, text):
self.text = text
def __repr__(self):
return f'Sentence({reprlib.repr(self.text)})'
def __iter__(self):
word_iter = RE_WORD.finditer(self.text) # <1>
return SentenceIter(word_iter) # <2>
| Sentence |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-rayyan/llama_index/readers/rayyan/base.py | {
"start": 169,
"end": 3989
} | class ____(BaseReader):
"""
Rayyan reader. Reads articles from a Rayyan review.
Args:
credentials_path (str): Rayyan credentials path.
rayyan_url (str, optional): Rayyan URL. Defaults to https://rayyan.ai.
Set to an alternative URL if you are using a non-production Rayyan instan... | RayyanReader |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran_tests/test_translator.py | {
"start": 1283,
"end": 2690
} | class ____(DagsterFivetranTranslator):
def get_asset_spec(self, props: FivetranConnectorTableProps) -> AssetSpec:
default_spec = super().get_asset_spec(props)
return default_spec.replace_attributes(
key=default_spec.key.with_prefix("prefix"),
metadata={**default_spec.metadata... | MyCustomTranslator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_column07.py | {
"start": 315,
"end": 1348
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_column07.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | scrapy__scrapy | scrapy/utils/testproc.py | {
"start": 1798,
"end": 2353
} | class ____(ProcessProtocol):
def __init__(self) -> None:
self.deferred: Deferred[TestProcessProtocol] = Deferred()
self.out: bytes = b""
self.err: bytes = b""
self.exitcode: int | None = None
def outReceived(self, data: bytes) -> None:
self.out += data
def errReceiv... | TestProcessProtocol |
python | plotly__plotly.py | plotly/graph_objs/choroplethmapbox/_stream.py | {
"start": 233,
"end": 3556
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmapbox"
_path_str = "choroplethmapbox.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpo... | Stream |
python | getsentry__sentry | src/sentry/integrations/metric_alerts.py | {
"start": 2112,
"end": 2277
} | class ____(TypedDict):
title_link: str
title: str
text: str
status: str
logo_url: str
date_started: NotRequired[datetime | None]
| AttachmentInfo |
python | coleifer__peewee | tests/fields.py | {
"start": 45676,
"end": 46018
} | class ____(TestModel):
nq = ForeignKeyField(NQ, backref='items')
nq_null = ForeignKeyField(NQ, backref='null_items', null=True)
nq_lazy = ForeignKeyField(NQ, lazy_load=False, backref='lazy_items')
nq_lazy_null = ForeignKeyField(NQ, lazy_load=False,
backref='lazy_null_i... | NQItem |
python | getsentry__sentry | tests/sentry/models/test_releasefile.py | {
"start": 7157,
"end": 10276
} | class ____(TransactionTestCase):
tick = 0.1 # seconds
def _create_update_fn(self, initial_delay, locked_delay, files, create):
def f():
sleep(initial_delay * self.tick)
with _ArtifactIndexGuard(self.release, None).writable_data(create=create) as data:
sleep(lock... | ArtifactIndexGuardTestCase |
python | django__django | django/db/migrations/serializer.py | {
"start": 5057,
"end": 5589
} | class ____(BaseSerializer):
def serialize(self):
enum_class = self.value.__class__
module = enum_class.__module__
if issubclass(enum_class, enum.Flag):
members = list(self.value)
else:
members = (self.value,)
return (
" | ".join(
... | EnumSerializer |
python | docker__docker-py | tests/unit/utils_test.py | {
"start": 16779,
"end": 22544
} | class ____(unittest.TestCase):
def test_split_port_with_host_ip(self):
internal_port, external_port = split_port("127.0.0.1:1000:2000")
assert internal_port == ["2000"]
assert external_port == [("127.0.0.1", "1000")]
def test_split_port_with_protocol(self):
for protocol in ['tcp... | PortsTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.