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 | cython__cython | Demos/benchmarks/bm_richards_cclass.py | {
"start": 3118,
"end": 3331
} | class ____(object):
def __init__(self):
self.taskTab = [None] * TASKTABSIZE
self.taskList = None
self.holdCount = 0
self.qpktCount = 0
taskWorkArea = TaskWorkArea()
| TaskWorkArea |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis15.py | {
"start": 315,
"end": 1409
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis15.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | pallets__flask | src/flask/views.py | {
"start": 5146,
"end": 6962
} | class ____(View):
"""Dispatches request methods to the corresponding instance methods.
For example, if you implement a ``get`` method, it will be used to
handle ``GET`` requests.
This can be useful for defining a REST API.
:attr:`methods` is automatically set based on the methods defined on
th... | MethodView |
python | django-haystack__django-haystack | haystack/fields.py | {
"start": 10250,
"end": 10671
} | class ____(SearchField):
field_type = "boolean"
def __init__(self, **kwargs):
if kwargs.get("facet_class") is None:
kwargs["facet_class"] = FacetBooleanField
super().__init__(**kwargs)
def prepare(self, obj):
return self.convert(super().prepare(obj))
def convert(s... | BooleanField |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/check_numerics_callback_test.py | {
"start": 1701,
"end": 2657
} | class ____(test_util.TensorFlowTestCase):
def testLimitStringLengthWithExplicitLimit(self):
self.assertEqual(
check_numerics_callback.limit_string_length("", max_len=2), "")
self.assertEqual(
check_numerics_callback.limit_string_length("e", max_len=2), "e")
self.assertEqual(
check... | LimitStringLengthTest |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/source_position.py | {
"start": 238,
"end": 294
} | class ____(NamedTuple):
line: int
col: int
| LineCol |
python | PrefectHQ__prefect | tests/server/database/test_queries.py | {
"start": 211,
"end": 8131
} | class ____:
@pytest.fixture
async def work_queue_1(self, session):
return await models.work_queues.create_work_queue(
session=session, work_queue=schemas.actions.WorkQueueCreate(name="q1")
)
@pytest.fixture
async def work_queue_2(self, session):
return await models.w... | TestGetRunsInQueueQuery |
python | langchain-ai__langchain | libs/core/langchain_core/messages/ai.py | {
"start": 1175,
"end": 2088
} | class ____(TypedDict, total=False):
"""Breakdown of input token counts.
Does *not* need to sum to full input token count. Does *not* need to have all keys.
Example:
```python
{
"audio": 10,
"cache_creation": 200,
"cache_read": 100,
}
```
... | InputTokenDetails |
python | matplotlib__matplotlib | lib/matplotlib/backend_managers.py | {
"start": 549,
"end": 840
} | class ____:
"""
Event carrying messages from toolmanager.
Messages usually get displayed to the user by the toolbar.
"""
def __init__(self, name, sender, message):
self.name = name
self.sender = sender
self.message = message
| ToolManagerMessageEvent |
python | agronholm__apscheduler | src/apscheduler/triggers/cron/expressions.py | {
"start": 2109,
"end": 4626
} | class ____(AllExpression):
value_re: ClassVar[Pattern] = re.compile(
r"(?P<first>\d+)(?:-(?P<last>\d+))?(?:/(?P<step>\d+))?$"
)
first: int = attrs.field(
converter=as_int, validator=[instance_of(int), non_negative_number]
)
last: int | None = attrs.field(
converter=as_int,
... | RangeExpression |
python | doocs__leetcode | solution/2000-2099/2075.Decode the Slanted Ciphertext/Solution.py | {
"start": 0,
"end": 363
} | class ____:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
ans = []
cols = len(encodedText) // rows
for j in range(cols):
x, y = 0, j
while x < rows and y < cols:
ans.append(encodedText[x * cols + y])
x, y = x + 1, y + ... | Solution |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_bitcoin_tx_is_confirmed.py | {
"start": 1906,
"end": 4776
} | class ____(ColumnMapExpectation):
"""Expect column values Bitcoin transaction hash is confirmed."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
... | ExpectColumnValuesBitcoinTxIsConfirmed |
python | tornadoweb__tornado | tornado/http1connection.py | {
"start": 3438,
"end": 30323
} | class ____(httputil.HTTPConnection):
"""Implements the HTTP/1.x protocol.
This class can be on its own for clients, or via `HTTP1ServerConnection`
for servers.
"""
def __init__(
self,
stream: iostream.IOStream,
is_client: bool,
params: Optional[HTTP1ConnectionParame... | HTTP1Connection |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 23783,
"end": 23981
} | class ____(StateMachineEvent):
"""Abstract base event for all the possible outcomes of a :class:`Compute`
instruction
"""
key: Key
__slots__ = ("key",)
@dataclass
| ExecuteDoneEvent |
python | django-haystack__django-haystack | haystack/forms.py | {
"start": 3615,
"end": 3994
} | class ____(ModelSearchForm):
selected_facets = forms.CharField(required=False, widget=forms.HiddenInput)
def search(self):
sqs = super().search()
if hasattr(self, "cleaned_data") and self.cleaned_data["selected_facets"]:
sqs = sqs.narrow(self.cleaned_data["selected_facets"])
... | FacetedModelSearchForm |
python | pydantic__pydantic | pydantic/v1/fields.py | {
"start": 50366,
"end": 50645
} | class ____:
"""
Used to postpone field preparation, while creating recursive generic models.
"""
def is_finalvar_with_default_val(type_: Type[Any], val: Any) -> bool:
return is_finalvar(type_) and val is not Undefined and not isinstance(val, FieldInfo)
| DeferredType |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 77894,
"end": 79397
} | class ____(UserDefinedObjectVariable):
def __init__(self, value, **kwargs):
super().__init__(value, **kwargs)
self.exc_vt = variables.ExceptionVariable(self.value_type, ())
@property
def fn(self):
return self.value_type
def call_method(self, tx, name, args, kwargs):
if ... | UserDefinedExceptionObjectVariable |
python | ansible__ansible | test/lib/ansible_test/_internal/provider/layout/collection.py | {
"start": 246,
"end": 6131
} | class ____(LayoutProvider):
"""Layout provider for Ansible collections."""
@staticmethod
def is_content_root(path: str) -> bool:
"""Return True if the given path is a content root for this provider."""
if os.path.basename(os.path.dirname(os.path.dirname(path))) == 'ansible_collections':
... | CollectionLayout |
python | spyder-ide__spyder | spyder/api/widgets/mixins.py | {
"start": 5071,
"end": 8708
} | class ____:
"""
Provide methods to create, add and get toolbars.
"""
def add_item_to_toolbar(self, action_or_widget, toolbar, section=None,
before=None, before_section=None):
"""
If you provide a `before` action, the action will be placed before this
... | SpyderToolbarMixin |
python | getsentry__sentry | src/sentry/testutils/hybrid_cloud.py | {
"start": 812,
"end": 2708
} | class ____:
@property
def ScheduledDeletion(self) -> type[BaseScheduledDeletion]:
return get_regional_scheduled_deletion(SiloMode.get_current_mode())
@assume_test_silo_mode(SiloMode.CONTROL)
def assert_org_member_mapping(self, org_member: OrganizationMember, expected=None):
org_member.r... | HybridCloudTestMixin |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/matrix_multiply.py | {
"start": 1246,
"end": 3935
} | class ____(MatrixMultiplyOperator):
"""Operator for matrix multiplication (torch.mm)."""
def __init__(self):
super().__init__("mm")
self.weight = 5.0
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.mm"
def can_p... | MMOperator |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 13238,
"end": 13506
} | class ____(AtomicRule):
n: Expr
a: Expr
b: Expr
def eval(self) -> Expr:
n, a, b, x = self.n, self.a, self.b, self.variable
if n == 0:
return Heaviside(a+b*x)/b
return DiracDelta(a+b*x, n-1)/b
@dataclass
| DiracDeltaRule |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/synapse.py | {
"start": 6896,
"end": 12409
} | class ____(BaseOperator):
"""
Execute a Synapse Pipeline.
:param pipeline_name: The name of the pipeline to execute.
:param azure_synapse_conn_id: The Airflow connection ID for Azure Synapse.
:param azure_synapse_workspace_dev_endpoint: The Azure Synapse workspace development endpoint.
:param w... | AzureSynapseRunPipelineOperator |
python | PyCQA__pylint | tests/functional/m/missing/missing_kwoa.py | {
"start": 1218,
"end": 1641
} | class ____(Parent):
def __init__(self, *, first, second):
super().__init__(first=first, second=second)
self._first = first + second
@contextlib.contextmanager
def run(*, a):
yield
def test_context_managers(**kw):
run(**kw)
with run(**kw):
pass
with run(**kw), run(**kw):... | Child |
python | kamyu104__LeetCode-Solutions | Python/distribute-candies-among-children-i.py | {
"start": 772,
"end": 1086
} | class ____(object):
def distributeCandies(self, n, limit):
"""
:type n: int
:type limit: int
:rtype: int
"""
return sum(min(limit, n-i)-max((n-i)-limit, 0)+1 for i in xrange(max(n-2*limit, 0), min(limit, n)+1))
# Time: O(n^2)
# Space: O(1)
# brute force
| Solution2 |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Data.py | {
"start": 12438,
"end": 12801
} | class ____(CtrlNode):
"""Calculate the maximum of an array across an axis.
"""
nodeName = 'Max'
uiTemplate = [
('axis', 'intSpin', {'value': 0, 'min': -1, 'max': 1000000}),
]
def processData(self, data):
s = self.stateGroup.state()
ax = None if s['axis'] == -1 else s... | Max |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/xaxis/_title.py | {
"start": 235,
"end": 2861
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.xaxis"
_path_str = "layout.scene.xaxis.title"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this axis' title font.
The 'font' property is an instance of Font
that may be spec... | Title |
python | google__jax | tests/pallas/tpu_pallas_distributed_test.py | {
"start": 1071,
"end": 16097
} | class ____(parameterized.TestCase):
def setUp(self):
super().setUp()
if jax.device_count() < 2:
self.skipTest('Only >=2 devices are supported.')
if not jtu.is_device_tpu(5, 'e'):
self.skipTest('Only works with TPU v5e.')
@parameterized.named_parameters(
('vmem', pltpu.VMEM),
('... | PallasCallRemoteDMATest |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 21958,
"end": 26905
} | class ____(LossFunctionWrapper):
"""Computes the cross-entropy loss between true labels and predicted labels.
Use this cross-entropy loss for binary (0 or 1) classification applications.
The loss function requires the following inputs:
- `y_true` (true label): This is either 0 or 1.
- `y_pred` (pr... | BinaryCrossentropy |
python | spack__spack | lib/spack/spack/spec_parser.py | {
"start": 8411,
"end": 11439
} | class ____(spack.error.SpecSyntaxError):
"""Syntax error in a spec string"""
def __init__(self, tokens: List[Token], text: str):
message = f"unexpected characters in the spec string\n{text}\n"
underline = ""
for token in tokens:
is_error = token.kind == SpecTokens.UNEXPECTE... | SpecTokenizationError |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_grad_scaler.py | {
"start": 613,
"end": 4169
} | class ____(FSDPTest):
@skip_if_lt_x_gpu(4)
def test_gradient_scaler(self):
self.run_subtests(
{"has_inf": [True, False], "test_2d": [True, False]},
self._test_gradient_scaler,
)
def _test_gradient_scaler(self, has_inf: bool, test_2d: bool):
torch.manual_seed(... | TestFullyShardGradientScaler |
python | ethereum__web3.py | web3/contract/base_contract.py | {
"start": 53911,
"end": 54188
} | class ____:
@staticmethod
def _raise_exception() -> NoReturn:
raise ABIReceiveNotFound("No receive function was found in the contract ABI.")
def __getattr__(self, attr: Any) -> Callable[[], None]:
return self._raise_exception
| NonExistentReceiveFunction |
python | ansible__ansible | test/units/module_utils/basic/test_run_command.py | {
"start": 3508,
"end": 4656
} | class ____:
# Format is command as passed to run_command, command to Popen as list, command to Popen as string
ARGS_DATA = (
(['/bin/ls', 'a', 'b', 'c'], [b'/bin/ls', b'a', b'b', b'c'], b'/bin/ls a b c'),
('/bin/ls a " b" "c "', [b'/bin/ls', b'a', b' b', b'c '], b'/bin/ls a " b" ... | TestRunCommandArgs |
python | conda__conda | conda/models/version.py | {
"start": 17320,
"end": 18819
} | class ____:
def __init__(self, spec_str, matcher, is_exact):
self.spec_str = spec_str
self._is_exact = is_exact
self.match = matcher
@property
def spec(self):
return self.spec_str
def is_exact(self):
return self._is_exact
def __eq__(self, other):
tr... | BaseSpec |
python | getsentry__sentry | tests/sentry/tasks/test_commit_context.py | {
"start": 4228,
"end": 39352
} | class ____(TestCommitContextIntegration):
def setUp(self) -> None:
super().setUp()
self.blame_recent = FileBlameInfo(
repo=self.repo,
path="sentry/recent.py",
ref="master",
code_mapping=self.code_mapping,
lineno=30,
commit=Commi... | TestCommitContextAllFrames |
python | huggingface__transformers | src/transformers/models/sam_hq/modeling_sam_hq.py | {
"start": 32924,
"end": 35021
} | class ____(nn.Module):
def __init__(self, config: SamHQMaskDecoderConfig):
super().__init__()
self.config = config
self.num_hidden_layers = config.num_hidden_layers
self.layers = nn.ModuleList()
for i in range(self.num_hidden_layers):
self.layers.append(SamHQTwo... | SamHQTwoWayTransformer |
python | django__django | tests/custom_lookups/models.py | {
"start": 31,
"end": 332
} | class ____(models.Model):
name = models.CharField(max_length=20)
alias = models.CharField(max_length=20)
age = models.IntegerField(null=True)
birthdate = models.DateField(null=True)
average_rating = models.FloatField(null=True)
def __str__(self):
return self.name
| Author |
python | wandb__wandb | wandb/sdk/artifacts/storage_handlers/tracking_handler.py | {
"start": 495,
"end": 2476
} | class ____(StorageHandler):
_scheme: str
def __init__(self, scheme: str = "") -> None:
"""Track paths with no modification or special processing.
Useful when paths being tracked are on file systems mounted at a standardized
location.
For example, if the data to track is locate... | TrackingHandler |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-oracleai/llama_index/readers/oracleai/base.py | {
"start": 802,
"end": 1618
} | class ____(HTMLParser):
"""Parse Oracle doc metadata..."""
def __init__(self) -> None:
super().__init__()
self.reset()
self.match = False
self.metadata = {}
def handle_starttag(self, tag, attrs):
if tag == "meta":
entry = ""
for name, value i... | ParseOracleDocMetadata |
python | walkccc__LeetCode | solutions/3448. Count Substrings Divisible By Last Digit/3448-2.py | {
"start": 0,
"end": 527
} | class ____:
def countSubstrings(self, s: str) -> int:
ans = 0
# dp[num][rem] := the number of substrings so far that have a remainder of
# `rem` when divided by `num`
dp = [[0] * 10 for _ in range(10)]
for c in s:
digit = int(c)
newDp = [[0] * 10 for _ in range(10)]
for num in r... | Solution |
python | kamyu104__LeetCode-Solutions | Python/flatten-nested-list-iterator.py | {
"start": 100,
"end": 945
} | class ____(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.__depth = [[nestedList, 0]]
def next(self):
"""
:rtype: int
"""
nestedList, i = self.__depth[-1]
... | NestedIterator |
python | huggingface__transformers | tests/models/seamless_m4t_v2/test_modeling_seamless_m4t_v2.py | {
"start": 22550,
"end": 25396
} | class ____(ModelTesterMixin, unittest.TestCase):
is_encoder_decoder = True
test_missing_keys = False
test_resize_embeddings = True
all_model_classes = (
(
SeamlessM4Tv2Model,
SeamlessM4Tv2ForTextToSpeech,
SeamlessM4Tv2ForTextToText,
)
if is_t... | SeamlessM4Tv2ModelWithTextInputTest |
python | milvus-io__pymilvus | tests/test_check.py | {
"start": 443,
"end": 1946
} | class ____:
@pytest.mark.parametrize("valid_address", [
"localhost:19530",
"example.com:19530"
])
def test_check_is_legal_address_true(self, valid_address):
valid = is_legal_address(valid_address)
assert valid is True
@pytest.mark.parametrize("invalid_address", [
... | TestChecks |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 98953,
"end": 103552
} | class ____(nn.Module):
"""Downsamples 4x by applying a 2D convolution and doing max pooling."""
def __init__(
self,
num_layers: int = 1,
in_channels: int = 3,
out_channels: int = 64,
use_batchnorm: bool = True,
):
"""
Constructs a Conv2DDownsample mod... | Conv2DDownsample |
python | protocolbuffers__protobuf | python/google/protobuf/internal/reflection_test.py | {
"start": 96397,
"end": 108423
} | class ____(unittest.TestCase):
def setUp(self):
self.proto = unittest_pb2.TestAllTypes()
self.extended_proto = more_extensions_pb2.ExtendedMessage()
self.packed_proto = unittest_pb2.TestPackedTypes()
self.packed_extended_proto = unittest_pb2.TestPackedExtensions()
def Size(self):
return self.p... | ByteSizeTest |
python | getlogbook__logbook | src/logbook/utils.py | {
"start": 118,
"end": 1609
} | class ____:
def __init__(self, threshold, func):
self.timer = threading.Timer(threshold, func)
def __enter__(self):
self.timer.start()
return self
def __exit__(self, *_):
self.timer.cancel()
_slow_logger = Logger("Slow")
def logged_if_slow(*args, **kwargs):
"""Conte... | _SlowContextNotifier |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 24467,
"end": 25363
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_... | NystromformerClassificationHead |
python | doocs__leetcode | solution/0400-0499/0474.Ones and Zeroes/Solution2.py | {
"start": 0,
"end": 377
} | class ____:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
f = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
a, b = s.count("0"), s.count("1")
for i in range(m, a - 1, -1):
for j in range(n, b - 1, -1):
f[i][j] = max(... | Solution |
python | google__pytype | pytype/tools/xref/testdata/class_def.py | {
"start": 335,
"end": 478
} | class ____(A):
pass
#- @Foo defines/binding ClassFoo
#- @A ref ClassA
#- @B ref ClassB
#- ClassFoo.node/kind record
#- ClassFoo.subkind class
| D |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/asset_event.py | {
"start": 1043,
"end": 1356
} | class ____(StrictBaseModel):
"""DagRun serializer for asset responses."""
run_id: str
dag_id: str
logical_date: datetime | None
start_date: datetime
end_date: datetime | None
state: str
data_interval_start: datetime | None
data_interval_end: datetime | None
| DagRunAssetReference |
python | boto__boto3 | tests/unit/s3/test_inject.py | {
"start": 6322,
"end": 8412
} | class ____(unittest.TestCase):
def setUp(self):
self.obj = mock.Mock(bucket_name='my_bucket', key='my_key')
self.copy_source = {'Bucket': 'foo', 'Key': 'bar'}
def test_upload_file_proxies_to_meta_client(self):
inject.object_upload_file(self.obj, Filename='foo')
self.obj.meta.cli... | TestObjectTransferMethods |
python | huggingface__transformers | examples/pytorch/image-pretraining/run_mae.py | {
"start": 6186,
"end": 14979
} | class ____(TrainingArguments):
base_learning_rate: float = field(
default=1e-3, metadata={"help": "Base learning rate: absolute_lr = base_lr * total_batch_size / 256."}
)
def collate_fn(examples):
pixel_values = torch.stack([example["pixel_values"] for example in examples])
return {"pixel_valu... | CustomTrainingArguments |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property17.py | {
"start": 262,
"end": 350
} | class ____(Protocol[T_co]):
@property
def prop(self) -> T_co: ...
@dataclass
| Proto |
python | miyuchina__mistletoe | test/test_span_token.py | {
"start": 6833,
"end": 7464
} | class ____(unittest.TestCase):
def test_parse_soft_break(self):
token, = span_token.tokenize_inner('\n')
self.assertIsInstance(token, span_token.LineBreak)
self.assertTrue(token.soft)
def test_parse_hard_break_with_double_blanks(self):
token, = span_token.tokenize_inner(' \n')
... | TestLineBreak |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_types05.py | {
"start": 315,
"end": 1790
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("types05.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels... | TestCompareXLSXFiles |
python | networkx__networkx | networkx/linalg/tests/test_algebraic_connectivity.py | {
"start": 10235,
"end": 13735
} | class ____:
_graphs = (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
@pytest.mark.parametrize("graph", _graphs)
def test_nullgraph(self, graph):
G = graph()
pytest.raises(nx.NetworkXError, nx.spectral_ordering, G)
@pytest.mark.parametrize("graph", _graphs)
def test_singleto... | TestSpectralOrdering |
python | spack__spack | lib/spack/spack/vendor/jinja2/loaders.py | {
"start": 16442,
"end": 18769
} | class ____(BaseLoader):
"""A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1'... | PrefixLoader |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 3053,
"end": 3259
} | class ____(BaseModelWithConfig):
name: Optional[str] = None
namespace: Optional[str] = None
prefix: Optional[str] = None
attribute: Optional[bool] = None
wrapped: Optional[bool] = None
| XML |
python | doocs__leetcode | solution/0700-0799/0723.Candy Crush/Solution.py | {
"start": 0,
"end": 1385
} | class ____:
def candyCrush(self, board: List[List[int]]) -> List[List[int]]:
m, n = len(board), len(board[0])
run = True
while run:
run = False
for i in range(m):
for j in range(2, n):
if board[i][j] and abs(board[i][j]) == abs(boar... | Solution |
python | django__django | tests/gis_tests/geoapp/test_indexes.py | {
"start": 224,
"end": 2804
} | class ____(TransactionTestCase):
available_apps = []
models = [City]
def get_indexes(self, table):
with connection.cursor() as cursor:
constraints = connection.introspection.get_constraints(cursor, table)
return {
name: constraint["columns"]
f... | SchemaIndexesTests |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectors.py | {
"start": 3308,
"end": 6218
} | class ____:
@staticmethod
def __hnsw(
*,
quantizer: Optional[_QuantizerConfigCreate] = None,
multivector: Optional[_MultiVectorConfigCreate] = None,
) -> _VectorIndexConfigHNSWCreate:
return _VectorIndexConfigHNSWCreate(
cleanupIntervalSeconds=None,
di... | _IndexWrappers |
python | conda__conda | conda/gateways/repodata/jlap/core.py | {
"start": 873,
"end": 4146
} | class ____(UserList):
@classmethod
def from_lines(cls, lines: Iterable[bytes], iv: bytes, pos=0, verify=True):
r"""
:param lines: iterator over input split by b'\n', with b'\n' removed
:param pos: initial position
:param iv: initialization vector (first line of .jlap stream, hex
... | JLAP |
python | sympy__sympy | sympy/geometry/line.py | {
"start": 56585,
"end": 61448
} | class ____(LinearEntity2D, Line):
"""An infinite line in space 2D.
A line is declared with two distinct points or a point and slope
as defined using keyword `slope`.
Parameters
==========
p1 : Point
pt : Point
slope : SymPy expression
See Also
========
sympy.geometry.poi... | Line2D |
python | bokeh__bokeh | src/bokeh/models/misc/group_by.py | {
"start": 1526,
"end": 1749
} | class ____(Model):
""" Base class for grouping behaviors. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| GroupBy |
python | celery__celery | t/unit/utils/test_graph.py | {
"start": 122,
"end": 1935
} | class ____:
def graph1(self):
res_a = self.app.AsyncResult('A')
res_b = self.app.AsyncResult('B')
res_c = self.app.GroupResult('C', [res_a])
res_d = self.app.GroupResult('D', [res_c, res_b])
node_a = (res_a, [])
node_b = (res_b, [])
node_c = (res_c, [res_a])
... | test_DependencyGraph |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 37017,
"end": 38511
} | class ____(HelperFunction):
def _calculate(self, X, y, logger, feat_type):
import sklearn.decomposition
pca = sklearn.decomposition.PCA(copy=True)
rs = np.random.RandomState(42)
indices = np.arange(X.shape[0])
for i in range(10):
try:
rs.shuffle(i... | PCA |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 352403,
"end": 357610
} | class ____:
class Foo:
def __init__(self, value):
self.value = value
self.iface = {'typestr': 'f8'}
def __float__(self):
return float(self.value)
@property
def __array_interface__(self):
return self.iface
f = Foo(0.5)
@pytes... | TestArrayInterface |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial001_py310.py | {
"start": 86,
"end": 363
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return item
| Item |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 2424,
"end": 17016
} | class ____:
def _test_subscribe_unsubscribe(
self, p, sub_type, unsub_type, sub_func, unsub_func, keys
):
for key in keys:
assert sub_func(key) is None
# should be a message for each channel/pattern we just subscribed to
for i, key in enumerate(keys):
ass... | TestPubSubSubscribeUnsubscribe |
python | django-extensions__django-extensions | django_extensions/management/commands/find_template.py | {
"start": 186,
"end": 671
} | class ____(LabelCommand):
help = "Finds the location of the given template by resolving its path"
args = "[template_path]"
label = "template path"
@signalcommand
def handle_label(self, template_path, **options):
try:
template = loader.get_template(template_path).template
... | Command |
python | walkccc__LeetCode | solutions/692. Top K Frequent Words/692.py | {
"start": 0,
"end": 367
} | class ____:
def topKFrequent(self, words: list[str], k: int) -> list[str]:
ans = []
bucket = [[] for _ in range(len(words) + 1)]
for word, freq in collections.Counter(words).items():
bucket[freq].append(word)
for b in reversed(bucket):
for word in sorted(b):
ans.append(word)
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 56257,
"end": 56835
} | class ____(sgqlc.types.Enum):
"""The possible types of patch statuses.
Enumeration Choices:
* `ADDED`: The file was added. Git status 'A'.
* `CHANGED`: The file's type was changed. Git status 'T'.
* `COPIED`: The file was copied. Git status 'C'.
* `DELETED`: The file was deleted. Git status 'D... | PatchStatus |
python | django__django | tests/model_fields/storage.py | {
"start": 69,
"end": 233
} | class ____(FileSystemStorage):
def open(self, *args, **kwargs):
raise AssertionError("This storage class does not support reading.")
| NoReadFileSystemStorage |
python | mahmoud__glom | glom/core.py | {
"start": 65059,
"end": 65197
} | class ____(type):
def __instancecheck__(cls, C):
return hasattr(C, "__dict__") and hasattr(C.__dict__, "keys")
| _ObjStyleKeysMeta |
python | dask__dask | dask/dataframe/utils.py | {
"start": 23702,
"end": 25800
} | class ____(NotImplementedError, AttributeError):
"""NotImplementedError and AttributeError"""
def meta_frame_constructor(like):
"""Return a serial DataFrame constructor
Parameters
----------
like :
Any series-like, Index-like or dataframe-like object.
"""
if is_dask_collection(lik... | AttributeNotImplementedError |
python | google__flatbuffers | tests/MyGame/Example/ArrayTable.py | {
"start": 1989,
"end": 3132
} | class ____(object):
# ArrayTableT
def __init__(
self,
a = None,
):
self.a = a # type: Optional[MyGame.Example.ArrayStruct.ArrayStructT]
@classmethod
def InitFromBuf(cls, buf, pos):
arrayTable = ArrayTable()
arrayTable.Init(buf, pos)
return cls.InitF... | ArrayTableT |
python | pyinstaller__pyinstaller | PyInstaller/loader/pyimod02_importers.py | {
"start": 17392,
"end": 26184
} | class ____:
"""
PyInstaller's frozen loader for modules in the PYZ archive, which are discovered by PyiFrozenFinder.
Since this loader is instantiated only from PyiFrozenFinder and since each loader instance is tied to a specific
module, the fact that the loader was instantiated serves as the proof tha... | PyiFrozenLoader |
python | numpy__numpy | numpy/ma/tests/test_core.py | {
"start": 104604,
"end": 123238
} | class ____:
# Test MaskedArray Arithmetic
def _create_intdata(self):
x = arange(10)
y = arange(10)
xm = arange(10)
xm[2] = masked
return x, y, xm
def _create_floatdata(self):
x, y, xm = self._create_intdata()
return x.astype(float), y.astype(float), x... | TestMaskedArrayInPlaceArithmetic |
python | ray-project__ray | python/ray/data/namespace_expressions/string_namespace.py | {
"start": 1357,
"end": 13361
} | class ____:
"""Namespace for string operations on expression columns.
This namespace provides methods for operating on string-typed columns using
PyArrow compute functions.
Example:
>>> from ray.data.expressions import col
>>> # Convert to uppercase
>>> expr = col("name").str.u... | _StringNamespace |
python | PyCQA__isort | isort/format.py | {
"start": 3631,
"end": 5487
} | class ____(BasicPrinter):
def __init__(self, error: str, success: str, output: TextIO | None):
super().__init__(error, success, output=output)
# Note: this constants are instance variables instead ofs class variables
# because they refer to colorama which might not be installed.
sel... | ColoramaPrinter |
python | marshmallow-code__apispec | tests/test_ext_marshmallow_openapi.py | {
"start": 472,
"end": 1789
} | class ____:
def test_fields_with_load_default_load(self, openapi):
class MySchema(Schema):
field = fields.Str(dump_default="foo", load_default="bar")
res = openapi.schema2parameters(MySchema, location="query")
if openapi.openapi_version.major < 3:
assert res[0]["defa... | TestMarshmallowFieldToOpenAPI |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 28185,
"end": 33337
} | class ____(LinearModel, metaclass=ABCMeta):
_parameter_constraints: dict = {
"alpha": [Interval(Real, 0, None, closed="left"), np.ndarray],
"fit_intercept": ["boolean"],
"copy_X": ["boolean"],
"max_iter": [Interval(Integral, 1, None, closed="left"), None],
"tol": [Interval(Re... | _BaseRidge |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/read_one/tutorial001.py | {
"start": 426,
"end": 1568
} | class ____(HeroBase):
id: int
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
app = FastAPI()... | HeroPublic |
python | PyCQA__pylint | tests/functional/a/access/access_member_before_definition.py | {
"start": 123,
"end": 329
} | class ____:
"""class with attributes defined in wrong order"""
def __init__(self):
var1 = self._var2 # [access-member-before-definition]
self._var2 = 3
self._var3 = var1
| Aaaa |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 16575,
"end": 18834
} | class ____:
"""Use this factory class to define the appropriate classes needed when defining near text and near vector sub-searches in hybrid queries."""
@staticmethod
def near_text(
query: Union[str, List[str]],
*,
certainty: Optional[float] = None,
distance: Optional[float... | HybridVector |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 63727,
"end": 64159
} | class ____(strip_align_x, strip_align_y):
"""
Alignment of the strip & its background w.r.t the panel border
Parameters
----------
theme_element : float
Value as a proportion of the strip text size. A good value
should be the range `[-1, 0.5]`. A negative value
puts the stri... | strip_align |
python | plotly__plotly.py | plotly/graph_objs/heatmap/_textfont.py | {
"start": 233,
"end": 9856
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "heatmap"
_path_str = "heatmap.textfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
de... | Textfont |
python | ray-project__ray | rllib/examples/learners/separate_vf_lr_and_optimizer.py | {
"start": 1158,
"end": 5788
} | class ____ details on how to override the main (torch) `configure_optimizers_for_module`
function.
We assume here that the users properly sets up their RLModule to have separate policy-
and value function networks. If any model pieces are shared between the two optimizers,
you should experience learning instability up... | for |
python | pytest-dev__pytest-cov | src/pytest_cov/engine.py | {
"start": 14516,
"end": 17161
} | class ____(CovController):
"""Implementation for distributed workers."""
@_ensure_topdir
def start(self):
# Determine whether we are collocated with master.
self.is_collocated = (
socket.gethostname() == self.config.workerinput['cov_master_host']
and self.topdir == s... | DistWorker |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/hstore.py | {
"start": 8342,
"end": 8461
} | class ____(sqlfunc.GenericFunction):
type = HSTORE
name = "delete"
inherit_cache = True
| _HStoreDeleteFunction |
python | joke2k__faker | faker/providers/phone_number/ru_RU/__init__.py | {
"start": 49,
"end": 379
} | class ____(PhoneNumberProvider):
formats = (
"+7 ### ### ####",
"+7 ### ### ## ##",
"+7 (###) ###-##-##",
"+7 (###) ###-####",
"+7##########",
"8 ### ### ####",
"8 ### ### ## ##",
"8 (###) ###-##-##",
"8 (###) ###-####",
"8##########",
... | Provider |
python | huggingface__transformers | src/transformers/models/edgetam/modeling_edgetam.py | {
"start": 19316,
"end": 21559
} | class ____(ModelOutput):
r"""
iou_scores (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_masks)`):
The Intersection over Union (IoU) scores of the predicted masks.
pred_masks (`torch.FloatTensor` of shape `(batch_size, point_batch_size, num_masks, height, width)`):
The pred... | EdgeTamImageSegmentationOutput |
python | google__flatbuffers | python/flatbuffers/number_types.py | {
"start": 974,
"end": 1116
} | class ____(object):
bytewidth = 1
min_val = False
max_val = True
py_type = bool
name = "bool"
packer_type = packer.boolean
| BoolFlags |
python | ray-project__ray | rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py | {
"start": 374,
"end": 6617
} | class ____(ConnectorV2):
"""Adds actions/rewards/terminateds/... to train batch. Excluding the infos column.
Note: This is one of the default Learner ConnectorV2 pieces that are added
automatically by RLlib into every Learner connector pipeline, unless
`config.add_default_connectors_to_learner_pipeline... | AddColumnsFromEpisodesToTrainBatch |
python | apache__airflow | providers/elasticsearch/src/airflow/providers/elasticsearch/hooks/elasticsearch.py | {
"start": 4678,
"end": 7140
} | class ____(DbApiHook):
"""
Interact with Elasticsearch through the elasticsearch-dbapi.
This hook uses the Elasticsearch conn_id.
:param elasticsearch_conn_id: The :ref:`ElasticSearch connection id <howto/connection:elasticsearch>`
used for Elasticsearch credentials.
"""
conn_name_att... | ElasticsearchSQLHook |
python | pytorch__pytorch | torch/ao/quantization/fx/graph_module.py | {
"start": 1301,
"end": 3188
} | class ____(GraphModule):
def __init__(
self,
root: torch.nn.Module | dict[str, Any],
graph: Graph,
preserved_attr_names: set[str],
):
self.preserved_attr_names = {
"_activation_post_process_map",
"_activation_post_process_indexes",
"_pa... | ObservedGraphModule |
python | davidhalter__parso | parso/python/errors.py | {
"start": 17865,
"end": 18215
} | class ____(IndentationRule):
message = 'expected an indented block'
def get_node(self, node):
leaf = node.get_next_leaf()
return list(leaf._split_prefix())[-1]
def is_issue(self, node):
# This is the beginning of a suite that is not indented.
return node.children[-1].type =... | _ExpectIndentedBlock |
python | kamyu104__LeetCode-Solutions | Python/change-the-root-of-a-binary-tree.py | {
"start": 54,
"end": 110
} | class ____:
def __init__(self, val):
pass
| Node |
python | huggingface__transformers | tests/models/sam/test_image_processing_sam.py | {
"start": 1138,
"end": 4049
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_pad=True,
pad_size=None,
mask_size=None,
mask_pad_size=None,
do_resize=True,
size=Non... | SamImageProcessingTester |
python | tensorflow__tensorflow | tensorflow/python/eager/backprop_test.py | {
"start": 54088,
"end": 62071
} | class ____(test.TestCase):
def _jacobian(self, experimental_use_pfor):
persistent = context.executing_eagerly and not experimental_use_pfor
with backprop.GradientTape(persistent=persistent) as g:
x = constant_op.constant([1., 2.])
y = constant_op.constant([3., 4.])
g.watch(x)
g.watch(... | JacobianTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.