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 | plotly__plotly.py | plotly/basedatatypes.py | {
"start": 215845,
"end": 216282
} | class ____(BasePlotlyType):
"""
Base class for all types in the trace hierarchy
"""
def __init__(self, plotly_name, **kwargs):
super(BaseTraceHierarchyType, self).__init__(plotly_name, **kwargs)
def _send_prop_set(self, prop_path_str, val):
if self.parent:
# ### Inform ... | BaseTraceHierarchyType |
python | fluentpython__example-code-2e | 23-descriptor/bulkfood/model_v5.py | {
"start": 707,
"end": 1004
} | class ____(Validated):
"""a string with at least one non-space character"""
def validate(self, name, value):
value = value.strip()
if not value: # <2>
raise ValueError(f'{name} cannot be blank')
return value # <3>
# end::MODEL_V5_VALIDATED_SUB[]
| NonBlank |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 458,
"end": 2279
} | class ____:
params = [
(np.int64, np.uint64, np.float64),
("unique_monotonic_inc", "nonunique_monotonic_inc"),
]
param_names = ["dtype", "index_structure"]
def setup(self, dtype, index_structure):
N = 10**6
indices = {
"unique_monotonic_inc": Index(range(N), ... | NumericSeriesIndexing |
python | jazzband__django-waffle | waffle/tests/test_utils.py | {
"start": 182,
"end": 663
} | class ____(TestCase):
def test_overridden_setting(self):
prefix = get_setting('CACHE_PREFIX')
self.assertEqual(settings.WAFFLE_CACHE_PREFIX, prefix)
def test_default_setting(self):
age = get_setting('MAX_AGE')
self.assertEqual(defaults.MAX_AGE, age)
def test_override_settin... | GetSettingTests |
python | ray-project__ray | python/ray/data/tests/test_split.py | {
"start": 1250,
"end": 35434
} | class ____:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
return self.value
def test_equal_split(shutdown_only):
ray.init(num_cpus=2)
def range2x(n):
return ray.data.range(2 * n)
def counts(shards):
@ray.remote(num_cpus=0)
... | Counter |
python | streamlit__streamlit | lib/tests/streamlit/elements/text_area_test.py | {
"start": 12261,
"end": 13251
} | class ____:
pass
def test_text_input_interaction():
"""Test interactions with an empty text_area widget."""
def script():
import streamlit as st
st.text_area("the label", value=None)
at = AppTest.from_function(script).run()
text_area = at.text_area[0]
assert text_area.value ... | SomeObj |
python | pytorch__pytorch | test/test_proxy_tensor.py | {
"start": 4748,
"end": 29699
} | class ____(TestCase):
# WARNING: if any of your inputs are index tensors, DO NOT use this
# function
def _test(self, f, inps):
fx_f = make_fx(f, tracing_mode=self.tracing_mode)(*inps)
new_inps = tree_map(_create_new_input, inps)
r1 = fx_f(*new_inps)
r2 = f(*new_inps)
... | TestGenericProxyTensor |
python | sqlalchemy__sqlalchemy | test/sql/test_sequences.py | {
"start": 4750,
"end": 13558
} | class ____(fixtures.TestBase):
__requires__ = ("sequences",)
__sparse_driver_backend__ = True
@classmethod
def setup_test_class(cls):
cls.seq = normalize_sequence(config, Sequence("my_sequence"))
cls.seq.create(testing.db)
@classmethod
def teardown_test_class(cls):
cls.... | SequenceExecTest |
python | django-import-export__django-import-export | tests/core/tests/resources.py | {
"start": 1577,
"end": 1695
} | class ____(resources.ModelResource):
class Meta:
model = Profile
exclude = ("user",)
| ProfileResource |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 21660,
"end": 27179
} | class ____(Scroll):
''' *toolbar icon*: |wheel_zoom_icon|
The wheel zoom tool will zoom the plot in and out, centered on the
current mouse location.
The wheel zoom tool also activates the border regions of a Plot for
"single axis" zooming. For instance, zooming in the vertical border or
axis w... | WheelZoomTool |
python | google__pytype | build_scripts/release.py | {
"start": 2587,
"end": 3833
} | class ____:
"""Context manager to build the pytype distribution package."""
def __enter__(self):
sdist_cmd = ["python", "setup.py", "sdist"]
print(f"Creating distribution package: {sdist_cmd}\n")
returncode, stdout = build_utils.run_cmd(sdist_cmd)
if returncode != 0:
raise ReleaseError(f"Runn... | DistributionPackage |
python | tornadoweb__tornado | demos/facebook/facebook.py | {
"start": 3613,
"end": 4146
} | class ____(tornado.web.UIModule):
def render(self, post):
return self.render_string("modules/post.html", post=post)
async def main():
tornado.options.parse_command_line()
if not (options.facebook_api_key and options.facebook_secret):
print("--facebook_api_key and --facebook_secret must be ... | PostModule |
python | sphinx-doc__sphinx | sphinx/transforms/__init__.py | {
"start": 3283,
"end": 5012
} | class ____(SphinxTransform):
"""Replace some substitutions if they aren't defined in the document."""
# run before the default Substitutions
default_priority = 210
def apply(self, **kwargs: Any) -> None:
# only handle those not otherwise defined in the document
to_handle = _DEFAULT_SUB... | DefaultSubstitutions |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 616,
"end": 816
} | class ____(str, BaseEnum):
"""Define how the query's hybrid fusion operation should be performed."""
RANKED = "FUSION_TYPE_RANKED"
RELATIVE_SCORE = "FUSION_TYPE_RELATIVE_SCORE"
| HybridFusion |
python | wandb__wandb | wandb/vendor/pygments/styles/bw.py | {
"start": 357,
"end": 1355
} | class ____(Style):
background_color = "#ffffff"
default_style = ""
styles = {
Comment: "italic",
Comment.Preproc: "noitalic",
Keyword: "bold",
Keyword.Pseudo: "nobold",
Keyword.Type: "nobold",
... | BlackWhiteStyle |
python | kubernetes-client__python | kubernetes/client/api/logs_api.py | {
"start": 543,
"end": 9507
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | LogsApi |
python | huggingface__transformers | src/transformers/core_model_loading.py | {
"start": 7296,
"end": 9084
} | class ____(ConversionOps):
"""Inverse of :class:`MergeModulelist` using explicit split sizes per group."""
def __init__(self, dim: int = 0):
self.dim = dim
@torch.no_grad
def convert(
self, input_dict: dict[str, torch.Tensor], source_patterns: list[str], target_patterns: list[str], **k... | SplitModulelist |
python | networkx__networkx | networkx/algorithms/tests/test_dominance.py | {
"start": 3442,
"end": 9811
} | class ____:
@pytest.mark.parametrize("G", [nx.Graph(), nx.MultiGraph()])
def test_raises_undirected(self, G):
"""Check that `dominance_frontiers` raises for undirected graphs."""
with pytest.raises(
nx.NetworkXNotImplemented, match=r"not implemented for undirected"
):
... | TestDominanceFrontiers |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_histograms.py | {
"start": 1002,
"end": 15855
} | class ____(TestCase):
def test_simple(self):
n = 100
v = np.random.rand(n)
(a, b) = histogram(v)
# check if the sum of the bins equals the number of samples
assert_equal(np.sum(a, axis=0), n)
# check that the bin counts are evenly spaced when the data is from
... | TestHistogram |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_async_job_manager.py | {
"start": 12687,
"end": 16194
} | class ____:
def test_refresh_throttle_uses_max_and_pings_account(self, mocker, api):
# Arrange: per_account=42, per_application=77 -> expect 77
api.api.ads_insights_throttle = MyFacebookAdsApi.Throttle(42.0, 77.0)
acct = mocker.Mock()
api.get_account.return_value = acct
limi... | TestAPILimit |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride4.py | {
"start": 1107,
"end": 1247
} | class ____(BaseC):
# This should generate an error because of the upper bound.
def method1[T: SubclassC](self, x: T) -> T: ...
| SubclassC |
python | viewflow__viewflow | viewflow/this_object.py | {
"start": 360,
"end": 1390
} | class ____:
"""
Reference to a method for forward references in class bodies.
This class is used to defer the resolution of a method reference until the
class is fully constructed. This is particularly useful in workflow or state
machine implementations where the flow references are declared before... | ThisMethod |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 41191,
"end": 42620
} | class ____(ASTDeclarator):
def __init__(self, declId: ASTNestedName, size: ASTExpression) -> None:
self.declId = declId
self.size = size
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTDeclaratorNameBitField):
return NotImplemented
return self.de... | ASTDeclaratorNameBitField |
python | PyCQA__pylint | tests/functional/p/protected_access.py | {
"start": 368,
"end": 561
} | class ____:
def __init__(self):
self._meta = 42
self._manager = 24
self._teta = 29
OBJ = Protected()
OBJ._meta
OBJ._manager
OBJ._teta # [protected-access]
| Protected |
python | pytorch__pytorch | test/dynamo/test_unspec.py | {
"start": 32050,
"end": 32878
} | class ____(torch._dynamo.test_case.TestCase):
def test_builtin_functions_on_device(self, device):
def fn(x, scaler):
m = torch.nn.ReLU()
m.to(device)
y = m(x) * scaler
return y
x = torch.randn([3, 6], device=device)
scaler = 0.23 # 0.23 is un... | UnspecTestsDevice |
python | doocs__leetcode | solution/1900-1999/1926.Nearest Exit from Entrance in Maze/Solution.py | {
"start": 0,
"end": 723
} | class ____:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
m, n = len(maze), len(maze[0])
i, j = entrance
q = deque([(i, j)])
maze[i][j] = "+"
ans = 0
while q:
ans += 1
for _ in range(len(q)):
i, j = q... | Solution |
python | getsentry__sentry | src/sentry/utils/sentry_apps/request_buffer.py | {
"start": 1468,
"end": 7558
} | class ____:
"""
Create a data structure to store basic information about Sentry App webhook requests in Redis
This should store the last 100 requests and last 100 errors (in different keys) for each event type, for each Sentry App
"""
def __init__(self, sentry_app: SentryApp | RpcSentryApp) -> None... | SentryAppWebhookRequestsBuffer |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/uniform.py | {
"start": 1319,
"end": 7093
} | class ____(distribution.Distribution):
"""Uniform distribution with `low` and `high` parameters.
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; a, b) = I[a <= x < b] / Z
Z = b - a
```
where
- `low = a`,
- `high = b`,
- `Z` is the normalizing constant, and
... | Uniform |
python | dask__dask | dask/dataframe/dask_expr/_indexing.py | {
"start": 10703,
"end": 14359
} | class ____(LocBase):
_projection_passthrough = True
@functools.cached_property
def start(self):
if self.iindexer.start is not None:
start = _get_partitions(self.frame, self.iindexer.start)
else:
start = 0
return start
@functools.cached_property
def s... | LocSlice |
python | keras-team__keras | keras/src/ops/image_test.py | {
"start": 490,
"end": 8937
} | class ____(testing.TestCase):
def setUp(self):
# Defaults to channels_last
self.data_format = backend.image_data_format()
backend.set_image_data_format("channels_last")
return super().setUp()
def tearDown(self):
backend.set_image_data_format(self.data_format)
ret... | ImageOpsDynamicShapeTest |
python | huggingface__transformers | tests/models/owlvit/test_modeling_owlvit.py | {
"start": 4434,
"end": 7268
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as OWLVIT does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (OwlViTVisionModel,) if is_torch_available() else ()
test_resize_emb... | OwlViTVisionModelTest |
python | kamyu104__LeetCode-Solutions | Python/minimum-replacements-to-sort-the-array.py | {
"start": 44,
"end": 435
} | class ____(object):
def minimumReplacement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
result = 0
curr = nums[-1]
for x in reversed(nums):
cnt = ceil_divide(x, curr)
... | Solution |
python | GoogleCloudPlatform__python-docs-samples | service_extensions/callouts/add_header/server.py | {
"start": 2672,
"end": 3737
} | class ____(service_pb2_grpc.ExternalProcessorServicer):
def Process(
self,
request_iterator: Iterator[service_pb2.ProcessingRequest],
context: ServicerContext,
) -> Iterator[service_pb2.ProcessingResponse]:
"Process the client request and add example headers"
for request ... | CalloutProcessor |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_sheet_views3.py | {
"start": 301,
"end": 4762
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_sheet_views() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_sheet_views1(self):
"""Test the _write_sheet_views() met... | TestWriteSheetViews |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/spacetobatch_op_test.py | {
"start": 23619,
"end": 27392
} | class ____(test.TestCase):
def _checkProperties(self, input_shape, block_shape, base_paddings, paddings,
crops):
"""Checks that `paddings` and `crops` satisfy invariants."""
num_block_dims = len(block_shape)
self.assertEqual(len(input_shape), num_block_dims)
if base_paddings is... | RequiredSpaceToBatchPaddingsTest |
python | plotly__plotly.py | plotly/graph_objs/_icicle.py | {
"start": 215,
"end": 66356
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "icicle"
_valid_props = {
"branchvalues",
"count",
"customdata",
"customdatasrc",
"domain",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
"hovertemplate",
"hovertemplate... | Icicle |
python | django__django | tests/generic_relations/models.py | {
"start": 852,
"end": 934
} | class ____(TaggedItem):
value = models.PositiveIntegerField()
| ValuableTaggedItem |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 32066,
"end": 35797
} | class ____(GroupedElement, Generative, TypedReturnsRows[Unpack[_Ts]]):
"""Core construct that represents a load of ORM objects from various
:class:`.ReturnsRows` and other classes including:
:class:`.Select`, :class:`.TextClause`, :class:`.TextualSelect`,
:class:`.CompoundSelect`, :class`.Insert`, :cla... | FromStatement |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 11784,
"end": 12053
} | class ____(PydanticValueError):
code = 'decimal.max_digits'
msg_template = 'ensure that there are no more than {max_digits} digits in total'
def __init__(self, *, max_digits: int) -> None:
super().__init__(max_digits=max_digits)
| DecimalMaxDigitsError |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 14976,
"end": 15460
} | class ____(LazyModuleMixin, torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def initialize_parameters(self, input):
with torch.no_grad():
self._param = torch.nn.Parameter(
torch.empty(input.x["a"][0].shape).fill_(0.5)
)
def forward(s... | LazyLayerWithNamedTupleInput |
python | sanic-org__sanic | sanic/server/websockets/impl.py | {
"start": 962,
"end": 36326
} | class ____:
ws_proto: ServerProtocol
io_proto: Optional[SanicProtocol]
loop: Optional[asyncio.AbstractEventLoop]
max_queue: int
close_timeout: float
ping_interval: Optional[float]
ping_timeout: Optional[float]
assembler: WebsocketFrameAssembler
# Dict[bytes, asyncio.Future[None]]
... | WebsocketImplProtocol |
python | doocs__leetcode | solution/1300-1399/1382.Balance a Binary Search Tree/Solution.py | {
"start": 192,
"end": 768
} | class ____:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(root: TreeNode):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
def build(i: int, j: int) -> TreeNode:
if i > j:
... | Solution |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/caching/service.py | {
"start": 668,
"end": 1134
} | class ____(RpcService):
key = "region_caching"
local_mode = SiloMode.REGION
@classmethod
def get_local_implementation(cls) -> RpcService:
from .impl import LocalRegionCachingService
return LocalRegionCachingService()
@regional_rpc_method(resolve=ByRegionName())
@abc.abstractme... | RegionCachingService |
python | coleifer__peewee | tests/fields.py | {
"start": 16928,
"end": 17097
} | class ____(TestModel):
first = CharField()
last = CharField()
data = TextField()
class Meta:
primary_key = CompositeKey('first', 'last')
| Composite |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/explorer.py | {
"start": 1877,
"end": 1935
} | class ____:
Main = 'Main'
| DirViewOpenWithSubMenuSections |
python | doocs__leetcode | solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/Solution.py | {
"start": 0,
"end": 392
} | class ____:
def captureForts(self, forts: List[int]) -> int:
n = len(forts)
i = ans = 0
while i < n:
j = i + 1
if forts[i]:
while j < n and forts[j] == 0:
j += 1
if j < n and forts[i] + forts[j] == 0:
... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/resource_requirement.py | {
"start": 6175,
"end": 6617
} | class ____(ResourceKeyRequirement):
key: str # pyright: ignore[reportIncompatibleMethodOverride]
attached_to: Optional[str]
hook_name: str
def describe_requirement(self) -> str:
attached_to_desc = f"attached to {self.attached_to}" if self.attached_to else ""
return (
f"reso... | HookResourceRequirement |
python | django__django | tests/gis_tests/geoapp/models.py | {
"start": 928,
"end": 991
} | class ____(NamedModel):
line = models.LineStringField()
| Track |
python | kamyu104__LeetCode-Solutions | Python/synonymous-sentences.py | {
"start": 664,
"end": 1814
} | class ____(object):
def generateSentences(self, synonyms, text):
"""
:type synonyms: List[List[str]]
:type text: str
:rtype: List[str]
"""
def assign_id(x, lookup, inv_lookup):
if x in lookup:
return
lookup[x] = len(lookup)
... | Solution |
python | optuna__optuna | optuna/importance/_ped_anova/evaluator.py | {
"start": 2393,
"end": 9346
} | class ____(BaseImportanceEvaluator):
"""PED-ANOVA importance evaluator.
Implements the PED-ANOVA hyperparameter importance evaluation algorithm.
PED-ANOVA fits Parzen estimators of :class:`~optuna.trial.TrialState.COMPLETE` trials better
than a user-specified baseline. Users can specify the baseline b... | PedAnovaImportanceEvaluator |
python | python__mypy | test-data/unit/plugins/class_callable.py | {
"start": 223,
"end": 1288
} | class ____(Plugin):
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname.startswith("mod.Attr"):
return attr_hook
return None
def attr_hook(ctx: FunctionContext) -> Type:
default = get_proper_type(ctx.default_return_type)
assert is... | AttrPlugin |
python | getsentry__sentry | src/sentry/preprod/vcs/status_checks/size/tasks.py | {
"start": 14122,
"end": 21655
} | class ____(_StatusCheckProvider):
def create_status_check(
self,
repo: str,
sha: str,
status: StatusCheckStatus,
title: str,
subtitle: str,
text: str | None,
summary: str,
external_id: str,
started_at: datetime,
completed_at: da... | _GitHubStatusCheckProvider |
python | django__django | django/db/models/expressions.py | {
"start": 72635,
"end": 75885
} | class ____(Expression):
"""
Model the frame clause in window expressions. There are two types of frame
clauses which are subclasses, however, all processing and validation (by no
means intended to be complete) is done here. Thus, providing an end for a
frame is optional (the default is UNBOUNDED FOL... | WindowFrame |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-google/llama_index/readers/google/chat/base.py | {
"start": 330,
"end": 9482
} | class ____(BasePydanticReader):
"""
Google Chat Reader.
Reads messages from Google Chat
"""
is_remote: bool = True
@classmethod
def class_name(cls) -> str:
"""Gets name identifier of class."""
return "GoogleChatReader"
def load_data(
self,
space_names:... | GoogleChatReader |
python | Netflix__metaflow | metaflow/plugins/datatools/s3/s3op.py | {
"start": 22236,
"end": 50253
} | class ____(object):
def __init__(self, s3config):
self.s3 = None
self.s3config = s3config
self.client_error = None
def reset_client(self, hard_reset=False):
from metaflow.plugins.datatools.s3.s3util import get_s3_client
if hard_reset or self.s3 is None:
self... | S3Ops |
python | python__mypy | mypy/test/data.py | {
"start": 27091,
"end": 29542
} | class ____(pytest.Collector):
"""Represents a single `.test` data driven test file.
More context: https://github.com/python/mypy/issues/11662
"""
parent: DataSuiteCollector
_fixes: list[DataFileFix]
@classmethod # We have to fight with pytest here:
def from_parent(
cls, parent: ... | DataFileCollector |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/asset.py | {
"start": 2240,
"end": 2443
} | class ____(BaseModel):
"""GET /api/assets response."""
items: list[DgApiAsset]
cursor: Optional[str] # Next cursor for pagination
has_more: bool # Whether more results exist
| DgApiAssetList |
python | pytorch__pytorch | test/test_multiprocessing_spawn.py | {
"start": 7880,
"end": 8484
} | class ____(TestCase, _TestMultiProcessing):
orig_paralell_env_val = None
def setUp(self):
super().setUp()
self.orig_paralell_env_val = os.environ.get(mp.ENV_VAR_PARALLEL_START)
os.environ[mp.ENV_VAR_PARALLEL_START] = "1"
def tearDown(self):
super().tearDown()
if sel... | ParallelForkServerShouldWorkTest |
python | getsentry__sentry | tests/sentry/seer/explorer/test_tools.py | {
"start": 74389,
"end": 80120
} | class ____(APITransactionTestCase, SnubaTestCase, TraceMetricsTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.ten_mins_ago = before_now(minutes=10)
self.nine_mins_ago = before_now(minutes=9)
self.trace_id = uuid.uuid4().hex
# Cr... | TestMetricsTraceQuery |
python | numba__numba | numba/core/lowering.py | {
"start": 923,
"end": 13110
} | class ____(object):
"""
Lower IR to LLVM
"""
def __init__(self, context, library, fndesc, func_ir, metadata=None):
self.library = library
self.fndesc = fndesc
self.blocks = utils.SortedMap(func_ir.blocks.items())
self.func_ir = func_ir
self.generator_info = func_... | BaseLower |
python | explosion__spaCy | spacy/schemas.py | {
"start": 12345,
"end": 14090
} | class ____(BaseModel):
# fmt: off
lang: StrictStr = Field(..., title="Two-letter language code, e.g. 'en'")
name: StrictStr = Field(..., title="Model name")
version: StrictStr = Field(..., title="Model version")
spacy_version: StrictStr = Field("", title="Compatible spaCy version identifier")
pa... | ModelMetaSchema |
python | Pylons__pyramid | tests/test_settings.py | {
"start": 18,
"end": 1014
} | class ____(unittest.TestCase):
def _callFUT(self, s):
from pyramid.settings import asbool
return asbool(s)
def test_s_is_None(self):
result = self._callFUT(None)
self.assertEqual(result, False)
def test_s_is_True(self):
result = self._callFUT(True)
self.ass... | Test_asbool |
python | huggingface__transformers | src/transformers/models/x_clip/modeling_x_clip.py | {
"start": 46710,
"end": 47475
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
embed_dim = config.projection_dim
self.cross_attn = XCLIPCrossAttention(config)
self.norm1 = nn.LayerNorm(embed_dim, eps=config.text_config.layer_norm_eps)
self.norm3 = nn.LayerNorm(embed_dim, eps=config.t... | PromptGeneratorLayer |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 59077,
"end": 90405
} | class ____(Scope):
# module_name string Python name of the module
# module_cname string C name of Python module object
# #module_dict_cname string C name of module dict object
# method_table_cname string C name of method table
# do... | ModuleScope |
python | Lightning-AI__lightning | tests/tests_fabric/helpers/datasets.py | {
"start": 429,
"end": 704
} | class ____(IterableDataset):
def __init__(self, size: int, count: int) -> None:
self.count = count
self.size = size
def __iter__(self) -> Iterator[Tensor]:
for _ in range(self.count):
yield torch.randn(self.size)
| RandomIterableDataset |
python | chroma-core__chroma | chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py | {
"start": 755,
"end": 6158
} | class ____(EmbeddingFunction[Embeddable]):
"""
This class is used as bridge between langchain embedding functions and custom chroma embedding functions.
"""
def __init__(self, embedding_function: Any) -> None:
"""
Initialize the ChromaLangchainEmbeddingFunction
Args:
... | ChromaLangchainEmbeddingFunction |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 70126,
"end": 78208
} | class ____(sgqlc.types.Enum):
"""The possible item types found in a timeline.
Enumeration Choices:
* `ADDED_TO_MERGE_QUEUE_EVENT`: Represents an
'added_to_merge_queue' event on a given pull request.
* `ADDED_TO_PROJECT_EVENT`: Represents a 'added_to_project' event
on a given issue or pull ... | PullRequestTimelineItemsItemType |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 32995,
"end": 77728
} | class ____(TestCase, BaseIncidentsTest):
@cached_property
def alert_rule(self):
return self.create_alert_rule(name="hello")
def create_error_event(self, **kwargs):
two_weeks_ago = before_now(days=14).replace(hour=10, minute=0, second=0, microsecond=0)
data = {
"event_id"... | UpdateAlertRuleTest |
python | huggingface__transformers | tests/test_tokenization_common.py | {
"start": 127070,
"end": 127466
} | class ____(TokenizersBackendTesterMixin, unittest.TestCase):
"""
A single test class that runs all tokenizers-backend tests once.
Uses BertTokenizer as a representative tokenizer.
"""
tokenizer_class = BertTokenizer
rust_tokenizer_class = BertTokenizerFast
from_pretrained_id = "google-bert/... | TokenizersBackendCommonTest |
python | numpy__numpy | numpy/lib/tests/test__datasource.py | {
"start": 1898,
"end": 4115
} | class ____:
def test_ValidHTTP(self, tmp_path):
ds = datasource.DataSource(tmp_path)
fh = ds.open(valid_httpurl())
assert_(fh)
fh.close()
def test_InvalidHTTP(self, tmp_path):
ds = datasource.DataSource(tmp_path)
url = invalid_httpurl()
assert_raises(OSEr... | TestDataSourceOpen |
python | ApeWorX__ape | src/ape/api/config.py | {
"start": 879,
"end": 1760
} | class ____(str, Enum):
"""
A configuration `Enum <https://docs.python.org/3/library/enum.html>`__ type.
Use this to limit the values of a config item, such as colors ``"RED"``, ``"BLUE"``,
``"GREEN"``, rather than any arbitrary ``str``.
Usage example::
class MyEnum(ConfigEnum):
... | ConfigEnum |
python | doocs__leetcode | solution/1000-1099/1049.Last Stone Weight II/Solution2.py | {
"start": 0,
"end": 308
} | class ____:
def lastStoneWeightII(self, stones: List[int]) -> int:
s = sum(stones)
m, n = len(stones), s >> 1
dp = [0] * (n + 1)
for v in stones:
for j in range(n, v - 1, -1):
dp[j] = max(dp[j], dp[j - v] + v)
return s - dp[-1] * 2
| Solution |
python | scikit-learn__scikit-learn | sklearn/linear_model/_omp.py | {
"start": 30243,
"end": 38358
} | class ____(RegressorMixin, LinearModel):
"""Cross-validated Orthogonal Matching Pursuit model (OMP).
See glossary entry for :term:`cross-validation estimator`.
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
copy : bool, default=True
Whether the design matrix X must be... | OrthogonalMatchingPursuitCV |
python | huggingface__transformers | src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py | {
"start": 5087,
"end": 7469
} | class ____(nn.Module):
def __init__(self, config: ASTConfig):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size {config.hidden_size} is not a multiple of the number of ... | ASTSelfAttention |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-openai-like/tests/test_openai_like.py | {
"start": 511,
"end": 5339
} | class ____(Tokenizer):
def encode(self, text: str) -> List[int]:
return [sum(ord(letter) for letter in word) for word in text.split(" ")]
STUB_MODEL_NAME = "models/stub.gguf"
STUB_API_KEY = "stub_key"
# Use these as kwargs for OpenAILike to connect to LocalAIs
DEFAULT_LOCALAI_PORT = 8080
# TODO: move to ... | StubTokenizer |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver.py | {
"start": 1593,
"end": 8614
} | class ____(ClusterResolver):
"""ClusterResolver for Kubernetes.
This is an implementation of cluster resolvers for Kubernetes. When given the
the Kubernetes namespace and label selector for pods, we will retrieve the
pod IP addresses of all running pods matching the selector, and return a
ClusterSpec based o... | KubernetesClusterResolver |
python | numpy__numpy | numpy/_core/tests/test_conversion_utils.py | {
"start": 5696,
"end": 6506
} | class ____:
""" Tests of PyArray_IntpConverter """
conv = mt.run_intp_converter
def test_basic(self):
assert self.conv(1) == (1,)
assert self.conv((1, 2)) == (1, 2)
assert self.conv([1, 2]) == (1, 2)
assert self.conv(()) == ()
def test_none(self):
with pytest.ra... | TestIntpConverter |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/boring_classes.py | {
"start": 1598,
"end": 1979
} | class ____(Dataset):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self, size: int, length: int):
self.len = length
self.data = torch.randn(length, size)
def __getitem__(self, index: int) -> Tensor:
return self.data[index]
... | RandomDataset |
python | pennersr__django-allauth | allauth/socialaccount/providers/meetup/views.py | {
"start": 181,
"end": 923
} | class ____(OAuth2Adapter):
provider_id = "meetup"
access_token_url = "https://secure.meetup.com/oauth2/access" # nosec
authorize_url = "https://secure.meetup.com/oauth2/authorize"
profile_url = "https://api.meetup.com/2/member/self"
def complete_login(self, request, app, token, **kwargs):
... | MeetupOAuth2Adapter |
python | realpython__materials | python-serialize/python-objects/customize-pickle/models.py | {
"start": 59,
"end": 465
} | class ____:
name: str
password: str
def __getstate__(self):
state = self.__dict__.copy()
state["timestamp"] = int(time.time())
del state["password"]
return state
def __setstate__(self, state):
self.__dict__.update(state)
with open("/dev/random", mode="rb... | User |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 13725,
"end": 17483
} | class ____(NamedTuple):
"""represents state to use for executing an "insertmanyvalues" statement.
The primary consumers of this object are the
:meth:`.SQLCompiler._deliver_insertmanyvalues_batches` and
:meth:`.DefaultDialect._deliver_insertmanyvalues_batches` methods.
.. versionadded:: 2.0
""... | _InsertManyValues |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_polymorphic_rel.py | {
"start": 74816,
"end": 79454
} | class ____(_PolymorphicTestBase, _PolymorphicUnions):
@testing.skip_if(
lambda: True, "join condition doesn't work w/ this mapping"
)
def test_lazyload_related_w_cache_check(self):
pass
def test_with_polymorphic_two_future_default_wp(self):
"""test #7262
compare to
... | PolymorphicUnionsTest |
python | geekcomputers__Python | Test-Case-Generator/test_case.py | {
"start": 24475,
"end": 25468
} | class ____(Case):
def __init__(self, master):
super(Type5, self).__init__(master)
self.forget_home()
self.take_input()
def take_input(self): # Type 5
try:
self.try_forget()
except AttributeError:
pass
self.get_t(0)
self.get_n(1)
... | Type5 |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_server_storage_version.py | {
"start": 383,
"end": 7146
} | 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... | V1alpha1ServerStorageVersion |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 180422,
"end": 181216
} | class ____(Operation):
def __init__(self, decimals=0, *, name=None):
super().__init__(name=name)
self.decimals = decimals
def call(self, x):
return backend.numpy.round(x, self.decimals)
def compute_output_spec(self, x):
sparse = getattr(x, "sparse", False)
return Ke... | Round |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 179505,
"end": 180966
} | class ____(rv_continuous):
r"""A Johnson SB continuous random variable.
%(before_notes)s
See Also
--------
johnsonsu
Notes
-----
The probability density function for `johnsonsb` is:
.. math::
f(x, a, b) = \frac{b}{x(1-x)} \phi(a + b \log \frac{x}{1-x} )
where :math... | johnsonsb_gen |
python | ray-project__ray | doc/source/serve/doc_code/model_composition/streaming_example.py | {
"start": 384,
"end": 1196
} | class ____:
def __init__(self, streamer: DeploymentHandle):
self._streamer = streamer.options(
# Must set `stream=True` on the handle, then the output will be a
# response generator.
stream=True,
)
async def __call__(self, limit: int) -> AsyncGenerator[int, N... | Caller |
python | plotly__plotly.py | plotly/graph_objs/layout/smith/imaginaryaxis/_tickfont.py | {
"start": 235,
"end": 9955
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.smith.imaginaryaxis"
_path_str = "layout.smith.imaginaryaxis.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Tickfont |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 20330,
"end": 20671
} | class ____(AsyncHTTPTestCase, SimpleHTTPClientTestMixin):
def setUp(self):
super().setUp()
self.http_client = self.create_client()
def get_app(self):
return self.mixin_get_app()
def create_client(self, **kwargs):
return SimpleAsyncHTTPClient(force_instance=True, **kwargs)
... | SimpleHTTPClientTestCase |
python | plotly__plotly.py | plotly/graph_objs/isosurface/caps/_x.py | {
"start": 233,
"end": 4043
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.caps"
_path_str = "isosurface.caps.x"
_valid_props = {"fill", "show"}
@property
def fill(self):
"""
Sets the fill ratio of the `caps`. The default fill value of
the `caps` is 1 meaning that they are entirely... | X |
python | pytorch__pytorch | torch/distributed/elastic/metrics/api.py | {
"start": 952,
"end": 1066
} | class ____(abc.ABC):
@abc.abstractmethod
def emit(self, metric_data: MetricData):
pass
| MetricHandler |
python | ashishps1__awesome-system-design-resources | implementations/python/rate_limiting/sliding_window_log.py | {
"start": 43,
"end": 1147
} | class ____:
def __init__(self, window_size, max_requests):
self.window_size = window_size # Size of the sliding window in seconds
self.max_requests = max_requests # Maximum number of requests per window
self.request_log = deque() # Log to keep track of request timestamps
def allow_re... | SlidingWindowLog |
python | numba__numba | numba/core/typeinfer.py | {
"start": 26728,
"end": 27138
} | class ____(CallConstraint):
def __call__(self, typeinfer):
with new_error_context("typing of intrinsic-call at {loc}",
loc=self.loc):
fnty = self.func
if fnty in utils.OPERATORS_TO_BUILTINS:
fnty = typeinfer.resolve_value_type(None, fnty... | IntrinsicCallConstraint |
python | plotly__plotly.py | plotly/graph_objs/densitymapbox/legendgrouptitle/_font.py | {
"start": 233,
"end": 9957
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymapbox.legendgrouptitle"
_path_str = "densitymapbox.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | pypa__warehouse | tests/unit/packaging/test_models.py | {
"start": 1715,
"end": 2444
} | class ____:
@pytest.mark.parametrize(("name", "normalized"), [("foo", "foo"), ("Bar", "bar")])
def test_traversal_finds(self, db_request, name, normalized):
project = DBProjectFactory.create(name=name)
root = ProjectFactory(db_request)
assert root[normalized] == project
def test_tr... | TestProjectFactory |
python | celery__celery | celery/contrib/migrate.py | {
"start": 8427,
"end": 14361
} | class ____:
def __init__(self, app, conn, filter,
limit=None, timeout=1.0,
ack_messages=False, tasks=None, queues=None,
callback=None, forever=False, on_declare_queue=None,
consume_from=None, state=None, accept=None, **kwargs):
self.app = ... | Filterer |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 100632,
"end": 102924
} | class ____(IndexFetcher):
def __init__(self, url_and_version: MirrorURLAndVersion, local_hash, urlopen=None) -> None:
self.local_hash = local_hash
self.ref = spack.oci.image.ImageReference.from_url(url_and_version.url)
self.urlopen = urlopen or spack.oci.opener.urlopen
def conditional_f... | OCIIndexFetcher |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar06.py | {
"start": 315,
"end": 1472
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | pennersr__django-allauth | allauth/socialaccount/providers/mediawiki/views.py | {
"start": 228,
"end": 1300
} | class ____(OAuth2Adapter):
provider_id = "mediawiki"
settings = app_settings.PROVIDERS.get(provider_id, {})
REST_API = settings.get("REST_API", "https://meta.wikimedia.org/w/rest.php")
access_token_url = REST_API + "/oauth2/access_token"
authorize_url = REST_API + "/oauth2/authorize"
profile_url... | MediaWikiOAuth2Adapter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis18.py | {
"start": 315,
"end": 1395
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis18.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.