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 | numpy__numpy | benchmarks/benchmarks/bench_core.py | {
"start": 7156,
"end": 8117
} | class ____(Benchmark):
def setup(self):
self.A = np.array([100 * 'x', 100 * 'y'])
self.B = np.array(1000 * ['aa'])
self.C = np.array([100 * 'x' + 'z', 100 * 'y' + 'z' + 'y', 100 * 'x'])
self.D = np.array(1000 * ['ab'] + 1000 * ['ac'])
def time_isalpha_small_list_big_string(self... | NumPyChar |
python | numba__numba | numba/cuda/tests/cudadrv/test_deallocations.py | {
"start": 4964,
"end": 8404
} | class ____(CUDATestCase):
"""
Ensure resources are deleted properly without ignored exception.
"""
@contextmanager
def check_ignored_exception(self, ctx):
with captured_stderr() as cap:
yield
ctx.deallocations.clear()
self.assertFalse(cap.getvalue())
def ... | TestDel |
python | scipy__scipy | scipy/interpolate/tests/test_interpolate.py | {
"start": 76810,
"end": 82874
} | class ____:
def test_derivative(self, xp):
x = xp.asarray([0, 1, 3])
c = xp.asarray([[3, 0], [0, 0], [0, 2]])
bp = BPoly(c, x) # [3*(1-x)**2, 2*((x-1)/2)**2]
bp_der = bp.derivative()
xp_assert_close(bp_der(0.4), xp.asarray(-6*(0.6), dtype=xp.float64))
xp_assert_close... | TestBPolyCalculus |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_captured_log_manager.py | {
"start": 1195,
"end": 8918
} | class ____(NoOpComputeLogManager):
"""Test compute log manager that does not actually capture logs, but generates an external url
to be shown within the Dagster UI.
"""
@classmethod
def from_config_value(
cls, inst_data: ConfigurableClassData, config_value: Mapping[str, Any]
) -> Self:
... | ExternalTestComputeLogManager |
python | python__mypy | mypy/plugin.py | {
"start": 20000,
"end": 20285
} | class ____(NamedTuple):
cls: ClassDef # The class definition
reason: Expression # The expression being applied (decorator, metaclass, base class)
api: SemanticAnalyzerPluginInterface
# A context for dynamic class definitions like
# Base = declarative_base()
| ClassDefContext |
python | pallets__werkzeug | examples/cupoftee/pages.py | {
"start": 170,
"end": 1451
} | class ____(Page):
url_rule = "/"
def order_link(self, name, title):
cls = ""
link = f"?order_by={name}"
desc = False
if name == self.order_by:
desc = not self.order_desc
cls = f' class="{"down" if desc else "up"}"'
if desc:
link += "&a... | ServerList |
python | psf__black | src/blib2to3/pgen2/driver.py | {
"start": 932,
"end": 1160
} | class ____:
start: int
end: int | None = None
tokens: list[Any] = field(default_factory=list)
def lock(self) -> None:
total_eaten = len(self.tokens)
self.end = self.start + total_eaten
| ReleaseRange |
python | cython__cython | Cython/Compiler/Errors.py | {
"start": 3941,
"end": 9415
} | class ____(PyrexError):
"""raised when the user enabled options.gdb_debug but no ElementTree
implementation was found
"""
def open_listing_file(path, echo_to_stderr=True):
# Begin a new error listing. If path is None, no file
# is opened, the error counter is just reset.
if path is not None:
... | NoElementTreeInstalledException |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 14487,
"end": 14671
} | class ____(
SuperMixin, OfflineTestCaseMixin, TestCase
):
templates_dir = "test_block_super_multiple"
expected_hash = "d3f749e83c81"
| OfflineCompressBlockSuperMultipleTestCase |
python | getsentry__sentry | src/sentry/seer/endpoints/project_seer_preferences.py | {
"start": 959,
"end": 1175
} | class ____(CamelSnakeSerializer):
tag_name = serializers.CharField(required=True)
tag_value = serializers.CharField(required=True)
branch_name = serializers.CharField(required=True)
| BranchOverrideSerializer |
python | getsentry__sentry | src/sentry/seer/similarity/grouping_records.py | {
"start": 588,
"end": 3885
} | class ____(TypedDict):
group_id: int
hash: str
project_id: int
exception_type: str | None
seer_grouping_connection_pool = connection_from_url(settings.SEER_GROUPING_URL)
def call_seer_to_delete_project_grouping_records(
project_id: int,
) -> bool:
try:
# TODO: Move this over to POST ... | CreateGroupingRecordData |
python | readthedocs__readthedocs.org | readthedocs/oauth/admin.py | {
"start": 1702,
"end": 2437
} | class ____(admin.ModelAdmin):
"""Admin configuration for the RemoteRepositoryRelation model."""
raw_id_fields = (
"account",
"remote_repository",
"user",
)
list_select_related = (
"remote_repository",
"user",
"account",
)
list_display = (
... | RemoteRepositoryRelationAdmin |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/marker/colorbar/_tickfont.py | {
"start": 233,
"end": 9979
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith.marker.colorbar"
_path_str = "scattersmith.marker.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Tickfont |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/opensearch_serverless.py | {
"start": 1167,
"end": 3217
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when an Amazon OpenSearch Serverless Collection reaches the ACTIVE state.
:param collection_id: A collection ID. You can't provide a name and an ID in the same request.
:param collection_name: A collection name. You can't provide a name and an ID in the sam... | OpenSearchServerlessCollectionActiveTrigger |
python | allegroai__clearml | examples/services/monitoring/slack_alerts.py | {
"start": 2807,
"end": 12881
} | class ____(Monitor):
"""
Create a monitoring service that alerts on Task failures / completion in a Slack channel
"""
def __init__(self, slack_api_token, channel, message_prefix=None, filters=None):
# type: (str, str, Optional[str], Optional[List[Callable[[Task], bool]]]) -> ()
"""
... | SlackMonitor |
python | sqlalchemy__sqlalchemy | test/orm/test_ac_relationships.py | {
"start": 10679,
"end": 12390
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
bs = relationship(lambda: B, back_populates="a")
class B(Base):
... | StructuralEagerLoadCycleTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 14884,
"end": 19493
} | class ____(GoogleCloudBaseOperator):
"""
Create an InspectTemplate to reuse frequently-used configurations for content, images, and storage.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPCreateInspectTemplateOperator`
... | CloudDLPCreateInspectTemplateOperator |
python | facelessuser__soupsieve | tests/test_api.py | {
"start": 14744,
"end": 17595
} | class ____(util.TestCase):
"""Test invalid."""
def test_immutable_object(self):
"""Test immutable object."""
obj = sv.ct.Immutable()
with self.assertRaises(AttributeError):
obj.member = 3
def test_immutable_dict_read_only(self):
"""Test immutable dictionary is... | TestInvalid |
python | mamba-org__mamba | micromamba/tests/test_config.py | {
"start": 659,
"end": 2875
} | class ____(yaml.Dumper):
"""A YAML dumper to properly indent lists.
https://github.com/yaml/pyyaml/issues/234#issuecomment-765894586
"""
def increase_indent(self, flow=False, *args, **kwargs):
return super().increase_indent(flow=flow, indentless=False)
def config(*args):
umamba = helpers... | Dumper |
python | PrefectHQ__prefect | tests/cli/test_task_run.py | {
"start": 9248,
"end": 19698
} | class ____:
async def test_when_num_logs_greater_than_page_size_then_pagination(
self, task_run_factory: Callable[[int], Awaitable[TaskRun]]
):
# Given
task_run = await task_run_factory(LOGS_DEFAULT_PAGE_SIZE)
# When/Then
await run_sync_in_worker_thread(
invo... | TestTaskRunLogs |
python | mlflow__mlflow | mlflow/entities/source_type.py | {
"start": 0,
"end": 1168
} | class ____:
"""Enum for originating source of a :py:class:`mlflow.entities.Run`."""
NOTEBOOK, JOB, PROJECT, LOCAL, UNKNOWN = range(1, 6)
_STRING_TO_SOURCETYPE = {
"NOTEBOOK": NOTEBOOK,
"JOB": JOB,
"PROJECT": PROJECT,
"LOCAL": LOCAL,
"UNKNOWN": UNKNOWN,
}
SOU... | SourceType |
python | jpadilla__pyjwt | jwt/algorithms.py | {
"start": 9121,
"end": 9867
} | class ____(Algorithm):
"""
Placeholder for use when no signing or verification
operations are required.
"""
def prepare_key(self, key: str | None) -> None:
if key == "":
key = None
if key is not None:
raise InvalidKeyError('When alg = "none", key value must ... | NoneAlgorithm |
python | django-guardian__django-guardian | guardian/testapp/models.py | {
"start": 3243,
"end": 3532
} | class ____(models.Model):
"""
Model for testing whether get_objects_for_user will work when the objects to
be returned have UUID primary keys.
"""
uuid_pk = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
)
| UUIDPKModel |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/converter.py | {
"start": 36240,
"end": 37296
} | class ____(mpl.ticker.Formatter): # pyright: ignore[reportAttributeAccessIssue]
"""
Formats the ticks along an axis controlled by a :class:`TimedeltaIndex`.
"""
axis: Axis
@staticmethod
def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
"""
Convert seconds to 'D days ... | TimeSeries_TimedeltaFormatter |
python | dask__distributed | distributed/scheduler.py | {
"start": 55777,
"end": 127919
} | class ____:
"""Underlying task state of dynamic scheduler
Tracks the current state of workers, data, and computations.
Handles transitions between different task states. Notifies the
Scheduler of changes by messaging passing through Queues, which the
Scheduler listens to responds accordingly.
... | SchedulerState |
python | huggingface__transformers | tests/models/zamba2/test_modeling_zamba2.py | {
"start": 20753,
"end": 25920
} | class ____(unittest.TestCase):
model = None
tokenizer = None
@classmethod
@slow
def setUpClass(cls):
model_id = "Zyphra/Zamba2-1.2B"
cls.model = Zamba2ForCausalLM.from_pretrained(model_id, dtype=torch.float32, revision="PR")
cls.tokenizer = AutoTokenizer.from_pretrained(mode... | Zamba2ModelIntegrationTest |
python | tiangolo__fastapi | docs_src/dependencies/tutorial004_py310.py | {
"start": 141,
"end": 607
} | class ____:
def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends()):
response = {}
if commons.q:
response.update({"q": commons.... | CommonQueryParams |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 204413,
"end": 204764
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "domain")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
domain = sgqlc.types.Field("VerifiableDomain", graphql_name="do... | AddVerifiableDomainPayload |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 526,
"end": 667
} | class ____:
@classmethod
def func(cls, data):
return data
@classmethod
def func1(cls):
return cls
| Classmethod |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py | {
"start": 1249,
"end": 1415
} | class ____:
""" __getnewargs_ex__ returns an integer """
def __getnewargs_ex__(self): # [invalid-getnewargs-ex-returned]
return 1
| FirstBadGetNewArgsEx |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 20682,
"end": 23143
} | class ____(RegexLexer):
"""
Generic `mako templates`_ lexer. Code that isn't Mako
markup is yielded as `Token.Other`.
.. versionadded:: 0.7
.. _mako templates: http://www.makotemplates.org/
"""
name = 'Mako'
aliases = ['mako']
filenames = ['*.mao']
mimetypes = ['application/x-... | MakoLexer |
python | pydantic__pydantic | pydantic/types.py | {
"start": 37190,
"end": 39681
} | class ____:
path_type: Literal['file', 'dir', 'new', 'socket']
def __get_pydantic_json_schema__(
self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
) -> JsonSchemaValue:
field_schema = handler(core_schema)
format_conversion = {'file': 'file-path', 'dir': 'direc... | PathType |
python | realpython__materials | python-class/stack.py | {
"start": 358,
"end": 583
} | class ____(list):
def push(self, item):
self.append(item)
def pop(self):
return super().pop()
def __repr__(self) -> str:
return f"{type(self).__name__}({super().__repr__()})"
| StackInheritance |
python | getsentry__sentry | tests/sentry/services/nodestore/bigtable/test_backend.py | {
"start": 3094,
"end": 6326
} | class ____(BigtableNodeStorage):
store_class = MockedBigtableKVStorage
@contextmanager
def get_temporary_bigtable_nodestorage() -> Generator[BigtableNodeStorage]:
if "BIGTABLE_EMULATOR_HOST" not in os.environ:
pytest.skip(
"Bigtable is not available, set BIGTABLE_EMULATOR_HOST environment ... | MockedBigtableNodeStorage |
python | getsentry__sentry | src/sentry/api/endpoints/seer_models.py | {
"start": 1351,
"end": 3263
} | class ____(Endpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.ML_AI
permission_classes = ()
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(limit=100, wi... | SeerModelsEndpoint |
python | huggingface__transformers | src/transformers/models/phimoe/modeling_phimoe.py | {
"start": 33807,
"end": 39857
} | class ____(PhimoePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Phimoe... | PhimoeForCausalLM |
python | networkx__networkx | networkx/exception.py | {
"start": 1658,
"end": 1824
} | class ____(NetworkXUnfeasible):
"""Exception for algorithms that should return a path when running
on graphs where such a path does not exist."""
| NetworkXNoPath |
python | bokeh__bokeh | tests/unit/bokeh/test_transform.py | {
"start": 6686,
"end": 7928
} | class ____:
def test_basic(self) -> None:
t = bt.jitter("foo", width=0.5, mean=0.1, distribution="normal")
assert isinstance(t, Field)
assert t.field == "foo"
assert isinstance(t.transform, Jitter)
assert t.transform.width == 0.5
assert t.transform.mean == 0.1
... | Test_jitter |
python | falconry__falcon | examples/asgilook/asgilook/store.py | {
"start": 92,
"end": 1203
} | class ____:
def __init__(self, config, image_id, size):
self._config = config
self.image_id = image_id
self.size = size
self.modified = datetime.datetime.now(datetime.timezone.utc)
@property
def path(self):
return self._config.storage_path / self.image_id
@prop... | Image |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 8396,
"end": 8711
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
range: LspRange
message: str
severity: Optional[DiagnosticSeverity] = None
code: Optional[Union[int, str]] = None
code_description: Optional[CodeDescription] = None
source: Optional[str] = None
@dataclasses.dataclass(frozen=True)
| Diagnostic |
python | jazzband__pip-tools | piptools/exceptions.py | {
"start": 2199,
"end": 2542
} | class ____(PipToolsError):
def __init__(self, ireq_a: InstallRequirement, ireq_b: InstallRequirement) -> None:
self.ireq_a = ireq_a
self.ireq_b = ireq_b
def __str__(self) -> str:
message = "Incompatible requirements found: {} and {}"
return message.format(self.ireq_a, self.ireq_... | IncompatibleRequirements |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams5.py | {
"start": 964,
"end": 995
} | class ____[R: (int, )]: ...
| ClassJ |
python | Textualize__textual | src/textual/containers.py | {
"start": 5109,
"end": 5382
} | class ____(Widget):
"""A non-expanding container with horizontal layout and no scrollbars."""
DEFAULT_CSS = """
HorizontalGroup {
width: 1fr;
height: auto;
layout: horizontal;
overflow: hidden hidden;
}
"""
| HorizontalGroup |
python | falconry__falcon | examples/recipes/raw_url_path_asgi.py | {
"start": 383,
"end": 931
} | class ____:
async def on_get(self, req, resp, url):
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.decode(url)
resp.media = {'url': url}
async def on_get_status(self, req, resp, url):
# NOTE: url here is potentially percent-encoded.
url = falcon.uri.d... | URLResource |
python | scikit-learn__scikit-learn | sklearn/svm/_base.py | {
"start": 2623,
"end": 23595
} | class ____(BaseEstimator, metaclass=ABCMeta):
"""Base class for estimators that use libsvm as backing library.
This implements support vector machine classification and regression.
Parameter documentation is in the derived `SVC` class.
"""
_parameter_constraints: dict = {
"kernel": [
... | BaseLibSVM |
python | walkccc__LeetCode | solutions/2395. Find Subarrays With Equal Sum/2395.py | {
"start": 0,
"end": 224
} | class ____:
def findSubarrays(self, nums: list[int]) -> bool:
seen = set()
for a, b in zip(nums, nums[1:]):
summ = a + b
if summ in seen:
return True
seen.add(summ)
return False
| Solution |
python | astropy__astropy | astropy/nddata/tests/test_nddata.py | {
"start": 811,
"end": 1214
} | class ____:
"""
Class that has a few of the attributes of a numpy array.
These attributes are checked for by NDData.
"""
def __init__(self):
super().__init__()
def shape(self):
pass
def __getitem__(self, key):
pass
def __array__(self, dtype=None, copy=None):
... | FakeNumpyArray |
python | pandas-dev__pandas | asv_bench/benchmarks/strings.py | {
"start": 5832,
"end": 6094
} | class ____(Dtypes):
params = (Dtypes.params, [True, False])
param_names = ["dtype", "regex"]
def setup(self, dtype, regex):
super().setup(dtype)
def time_contains(self, dtype, regex):
self.s.str.contains("A", regex=regex)
| Contains |
python | PrefectHQ__prefect | tests/runtime/test_task_run.py | {
"start": 3032,
"end": 3385
} | class ____:
async def test_id_is_attribute(self):
assert "id" in dir(task_run)
async def test_id_is_none_when_not_set(self):
assert task_run.id is None
async def test_id_from_context(self):
with TaskRunContext.model_construct(task_run=TaskRun.model_construct(id="foo")):
... | TestID |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/overrides.py | {
"start": 3946,
"end": 4017
} | class ____:
def return_source(self):
pass
| BaseWithDeclaration |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called_extensions_py310.py | {
"start": 258,
"end": 355
} | class ____(TestProto):
"""An implementation."""
def __init__(self):
...
| TestParent |
python | apache__airflow | providers/apache/beam/tests/unit/apache/beam/hooks/test_beam.py | {
"start": 17553,
"end": 26043
} | class ____:
@pytest.mark.asyncio
@pytest.mark.skipif(APACHE_BEAM_VERSION is None, reason="Apache Beam not installed in current env")
async def test_beam_version(self):
version = await BeamAsyncHook._beam_version(sys.executable)
assert version == APACHE_BEAM_VERSION
@pytest.mark.asyncio
... | TestBeamAsyncHook |
python | openai__openai-python | src/openai/types/conversations/conversation_item.py | {
"start": 5345,
"end": 7188
} | class ____(BaseModel):
id: str
"""The unique ID of the tool call."""
arguments: str
"""A JSON string of the arguments passed to the tool."""
name: str
"""The name of the tool that was run."""
server_label: str
"""The label of the MCP server running the tool."""
type: Literal["mcp... | McpCall |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/cloudwatch/loggers.py | {
"start": 856,
"end": 9470
} | class ____(logging.Handler):
def __init__(
self,
log_group_name,
log_stream_name,
aws_region=None,
aws_access_key_id: Optional[str] = None,
aws_secret_access_key: Optional[str] = None,
endpoint_url: Optional[str] = None,
use_ssl: bool = True,
a... | CloudwatchLogsHandler |
python | apache__thrift | test/py/FastbinaryTest.py | {
"start": 3248,
"end": 7422
} | class ____(object):
def __init__(self, fast, slow):
self._fast = fast
self._slow = slow
def _check_write(self, o):
trans_fast = TTransport.TMemoryBuffer()
trans_slow = TTransport.TMemoryBuffer()
prot_fast = self._fast(trans_fast, fallback=False)
prot_slow = self.... | Test |
python | google__pytype | pytype/rewrite/frame_test.py | {
"start": 2191,
"end": 2623
} | class ____(unittest.TestCase):
def test_enclosing(self):
sn = frame_lib._ShadowedNonlocals()
sn.add_enclosing('x')
self.assertTrue(sn.has_enclosing('x'))
self.assertCountEqual(sn.get_enclosing_names(), {'x'})
def test_global(self):
sn = frame_lib._ShadowedNonlocals()
sn.add_global('x')
... | ShadowedNonlocalsTest |
python | rapidsai__cudf | python/cudf/cudf/core/byte_pair_encoding.py | {
"start": 209,
"end": 1629
} | class ____:
"""
Given a merge pairs strings series, performs byte pair encoding on
a strings series using the provided separator.
Parameters
----------
merges_pairs : str
Strings column of merge pairs
Returns
-------
BytePairEncoder
"""
def __init__(self, merges_pa... | BytePairEncoder |
python | walkccc__LeetCode | solutions/1214. Two Sum BSTs/1214.py | {
"start": 572,
"end": 1096
} | class ____:
def twoSumBSTs(
self,
root1: TreeNode | None,
root2: TreeNode | None,
target: int,
) -> bool:
bst1 = BSTIterator(root1, True)
bst2 = BSTIterator(root2, False)
l = bst1.next()
r = bst2.next()
while True:
summ = l + r
if summ == target:
retu... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/freshness_tests/test_freshness_evaluation.py | {
"start": 14289,
"end": 45421
} | class ____:
@pytest.mark.asyncio
async def test_cron_freshness_pass(self, instance: DagsterInstance):
"""Test that an asset with a cron freshness policy is evaluated as fresh if its last materialization was within the expected time window."""
def create_defs() -> dg.Definitions:
@dg... | TestCronFreshnessPolicyEvaluator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1599664,
"end": 1599855
} | class ____(sgqlc.types.Union):
"""Types that can be inside a StatusCheckRollup context."""
__schema__ = github_schema
__types__ = (CheckRun, StatusContext)
| StatusCheckRollupContext |
python | walkccc__LeetCode | solutions/266. Palindrome Permutation/266.py | {
"start": 0,
"end": 202
} | class ____:
def canPermutePalindrome(self, s: str) -> bool:
seen = set()
for c in s:
if c in seen:
seen.remove(c)
else:
seen.add(c)
return len(seen) <= 1
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ssm/resources.py | {
"start": 4445,
"end": 4619
} | class ____(Config):
key: str = Field(description="Tag key to search for.")
values: Optional[list[str]] = Field(default=None, description="List")
@beta
| ParameterStoreTag |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 374559,
"end": 380897
} | class ____(rv_continuous):
r"""
Crystalball distribution
%(before_notes)s
Notes
-----
The probability density function for `crystalball` is:
.. math::
f(x, \beta, m) = \begin{cases}
N \exp(-x^2 / 2), &\text{for } x > -\beta\\
... | crystalball_gen |
python | miyuchina__mistletoe | test/test_span_token.py | {
"start": 8001,
"end": 8578
} | class ____(unittest.TestCase):
def setUp(self):
span_token.add_token(span_token.HtmlSpan)
self.addCleanup(span_token.reset_tokens)
def test_parse(self):
tokens = span_token.tokenize_inner('<a>')
self.assertIsInstance(tokens[0], span_token.HtmlSpan)
self.assertEqual('<a>'... | TestHtmlSpan |
python | getsentry__sentry | src/sentry/explore/migrations/0005_explore_django_json_field.py | {
"start": 244,
"end": 1776
} | 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 | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 16194,
"end": 17616
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
if config.feat_extract_norm == "group":
conv_layers = [SEWDGroupNormConvLayer(config, layer_id=0)] + [
SEWDNoLayerNormConvLayer(config, layer_i... | SEWDFeatureEncoder |
python | huggingface__transformers | src/transformers/models/aria/image_processing_aria.py | {
"start": 2801,
"end": 24472
} | class ____(BaseImageProcessor):
"""
A vision processor for the Aria model that handles image preprocessing.
Initialize the AriaImageProcessor.
Args:
image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
Mean values for normalization.
image_std (`list`, *optional*, de... | AriaImageProcessor |
python | pytorch__pytorch | test/quantization/fx/test_equalize_fx.py | {
"start": 2363,
"end": 38613
} | class ____(QuantizationTestCase):
def channel_minmax(self, input, axis=1):
''' Finds the min/max of inputs associated with a specific channel
'''
size_of_tensor_dim = input.ndim
axis_list = list(range(size_of_tensor_dim))
axis_list.remove(axis)
axis_list.sort(reverse=... | TestEqualizeFx |
python | pytransitions__transitions | transitions/extensions/markup.py | {
"start": 10799,
"end": 11802
} | class ____(MarkupMachine, HierarchicalMachine):
"""Extends transitions.extensions.nesting.HierarchicalMachine with markup capabilities."""
def rep(func, format_references=None):
"""Return a string representation for `func`."""
if isinstance(func, string_types):
return func
if isinstance(func, ... | HierarchicalMarkupMachine |
python | django__django | tests/settings_tests/tests.py | {
"start": 2717,
"end": 3228
} | class ____(TestCase):
def test_override(self):
self.assertEqual(settings.ITEMS, ["b", "c", "d"])
self.assertEqual(settings.TEST, "override")
@modify_settings(
ITEMS={
"append": "e",
"prepend": "a",
"remove": "c",
}
)
@override_settings... | FullyDecoratedTestCase |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 54267,
"end": 55597
} | class ____(ASTBase):
def __init__(
self, arg: ASTNestedName | None, ellipsis: bool = False, variadic: bool = False
) -> None:
self.arg = arg
self.ellipsis = ellipsis
self.variadic = variadic
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTMacroPa... | ASTMacroParameter |
python | Netflix__metaflow | test/test_config/runner_flow.py | {
"start": 46,
"end": 298
} | class ____(FlowSpec):
@step
def start(self):
with Runner("./mutable_flow.py") as r:
r.run()
self.next(self.end)
@step
def end(self):
print("Done")
if __name__ == "__main__":
RunnerFlow()
| RunnerFlow |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_context_cache.py | {
"start": 1352,
"end": 5489
} | class ____:
"""Test the integration of SecretCache with connection access."""
@staticmethod
@conf_vars({("secrets", "use_cache"): "true"})
def setup_method():
SecretCache.reset()
SecretCache.init()
@staticmethod
def teardown_method():
SecretCache.reset()
@patch("ai... | TestConnectionCacheIntegration |
python | FactoryBoy__factory_boy | factory/fuzzy.py | {
"start": 4237,
"end": 5050
} | class ____(BaseFuzzyAttribute):
"""Random date within a given date range."""
def __init__(self, start_date, end_date=None):
super().__init__()
if end_date is None:
if random.randgen.state_set:
cls_name = self.__class__.__name__
warnings.warn(random_se... | FuzzyDate |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 29889,
"end": 30654
} | class ____(Reduction):
_parameters = ["frame", "skipna", "numeric_only", "split_every"]
_defaults = {"skipna": True, "numeric_only": False, "split_every": False}
reduction_chunk = idxmaxmin_chunk
reduction_combine = idxmaxmin_combine
reduction_aggregate = idxmaxmin_agg
_reduction_attribute = "id... | IdxMin |
python | django__django | tests/user_commands/management/commands/subparser_vanilla.py | {
"start": 71,
"end": 370
} | class ____(BaseCommand):
def add_arguments(self, parser):
subparsers = parser.add_subparsers(parser_class=argparse.ArgumentParser)
parser_foo = subparsers.add_parser("foo")
parser_foo.add_argument("bar", type=int)
def handle(self, *args, **options):
pass
| Command |
python | django__django | tests/admin_registration/models.py | {
"start": 287,
"end": 356
} | class ____(Location):
name = models.CharField(max_length=200)
| Place |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/utils/config.py | {
"start": 32670,
"end": 32964
} | class ____:
"""
Configuration for the cudf-polars in-memory executor.
The in-memory executor only supports single-GPU execution.
"""
name: Literal["in-memory"] = dataclasses.field(default="in-memory", init=False)
@dataclasses.dataclass(frozen=True, eq=True)
| InMemoryExecutor |
python | apache__airflow | airflow-core/src/airflow/serialization/definitions/taskgroup.py | {
"start": 9785,
"end": 11246
} | class ____(SerializedTaskGroup):
"""Serialized representation of a MappedTaskGroup used in protected processes."""
_expand_input: SchedulerExpandInput = attrs.field(alias="expand_input")
is_mapped: ClassVar[bool] = True
def __repr__(self) -> str:
return f"<SerializedMappedTaskGroup: {self.gro... | SerializedMappedTaskGroup |
python | django__django | tests/admin_scripts/tests.py | {
"start": 23551,
"end": 27219
} | class ____(AdminScriptTestCase):
"""
A series of tests for django-admin when multiple settings files
(including the default 'settings.py') are available. The default settings
file is insufficient for performing the operations described, so the
alternate settings must be used by the running script.
... | DjangoAdminMultipleSettings |
python | django__django | tests/admin_views/models.py | {
"start": 26030,
"end": 26275
} | class ____(models.Model):
referer = models.ForeignKey(InlineReferer, models.CASCADE)
fk = models.ForeignKey(
ReferencedByInline,
models.CASCADE,
to_field="name",
related_name="hidden+",
)
| InlineReference |
python | sympy__sympy | sympy/matrices/matrices.py | {
"start": 16135,
"end": 20180
} | class ____(MatrixCommon):
"""Provides calculus-related matrix operations."""
def diff(self, *args, evaluate=True, **kwargs):
"""Calculate the derivative of each element in the matrix.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import x, y
... | MatrixCalculus |
python | kamyu104__LeetCode-Solutions | Python/equal-rational-numbers.py | {
"start": 62,
"end": 912
} | class ____(object):
def isRationalEqual(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def frac(S):
if '.' not in S:
return Fraction(int(S), 1)
i = S.index('.')
result = Fraction(int(S[:i]), 1)
... | Solution |
python | openai__openai-python | src/openai/types/realtime/client_secret_create_params.py | {
"start": 475,
"end": 1030
} | class ____(TypedDict, total=False):
expires_after: ExpiresAfter
"""Configuration for the client secret expiration.
Expiration refers to the time after which a client secret will no longer be
valid for creating sessions. The session itself may continue after that time
once started. A secret can be u... | ClientSecretCreateParams |
python | PrefectHQ__prefect | src/prefect/client/schemas/sorting.py | {
"start": 2384,
"end": 2579
} | class ____(AutoEnum):
"""Defines block document sorting options."""
NAME_DESC = AutoEnum.auto()
NAME_ASC = AutoEnum.auto()
BLOCK_TYPE_AND_NAME_ASC = AutoEnum.auto()
| BlockDocumentSort |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 5378,
"end": 8067
} | class ____(_UnsupportedGroupCVMixin, BaseCrossValidator):
"""Leave-One-Out cross-validator.
Provides train/test indices to split data in train/test sets. Each
sample is used once as a test set (singleton) while the remaining
samples form the training set.
Note: ``LeaveOneOut()`` is equivalent to `... | LeaveOneOut |
python | getsentry__sentry | src/sentry/api/permissions.py | {
"start": 11681,
"end": 13735
} | class ____(SentryPermission):
"""
A permission class that extends `SentryPermission` to provide read-only access for users
in a demo mode. This class modifies the access control logic to ensure that users identified
as read-only can only perform safe operations, such as GET and HEAD requests, on resourc... | DemoSafePermission |
python | instagram__MonkeyType | demo/models.py | {
"start": 2290,
"end": 2873
} | class ____:
def get_feed_entries_by_ids(
self, ids: Collection[FeedEntryId]
) -> Dict[FeedEntryId, Optional[FeedEntry]]:
raise NotImplementedError()
def get_feed_entries_for_user_id(self, user_id: UserId) -> List[FeedEntry]:
raise NotImplementedError()
def get_users_by_ids(sel... | RepoInterface |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detection.py | {
"start": 548,
"end": 848
} | class ____:
def report(self, event_data: Mapping[str, Any], event_project_id: int) -> Event:
from sentry.event_manager import EventManager
manager = EventManager(dict(event_data))
manager.normalize()
return manager.save(project_id=event_project_id)
| SDKCrashReporter |
python | pandas-dev__pandas | pandas/tests/frame/test_logical_ops.py | {
"start": 190,
"end": 7066
} | class ____:
# &, |, ^
@pytest.mark.parametrize(
"left, right, op, expected",
[
(
[True, False, np.nan],
[True, False, True],
operator.and_,
[True, False, False],
),
(
[True, False... | TestDataFrameLogicalOperators |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 3336,
"end": 4513
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
Masked image modeling (MLM) loss.
reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Reconstructed pixel values.
resh... | FocalNetMaskedImageModelingOutput |
python | celery__celery | celery/bin/base.py | {
"start": 8120,
"end": 8513
} | class ____(ParamType):
"""ISO 8601 Date Time or float argument."""
name = "iso-86091 or float"
def convert(self, value, param, ctx):
try:
return float(value)
except (TypeError, ValueError):
pass
try:
return maybe_iso8601(value)
except (T... | ISO8601DateTimeOrFloat |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox22.py | {
"start": 315,
"end": 950
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox22.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/eager/context.py | {
"start": 10709,
"end": 12459
} | class ____(threading.local):
"""A thread-local stack of context switches."""
def __init__(self, eager):
super().__init__()
self.stack = []
if eager:
# Initialize the stack with a pointer to enter the eager context; this
# ensures that the fact that eager execution was enabled is propagated
... | _ContextSwitchStack |
python | getsentry__sentry | tests/sentry/discover/test_dataset_split.py | {
"start": 24654,
"end": 28002
} | class ____(DiscoverSavedQueryDatasetSplitTestCase):
def setUp(self) -> None:
super().setUp()
self.dry_run = True
@pytest.fixture
def owner() -> User:
return Factories.create_user()
@pytest.fixture
def organization(owner: User) -> Organization:
return Factories.create_organization(owner=o... | DiscoverSavedQueryDatasetSplitDryRunTestCase |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-self-discover/llama_index/packs/self_discover/base.py | {
"start": 6567,
"end": 8935
} | class ____(Workflow):
"""Self discover workflow."""
@step(pass_context=True)
async def get_modules(self, ctx: Context, ev: StartEvent) -> GetModulesEvent:
"""Get modules step."""
# get input data, store llm into ctx
task = ev.get("task")
llm: LLM = ev.get("llm")
if ... | SelfDiscoverWorkflow |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/aot_autograd_result.py | {
"start": 8066,
"end": 8252
} | class ____(InductorOutput[TOut]):
# Used by AOTDispatchAutograd.post_compile
backward_state_indices: list[int]
num_symints_saved_for_bw_: int
@dataclass
| GenericCompiledBackward |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-k-free-subsets.py | {
"start": 86,
"end": 675
} | class ____(object):
def countTheNumOfKFreeSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def count(x):
y = x
while y-k in cnt:
y -= k
dp = [1, 0] # dp[0]: count without i, dp[1]: coun... | Solution |
python | ansible__ansible | test/lib/ansible_test/_internal/docker_util.py | {
"start": 8909,
"end": 16442
} | class ____:
"""Container host properties detected at run time."""
audit_code: str
max_open_files: int
loginuid: t.Optional[int]
cgroup_v1: SystemdControlGroupV1Status
cgroup_v2: bool
@mutex
def detect_host_properties(args: CommonConfig) -> ContainerHostProperties:
"""
Detect and retur... | ContainerHostProperties |
python | astropy__astropy | astropy/io/fits/tests/test_uint.py | {
"start": 226,
"end": 6058
} | class ____(FitsTestCase):
@classmethod
def setup_class(cls):
cls.utypes = ("u2", "u4", "u8")
cls.utype_map = {"u2": np.uint16, "u4": np.uint32, "u8": np.uint64}
cls.itype_map = {"u2": np.int16, "u4": np.int32, "u8": np.int64}
cls.format_map = {"u2": "I", "u4": "J", "u8": "K"}
... | TestUintFunctions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.