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 | google__pytype | pytype/tests/test_stdlib2.py | {
"start": 3809,
"end": 18265
} | class ____(test_base.BaseTest, test_utils.TestCollectionsMixin):
"""Tests for files in typeshed/stdlib."""
def test_collections_smoke_test(self):
# These classes are not fully implemented in typing.py.
self.Check("""
import collections
collections.AsyncIterable
collections.AsyncIterator
... | StdlibTestsFeatures |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 6714,
"end": 8346
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(
self,
name: str,
host: str,
routing_key: str,
ssl: Optional[bool] = None,
port: Optional[int] = None,
virtual_host: Optional[str] = None,
username: Optional[str] = None,
passwor... | RabbitmqDestination |
python | protocolbuffers__protobuf | python/google/protobuf/descriptor.py | {
"start": 1669,
"end": 2974
} | class ____(object):
"""Wrapper class of threading.Lock(), which is allowed by 'with'."""
def __new__(cls):
self = object.__new__(cls)
self._lock = threading.Lock() # pylint: disable=protected-access
return self
def __enter__(self):
self._lock.acquire()
def __exit__(self, exc_type, exc_value,... | _Lock |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-meta/llama_index/llms/meta/base.py | {
"start": 150,
"end": 1390
} | class ____(OpenAILike):
"""
Llama LLM.
Examples:
`pip install llama-index-llms-meta`
```python
from llama_index.llms.meta import LlamaLLM
# set api key in env or in llm
# import os
# os.environ["LLAMA_API_KEY"] = "your api key"
llm = LlamaLLM(
... | LlamaLLM |
python | pytorch__pytorch | test/test_fx_passes.py | {
"start": 17722,
"end": 18266
} | class ____:
@staticmethod
def forward(x):
x += 3
x = x.dequantize()
x = torch.sigmoid(x)
x = x.to(torch.float16)
return x
@staticmethod
def pattern(x):
x = x.dequantize()
x = torch.sigmoid(x)
x = x.to(torch.float16)
return x
t... | QuantizationModel |
python | jina-ai__jina | jina/serve/runtimes/gateway/streamer.py | {
"start": 19242,
"end": 22482
} | class ____:
def __init__(self, connection_pool: GrpcConnectionPool, executor_name: str) -> None:
self._connection_pool: GrpcConnectionPool = connection_pool
self.executor_name = executor_name
async def post(
self,
inputs: DocumentArray,
request_size: int = 100,
o... | _ExecutorStreamer |
python | numba__numba | numba/core/errors.py | {
"start": 18817,
"end": 18913
} | class ____(NumbaError):
"""
Functionality is deprecated.
"""
pass
| DeprecationError |
python | ansible__ansible | lib/ansible/plugins/become/__init__.py | {
"start": 710,
"end": 5210
} | class ____(AnsiblePlugin):
name = None # type: str | None
# messages for detecting prompted password issues
fail = tuple() # type: tuple[str, ...]
missing = tuple() # type: tuple[str, ...]
# many connection plugins cannot provide tty, set to True if your become
# plugin requires a tty, i.e... | BecomeBase |
python | pyodide__pyodide | tools/backport.py | {
"start": 2380,
"end": 3793
} | class ____:
"""Store the history of the GitHub PRs with a map from pr_number to CommitInfo"""
commits: dict[int, CommitInfo]
@classmethod
def from_git(self, *args):
result = run(["git", "log", "--oneline", *args], capture_output=True)
lines = result.stdout.splitlines()
return C... | CommitHistory |
python | realpython__materials | solid-principles-python/file_manager_srp.py | {
"start": 644,
"end": 909
} | class ____:
def __init__(self, filename):
self.path = Path(filename)
def read(self, encoding="utf-8"):
return self.path.read_text(encoding)
def write(self, data, encoding="utf-8"):
self.path.write_text(data, encoding)
| FileManager |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scalarbool.py | {
"start": 498,
"end": 1393
} | class ____(int):
def __new__(cls, *args, **kw):
# type: (Any, Any, Any) -> Any
anchor = kw.pop('anchor', None)
b = int.__new__(cls, *args, **kw)
if anchor is not None:
b.yaml_set_anchor(anchor, always_dump=True)
return b
@property
def anchor(self):
... | ScalarBoolean |
python | getsentry__sentry | src/sentry/issue_detection/detectors/experiments/n_plus_one_api_calls_detector.py | {
"start": 952,
"end": 11039
} | class ____(PerformanceDetector):
"""
Detect parallel network calls to the same parameterized endpoint.
[-------- transaction -----------]
[-------- parent span -----------]
[n0] https://service.io/resources/1/?id=12443
[n1] https://service.io/resources/2/?id=13342
[... | NPlusOneAPICallsExperimentalDetector |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amplitude/integration_tests/integration_test.py | {
"start": 406,
"end": 4905
} | class ____(YamlDeclarativeSource):
def __init__(self):
with open("../manifest.yaml", "r") as yaml_file:
primary_manifest = yaml.safe_load(yaml_file)
test_manifest = primary_manifest
stream_list = []
# We are only testing the annotations and cohorts streams
for ... | SourceAmplitudeTest |
python | joke2k__faker | faker/providers/person/zh_TW/__init__.py | {
"start": 81,
"end": 27338
} | class ____(PersonProvider):
# update: 2025 04 30
# source:
# 中華民國(ROC)人口 2025 3月: 23,374,742
# (As of March 2025, the total population of the Republic of China (Taiwan) is 23,374,742.)
# https://www.ris.gov.tw/app/portal/346
# 臺灣原住民人口 2024 12月 612,000
# (As of December 2024, the indigenous... | Provider |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 55797,
"end": 58297
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global people, employees, tags, peopleTags
people = Table(
"people",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
)... | InheritingEagerTest |
python | huggingface__transformers | src/transformers/models/swin2sr/modeling_swin2sr.py | {
"start": 6164,
"end": 6699
} | class ____(nn.Module):
r"""Image to Patch Unembedding"""
def __init__(self, config):
super().__init__()
self.embed_dim = config.embed_dim
def forward(self, embeddings, x_size):
batch_size, height_width, num_channels = embeddings.shape
embeddings = embeddings.transpose(1, 2... | Swin2SRPatchUnEmbeddings |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 967,
"end": 1096
} | class ____(BaseModel, extra="forbid"):
abort_transfer: "AbortShardTransfer" = Field(..., description="")
| AbortTransferOperation |
python | ApeWorX__ape | tests/functional/test_project.py | {
"start": 31758,
"end": 34434
} | class ____:
@pytest.fixture
def mock_github(self, mocker):
return mocker.MagicMock()
@pytest.fixture(scope="class")
def gitmodules(self):
return """
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
branch = v1.5.2
[submodule "lib... | TestFoundryProject |
python | spyder-ide__spyder | spyder/plugins/shortcuts/widgets/table.py | {
"start": 18535,
"end": 24115
} | class ____(QAbstractTableModel):
def __init__(self, parent):
QAbstractTableModel.__init__(self)
self._parent = parent
self.shortcuts = []
self.scores = []
self.rich_text = []
self.normal_text = []
self.context_rich_text = []
self.letters = ''
... | ShortcutsModel |
python | pydantic__pydantic | pydantic-core/tests/validators/test_is_instance.py | {
"start": 183,
"end": 210
} | class ____(Foo):
pass
| Bar |
python | numba__numba | numba/cuda/cudadrv/nvvm.py | {
"start": 6589,
"end": 14569
} | class ____(object):
def __init__(self):
self.driver = NVVM()
self._handle = nvvm_program()
err = self.driver.nvvmCreateProgram(byref(self._handle))
self.driver.check_error(err, 'Failed to create CU')
def __del__(self):
driver = NVVM()
err = driver.nvvmDestroyProg... | CompilationUnit |
python | pytorch__pytorch | test/test_fake_tensor.py | {
"start": 2564,
"end": 40906
} | class ____(TestCase):
def checkType(self, t, device_str, size):
self.assertTrue(isinstance(t, FakeTensor))
self.assertEqual(t.device.type, device_str)
self.assertEqual(list(t.size()), size)
@unittest.skipIf(not RUN_CUDA, "requires cuda")
def test_cuda_initialized(self):
# do... | FakeTensorTest |
python | huggingface__transformers | src/transformers/models/albert/modeling_albert.py | {
"start": 1636,
"end": 5675
} | class ____(nn.Module):
"""
Construct the embeddings from word, position and token_type embeddings.
"""
def __init__(self, config: AlbertConfig):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
self... | AlbertEmbeddings |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 129515,
"end": 131726
} | class ____(Response):
"""
Response of projects.get_task_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if
'include_system' is set to 'true' in the request
:type system_tags: Sequ... | GetTaskTagsResponse |
python | doocs__leetcode | solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/Solution.py | {
"start": 0,
"end": 221
} | class ____:
def averageValue(self, nums: List[int]) -> int:
s = n = 0
for x in nums:
if x % 6 == 0:
s += x
n += 1
return 0 if n == 0 else s // n
| Solution |
python | django__django | django/utils/dateformat.py | {
"start": 1485,
"end": 5935
} | class ____(Formatter):
def __init__(self, obj):
self.data = obj
self.timezone = None
if isinstance(obj, datetime):
# Timezone is only supported when formatting datetime objects, not
# date objects (timezone information not appropriate), or time
# objects ... | TimeFormat |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/pex_builder/parse_workspace.py | {
"start": 104,
"end": 1220
} | class ____:
name: str
directory: str
build_folder: str
location_file: str
def get_locations(dagster_cloud_yaml_file) -> list[Location]:
"""Returns list of locations parsed from dagster_cloud.yaml."""
base_dir = os.path.abspath(os.path.dirname(dagster_cloud_yaml_file))
with open(dagster_cl... | Location |
python | tox-dev__tox | src/tox/config/loader/toml/_replace.py | {
"start": 3949,
"end": 5952
} | class ____(ReplaceReference):
def __init__(self, conf: Config, loader: TomlLoader) -> None:
self.conf = conf
self.loader = loader
def __call__(self, value: str, conf_args: ConfigLoadArgs) -> str | None:
if match := _REFERENCE_PATTERN.search(value):
settings = match.groupdict... | TomlReplaceLoader |
python | streamlit__streamlit | lib/streamlit/elements/layouts.py | {
"start": 1953,
"end": 47147
} | class ____:
@gather_metrics("container")
def container(
self,
*,
border: bool | None = None,
key: Key | None = None,
width: Width = "stretch",
height: Height = "content",
horizontal: bool = False,
horizontal_alignment: HorizontalAlignment = "left",... | LayoutsMixin |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 50985,
"end": 57541
} | class ____(TestCase):
"""Test code generation for the different loop types defined by ufunc.
This test relies on class variables to configure the test. Subclasses
of this class can just override some of these variables to check other
ufuncs in a different compilation context. The variables supported ar... | _LoopTypesTester |
python | eth-brownie__brownie | brownie/network/contract.py | {
"start": 31794,
"end": 47719
} | class ____(_DeployedContractBase):
"""
Object to interact with a deployed contract outside of a project.
"""
def __init__(
self,
address_or_alias: HexAddress | ContractName,
*args: Any,
owner: Optional[AccountsType] = None,
**kwargs: Any,
) -> None:
"... | Contract |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 5652,
"end": 7196
} | class ____(test_lib.TestCase):
def _log_poisson_loss(self, x, z, compute_full_loss=False):
lpl = np.exp(x) - z * x
if compute_full_loss:
stirling_approx = z * np.log(z) - z + 0.5 * np.log(2. * np.pi * z)
lpl += np.ma.masked_array(stirling_approx, mask=(z <= 1)).filled(0.)
return lpl
def te... | LogPoissonLossTest |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 26404,
"end": 27918
} | class ____(Container):
"""
Accordion Group (pane) object. It wraps given fields inside an accordion
tab. It takes accordion tab name as first argument.
Tab object. It wraps fields in a div whose default class is "tab-pane" and
takes a name as first argument.
Attributes
----------
templ... | AccordionGroup |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_ddp_integration.py | {
"start": 10037,
"end": 12663
} | class ____(BoringModel):
def configure_optimizers(self):
return ZeroRedundancyOptimizer(self.layer.parameters(), optimizer_class=torch.optim.Adam, lr=0.1)
# ZeroRedundancyOptimizer internally calls `torch.load` with `weights_only` not set, triggering the FutureWarning
@pytest.mark.filterwarnings("ignore::... | BoringZeroRedundancyOptimizerModel |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0087_relink_crons_to_compatible_issue_workflows.py | {
"start": 1996,
"end": 13585
} | class ____:
"""Represents a workflow with all its conditions and actions."""
workflow: Any
project_id: int
environment_id: int | None
frequency: int | None
when_conditions: tuple[ConditionData, ...] = field(default_factory=tuple)
action_groups: tuple[ActionGroupData, ...] = field(default_fa... | WorkflowData |
python | scrapy__scrapy | tests/test_extension_periodic_log.py | {
"start": 1785,
"end": 2127
} | class ____(PeriodicLog):
def set_a(self):
self.stats._stats = stats_dump_1
def set_b(self):
self.stats._stats = stats_dump_2
def extension(settings: dict[str, Any] | None = None) -> CustomPeriodicLog:
crawler = get_crawler(MetaSpider, settings)
return CustomPeriodicLog.from_crawler(cr... | CustomPeriodicLog |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/black/cases/class_blank_parentheses.py | {
"start": 423,
"end": 541
} | class ____ (
):
def func_for_testing(self, first, second):
sum = first + second
return sum
| NormalClass |
python | tensorflow__tensorflow | tensorflow/python/profiler/model_analyzer_test.py | {
"start": 1750,
"end": 31972
} | class ____(test.TestCase):
def _no_rewrite_session_config(self):
rewriter_config = rewriter_config_pb2.RewriterConfig(
pin_to_host_optimization=rewriter_config_pb2.RewriterConfig.OFF)
graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config)
return config_pb2.ConfigProto(graph_opti... | PrintModelAnalysisTest |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 1233,
"end": 1409
} | class ____(ProxyBase):
class Meta:
proxy = True
def __unicode__(self):
return f"<ProxyB: {self.title}>"
# Internals for management command tests
| ProxyB |
python | davidhalter__jedi | test/static_analysis/star_arguments.py | {
"start": 2140,
"end": 2237
} | class ____(): pass
#! 12 type-error-star-star
simple(1, **A())
#! 11 type-error-star
simple(1, *1)
| A |
python | pydantic__pydantic | pydantic/types.py | {
"start": 104314,
"end": 105431
} | class ____(_fields.PydanticMetadata, BaseMetadata):
"""A `FailFast` annotation can be used to specify that validation should stop at the first error.
This can be useful when you want to validate a large amount of data and you only need to know if it's valid or not.
You might want to enable this setting if... | FailFast |
python | PrefectHQ__prefect | src/integrations/prefect-aws/tests/observers/test_ecs_observer.py | {
"start": 43344,
"end": 44066
} | class ____:
@patch("prefect_aws.observers.ecs.ecs_observer")
async def test_start_and_stop_observer(self, mock_observer):
mock_observer.run = AsyncMock(
side_effect=lambda started_event: started_event.set()
)
await start_observer()
mock_observer.run.assert_called_on... | TestObserverManagement |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 958,
"end": 2672
} | class ____(Definition):
__slots__ = ('loc', 'operation', 'name', 'variable_definitions', 'directives', 'selection_set',)
_fields = ('operation', 'name', 'variable_definitions', 'directives', 'selection_set',)
def __init__(self, operation, selection_set, name=None, variable_definitions=None, directives=None... | OperationDefinition |
python | walkccc__LeetCode | solutions/3189. Minimum Moves to Get a Peaceful Board/3189.py | {
"start": 0,
"end": 347
} | class ____:
def minMoves(self, rooks: list[list[int]]) -> int:
n = len(rooks)
sortedByRow = sorted(rooks, key=lambda x: x[0])
sortedByCol = sorted(rooks, key=lambda x: x[1])
return (sum(abs(i - row) for (i, _), row in zip(sortedByRow, range(n))) +
sum(abs(j - col) for (_, j), col in zip(so... | Solution |
python | PyCQA__pylint | tests/functional/a/access/access_member_before_definition.py | {
"start": 329,
"end": 758
} | class ____:
A = 23
B = A
def __getattr__(self, attr):
try:
return self.__repo
except AttributeError:
self.__repo = attr
return attr
def catchme(self, attr):
"""no AttributeError caught"""
try:
return self._repo # [access-... | Bbbb |
python | tiangolo__fastapi | docs_src/request_form_models/tutorial002.py | {
"start": 84,
"end": 267
} | class ____(BaseModel):
username: str
password: str
model_config = {"extra": "forbid"}
@app.post("/login/")
async def login(data: FormData = Form()):
return data
| FormData |
python | Lightning-AI__lightning | src/lightning/pytorch/_graveyard/hpu.py | {
"start": 1216,
"end": 1440
} | class ____:
def __init__(self, *_: Any, **__: Any) -> None:
raise NotImplementedError(
"The `SingleHPUStrategy` class has been removed. Please contact developer@lightning.ai"
)
| SingleHPUStrategy |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/execute_in_process_result.py | {
"start": 661,
"end": 5868
} | class ____(ExecutionResult):
"""Result object returned by in-process testing APIs.
Users should not instantiate this object directly. Used for retrieving run success, events, and outputs from execution methods that return this object.
This object is returned by:
- :py:meth:`dagster.GraphDefinition.exe... | ExecuteInProcessResult |
python | ansible__ansible | test/integration/targets/jinja_plugins/filter_plugins/bad_filter.py | {
"start": 180,
"end": 261
} | class ____:
def filters(self):
raise TypeError('bad_filter')
| FilterModule |
python | dask__distributed | distributed/shuffle/tests/test_shuffle.py | {
"start": 96395,
"end": 96825
} | class ____(ShuffleSchedulerPlugin):
def __init__(self, scheduler):
super().__init__(scheduler)
self.counts = defaultdict(int)
def get(self, *args, **kwargs):
self.counts["get"] += 1
return super().get(*args, **kwargs)
def get_or_create(self, *args, **kwargs):
self.c... | RequestCountingSchedulerPlugin |
python | chroma-core__chroma | chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py | {
"start": 481,
"end": 5552
} | class ____(SparseEmbeddingFunction[Documents]):
def __init__(
self,
api_key_env_var: str = "CHROMA_API_KEY",
model: ChromaCloudSpladeEmbeddingModel = ChromaCloudSpladeEmbeddingModel.SPLADE_PP_EN_V1,
):
"""
Initialize the ChromaCloudSpladeEmbeddingFunction.
Args:
... | ChromaCloudSpladeEmbeddingFunction |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/cpython/mac_os.py | {
"start": 611,
"end": 2194
} | class ____(CPython, ABC):
@classmethod
def can_describe(cls, interpreter):
return is_mac_os_framework(interpreter) and super().can_describe(interpreter)
def create(self):
super().create()
# change the install_name of the copied python executables
target = self.desired_mach_... | CPythonmacOsFramework |
python | ray-project__ray | rllib/models/torch/mingpt.py | {
"start": 4067,
"end": 7829
} | class ____(nn.Module):
"""an unassuming Transformer block"""
def __init__(self, config: GPTConfig):
super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embed)
self.attn = CausalSelfAttention(config)
self.ln_2 = nn.LayerNorm(config.n_embed)
self.mlp = nn.ModuleDict(
... | Block |
python | lepture__authlib | tests/django/test_oauth2/models.py | {
"start": 3364,
"end": 4044
} | class ____(Model, AuthorizationCodeMixin):
user = ForeignKey(User, on_delete=CASCADE)
client_id = CharField(max_length=48, db_index=True)
code = CharField(max_length=120, unique=True, null=False)
redirect_uri = TextField(default="", null=True)
response_type = TextField(default="")
scope = TextFi... | OAuth2Code |
python | PrefectHQ__prefect | tests/client/api/test_flow_runs.py | {
"start": 222,
"end": 4971
} | class ____:
@pytest.fixture
async def flow_runs(self, flow, work_queue_1, session):
flow_2 = await models.flows.create_flow(
session=session,
flow=actions.FlowCreate(name="another-test"),
)
flow_run_1 = await models.flow_runs.create_flow_run(
session=... | TestReadFlowRuns |
python | astropy__astropy | astropy/coordinates/builtin_frames/baseradec.py | {
"start": 1457,
"end": 2017
} | class ____(BaseCoordinateFrame):
"""
A base class that defines default representation info for frames that
represent longitude and latitude as Right Ascension and Declination
following typical "equatorial" conventions.
"""
frame_specific_representation_info = {
r.SphericalRepresentation... | BaseRADecFrame |
python | PyCQA__pylint | tests/functional/a/arguments.py | {
"start": 6907,
"end": 8341
} | class ____:
def _pick_fruit(fruit):
def _print_selection(self):
print(f"Selected: {fruit}!")
return _print_selection
pick_apple = _pick_fruit("apple")
pick_pear = _pick_fruit("pear")
picker = FruitPicker()
picker.pick_apple()
picker.pick_pear()
def name1(apple, /, **kwargs):
... | FruitPicker |
python | crytic__slither | slither/core/declarations/solidity_variables.py | {
"start": 4206,
"end": 5343
} | class ____(SourceMapping):
def __init__(self, name: str) -> None:
super().__init__()
self._check_name(name)
self._name = name
# dev function, will be removed once the code is stable
def _check_name(self, name: str) -> None:
assert name in SOLIDITY_VARIABLES or name.endswith(... | SolidityVariable |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams5.py | {
"start": 380,
"end": 503
} | class ____[T]:
...
# This should generate an error because variadic type params don't
# support bound expressions.
| ClassE |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/diag_op_test.py | {
"start": 22603,
"end": 31133
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testSquare(self):
with self.session():
v = np.array([1.0, 2.0, 3.0])
mat = np.array([[0.0, 1.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]])
mat_set_diag = np.array([[1.0, 1.0, 0.0], [1.0, 2.0, 1.0],
[1.0, ... | MatrixSetDiagTest |
python | jazzband__django-polymorphic | example/pexp/models.py | {
"start": 1969,
"end": 2048
} | class ____(NormalModelB):
field3 = models.CharField(max_length=10)
| NormalModelC |
python | joke2k__faker | tests/providers/test_color.py | {
"start": 14281,
"end": 14633
} | class ____:
"""Test de_CH color provider methods"""
def test_color_name(self, faker, num_samples):
for _ in range(num_samples):
color_name = faker.color_name()
assert isinstance(color_name, str)
assert color_name in DeChColorProvider.all_colors.keys()
ass... | TestDeCh |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 3660,
"end": 4470
} | class ____(Operation):
def call(self, x):
return backend.nn.softplus(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["keras.ops.softplus", "keras.ops.nn.softplus"])
def softplus(x):
"""Softplus activation function.
It is defined as `f(x)... | Softplus |
python | getsentry__sentry | src/sentry/identity/bitbucket/provider.py | {
"start": 372,
"end": 603
} | class ____(Provider):
key = IntegrationProviderSlug.BITBUCKET.value
name = "Bitbucket"
def get_pipeline_views(self) -> list[PipelineView[IdentityPipeline]]:
return [BitbucketLoginView()]
| BitbucketIdentityProvider |
python | pytorch__pytorch | torch/testing/_internal/distributed/fake_pg.py | {
"start": 119,
"end": 1126
} | class ____(dist.Store):
"""
A fake store is a fake Key-Value store simply for initialization usage
the of fake process group, one can either use FakeStore or HashStore.
"""
def _create_fake_pg(common_opts, backend_opts):
"""
A fake process group (not related to FakeTensor) is a process group w... | FakeStore |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 332240,
"end": 333158
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdateDiscussion"""
__schema__ = github_schema
__field_names__ = ("discussion_id", "title", "body", "category_id", "client_mutation_id")
discussion_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="discussionId")
"""The Node... | UpdateDiscussionInput |
python | getsentry__sentry | src/sentry/snuba/metrics/fields/base.py | {
"start": 30827,
"end": 31386
} | class ____(DerivedMetricExpressionDefinition, MetricExpressionBase, ABC):
def _raise_entity_validation_exception(self, func_name: str) -> None:
raise DerivedMetricParseException(
f"Method `{func_name}` can only be called on instance of "
f"{self.__class__.__name__} "
f"{g... | DerivedMetricExpression |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 16913,
"end": 21031
} | class ____:
project_id: int
event_id: str
def query_suspect_span_groups(
snuba_params: SnubaParams,
fields: list[str],
query: str | None,
span_ops: list[str] | None,
exclude_span_ops: list[str] | None,
span_groups: list[str] | None,
direction: str,
orderby: str,
limit: int,... | EventID |
python | walkccc__LeetCode | solutions/253. Meeting Rooms II/253.py | {
"start": 0,
"end": 368
} | class ____:
def minMeetingRooms(self, intervals: list[list[int]]) -> int:
minHeap = [] # Store the end times of each room.
for start, end in sorted(intervals):
# There's no overlap, so we can reuse the same room.
if minHeap and start >= minHeap[0]:
heapq.heappop(minHeap)
heapq.heap... | Solution |
python | django__django | tests/serializers/models/base.py | {
"start": 1360,
"end": 1521
} | class ____(models.Model):
name = models.CharField(max_length=255)
category = models.ForeignKey(Category, models.CASCADE)
objects = TopicManager()
| Topic |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops.py | {
"start": 16104,
"end": 211194
} | class ____:
"""Use Python2/Python3 division delegation to implement divide for tensors."""
def __init__(self, x, name):
"""Construct DivideDelegateWithName.
Args:
x: Tensor to use as left operand in operator overloads
name: The name that is preferred for the op created.
"""
self.x = x
... | DivideDelegateWithName |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 1579,
"end": 3855
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(
config.vocab_size, config.input_embedding_size, padding_idx=config.pad_token_id
)
... | RemBertEmbeddings |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/conjecture/test_provider.py | {
"start": 18949,
"end": 21413
} | class ____(ExhaustibleProvider):
scope = "verified"
@pytest.mark.parametrize("provider", [ExhaustibleProvider, UnsoundVerifierProvider])
def test_notes_incorrect_verification(provider):
msg = "backend='p' claimed to verify this test passes - please send them a bug report!"
with temp_register_backend("p", ... | UnsoundVerifierProvider |
python | django__django | tests/model_fields/models.py | {
"start": 6681,
"end": 6980
} | class ____(models.Model):
ip = models.GenericIPAddressField(null=True, protocol="ipv4")
###############################################################################
# These models aren't used in any test, just here to ensure they validate
# successfully.
# See ticket #16570.
| GenericIPAddress |
python | neetcode-gh__leetcode | python/2554-maximum-number-of-integers-to-choose-from-a-range-i.py | {
"start": 0,
"end": 454
} | class ____:
def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:
nums = {x:1 for x in range(1, n + 1)} # hashmap for storing the required elements
for i in banned:
if nums.get(i):
del nums[i]
sum = 0
count = 0
for i in nums:
... | Solution |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 30387,
"end": 31718
} | class ____(nn.Module):
def __init__(self, config: EdgeTamVideoConfig):
super().__init__()
hidden_size = config.memory_encoder_hidden_size
output_channels = config.memory_encoder_output_channels
self.mask_downsampler = EdgeTamVideoMaskDownSampler(config)
self.feature_projecti... | EdgeTamVideoMemoryEncoder |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_point_within_geo_region.py | {
"start": 1024,
"end": 3098
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
# Please see {some doc} for information on how to choose an id string for your Metric.
condition_metric_name = "column_values.point_within_geo_region"
condition_value_keys = ("country_iso_a3", "polyg... | ColumnValuesPointWithinGeoRegion |
python | hynek__structlog | tests/processors/test_processors.py | {
"start": 1727,
"end": 2426
} | class ____:
def test_decodes(self):
"""
Byte strings get decoded (as UTF-8 by default).
"""
ud = UnicodeDecoder()
assert {"foo": "b\xe4r"} == ud(None, None, {"foo": b"b\xc3\xa4r"})
def test_passes_arguments(self):
"""
Encoding options are passed into the... | TestUnicodeDecoder |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py | {
"start": 20531,
"end": 20859
} | class ____:
"""Test edge cases and error handling."""
def test_empty_tools_list_raises_error(self) -> None:
"""Test that empty tools list raises an error in schema creation."""
with pytest.raises(AssertionError, match="tools must be non-empty"):
_create_tool_selection_response([])
| TestEdgeCases |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 14105,
"end": 14355
} | class ____(BaseSafeMigrationTest):
app = "good_flow_delete_field_pending_with_not_null_m2m_app"
migrate_from = "0001"
migrate_to = "0002"
def test(self) -> None:
self.run_migration()
| DeletionFieldGoodDeletePendingWithNotNullM2M |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/pipes/client.py | {
"start": 5225,
"end": 6357
} | class ____(ABC):
@abstractmethod
@contextmanager
def inject_context(self, context_data: "PipesContextData") -> Iterator[PipesParams]:
"""A `@contextmanager` that injects context data into the external process.
This method should write the context data to a location accessible to the externa... | PipesContextInjector |
python | doocs__leetcode | solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/Solution.py | {
"start": 0,
"end": 151
} | class ____:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
| Solution |
python | cython__cython | Cython/Compiler/StringEncoding.py | {
"start": 677,
"end": 1632
} | class ____:
"""Assemble a byte string or char value.
"""
def __init__(self, target_encoding):
self.chars = []
self.target_encoding = target_encoding
def append(self, characters):
if isinstance(characters, str):
characters = characters.encode(self.target_encoding)
... | BytesLiteralBuilder |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/mock_communicator.py | {
"start": 849,
"end": 3931
} | class ____(Communicator):
def __init__(
self,
discrete_action=False,
visual_inputs=0,
num_agents=3,
brain_name="RealFakeBrain",
vec_obs_size=3,
):
"""
Python side of the grpc communication. Python is the client and Unity the server
"""
... | MockCommunicator |
python | huggingface__transformers | src/transformers/models/fsmt/modeling_fsmt.py | {
"start": 19672,
"end": 26099
} | class ____(nn.Module):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DecoderLayer`]
Args:
config: FSMTConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: FSMTConfig):
super().__init__()
self.d... | FSMTDecoder |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/utils/config.py | {
"start": 11348,
"end": 14620
} | class ____:
"""
Configuration for statistics-based query planning.
These options can be configured via environment variables
with the prefix ``CUDF_POLARS__EXECUTOR__STATS_PLANNING__``.
Parameters
----------
use_io_partitioning
Whether to use estimated file-size statistics to calcu... | StatsPlanningOptions |
python | kubernetes-client__python | kubernetes/client/models/v1_storage_os_persistent_volume_source.py | {
"start": 383,
"end": 8636
} | 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... | V1StorageOSPersistentVolumeSource |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_container.py | {
"start": 11751,
"end": 13643
} | class ____:
def test_valid(self) -> None:
prop0 = bcpc.Tuple()
assert prop0.is_valid(())
prop1 = bcpc.Tuple(Int)
assert prop1.is_valid((0,))
prop2 = bcpc.Tuple(Int, Int)
assert prop2.is_valid((0, 0))
prop = bcpc.Tuple(Int, String, bcpc.List(Int))
... | Test_Tuple |
python | doocs__leetcode | solution/0600-0699/0606.Construct String from Binary Tree/Solution.py | {
"start": 192,
"end": 623
} | class ____:
def tree2str(self, root: Optional[TreeNode]) -> str:
def dfs(root):
if root is None:
return ''
if root.left is None and root.right is None:
return str(root.val)
if root.right is None:
return f'{root.val}({dfs(roo... | Solution |
python | django__django | tests/gis_tests/test_geoip2.py | {
"start": 654,
"end": 7736
} | class ____(SimpleTestCase):
fqdn = "sky.uk"
ipv4_str = "2.125.160.216"
ipv6_str = "::ffff:027d:a0d8"
ipv4_addr = ipaddress.ip_address(ipv4_str)
ipv6_addr = ipaddress.ip_address(ipv6_str)
query_values = (fqdn, ipv4_str, ipv6_str, ipv4_addr, ipv6_addr)
expected_city = {
"accuracy_radi... | GeoLite2Test |
python | great-expectations__great_expectations | great_expectations/metrics/batch/batch_column_types.py | {
"start": 220,
"end": 279
} | class ____(BaseModel):
name: str
type: Any
| ColumnType |
python | donnemartin__system-design-primer | solutions/system_design/query_cache/query_cache_snippets.py | {
"start": 1071,
"end": 2610
} | class ____(object):
def __init__(self, MAX_SIZE):
self.MAX_SIZE = MAX_SIZE
self.size = 0
self.lookup = {}
self.linked_list = LinkedList()
def get(self, query):
"""Get the stored query result from the cache.
Accessing a node updates its position to the front of ... | Cache |
python | tiangolo__fastapi | tests/test_additional_responses_custom_validationerror.py | {
"start": 178,
"end": 261
} | class ____(JSONResponse):
media_type = "application/vnd.api+json"
| JsonApiResponse |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 23999,
"end": 24707
} | class ____:
class B:
def foo():
bar(
"[{}]: xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx={}"
" xxxx_xxxx_xxxxxxxxxx={}, xxxx={})".format(
xxxx._xxxxxxxxxxxxxx, xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx, xxxxxxx
),
varX,
... | A |
python | getsentry__sentry | tests/sentry_plugins/bitbucket/endpoints/test_webhooks.py | {
"start": 395,
"end": 1895
} | class ____(APITestCase):
def test_get(self) -> None:
project = self.project # force creation
url = f"/plugins/bitbucket/organizations/{project.organization.id}/webhook/"
response = self.client.get(url)
assert response.status_code == 405
def test_unregistered_event(self) -> N... | WebhookTest |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-dappier/tests/test_tools_dappier_real_time_search.py | {
"start": 609,
"end": 2601
} | class ____:
def test_init_without_api_key_raises_value_error(self, monkeypatch):
monkeypatch.delenv("DAPPIER_API_KEY", raising=False)
dappier_client = MagicMock()
with patch("dappier.Dappier", return_value=dappier_client):
with pytest.raises(ValueError) as excinfo:
... | TestDappierRealTimeSearchTool |
python | langchain-ai__langchain | libs/core/tests/unit_tests/fake/callbacks.py | {
"start": 6848,
"end": 9683
} | class ____(AsyncCallbackHandler, BaseFakeCallbackHandlerMixin):
"""Fake async callback handler for testing."""
@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_
@property
def ignore_chain(self) -> bool:
"""Whether to igno... | FakeAsyncCallbackHandler |
python | walkccc__LeetCode | solutions/1409. Queries on a Permutation With Key/1409.py | {
"start": 0,
"end": 421
} | class ____:
def __init__(self, n: int):
self.sums = [0] * (n + 1)
def add(self, i: int, delta: int) -> None:
while i < len(self.sums):
self.sums[i] += delta
i += FenwickTree.lowbit(i)
def get(self, i: int) -> int:
summ = 0
while i > 0:
summ += self.sums[i]
i -= FenwickTre... | FenwickTree |
python | dagster-io__dagster | scripts/gen_airbyte_classes.py | {
"start": 2845,
"end": 3928
} | class ____(SchemaType):
def __init__(self, schema_type_str: str, const_value: Optional[Any] = None):
if schema_type_str in TYPE_MAPPING:
self.type_str = TYPE_MAPPING[schema_type_str]
else:
self.type_str = schema_type_str
self._const_value = const_value
def __str_... | RawType |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_change_char_type_that_unsafe_app/migrations/0001_initial.py | {
"start": 153,
"end": 647
} | class ____(CheckedMigration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestTable",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, s... | Migration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.