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 | ansible__ansible | lib/ansible/plugins/connection/winrm.py | {
"start": 9078,
"end": 38390
} | class ____(ConnectionBase):
"""WinRM connections over HTTP/HTTPS."""
transport = 'winrm'
module_implementation_preferences = ('.ps1', '.exe', '')
allow_executable = False
has_pipelining = True
allow_extras = True
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
self.alwa... | Connection |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/status.py | {
"start": 848,
"end": 1287
} | class ____(StatusBarWidget):
"""Status bar widget for the current file end of line."""
ID = "eol_status"
def update_eol(self, os_name):
"""Update end of line status."""
os_name = str(os_name)
value = {"nt": "CRLF", "posix": "LF"}.get(os_name, "CR")
self.set_value(value)
... | EOLStatus |
python | scrapy__scrapy | tests/test_utils_iterators.py | {
"start": 10448,
"end": 13486
} | class ____(TestXmliterBase):
def xmliter(
self, obj: Response | str | bytes, nodename: str, *args: Any
) -> Iterator[Selector]:
return xmliter_lxml(obj, nodename, *args)
def test_xmliter_iterate_namespace(self):
body = b"""
<?xml version="1.0" encoding="UTF-8"?>
... | TestLxmlXmliter |
python | apache__airflow | providers/google/tests/unit/google/cloud/transfers/test_bigquery_to_mssql.py | {
"start": 1694,
"end": 8018
} | class ____:
@mock.patch("airflow.providers.google.cloud.transfers.bigquery_to_mssql.BigQueryTableLink")
@mock.patch("airflow.providers.google.cloud.transfers.bigquery_to_sql.BigQueryHook")
def test_execute_good_request_to_bq(self, mock_hook, mock_link):
destination_table = "table"
operator =... | TestBigQueryToMsSqlOperator |
python | ray-project__ray | doc/source/ray-core/doc_code/cgraph_nccl.py | {
"start": 1171,
"end": 1971
} | class ____:
def recv(self, tensor: torch.Tensor):
assert tensor.device.type == "cuda"
return tensor.shape
sender = GPUSender.remote()
receiver = GPUReceiver.remote()
# __cgraph_nccl_setup_end__
# __cgraph_nccl_exec_start__
with ray.dag.InputNode() as inp:
dag = sender.send.bind(inp)
# Add... | GPUReceiver |
python | PrefectHQ__prefect | src/prefect/cli/transfer/_dag.py | {
"start": 1372,
"end": 13115
} | class ____:
"""
Execution DAG for managing resource transfer dependencies.
Uses Kahn's algorithm for topological sorting and concurrent execution.
See: https://en.wikipedia.org/wiki/Topological_sorting#Kahn%27s_algorithm
The DAG ensures resources are transferred in dependency order while
maxim... | TransferDAG |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1410633,
"end": 1462412
} | class ____(
sgqlc.types.Type, Node, ProjectV2Recent, ProjectOwner, PackageOwner, Subscribable, Starrable, UniformResourceLocatable, RepositoryInfo
):
"""A repository contains the content for a project."""
__schema__ = github_schema
__field_names__ = (
"allow_update_branch",
"assignable_... | Repository |
python | python__mypy | mypyc/ir/ops.py | {
"start": 12031,
"end": 12734
} | class ____(ControlOp):
"""Unconditional jump."""
error_kind = ERR_NEVER
def __init__(self, label: BasicBlock, line: int = -1) -> None:
super().__init__(line)
self.label = label
def targets(self) -> Sequence[BasicBlock]:
return (self.label,)
def set_target(self, i: int, ne... | Goto |
python | google__jax | jax/_src/errors.py | {
"start": 23837,
"end": 24777
} | class ____(JAXTypeError):
"""
This error occurs when a PRNG key is reused in an unsafe manner.
Key reuse is checked only when `jax_debug_key_reuse` is
set to `True`.
Here is a simple example of code that would lead to such an error::
>>> with jax.debug_key_reuse(True): # doctest: +SKIP
... key = ... | KeyReuseError |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 51627,
"end": 61288
} | class ____(MMGroundingDinoPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
[`MMGroundingDinoEncoderLayer`].
The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
Args:
... | MMGroundingDinoEncoder |
python | Textualize__textual | src/textual/widgets/_tooltip.py | {
"start": 73,
"end": 450
} | class ____(Static, inherit_css=False):
DEFAULT_CSS = """
Tooltip {
layer: _tooltips;
margin: 1 0;
padding: 1 2;
background: $panel;
width: auto;
height: auto;
constrain: inside inflect;
max-width: 40;
display: none;
offset-x: -50%;
... | Tooltip |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/custom_object_launcher.py | {
"start": 8202,
"end": 15447
} | class ____(LoggingMixin):
"""Launches PODS."""
def __init__(
self,
name: str | None,
namespace: str | None,
kube_client: CoreV1Api,
custom_obj_api: CustomObjectsApi,
template_body: str | None = None,
):
"""
Create custom object launcher(sparka... | CustomObjectLauncher |
python | django__django | tests/one_to_one/models.py | {
"start": 1630,
"end": 1897
} | class ____(models.Model):
link1 = models.OneToOneField(Place, models.CASCADE)
link2 = models.OneToOneField(ManualPrimaryKey, models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
return "Multimodel %s" % self.name
| MultiModel |
python | walkccc__LeetCode | solutions/870. Advantage Shuffle/870.py | {
"start": 42,
"end": 323
} | class ____:
def advantageCount(self, nums1: list[int], nums2: list[int]) -> list[int]:
sl = SortedList(nums1)
for i, num in enumerate(nums2):
index = 0 if sl[-1] <= num else sl.bisect_right(num)
nums1[i] = sl[index]
del sl[index]
return nums1
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/strava/views.py | {
"start": 181,
"end": 938
} | class ____(OAuth2Adapter):
provider_id = "strava"
access_token_url = "https://www.strava.com/oauth/token" # nosec
authorize_url = "https://www.strava.com/oauth/authorize"
profile_url = "https://www.strava.com/api/v3/athlete"
def complete_login(self, request, app, token, **kwargs):
headers ... | StravaOAuth2Adapter |
python | google__pytype | pytype/tests/test_operators1.py | {
"start": 110,
"end": 6830
} | class ____(test_base.BaseTest, test_utils.OperatorsTestMixin):
"""Tests for operators on concrete values (no unknowns)."""
def test_add(self):
self.check_expr("x + y", ["x=1", "y=2"], "int")
self.check_expr("x + y", ["x=1.0", "y=2"], "float")
self.check_expr("x + y", ["x=1", "y=2.0"], "float")
self... | ConcreteTest |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/formatters/svg.py | {
"start": 726,
"end": 7174
} | class ____(Formatter):
"""
Format tokens as an SVG graphics file. This formatter is still experimental.
Each line of code is a ``<text>`` element with explicit ``x`` and ``y``
coordinates containing ``<tspan>`` elements with the individual token styles.
By default, this formatter outputs a full SV... | SvgFormatter |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial005.py | {
"start": 109,
"end": 741
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: Set[str] = set()
@app.post(
"/items/",
response_model=Item,
summary="Create an item",
response_description="The created item",
)
async def create_item(item: Item)... | Item |
python | getsentry__sentry | src/sentry/search/events/builder/profile_functions.py | {
"start": 5003,
"end": 9489
} | class ____(ProfileFunctionsTimeseriesQueryBuilder):
config_class = ProfileFunctionsDatasetConfig
def __init__(
self,
dataset: Dataset,
params: ParamsType,
interval: int,
top_events: list[dict[str, Any]],
snuba_params: SnubaParams | None = None,
other: boo... | ProfileTopFunctionsTimeseriesQueryBuilder |
python | Textualize__textual | src/textual/css/stylesheet.py | {
"start": 1047,
"end": 1310
} | class ____(StylesheetError):
"""Raised when the stylesheet could not be parsed."""
def __init__(self, errors: StylesheetErrors) -> None:
self.errors = errors
def __rich__(self) -> RenderableType:
return self.errors
| StylesheetParseError |
python | kamyu104__LeetCode-Solutions | Python/predict-the-winner.py | {
"start": 31,
"end": 486
} | class ____(object):
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) % 2 == 0 or len(nums) == 1:
return True
dp = [0] * len(nums)
for i in reversed(xrange(len(nums))):
dp[i] = nums[i]
... | Solution |
python | pydantic__pydantic | pydantic/v1/types.py | {
"start": 13028,
"end": 14606
} | class ____(set): # type: ignore
# Needed for pydantic to detect that this is a set
__origin__ = set
__args__: Set[Type[T]] # type: ignore
min_items: Optional[int] = None
max_items: Optional[int] = None
item_type: Type[T] # type: ignore
@classmethod
def __get_validators__(cls) -> 'Ca... | ConstrainedSet |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/window.py | {
"start": 19744,
"end": 26912
} | class ____(QSplitter):
def __init__(self):
QSplitter.__init__(self)
self._plugin = None
self.dock_action = None
self.undock_action = None
self.close_action = None
self.windowwidget = None
self.lock_unlock_action = None
menu_actions = []
self... | EditorMainWidgetExample |
python | justquick__django-activity-stream | actstream/drf/serializers.py | {
"start": 2274,
"end": 2607
} | class ____(DEFAULT_SERIALIZER):
"""
Serializer for actstream.Action models in the activity feeds
"""
actor = get_grf()
target = get_grf()
action_object = get_grf()
class Meta:
model = Action
fields = 'id verb public description timestamp actor target action_object'.split()
... | ActionSerializer |
python | pydata__xarray | xarray/core/_typed_ops.py | {
"start": 678,
"end": 6733
} | class ____:
__slots__ = ()
def _binary_op(
self, other: DtCompatible, f: Callable, reflexive: bool = False
) -> Self:
raise NotImplementedError
def __add__(self, other: DtCompatible) -> Self:
return self._binary_op(other, operator.add)
def __sub__(self, other: DtCompatible... | DataTreeOpsMixin |
python | streamlit__streamlit | lib/tests/streamlit/web/server/server_util_test.py | {
"start": 884,
"end": 5208
} | class ____(unittest.TestCase):
def test_allowlisted_origins_empty_string(self):
with testutil.patch_config_options({"server.corsAllowedOrigins": []}):
assert server_util.allowlisted_origins() == set()
def test_allowlisted_origins_singleton(self):
with testutil.patch_config_options(
... | ServerUtilTest |
python | pytorch__pytorch | torch/package/package_importer.py | {
"start": 28802,
"end": 28948
} | class ____(_PathNode):
__slots__ = ["source_file"]
def __init__(self, source_file: str):
self.source_file = source_file
| _ModuleNode |
python | redis__redis-py | redis/sentinel.py | {
"start": 6591,
"end": 15013
} | class ____(SentinelCommands):
"""
Redis Sentinel cluster client
>>> from redis.sentinel import Sentinel
>>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
>>> master.set('foo', 'bar')
>>> slave = sentinel.slav... | Sentinel |
python | numpy__numpy | numpy/linalg/tests/test_regression.py | {
"start": 301,
"end": 6796
} | class ____:
def test_eig_build(self):
# Ticket #652
rva = array([1.03221168e+02 + 0.j,
-1.91843603e+01 + 0.j,
-6.04004526e-01 + 15.84422474j,
-6.04004526e-01 - 15.84422474j,
-1.13692929e+01 + 0.j,
... | TestRegression |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_access_request_details.py | {
"start": 2178,
"end": 6139
} | class ____(APITestCase):
def test_approve_request(self) -> None:
self.login_as(user=self.user)
organization = self.create_organization(name="foo", owner=self.user)
user = self.create_user("bar@example.com")
member = self.create_member(organization=organization, user=user, role="memb... | UpdateOrganizationAccessRequestTest |
python | doocs__leetcode | solution/2600-2699/2639.Find the Width of Columns of a Grid/Solution.py | {
"start": 0,
"end": 152
} | class ____:
def findColumnWidth(self, grid: List[List[int]]) -> List[int]:
return [max(len(str(x)) for x in col) for col in zip(*grid)]
| Solution |
python | ipython__ipython | docs/source/conf.py | {
"start": 5550,
"end": 6435
} | class ____(logging.Filter):
"""
This is a filter to remove in sphinx 3+ the error about config traits being duplicated.
As we autogenerate configuration traits from, subclasses have lots of
duplication and we want to silence them. Indeed we build on travis with
warnings-as-error set to True, so tho... | ConfigtraitFilter |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_view_ops.py | {
"start": 1888,
"end": 2428
} | class ____(DimSpec):
"""Output dimension is the input dimension repeated n-times."""
input_dim: DimSpec
times: int
@classmethod
def new(cls, dim: DimSpec, times: int) -> DimSpec:
if times == 1:
return dim
elif isinstance(dim, Singleton):
# repeating a single... | Repeat |
python | mlflow__mlflow | mlflow/server/auth/sqlalchemy_store.py | {
"start": 985,
"end": 14932
} | class ____:
def init_db(self, db_uri):
self.db_uri = db_uri
self.db_type = extract_db_type_from_uri(db_uri)
self.engine = create_sqlalchemy_engine_with_retry(db_uri)
dbutils.migrate_if_needed(self.engine, "head")
SessionMaker = sessionmaker(bind=self.engine)
self.Mana... | SqlAlchemyStore |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 7092,
"end": 7522
} | class ____(resource.Resource):
def render(self, request):
from twisted.internet import reactor
def response():
request.write(b"chunked ")
request.write(b"content\n")
# Disable terminating chunk on finish.
request.chunked = False
close_conn... | BrokenChunkedResource |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py | {
"start": 24429,
"end": 27525
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
# feature dim might need to be down-projected
if config.output_hidden_size != config.hidden_size:
self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
self.proj_layer_norm = nn.Layer... | Wav2Vec2BertAdapter |
python | walkccc__LeetCode | solutions/3049. Earliest Second to Mark Indices II/3049.py | {
"start": 0,
"end": 2276
} | class ____:
def earliestSecondToMarkIndices(
self,
nums: list[int],
changeIndices: list[int],
) -> int:
# {the second: the index of nums can be zeroed at the current second}
secondToIndex = self._getSecondToIndex(nums, changeIndices)
numsSum = sum(nums)
def canMark(maxSecond: int)... | Solution |
python | walkccc__LeetCode | solutions/2428. Maximum Sum of an Hourglass/2428.py | {
"start": 0,
"end": 305
} | class ____:
def maxSum(self, grid: list[list[int]]) -> int:
return max(
grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + grid[i][j] +
grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1]
for i in range(1, len(grid) - 1) for j in range(1, len(grid[0]) - 1))
| Solution |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 43160,
"end": 43232
} | class ____:
pass
@dataclass(frozen=True, slots=True)
| SingletonConstant |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 31739,
"end": 33977
} | class ____(nn.Module):
def __init__(self, config: ChineseCLIPVisionConfig):
super().__init__()
self.config = config
embed_dim = config.hidden_size
self.embeddings = ChineseCLIPVisionEmbeddings(config)
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
... | ChineseCLIPVisionTransformer |
python | kamyu104__LeetCode-Solutions | Python/find-the-number-of-distinct-colors-among-the-balls.py | {
"start": 63,
"end": 635
} | class ____(object):
def queryResults(self, limit, queries):
"""
:type limit: int
:type queries: List[List[int]]
:rtype: List[int]
"""
result = [0]*len(queries)
lookup = {}
cnt = collections.Counter()
for i, (x, y) in enumerate(queries):
... | Solution |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py | {
"start": 23943,
"end": 25082
} | class ____(nn.Module):
def __init__(
self,
input_dim: int,
hidden_dim: int,
output_dim: int,
num_layers: int,
activation: str = "relu",
sigmoid_output: bool = False,
):
super().__init__()
self.num_layers = num_layers
self.activation... | Sam3TrackerVideoFeedForward |
python | langchain-ai__langchain | libs/partners/fireworks/langchain_fireworks/chat_models.py | {
"start": 9976,
"end": 41777
} | class ____(BaseChatModel):
"""`Fireworks` Chat large language models API.
To use, you should have the
environment variable `FIREWORKS_API_KEY` set with your API key.
Any parameters that are valid to be passed to the fireworks.create call
can be passed in, even if not explicitly saved on this class... | ChatFireworks |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_resolver.py | {
"start": 14668,
"end": 25207
} | class ____(ResolverBase):
def test_resolver(self):
url = self.resolver.resolve(project=self.pip)
self.assertEqual(url, "http://pip.readthedocs.org/en/latest/")
def test_resolver_domain(self):
self.domain = fixture.get(
Domain,
domain="docs.foobar.com",
... | ResolverTests |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 119644,
"end": 120359
} | class ____(Operation):
def call(self, x):
return backend.numpy.isfinite(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype="bool")
@keras_export(["keras.ops.isfinite", "keras.ops.numpy.isfinite"])
def isfinite(x):
"""Return whether a tensor is finite, element-wise.
... | Isfinite |
python | PrefectHQ__prefect | src/prefect/server/schemas/ui.py | {
"start": 127,
"end": 266
} | class ____(CoreTaskRun):
"""A task run with additional details for display in the UI."""
flow_run_name: Optional[str] = None
| UITaskRun |
python | pypa__warehouse | warehouse/packaging/services.py | {
"start": 13182,
"end": 13780
} | class ____(GenericGCSBlobStorage):
@classmethod
@google.api_core.retry.Retry(
predicate=google.api_core.retry.if_exception_type(
google.api_core.exceptions.ServiceUnavailable
)
)
def create_service(cls, context, request):
storage_client = request.find_service(name="gc... | GCSFileStorage |
python | neetcode-gh__leetcode | python/0706-design-hashmap.py | {
"start": 0,
"end": 139
} | class ____:
def __init__(self, key=-1, val=-1, next=None):
self.key = key
self.val = val
self.next = next
| ListNode |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingTypeArg1.py | {
"start": 262,
"end": 664
} | class ____(Class1):
pass
# This should generate an error when reportMissingTypeArgument is enabled.
_T2 = TypeVar("_T2", bound=Class1)
# This should generate an error when reportMissingTypeArgument is enabled.
var1: Class1 | None = None
GenericTypeAlias = Class1[_T1] | int
# This should generate an error wh... | Class2 |
python | django-extensions__django-extensions | django_extensions/management/commands/syncdata.py | {
"start": 817,
"end": 11067
} | class ____(BaseCommand):
"""syncdata command"""
help = "Makes the current database have the same data as the fixture(s), no more, no less." # noqa: E501
args = "fixture [fixture ...]"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--sk... | Command |
python | plotly__plotly.py | plotly/graph_objs/scattergeo/unselected/_marker.py | {
"start": 233,
"end": 4065
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergeo.unselected"
_path_str = "scattergeo.unselected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exi... | Marker |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 152142,
"end": 153678
} | class ____:
def test_simple(self):
[x, y] = np.indices((4, 3))
assert_array_equal(x, np.array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]]))
assert_array_equal(y, np.array... | TestIndices |
python | conda__conda | tests/plugins/test_post_solves.py | {
"start": 504,
"end": 2175
} | class ____:
def post_solve_action(self) -> None:
pass
@plugins.hookimpl
def conda_post_solves(self):
yield plugins.CondaPostSolve(
name="custom-post-solve",
action=self.post_solve_action,
)
@pytest.fixture
def post_solve_plugin(
mocker: MockerFixture,
... | PostSolvePlugin |
python | ansible__ansible | test/units/playbook/test_base.py | {
"start": 9637,
"end": 12486
} | class ____(base.Base):
name = FieldAttribute(isa='string', default='', always_post_validate=True)
test_attr_bool = FieldAttribute(isa='bool', always_post_validate=True)
test_attr_int = FieldAttribute(isa='int', always_post_validate=True)
test_attr_float = FieldAttribute(isa='float', default=3.14159, alw... | BaseSubClass |
python | spyder-ide__spyder | spyder/api/widgets/auxiliary_widgets.py | {
"start": 566,
"end": 1947
} | class ____(QMainWindow, SpyderMainWindowMixin):
"""MainWindow subclass that contains a SpyderDockablePlugin."""
# ---- Signals
# ------------------------------------------------------------------------
sig_closed = Signal()
"""This signal is emitted when the close event is fired."""
sig_window... | SpyderWindowWidget |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 66178,
"end": 67349
} | class ____(test_util.TensorFlowTestCase):
def testSimple(self):
a = array_ops.constant(10)
guarantee_a = array_ops.guarantee_const(a)
self.assertEqual(10, self.evaluate(guarantee_a))
def testVariables(self):
for use_resource in [False, True]:
with self.subTest(use_resource=use_resource):
... | GuaranteeConstOpTest |
python | django__django | tests/sitemaps_tests/test_generic.py | {
"start": 238,
"end": 3841
} | class ____(SitemapTestsBase):
def test_generic_sitemap_attributes(self):
datetime_value = datetime.now()
queryset = TestModel.objects.all()
generic_sitemap = GenericSitemap(
info_dict={
"queryset": queryset,
"date_field": datetime_value,
... | GenericViewsSitemapTests |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 10452,
"end": 14183
} | class ____:
@staticmethod
def pq(
bit_compression: Optional[bool] = None,
centroids: Optional[int] = None,
encoder_distribution: Optional[PQEncoderDistribution] = None,
encoder_type: Optional[PQEncoderType] = None,
segments: Optional[int] = None,
training_limit: O... | _VectorIndexQuantizer |
python | readthedocs__readthedocs.org | readthedocs/embed/v3/tests/test_access.py | {
"start": 878,
"end": 4242
} | class ____(TestCase):
def setUp(self):
self.user = get(User)
self.project = get(
Project,
slug="docs",
privacy_level=PUBLIC,
users=[self.user],
)
self.version = self.project.versions.get(slug=LATEST)
self.version.privacy_level =... | TestEmbedAPIV3Access |
python | weaviate__weaviate-python-client | weaviate/collections/batch/base.py | {
"start": 2093,
"end": 2999
} | class ____(ABC, Generic[TBatchInput, TBatchReturn]):
"""`BatchRequest` abstract class used as a interface for batch requests."""
def __init__(self) -> None:
self._items: List[TBatchInput] = []
self._lock = threading.Lock()
def __len__(self) -> int:
return len(self._items)
def ... | BatchRequest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_raw_message_start_event.py | {
"start": 239,
"end": 343
} | class ____(BaseModel):
message: BetaMessage
type: Literal["message_start"]
| BetaRawMessageStartEvent |
python | pypa__pip | tests/unit/test_utils_compatibility_tags.py | {
"start": 1579,
"end": 2413
} | class ____:
@pytest.mark.parametrize(
"manylinux2010,manylinux1",
[
("manylinux2010_x86_64", "manylinux1_x86_64"),
("manylinux2010_i686", "manylinux1_i686"),
],
)
def test_manylinux2010_implies_manylinux1(
self, manylinux2010: str, manylinux1: str
... | TestManylinux2010Tags |
python | wandb__wandb | tests/unit_tests/test_launch/test_inputs/test_internal.py | {
"start": 3553,
"end": 25875
} | class ____(BaseModel):
trainer: Trainer
def test_validate_schema_pydantic_lists():
class Item(BaseModel):
name: str
epochs: int = Field(ge=1)
class GenericLists(BaseModel):
# TODO: Only list of enums are supported for now
# tags: list[str] = Field(min_length=0, max_length=... | ExampleSchema |
python | huggingface__transformers | src/transformers/models/mra/modeling_mra.py | {
"start": 20850,
"end": 25231
} | class ____(nn.Module):
def __init__(self, config):
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 attention... | MraSelfAttention |
python | walkccc__LeetCode | solutions/3420. Count Non-Decreasing Subarrays After K Operations/3420-2.py | {
"start": 0,
"end": 666
} | class ____:
def countNonDecreasingSubarrays(self, nums: list[int], k: int) -> int:
ans = 0
cost = 0
# Store indices (i) of nums with nums[i] in non-increasing order.
dq = collections.deque()
j = len(nums) - 1
for i, num in reversed(list(enumerate(nums))):
while dq and nums[dq[-1]] < num... | Solution |
python | jina-ai__jina | tests/integration/docarray_v2/test_streaming.py | {
"start": 671,
"end": 3592
} | class ____(Executor):
@requests(on='/task1')
async def task1(self, doc: MyDocument, **kwargs) -> OutputDocument:
for i in range(100):
yield OutputDocument(text=f'{doc.text} {doc.number}-{i}-task1')
@requests(on='/task2')
async def task2(
self, doc: MyDocument, **kwargs
)... | CustomResponseExecutor |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_formats.py | {
"start": 92,
"end": 3855
} | class ____:
def test_repr_round_days_non_nano(self):
# GH#55405
# we should get "1 days", not "1 days 00:00:00" with non-nano
tdi = TimedeltaIndex(["1 days"], freq="D").as_unit("s")
result = repr(tdi)
expected = "TimedeltaIndex(['1 days'], dtype='timedelta64[s]', freq='D')"
... | TestTimedeltaIndexRendering |
python | falconry__falcon | falcon/asgi_spec.py | {
"start": 736,
"end": 1508
} | class ____:
"""Standard ASGI event type strings."""
HTTP_REQUEST = 'http.request'
HTTP_RESPONSE_START = 'http.response.start'
HTTP_RESPONSE_BODY = 'http.response.body'
HTTP_DISCONNECT = 'http.disconnect'
LIFESPAN_STARTUP = 'lifespan.startup'
LIFESPAN_STARTUP_COMPLETE = 'lifespan.startup.co... | EventType |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_sort_values.py | {
"start": 180,
"end": 22211
} | class ____:
@pytest.mark.parametrize("dtype", [np.uint8, bool])
def test_sort_values_sparse_no_warning(self, dtype):
# GH#45618
ser = pd.Series(Categorical(["a", "b", "a"], categories=["a", "b", "c"]))
df = pd.get_dummies(ser, dtype=dtype, sparse=True)
with tm.assert_produces_wa... | TestDataFrameSortValues |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/pandas_data_sampler.py | {
"start": 360,
"end": 5892
} | class ____(DataSampler):
"""Methods for sampling a pandas dataframe."""
def sample_using_limit(self, df: pd.DataFrame, batch_spec: BatchSpec) -> pd.DataFrame:
"""Sample the first n rows of data.
Args:
df: pandas dataframe.
batch_spec: Should contain key `n` in sampling_... | PandasDataSampler |
python | modin-project__modin | modin/core/execution/ray/implementations/pandas_on_ray/dataframe/dataframe.py | {
"start": 1121,
"end": 2884
} | class ____(PandasDataframe):
"""
The class implements the interface in ``PandasDataframe`` using Ray.
Parameters
----------
partitions : np.ndarray
A 2D NumPy array of partitions.
index : sequence
The index for the dataframe. Converted to a ``pandas.Index``.
columns : sequen... | PandasOnRayDataframe |
python | huggingface__transformers | tests/models/cwm/test_modeling_cwm.py | {
"start": 1709,
"end": 2333
} | class ____(CausalLMModelTest, unittest.TestCase):
all_model_classes = (
(
CwmModel,
CwmForCausalLM,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"feature-extraction": CwmModel,
"text-generation": CwmF... | CwmModelTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 116699,
"end": 124923
} | class ____(Request):
"""
Update a model
:param model: Model id
:type model: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tag... | UpdateRequest |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 38341,
"end": 38678
} | class ____(VOWarning, ValueError):
"""Incorrect number of elements in array.
The number of array elements in the data does not match that specified
in the FIELD specifier.
"""
message_template = (
"Incorrect number of elements in array. Expected multiple of {}, got {}"
)
default_ar... | E02 |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 24773,
"end": 25331
} | class ____:
# GH 14338
params = ["period_range", "date_range", "date_range_tz"]
param_names = ["grouper"]
def setup(self, grouper):
N = 10**4
rng_map = {
"period_range": period_range,
"date_range": date_range,
"date_range_tz": partial(date_range, tz="... | Datelike |
python | chroma-core__chroma | chromadb/utils/embedding_functions/google_embedding_function.py | {
"start": 14381,
"end": 19807
} | class ____(EmbeddingFunction[Documents]):
"""To use this EmbeddingFunction, you must have the vertexai Python package installed and have Google Cloud credentials configured."""
def __init__(
self,
api_key: Optional[str] = None,
model_name: str = "textembedding-gecko",
project_id... | GoogleVertexEmbeddingFunction |
python | huggingface__transformers | src/transformers/models/seamless_m4t/processing_seamless_m4t.py | {
"start": 1054,
"end": 1179
} | class ____(ProcessingKwargs, total=False):
text_kwargs: SeamlessM4TTextKwargs
_defaults = {}
| SeamlessM4TProcessorKwargs |
python | pypa__setuptools | setuptools/_distutils/filelist.py | {
"start": 11942,
"end": 15337
} | class ____(set):
"""
Exclude previously-seen dirs from walk results,
avoiding infinite recursion.
Ref https://bugs.python.org/issue44497.
"""
def __call__(self, walk_item):
"""
Given an item from an os.walk result, determine
if the item represents a unique dir for this i... | _UniqueDirs |
python | apache__airflow | task-sdk/src/airflow/sdk/bases/operator.py | {
"start": 24107,
"end": 77318
} | class ____(AbstractOperator, metaclass=BaseOperatorMeta):
r"""
Abstract base class for all operators.
Since operators create objects that become nodes in the Dag, BaseOperator
contains many recursive methods for Dag crawling behavior. To derive from
this class, you are expected to override the cons... | BaseOperator |
python | falconry__falcon | falcon/bench/bench.py | {
"start": 1775,
"end": 11334
} | class ____:
"""Mock object representing a WSGI `start_response` callable."""
def __init__(self):
self._called = 0
self.status = None
self.headers = None
self.exc_info = None
def __call__(self, status, headers, exc_info=None):
"""Implement the PEP-3333 `start_respons... | StartResponseMockLite |
python | walkccc__LeetCode | solutions/132. Palindrome Partitioning II/132.py | {
"start": 0,
"end": 685
} | class ____:
def minCut(self, s: str) -> int:
n = len(s)
# isPalindrome[i][j] := True if s[i..j] is a palindrome
isPalindrome = [[True] * n for _ in range(n)]
# dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i]
dp = [n] * n
for l in range(2, n + 1):
i = 0
fo... | Solution |
python | pandas-dev__pandas | pandas/tests/indexes/categorical/test_indexing.py | {
"start": 11558,
"end": 12585
} | class ____:
def test_where(self, listlike_box):
klass = listlike_box
i = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
cond = [True] * len(i)
expected = i
result = i.where(klass(cond))
tm.assert_index_equal(result, expected)
cond = ... | TestWhere |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 88234,
"end": 89177
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, api_token: str, workspace: str, start_date: Optional[str] = None):
"""Airbyte Source for Orbit.
Documentation can be found at https://docs.airbyte.com/integrations/sources/orbit
Args:
name (str): The ... | OrbitSource |
python | Netflix__metaflow | metaflow/tutorials/04-playlist-plus/playlist.py | {
"start": 506,
"end": 5021
} | class ____(FlowSpec):
"""
The next version of our playlist generator that adds a 'hint' parameter to
choose a bonus movie closest to the 'hint'.
The flow performs the following steps:
1) Load the genre-specific statistics from the MovieStatsFlow.
2) In parallel branches:
- A) Build a pl... | PlayListFlow |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_not_be_in_set.py | {
"start": 2136,
"end": 15347
} | class ____(ColumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnValuesToNotBeInSet is a \
Column Map Expectation.
Column Map Expectations are one of the most common types of Expectation.
They are evaluated for a single column and ask a yes/no question for every row in t... | ExpectColumnValuesToNotBeInSet |
python | sphinx-doc__sphinx | sphinx/builders/_epub_base.py | {
"start": 2183,
"end": 2263
} | class ____(NamedTuple):
href: str
id: str
media_type: str
| ManifestItem |
python | coleifer__peewee | playhouse/apsw_ext.py | {
"start": 4965,
"end": 5018
} | class ____(_DecimalField):
db_value = nh
| DecimalField |
python | Netflix__metaflow | metaflow/plugins/cards/exception.py | {
"start": 163,
"end": 638
} | class ____(MetaflowException):
"""
This exception is raised with MetaflowCard class is not present for a particular card type.
"""
headline = "MetaflowCard not found"
def __init__(self, card_name):
exc = traceback.format_exc()
msg = (
"MetaflowCard named %s not found. C... | CardClassFoundException |
python | astropy__astropy | astropy/io/fits/column.py | {
"start": 15223,
"end": 15613
} | class ____(_FormatP):
"""Carries type description of the Q format for variable length arrays.
The Q format is like the P format but uses 64-bit integers in the array
descriptors, allowing for heaps stored beyond 2GB into a file.
"""
_format_code = "Q"
_format_re = re.compile(_FormatP._format_r... | _FormatQ |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 6939,
"end": 9593
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
__requires__ = ("index_reflection",)
@classmethod
def define_tables(cls, metadata):
tt = Table(
"test_table",
metadata,
Column("id", Integer, primary_key=True),
Column("data", Strin... | HasIndexTest |
python | pytorch__pytorch | test/inductor/test_triton_syntax.py | {
"start": 179,
"end": 1898
} | class ____(TestCase):
@requires_gpu()
def test_triton_sqrt(self):
# https://github.com/pytorch/pytorch/issues/142328
import math
import torch.nn as nn
def newtonschulz5(G, steps: int, eps=1e-7):
assert len(G.shape) == 2
a, b, c = (3.4445, -4.7750, 2.0315... | TestTritonSyntacticallyValid |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 23211,
"end": 23317
} | class ____(TestEsES):
def setUp(self):
self.fake = Faker("es_CA")
Faker.seed(0)
| TestEsCA |
python | kamyu104__LeetCode-Solutions | Python/count-subarrays-with-score-less-than-k.py | {
"start": 60,
"end": 489
} | class ____(object):
def countSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = total = left = 0
for right in xrange(len(nums)):
total += nums[right]
while total*(right-left+1) >= k:
... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_write_style_sheet.py | {
"start": 295,
"end": 835
} | class ____(unittest.TestCase):
"""
Test the Styles _write_style_sheet() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_style_sheet(self):
"""Test the _write_style_sheet() method"""
... | TestWriteStyleSheet |
python | django__django | tests/admin_views/admin.py | {
"start": 19743,
"end": 20036
} | class ____(admin.ModelAdmin):
list_display = ("name", "age", "is_employee", "colored_name")
ordering = ("name",)
@admin.display(ordering="name")
def colored_name(self, obj):
return format_html('<span style="color: #ff00ff;">{}</span>', obj.name)
| ComplexSortedPersonAdmin |
python | pexpect__pexpect | tests/test_unicode.py | {
"start": 294,
"end": 6531
} | class ____(PexpectTestCase.PexpectTestCase):
def test_expect_basic (self):
p = pexpect.spawnu('cat')
p.sendline('Hello')
p.sendline('there')
p.sendline('Mr. þython') # þ is more like th than p, but never mind
p.expect('Hello')
p.expect('there')
p.expect('Mr. þ... | UnicodeTests |
python | django__django | django/db/models/functions/datetime.py | {
"start": 5140,
"end": 5195
} | class ____(Extract):
lookup_name = "hour"
| ExtractHour |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/definition_config_schema.py | {
"start": 1552,
"end": 2727
} | class ____(ABC):
@abstractmethod
def as_field(self) -> Field:
raise NotImplementedError()
@property
def config_type(self) -> Optional[ConfigType]:
field = self.as_field()
return field.config_type if field else None
@property
def is_required(self) -> bool:
field ... | IDefinitionConfigSchema |
python | pytorch__pytorch | torch/distributed/optim/functional_adamw.py | {
"start": 812,
"end": 7511
} | class ____:
def __init__(
self,
params: list[Tensor],
lr: float = 1e-3,
betas: tuple[float, float] = (0.9, 0.999),
eps: float = 1e-8,
weight_decay: float = 1e-2,
amsgrad: bool = False,
maximize: bool = False,
foreach: bool = False,
fuse... | _FunctionalAdamW |
python | pennersr__django-allauth | allauth/headless/base/response.py | {
"start": 5297,
"end": 5433
} | class ____(APIResponse):
def __init__(self, request):
super().__init__(request, status=HTTPStatus.FORBIDDEN)
| ForbiddenResponse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.