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 | sympy__sympy | sympy/stats/crv_types.py | {
"start": 75011,
"end": 76825
} | class ____(SingleContinuousDistribution):
_argnames = ('alpha', 'lamda',)
set = Interval(0, oo)
@staticmethod
def check(alpha, lamda):
_value_check(alpha.is_real, "Shape parameter should be real.")
_value_check(lamda.is_real, "Scale parameter should be real.")
_value_check(alpha... | LomaxDistribution |
python | python__mypy | mypyc/analysis/dataflow.py | {
"start": 4773,
"end": 8577
} | class ____(OpVisitor[GenAndKill[T]]):
def visit_goto(self, op: Goto) -> GenAndKill[T]:
return set(), set()
@abstractmethod
def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]:
raise NotImplementedError
@abstractmethod
def visit_assign(self, op: Assign) -> GenAndKill[T]:
... | BaseAnalysisVisitor |
python | anthropics__anthropic-sdk-python | src/anthropic/_models.py | {
"start": 23941,
"end": 30891
} | class ____:
field_name: str
"""The name of the discriminator field in the variant class, e.g.
```py
class Foo(BaseModel):
type: Literal['foo']
```
Will result in field_name='type'
"""
field_alias_from: str | None
"""The name of the discriminator field in the API response, ... | DiscriminatorDetails |
python | doocs__leetcode | solution/2600-2699/2606.Find the Substring With Maximum Cost/Solution.py | {
"start": 0,
"end": 346
} | class ____:
def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int:
d = {c: v for c, v in zip(chars, vals)}
ans = tot = mi = 0
for c in s:
v = d.get(c, ord(c) - ord('a') + 1)
tot += v
ans = max(ans, tot - mi)
mi = min(mi, to... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 3342,
"end": 3425
} | class ____(Variadic_TA[T]): ...
# This should generate an error.
| VariadicChild_WithTA |
python | realpython__materials | python-iterators-iterables/inf_fib.py | {
"start": 0,
"end": 356
} | class ____:
def __init__(self):
self._index = 0
self._current = 0
self._next = 1
def __iter__(self):
return self
def __next__(self):
self._index += 1
fib_number = self._current
self._current, self._next = self._next, self._current + self._next
... | FibonacciInfIterator |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 1007,
"end": 1080
} | class ____(AlternatesI18nSitemap):
x_default = True
| XDefaultI18nSitemap |
python | dask__dask | dask/dataframe/dask_expr/_dummies.py | {
"start": 5061,
"end": 5699
} | class ____(Blockwise):
_parameters = [
"frame",
"prefix",
"prefix_sep",
"dummy_na",
"columns",
"sparse",
"drop_first",
"dtype",
]
_defaults = {
"prefix": None,
"prefix_sep": "_",
"dummy_na": False,
"columns": Non... | GetDummies |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 9486,
"end": 9539
} | class ____:
def __init__(self, x):
pass
| Foo |
python | getsentry__sentry | src/sentry/notifications/api/endpoints/notification_actions_details.py | {
"start": 1396,
"end": 7630
} | class ____(OrganizationEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
"""
Manages a single NotificationAction via the action_id passed in the path.
GET: Returns... | NotificationActionsDetailsEndpoint |
python | django__django | django/db/models/functions/math.py | {
"start": 3724,
"end": 3980
} | class ____(NumericOutputFieldMixin, Func):
function = "PI"
arity = 0
def as_oracle(self, compiler, connection, **extra_context):
return super().as_sql(
compiler, connection, template=str(math.pi), **extra_context
)
| Pi |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/interleave_test.py | {
"start": 3738,
"end": 17134
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
input_values=[[4, 5, 6]],
cycle_length=1,
block_length=1,
expected_... | InterleaveTest |
python | ray-project__ray | python/ray/data/_internal/planner/plan_expression/expression_evaluator.py | {
"start": 6166,
"end": 13996
} | class ____(ast.NodeVisitor):
# TODO: Deprecate this visitor after we remove string support in filter API.
def visit_Compare(self, node: ast.Compare) -> ds.Expression:
"""Handle comparison operations (e.g., a == b, a < b, a in b).
Args:
node: The AST node representing a comparison op... | _ConvertToArrowExpressionVisitor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 259382,
"end": 259900
} | class ____(sgqlc.types.Input):
"""Ways in which lists of package versions can be ordered upon
return.
"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(PackageVersionOrderField, graphql_name="field")
"""The field in which to order package vers... | PackageVersionOrder |
python | lepture__mistune | src/mistune/directives/_rst.py | {
"start": 1025,
"end": 2282
} | class ____(BaseDirective):
"""A RST style of directive syntax is inspired by reStructuredText.
The syntax is very powerful that you can define a lot of custom
features on your own. The syntax looks like:
.. code-block:: text
.. directive-type:: directive value
:option-key: option va... | RSTDirective |
python | Lightning-AI__lightning | tests/tests_pytorch/utilities/test_dtype_device_mixin.py | {
"start": 1019,
"end": 1176
} | class ____(BoringModel):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.module = SubModule()
| TopModule |
python | Textualize__textual | src/textual/widgets/_rule.py | {
"start": 1448,
"end": 1544
} | class ____(Exception):
"""Exception raised for an invalid rule line style."""
| InvalidLineStyle |
python | coleifer__peewee | peewee.py | {
"start": 41145,
"end": 41849
} | class ____(ColumnBase):
def __init__(self, value, converter=None, unpack=True):
self.value = value
self.converter = converter
self.multi = unpack and isinstance(self.value, multi_types)
if self.multi:
self.values = []
for item in self.value:
if... | Value |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/pipes.py | {
"start": 5322,
"end": 15099
} | class ____(BasePipesDatabricksClient, TreatAsResourceParam):
"""Pipes client for databricks.
Args:
client (WorkspaceClient): A databricks `WorkspaceClient` object.
env (Optional[Mapping[str,str]]: An optional dict of environment
variables to pass to the databricks job.
conte... | PipesDatabricksClient |
python | getsentry__sentry | tests/sentry/incidents/models/test_alert_rule.py | {
"start": 5687,
"end": 7991
} | class ____(TestCase):
def test_empty(self) -> None:
alert_rule = AlertRule.objects.fetch_for_organization(self.organization)
assert [] == list(alert_rule)
def test_simple(self) -> None:
alert_rule = self.create_alert_rule()
assert [alert_rule] == list(AlertRule.objects.fetch_fo... | AlertRuleFetchForOrganizationTest |
python | plotly__plotly.py | plotly/graph_objs/histogram/_cumulative.py | {
"start": 233,
"end": 6560
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram"
_path_str = "histogram.cumulative"
_valid_props = {"currentbin", "direction", "enabled"}
@property
def currentbin(self):
"""
Only applies if cumulative is enabled. Sets whether the current
bin is included, e... | Cumulative |
python | huggingface__transformers | tests/test_image_transforms.py | {
"start": 1563,
"end": 25416
} | class ____(unittest.TestCase):
@parameterized.expand(
[
("numpy_float_channels_first", (3, 4, 5), np.float32),
("numpy_float_channels_last", (4, 5, 3), np.float32),
("numpy_float_channels_first", (3, 4, 5), np.float64),
("numpy_float_channels_last", (4, 5, 3),... | ImageTransformsTester |
python | Textualize__textual | src/textual/notifications.py | {
"start": 465,
"end": 589
} | class ____(Message, bubble=False):
"""Message to show a notification."""
notification: Notification
@dataclass
| Notify |
python | scrapy__scrapy | scrapy/robotstxt.py | {
"start": 1249,
"end": 2139
} | class ____(metaclass=ABCMeta):
@classmethod
@abstractmethod
def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self:
"""Parse the content of a robots.txt_ file as bytes. This must be a class method.
It must return a new instance of the parser backend.
:param crawler: ... | RobotParser |
python | getsentry__sentry | src/sentry/utils/warnings.py | {
"start": 1257,
"end": 2286
} | class ____:
"""
Transforms warnings into a standard form and invokes handlers.
"""
def __init__(
self, handlers: tuple[_WarningHandler, ...], default_category: type[Warning] = Warning
) -> None:
self.__handlers = handlers
self.__default_category = default_category
def w... | WarningManager |
python | getsentry__sentry | tests/sentry/rules/processing/test_delayed_processing.py | {
"start": 25499,
"end": 26494
} | class ____(TestCase):
def test_empty_input(self) -> None:
result = get_rules_to_groups({})
assert result == defaultdict(set)
def test_single_rule_group(self) -> None:
input_data = {"1:100": "event_data"}
expected = defaultdict(set, {1: {100}})
result = get_rules_to_group... | GetRulesToGroupsTest |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 16307,
"end": 17745
} | class ____(ASTLiteral):
def __init__(self, prefix: str, data: str) -> None:
self.prefix = prefix # may be None when no prefix
self.data = data
assert prefix in _id_char_from_prefix
self.type = _id_char_from_prefix[prefix]
decoded = data.encode().decode('unicode-escape')
... | ASTCharLiteral |
python | huggingface__transformers | src/transformers/models/cohere2_vision/modeling_cohere2_vision.py | {
"start": 11727,
"end": 17488
} | class ____(Cohere2VisionPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {}
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
def __init__(self, config: Cohere2VisionConfig):
super().__init__(config)
self.model = Cohere2VisionModel(config... | Cohere2VisionForConditionalGeneration |
python | gabrielfalcao__HTTPretty | tests/bugfixes/pytest/test_426_mypy_segfault.py | {
"start": 85,
"end": 1059
} | class ____(type):
def __init__(cls, name, bases, attrs):
if name in ('GenerateTestMeta',): return
count = getattr(cls, '__generate_count__', attrs.get('__generate_count__'))
if not isinstance(count, int):
raise SyntaxError(f'Metaclass requires def `__generate_count__ = NUMBER_OF... | GenerateTests |
python | mlflow__mlflow | mlflow/entities/run_info.py | {
"start": 757,
"end": 909
} | class ____(property):
# Wrapper class over property to designate some of the properties as orderable
# run attributes
pass
| orderable_attribute |
python | walkccc__LeetCode | solutions/509. Fibonacci Number/509.py | {
"start": 0,
"end": 214
} | class ____:
def fib(self, n: int) -> int:
if n < 2:
return n
dp = [0, 0, 1]
for i in range(2, n + 1):
dp[0] = dp[1]
dp[1] = dp[2]
dp[2] = dp[0] + dp[1]
return dp[2]
| Solution |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_w0wzcdm.py | {
"start": 6969,
"end": 11093
} | class ____(FlatFLRWMixinTest, Testw0wzCDM):
"""Test :class:`astropy.cosmology.Flatw0wzCDM`."""
def setup_class(self):
"""Setup for testing."""
super().setup_class(self)
self.cls = Flatw0wzCDM
def test_repr(self, cosmo_cls, cosmo):
"""Test method ``.__repr__()``."""
... | TestFlatw0wzCDM |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 356594,
"end": 357449
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateOrganizationWebCommitSignoffSetting
"""
__schema__ = github_schema
__field_names__ = ("organization_id", "web_commit_signoff_required", "client_mutation_id")
organization_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql... | UpdateOrganizationWebCommitSignoffSettingInput |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 262020,
"end": 263426
} | class ____(ExternKernel):
"""
This needs to be a custom class to handle mutation and indices properly
"""
def codegen(self, wrapper: PythonWrapperCodegen) -> None:
wrapper.generate_index_put_fallback(self)
def should_allocate(self) -> bool:
return False
def get_mutation_names(... | IndexPutFallback |
python | pallets__jinja | src/jinja2/compiler.py | {
"start": 4664,
"end": 7556
} | class ____:
"""Holds compile time information for us."""
def __init__(
self,
eval_ctx: EvalContext,
parent: t.Optional["Frame"] = None,
level: int | None = None,
) -> None:
self.eval_ctx = eval_ctx
# the parent of this frame
self.parent = parent
... | Frame |
python | google__pytype | pytype/tools/analyze_project/pytype_runner_test.py | {
"start": 17151,
"end": 18174
} | class ____(TestBase):
"""Tests for PytypeRunner.write_ninja_preamble."""
def test_write(self):
conf = self.parser.config_from_defaults()
with test_utils.Tempdir() as d:
conf.output = d.path
runner = make_runner([], [], conf)
runner.write_ninja_preamble()
with open(runner.ninja_file)... | TestNinjaPreamble |
python | pypa__setuptools | setuptools/_scripts.py | {
"start": 8796,
"end": 11247
} | class ____(WindowsScriptWriter):
@classmethod
def _get_script_args(cls, type_, name, header, script_text):
"""
For Windows, add a .py extension and an .exe launcher
"""
if type_ == 'gui':
launcher_type = 'gui'
ext = '-script.pyw'
old = ['.pyw']... | WindowsExecutableLauncherWriter |
python | numba__numba | numba/tests/gdb/test_conditional_breakpoint.py | {
"start": 238,
"end": 1224
} | class ____(TestCase):
def test(self):
@njit(debug=True)
def foo(x, y):
c = x + y # break-here
return c
@njit(debug=True)
def call_foo(a):
acc = 0
for i in range(10):
acc += foo(i, a)
return acc
c... | Test |
python | walkccc__LeetCode | solutions/1557. Minimum Number of Vertices to Reach All Nodes/1557.py | {
"start": 0,
"end": 254
} | class ____:
def findSmallestSetOfVertices(
self,
n: int,
edges: list[list[int]],
) -> list[int]:
inDegrees = [0] * n
for _, v in edges:
inDegrees[v] += 1
return [i for i, d in enumerate(inDegrees) if d == 0]
| Solution |
python | huggingface__transformers | tests/quantization/quanto_integration/test_quanto.py | {
"start": 14558,
"end": 15791
} | class ____(QuantoQuantizationTest):
"""
Perform the same tests as in QuantoQuantizationTest but with a serialized model.
"""
def setUp(self):
"""
Setup quantized model
"""
quantization_config = QuantoConfig(
weights=self.weights,
activations=self.... | QuantoQuantizationSerializationTest |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_profile_functions.py | {
"start": 127,
"end": 1952
} | class ____(OrganizationEventsEndpointTestBase):
dataset = "profile_functions"
def test_simple(self) -> None:
profile_functions = [
self.create_profile_function(attributes={"name": "foo", "self_time_ns": 1}),
self.create_profile_function(attributes={"name": "bar", "self_time_ns":... | OrganizationEventsProfileFunctionsEndpointTest |
python | gevent__gevent | src/greentest/3.9/test_asyncore.py | {
"start": 14702,
"end": 25058
} | class ____:
def tearDown(self):
asyncore.close_all(ignore_all=True)
def loop_waiting_for_flag(self, instance, timeout=5):
timeout = float(timeout) / 100
count = 100
while asyncore.socket_map and count > 0:
asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll)... | BaseTestAPI |
python | getsentry__sentry | src/sentry/api/serializers/models/project_key.py | {
"start": 970,
"end": 1447
} | class ____(TypedDict):
"""
This represents a Sentry Project Client Key.
"""
id: str
name: str
label: str
public: str | None
secret: str | None
projectId: int
isActive: bool
rateLimit: RateLimit | None
dsn: DSN
browserSdkVersion: str
browserSdk: BrowserSDK
dat... | ProjectKeySerializerResponse |
python | pypa__warehouse | warehouse/authnz/_permissions.py | {
"start": 66,
"end": 4355
} | class ____(StrEnum):
"""
Permissions can be specified in an ACL (`__acl__`) or `@view_config(permission=...)`
instead of using a string literal, minimizing the chance of typos.
They are also disconnected from Principals (users, groups, etc.), so they can be
used in a more generic way. For example, ... | Permissions |
python | encode__django-rest-framework | tests/test_serializer_nested.py | {
"start": 11130,
"end": 12826
} | class ____:
"""
Test that raise_errors_on_nested_writes does not raise `AssertionError` when the
model field is not a relation.
"""
def test_nested_serializer_create_and_update(self):
class NonRelationalPersonDataSerializer(serializers.Serializer):
occupation = serializers.Char... | TestNestedNonRelationalFieldWrite |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 9202,
"end": 23330
} | class ____:
_creation_counter = 0
default_error_messages = {
'required': _('This field is required.'),
'null': _('This field may not be null.')
}
default_validators = []
default_empty_html = empty
initial = None
def __init__(self, *, read_only=False, write_only=False,
... | Field |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/assets.py | {
"start": 808,
"end": 983
} | class ____(graphene.Union):
class Meta:
types = (GrapheneAssetRecordConnection, GraphenePythonError)
name = "AssetRecordsOrError"
| GrapheneAssetRecordsOrError |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 109053,
"end": 109382
} | class ____(spack.error.SpackError):
"""
Raised when multiple keys can be used to sign.
"""
def __init__(self, keys):
err_msg = "Multiple keys available for signing\n%s\n" % keys
err_msg += "Use spack buildcache create -k <key hash> to pick a key."
super().__init__(err_msg)
| PickKeyException |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 15553,
"end": 17271
} | class ____(Generic[Properties, IReferences]):
def __init__(
self,
objects: Optional[List[Object[Properties, IReferences]]],
):
self.__objects = objects
@classmethod
def _from(
cls, objects: List[Object[Properties, IReferences]]
) -> "_CrossReference[Properties, IRefe... | _CrossReference |
python | google__pytype | pytype/pytd/visitors_test.py | {
"start": 34881,
"end": 39169
} | class ____(parser_test_base.ParserTest):
"""Tests for RemoveNamePrefix."""
def test_remove_name_prefix(self):
src = textwrap.dedent("""
from typing import TypeVar
def f(a: T) -> T: ...
T = TypeVar("T")
class X(Generic[T]):
pass
""")
expected = textwrap.dedent("""
f... | RemoveNamePrefixTest |
python | Lightning-AI__lightning | src/lightning/pytorch/loggers/csv_logs.py | {
"start": 1338,
"end": 2156
} | class ____(_FabricExperimentWriter):
r"""Experiment writer for CSVLogger.
Currently, supports to log hyperparameters and metrics in YAML and CSV
format, respectively.
This logger supports logging to remote filesystems via ``fsspec``. Make sure you have it installed.
Args:
log_dir: Directo... | ExperimentWriter |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 9304,
"end": 9780
} | class ____(GestureTool):
''' A base class for tools that perform "selections", e.g. ``BoxSelectTool``.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
renderers = Either(Auto, List(Instance(DataRen... | SelectTool |
python | django__django | tests/m2m_through/tests.py | {
"start": 21536,
"end": 22898
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.pea = Ingredient.objects.create(iname="pea")
cls.potato = Ingredient.objects.create(iname="potato")
cls.tomato = Ingredient.objects.create(iname="tomato")
cls.curry = Recipe.objects.create(rname="curry")
Recip... | M2mThroughToFieldsTests |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 23266,
"end": 24971
} | class ____:
"""
An object that represents a method on an element as a function;
the function takes either an element or an HTML string. It
returns whatever the function normally returns, or if the function
works in-place (and so returns None) it returns a serialized form
of the resulting docume... | _MethodFunc |
python | tiangolo__fastapi | fastapi/routing.py | {
"start": 18916,
"end": 27202
} | class ____(routing.Route):
def __init__(
self,
path: str,
endpoint: Callable[..., Any],
*,
response_model: Any = Default(None),
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[params.Dep... | APIRoute |
python | langchain-ai__langchain | libs/partners/anthropic/tests/unit_tests/test_chat_models.py | {
"start": 44066,
"end": 52792
} | class ____(BaseTracer):
"""Fake tracer to capture inputs to `chat_model_start`."""
def __init__(self) -> None:
super().__init__()
self.chat_model_start_inputs: list = []
def _persist_run(self, run: Run) -> None:
"""Persist a run."""
def on_chat_model_start(self, *args: Any, **... | FakeTracer |
python | spack__spack | lib/spack/spack/test/variant.py | {
"start": 11771,
"end": 13884
} | class ____:
def test_validation(self):
a = Variant(
"foo", default="", description="", values=("bar", "baz", "foobar"), multi=False
)
# Valid vspec, shouldn't raise
vspec = a.make_variant("bar")
a.validate_or_raise(vspec, "test-package")
# Multiple values... | TestVariant |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 483479,
"end": 484185
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for CWE."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("CWEEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Fi... | CWEConnection |
python | getsentry__sentry | src/sentry/integrations/jira/views/extension_configuration.py | {
"start": 406,
"end": 1162
} | class ____(IntegrationExtensionConfigurationView):
"""
Handle the UI for adding the Jira integration to a Sentry org.
"""
provider = IntegrationProviderSlug.JIRA.value
external_provider_key = IntegrationProviderSlug.JIRA.value
def map_params_to_state(self, original_params):
# decode th... | JiraExtensionConfigurationView |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmd_tf.py | {
"start": 517,
"end": 4802
} | class ____:
def __init__(self, M):
self.M = M # number of hidden states
def set_session(self, session):
self.session = session
def fit(self, X, max_iter=10, print_period=1):
# train the HMM model using stochastic gradient descent
N = len(X)
print("number of tra... | HMM |
python | coleifer__peewee | tests/sql.py | {
"start": 74554,
"end": 76569
} | class ____(BaseTestCase):
def test_case_function(self):
NameNum = Table('nn', ('name', 'number'))
query = (NameNum
.select(NameNum.name, Case(NameNum.number, (
(1, 'one'),
(2, 'two')), '?').alias('num_str')))
self.assertSQL(query, (... | TestCaseFunction |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 337411,
"end": 338636
} | class ____(Response):
"""
Response of tasks.get_types endpoint.
:param types: Unique list of the task types used in the requested projects
:type types: Sequence[str]
"""
_service = "tasks"
_action = "get_types"
_version = "2.20"
_schema = {
"definitions": {},
"prope... | GetTypesResponse |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/cloud_formation.py | {
"start": 3030,
"end": 5019
} | class ____(AwsBaseSensor[CloudFormationHook]):
"""
Waits for a stack to be deleted successfully on AWS CloudFormation.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:CloudFormationDeleteStackSensor`
:param stack_name: The name ... | CloudFormationDeleteStackSensor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-monday/components.py | {
"start": 21660,
"end": 22200
} | class ____(RecordTransformation):
def transform(self, record: MutableMapping[str, Any], config: Optional[Config] = None, **kwargs) -> MutableMapping[str, Any]:
# Oncall issue: https://github.com/airbytehq/oncall/issues/4337
column_values = record.get("column_values", [])
for values in column... | MondayTransformation |
python | django-haystack__django-haystack | haystack/templatetags/more_like_this.py | {
"start": 178,
"end": 3465
} | class ____(template.Node):
def __init__(self, model, varname, for_types=None, limit=None):
self.model = template.Variable(model)
self.varname = varname
self.for_types = for_types
self.limit = limit
if self.limit is not None:
self.limit = int(self.limit)
def ... | MoreLikeThisNode |
python | openai__openai-python | src/openai/resources/beta/realtime/transcription_sessions.py | {
"start": 13512,
"end": 13811
} | class ____:
def __init__(self, transcription_sessions: TranscriptionSessions) -> None:
self._transcription_sessions = transcription_sessions
self.create = to_streamed_response_wrapper(
transcription_sessions.create,
)
| TranscriptionSessionsWithStreamingResponse |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/test_utils.py | {
"start": 14139,
"end": 19232
} | class ____(SecretsLoader, ConfigurableClass):
def __init__(self, inst_data: Optional[ConfigurableClassData], env_vars: dict[str, str]):
self._inst_data = inst_data
self.env_vars = env_vars
def get_secrets_for_environment(self, location_name: str) -> dict[str, str]: # pyright: ignore[reportInco... | TestSecretsLoader |
python | huggingface__transformers | tests/repo_utils/test_check_copies.py | {
"start": 2944,
"end": 3488
} | class ____:
attr_1 = 1
attr_2 = 2
def __init__(self, a=1, b=2):
self.a = a
self.b = b
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
def forward(self, c):
return 1
def existing_common(self, c):
return 4
def existing... | BertDummyModel |
python | bokeh__bokeh | src/bokeh/models/mappers.py | {
"start": 2692,
"end": 3348
} | class ____(Mapper):
''' Base class for color mapper types.
'''
def __init__(self, *args, **kwargs) -> None:
if len(args) == 1:
kwargs['palette'] = args[0]
super().__init__(**kwargs)
palette = Seq(Color, help="""
A sequence of colors to use as the target palette for map... | ColorMapper |
python | encode__django-rest-framework | rest_framework/versioning.py | {
"start": 3321,
"end": 5099
} | class ____(BaseVersioning):
"""
To the client this is the same style as `URLPathVersioning`.
The difference is in the backend - this implementation uses
Django's URL namespaces to determine the version.
An example URL conf that is namespaced into two separate versions
# users/urls.py
urlpa... | NamespaceVersioning |
python | spyder-ide__spyder | spyder/utils/qthelpers.py | {
"start": 24965,
"end": 31206
} | class ____(QApplication, SpyderConfigurationAccessor,
SpyderFontsMixin):
"""Subclass with several adjustments for Spyder."""
sig_open_external_file = Signal(str)
def __init__(self, *args):
QApplication.__init__(self, *args)
self._never_shown = True
self._ha... | SpyderApplication |
python | kamyu104__LeetCode-Solutions | Python/find-two-non-overlapping-sub-arrays-each-with-target-sum.py | {
"start": 29,
"end": 761
} | class ____(object):
def minSumOfLengths(self, arr, target):
"""
:type arr: List[int]
:type target: int
:rtype: int
"""
prefix, dp = {0: -1}, [0]*len(arr) # dp[i], min len of target subarray until i
result = min_len = float("inf")
accu = 0
for ... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0101_remove_is_single_written_field.py | {
"start": 239,
"end": 1562
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | sympy__sympy | sympy/sets/ordinals.py | {
"start": 7163,
"end": 7612
} | class ____(Ordinal):
"""The ordinal omega which forms the base of all ordinals in cantor normal form.
OrdinalOmega can be imported as ``omega``.
Examples
========
>>> from sympy.sets.ordinals import omega
>>> omega + omega
w*2
"""
def __new__(cls):
return Ordinal.__new__(c... | OrdinalOmega |
python | google__pytype | pytype/tests/test_stdlib2.py | {
"start": 116,
"end": 3809
} | class ____(test_base.BaseTest, test_utils.TestCollectionsMixin):
"""Tests for files in typeshed/stdlib."""
def test_collections_deque(self):
# This method is different from the preceding ones because we model
# collections.deque as a subclass, rather than an alias, of typing.Deque.
errors = self.CheckW... | StdLibTestsBasic |
python | kubernetes-client__python | kubernetes/client/api/admissionregistration_api.py | {
"start": 543,
"end": 5215
} | 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
... | AdmissionregistrationApi |
python | coleifer__peewee | tests/sqlite_udf.py | {
"start": 1622,
"end": 1809
} | class ____(ModelTestCase):
database = database
def sql1(self, sql, *params):
cursor = self.database.execute_sql(sql, params)
return cursor.fetchone()[0]
| BaseTestUDF |
python | huggingface__transformers | tests/models/paligemma/test_modeling_paligemma.py | {
"start": 1332,
"end": 6074
} | class ____:
def __init__(
self,
parent,
ignore_index=-100,
image_token_index=0,
projector_hidden_act="gelu",
seq_length=25,
vision_feature_select_strategy="default",
vision_feature_layer=-1,
projection_dim=32,
text_config={
... | PaliGemmaVisionText2TextModelTester |
python | huggingface__transformers | src/transformers/models/sam2/configuration_sam2.py | {
"start": 11236,
"end": 13323
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Sam2PromptEncoder`]. The [`Sam2PromptEncoder`]
module is used to encode the input 2D points and bounding boxes.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the mod... | Sam2PromptEncoderConfig |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 32840,
"end": 33292
} | class ____(Base):
active: Mapped[bool] = mapped_column(default=True)
name: Mapped[str]
limit: Mapped[int]
active_slots: Mapped[int] = mapped_column(default=0)
denied_slots: Mapped[int] = mapped_column(default=0)
slot_decay_per_second: Mapped[float] = mapped_column(default=0.0)
avg_slot_occu... | ConcurrencyLimitV2 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 5227,
"end": 5452
} | class ____(FromClauseRole):
__slots__ = ()
if TYPE_CHECKING:
def _anonymous_fromclause(
self, *, name: Optional[str] = None, flat: bool = False
) -> FromClause: ...
| AnonymizedFromClauseRole |
python | huggingface__transformers | tests/models/owlv2/test_modeling_owlv2.py | {
"start": 4720,
"end": 7647
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as OWLV2 does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (Owlv2VisionModel,) if is_torch_available() else ()
test_resize_embed... | Owlv2VisionModelTest |
python | urllib3__urllib3 | src/urllib3/contrib/emscripten/request.py | {
"start": 134,
"end": 566
} | class ____:
method: str
url: str
params: dict[str, str] | None = None
body: _TYPE_BODY | None = None
headers: dict[str, str] = field(default_factory=dict)
timeout: float = 0
decode_content: bool = True
def set_header(self, name: str, value: str) -> None:
self.headers[name.capita... | EmscriptenRequest |
python | run-llama__llama_index | llama-index-integrations/storage/index_store/llama-index-storage-index-store-redis/llama_index/storage/index_store/redis/base.py | {
"start": 216,
"end": 1740
} | class ____(KVIndexStore):
"""
Redis Index store.
Args:
redis_kvstore (RedisKVStore): Redis key-value store
namespace (str): namespace for the index store
"""
def __init__(
self,
redis_kvstore: RedisKVStore,
namespace: Optional[str] = None,
collectio... | RedisIndexStore |
python | numba__numba | numba/core/errors.py | {
"start": 17949,
"end": 18087
} | class ____(IRError):
"""
An error occurred during interpretation of IR due to variable redefinition.
"""
pass
| RedefinedError |
python | kamyu104__LeetCode-Solutions | Python/index-pairs-of-a-string.py | {
"start": 2247,
"end": 2727
} | class ____(object):
def indexPairs(self, text, words):
"""
:type text: str
:type words: List[str]
:rtype: List[List[int]]
"""
result = []
reversed_words = [w[::-1] for w in words]
trie = AhoTrie(reversed_words)
for i in reversed(xrange(len(text... | Solution |
python | wandb__wandb | wandb/apis/importers/wandb.py | {
"start": 2738,
"end": 10533
} | class ____:
def __init__(
self,
run: Run,
*,
src_base_url: str,
src_api_key: str,
dst_base_url: str,
dst_api_key: str,
) -> None:
self.run = run
self.api = wandb.Api(
api_key=src_api_key,
overrides={"base_url": src_b... | WandbRun |
python | jmcnamara__XlsxWriter | xlsxwriter/test/sharedstrings/test_write_si.py | {
"start": 309,
"end": 794
} | class ____(unittest.TestCase):
"""
Test the SharedStrings _write_si() method.
"""
def setUp(self):
self.fh = StringIO()
self.sharedstrings = SharedStrings()
self.sharedstrings._set_filehandle(self.fh)
def test_write_si(self):
"""Test the _write_si() method"""
... | TestWriteSi |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_git_sync_triggerer.py | {
"start": 900,
"end": 4948
} | class ____:
"""Test git sync triggerer."""
def test_validate_sshkeysecret_not_added_when_persistence_is_enabled(self):
docs = render_chart(
values={
"dags": {
"gitSync": {
"enabled": True,
"containerName": "... | TestGitSyncTriggerer |
python | getsentry__sentry | src/sentry/models/releasefile.py | {
"start": 7739,
"end": 13981
} | class ____:
"""Ensures atomic write operations to the artifact index"""
def __init__(self, release: Release, dist: Distribution | None, **filter_args):
self._release = release
self._dist = dist
self._ident = ReleaseFile.get_ident(ARTIFACT_INDEX_FILENAME, dist and dist.name)
self... | _ArtifactIndexGuard |
python | huggingface__transformers | tests/models/dbrx/test_modeling_dbrx.py | {
"start": 3560,
"end": 4366
} | class ____(unittest.TestCase):
@slow
def test_tiny_model_logits(self):
model = DbrxForCausalLM.from_pretrained("Rocketknight1/dbrx-tiny-random")
input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
output = model(input_ids)[0]
vocab_size = model.vocab_size
expected_shape = tor... | DbrxModelIntegrationTest |
python | kubernetes-client__python | kubernetes/client/models/v1_namespace_spec.py | {
"start": 383,
"end": 3826
} | 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... | V1NamespaceSpec |
python | kamyu104__LeetCode-Solutions | Python/best-sightseeing-pair.py | {
"start": 29,
"end": 311
} | class ____(object):
def maxScoreSightseeingPair(self, A):
"""
:type A: List[int]
:rtype: int
"""
result, curr = 0, 0
for x in A:
result = max(result, curr+x)
curr = max(curr, x)-1
return result
| Solution |
python | great-expectations__great_expectations | great_expectations/data_context/data_context_variables.py | {
"start": 2087,
"end": 8055
} | class ____(ABC):
"""
Wrapper object around data context variables set in the `great_expectations.yml` config file.
Child classes should instantiate their own stores to ensure that changes made to this object
are persisted for future usage (i.e. filesystem I/O or HTTP request to a Cloud endpoint).
... | DataContextVariables |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 3332,
"end": 3417
} | class ____(CommandTimeout):
exit_code = ExitCode.COMMAND_TIMEOUT
| TestCommandTimeout |
python | viewflow__viewflow | viewflow/workflow/context.py | {
"start": 56,
"end": 1540
} | class ____(object):
"""Thread-local activation context, dynamically scoped.
:keyword propagate_exception: If True, on activation failure
exception will be propagated to
previous activation. If False,
current t... | Context |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_batch.py | {
"start": 998,
"end": 3007
} | class ____:
JOB_ID = "test_job_id"
@pytest.fixture(autouse=True)
def _setup_test_cases(self, monkeypatch):
self.client = boto3.client("batch", region_name="eu-west-3")
monkeypatch.setattr(BatchClientHook, "conn", self.client)
@pytest.fixture
def mock_describe_jobs(self):
""... | TestCustomBatchServiceWaiters |
python | davidhalter__jedi | test/test_inference/test_signature.py | {
"start": 1371,
"end": 1726
} | class ____:
@classmethod
def x(cls, a, b):
pass
@staticmethod
def static(a, b):
pass
'''
partial_code = '''
import functools
def func(a, b, c):
pass
a = functools.partial(func)
b = functools.partial(func, 1)
c = functools.partial(func, 1, c=2)
d = functools.partial()
'''
parti... | X |
python | protocolbuffers__protobuf | python/google/protobuf/internal/well_known_types_test.py | {
"start": 37362,
"end": 41626
} | class ____(unittest.TestCase):
def testAnyMessage(self):
# Creates and sets message.
msg = well_known_types_test_pb2.TestAny()
msg_descriptor = msg.DESCRIPTOR
all_types = unittest_pb2.TestAllTypes()
all_descriptor = all_types.DESCRIPTOR
all_types.repeated_string.append('\u00fc\ua71f')
# P... | AnyTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_assets.py | {
"start": 154352,
"end": 168670
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_asset_event_history_no_observation_events(
self, graphql_context: WorkspaceRequestContext
):
"""Documents current behavior of the asset event history query for OSS. It
currently does not include asset failed to materialize events.
... | TestAssetEventHistory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.