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 | huggingface__transformers | tests/pipelines/test_pipelines_zero_shot_image_classification.py | {
"start": 1187,
"end": 9087
} | class ____(unittest.TestCase):
# Deactivating auto tests since we don't have a good MODEL_FOR_XX mapping,
# and only CLIP would be there for now.
# model_mapping = {CLIPConfig: CLIPModel}
# def get_test_pipeline(self, model, tokenizer, processor):
# if tokenizer is None:
# # Side ef... | ZeroShotImageClassificationPipelineTests |
python | openai__openai-python | tests/api_resources/test_uploads.py | {
"start": 5593,
"end": 11275
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_create(self, async_client: AsyncOpenAI) -> None:
upload = await async_client.uploads.creat... | TestAsyncUploads |
python | bokeh__bokeh | src/bokeh/core/property/bases.py | {
"start": 19341,
"end": 20294
} | class ____(ParameterizedProperty[T]):
""" A base class for Container-like type properties.
"""
def _may_have_unstable_default(self) -> bool:
# all containers are mutable, so the default can be modified
return self._default is not Undefined
def validation_on() -> bool:
""" Check if pro... | ContainerProperty |
python | keras-team__keras | keras/src/optimizers/lamb_test.py | {
"start": 151,
"end": 2705
} | class ____(testing.TestCase):
def test_config(self):
optimizer = Lamb(
learning_rate=0.5,
beta_1=0.5,
beta_2=0.67,
epsilon=1e-5,
)
self.run_class_serialization_test(optimizer)
def test_single_step(self):
optimizer = Lamb(learning_r... | LambTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_datacatalog.py | {
"start": 52340,
"end": 69208
} | class ____:
def setup_method(self):
with pytest.warns(AirflowProviderDeprecationWarning):
with mock.patch(
"airflow.providers.google.cloud.hooks.datacatalog.CloudDataCatalogHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
... | TestCloudDataCatalogMissingProjectIdHook |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/git_url_top_level/package.py | {
"start": 217,
"end": 2058
} | class ____(Package):
"""Mock package that top-level git and url attributes.
This demonstrates how Spack infers fetch mechanisms from parameters
to the ``version`` directive.
"""
homepage = "http://www.git-fetch-example.com"
git = "https://example.com/some/git/repo"
url = "https://example... | GitUrlTopLevel |
python | Textualize__textual | src/textual/css/_help_text.py | {
"start": 893,
"end": 30032
} | class ____:
"""
Args:
inline: Information only relevant to users who are using inline styling.
css: Information only relevant to users who are using CSS.
"""
inline: Sequence[Bullet]
css: Sequence[Bullet]
def get_by_context(self, context: StylingContext) -> list[Bullet]:
... | ContextSpecificBullets |
python | scikit-learn__scikit-learn | sklearn/externals/array_api_compat/common/_typing.py | {
"start": 1341,
"end": 1576
} | class ____(Protocol):
@property
def __class__(self, /) -> type[complex]: ...
@__class__.setter
def __class__(self, value: type[complex], /) -> None: ... # pyright: ignore[reportIncompatibleMethodOverride]
#
| JustComplex |
python | scikit-learn__scikit-learn | sklearn/tests/test_base.py | {
"start": 15717,
"end": 17068
} | class ____(DecisionTreeClassifier):
def __getstate__(self):
return self.__dict__
def test_pickle_version_warning_is_issued_when_no_version_info_in_pickle():
iris = datasets.load_iris()
# TreeNoVersion has no getstate, like pre-0.18
tree = TreeNoVersion().fit(iris.data, iris.target)
tree_p... | TreeNoVersion |
python | django__django | tests/forms_tests/tests/test_input_formats.py | {
"start": 35033,
"end": 39395
} | class ____(SimpleTestCase):
def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format"
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
f.clean("13:30:05 21.12.2010")
... | SimpleDateTimeFormatTests |
python | realpython__materials | python-yaml/models.py | {
"start": 74,
"end": 129
} | class ____:
first_name: str
last_name: str
| Person |
python | wandb__wandb | wandb/vendor/pygments/lexers/d.py | {
"start": 9289,
"end": 9530
} | class ____(CrocLexer):
"""
For MiniD source. MiniD is now known as Croc.
"""
name = 'MiniD'
filenames = [] # don't lex .md as MiniD, reserve for Markdown
aliases = ['minid']
mimetypes = ['text/x-minidsrc']
| MiniDLexer |
python | doocs__leetcode | solution/1400-1499/1496.Path Crossing/Solution.py | {
"start": 0,
"end": 469
} | class ____:
def isPathCrossing(self, path: str) -> bool:
i = j = 0
vis = {(0, 0)}
for c in path:
match c:
case 'N':
i -= 1
case 'S':
i += 1
case 'E':
j += 1
... | Solution |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 169796,
"end": 173595
} | class ____(TopLevelMixin, core.TopLevelHConcatSpec):
"""A chart with horizontally-concatenated facets."""
@utils.use_signature(core.TopLevelHConcatSpec)
def __init__(
self,
data: Optional[ChartDataType] = Undefined,
hconcat: Sequence[ConcatType] = (),
**kwargs: Any,
) ->... | HConcatChart |
python | kamyu104__LeetCode-Solutions | Python/group-shifted-strings.py | {
"start": 54,
"end": 754
} | class ____(object):
# @param {string[]} strings
# @return {string[][]}
def groupStrings(self, strings):
groups = collections.defaultdict(list)
for s in strings: # Grouping.
groups[self.hashStr(s)].append(s)
result = []
for key, val in groups.iteritems():
... | Solution |
python | ansible__ansible | lib/ansible/playbook/delegatable.py | {
"start": 241,
"end": 625
} | class ____:
delegate_to = FieldAttribute(isa='string')
delegate_facts = FieldAttribute(isa='bool')
def _post_validate_delegate_to(self, attr, value, templar):
"""This method exists just to make it clear that ``Task.post_validate``
does not template this value, it is set via ``TaskExecutor._... | Delegatable |
python | ZoranPandovski__al-go-rithms | recursive_algorithms/shortest_path_algorithm.py | {
"start": 175,
"end": 2616
} | class ____():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(" ... | Graph |
python | scikit-image__scikit-image | tests/skimage/morphology/test_footprints.py | {
"start": 10144,
"end": 11762
} | class ____:
@pytest.mark.parametrize("i", [0, 1, 2, 3, 4])
@pytest.mark.parametrize("j", [0, 1, 2, 3, 4])
def test_rectangle(self, i, j):
desired = np.ones((i, j), dtype='uint8')
actual = footprint_rectangle((i, j))
assert_equal(actual, desired)
@pytest.mark.parametrize("i", [0,... | Test_footprint_rectangule |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/pandas_datasource.py | {
"start": 18408,
"end": 23092
} | class ____(Datasource, Generic[_DataAssetT]):
# class attributes
asset_types: ClassVar[Sequence[Type[DataAsset]]] = []
# instance attributes
assets: MutableSequence[_DataAssetT] = []
# Abstract Methods
@property
@override
def execution_engine_type(self) -> Type[PandasExecutionEngine]:
... | _PandasDatasource |
python | pytorch__pytorch | torch/__init__.py | {
"start": 83066,
"end": 86628
} | class ____:
compiler_name = "inductor"
def __init__(self, mode, options, dynamic):
from torch._inductor.compiler_bisector import CompilerBisector
self.config: dict[str, _Any] = {}
self.dynamic = dynamic
self.apply_mode(mode)
self.apply_options(options)
self.appl... | _TorchCompileInductorWrapper |
python | geekcomputers__Python | Windows_Wallpaper_Script/wallpaper_extract.py | {
"start": 61,
"end": 4475
} | class ____:
# Set Environment Variables
username = os.environ["USERNAME"]
# An Amazing Code You Will Love To Have
# All file urls
file_urls = {
"wall_src": "C:\\Users\\"
+ username
+ "\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\"
... | Wallpaper |
python | tensorflow__tensorflow | tensorflow/python/framework/importer_test.py | {
"start": 1996,
"end": 49764
} | class ____(test.TestCase):
def _MakeGraphDef(self,
text,
producer=versions.GRAPH_DEF_VERSION,
min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER):
text = "versions: { producer: %d min_consumer: %d };\n%s" % (producer,
... | ImportGraphDefTest |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 38444,
"end": 38644
} | class ____(Sky2PixProjection, QuadCube):
r"""
Tangential spherical cube projection - sky to pixel.
Corresponds to the ``TSC`` projection in FITS WCS.
"""
| Sky2Pix_TangentialSphericalCube |
python | pypa__setuptools | setuptools/_distutils/tests/test_archive_util.py | {
"start": 1014,
"end": 11761
} | class ____(support.TempdirManager):
@pytest.mark.usefixtures('needs_zlib')
def test_make_tarball(self, name='archive'):
# creating something to tar
tmpdir = self._create_files()
self._make_tarball(tmpdir, name, '.tar.gz')
# trying an uncompressed one
self._make_tarball(tm... | ArchiveUtilTestCase |
python | streamlit__streamlit | lib/tests/streamlit/dataframe_util_test.py | {
"start": 31846,
"end": 35868
} | class ____(DeltaGeneratorTestCase):
"""Test class for the automatic arrow truncation feature."""
@patch_config_options(
{"server.maxMessageSize": 3, "server.enableArrowTruncation": True}
)
def test_truncate_larger_table(self):
"""Test that `_maybe_truncate_table` correctly truncates a t... | TestArrowTruncation |
python | scikit-image__scikit-image | tests/skimage/feature/test_texture.py | {
"start": 265,
"end": 9188
} | class ____:
def setup_method(self):
self.image = np.array(
[[0, 0, 1, 1], [0, 0, 1, 1], [0, 2, 2, 2], [2, 2, 3, 3]], dtype=np.uint8
)
@run_in_parallel()
def test_output_angles(self):
result = graycomatrix(
self.image, [1], [0, np.pi / 4, np.pi / 2, 3 * np.pi ... | TestGLCM |
python | Netflix__metaflow | metaflow/metadata_provider/heartbeat.py | {
"start": 423,
"end": 3127
} | class ____(object):
def __init__(self):
self.headers = SERVICE_HEADERS
self.req_thread = Thread(target=self._ping)
self.req_thread.daemon = True
self.default_frequency_secs = 10
self.hb_url = None
def process_message(self, msg):
# type: (Message) -> None
... | MetadataHeartBeat |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 304032,
"end": 305597
} | class ____:
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __init__(self, path, options=''):
if isinstance( path, str):
pass
elif hasattr( path, 'absolute'):
path = str( path)
elif hasattr( path, 'name'):
... | DocumentWriter |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/utils/config.py | {
"start": 14620,
"end": 18125
} | class ____:
"""
Configuration for the default memory resource.
Parameters
----------
qualname
The fully qualified name of the memory resource class to use.
options
This can be either a dictionary representing the options to pass
to the memory resource class, or, a dictio... | MemoryResourceConfig |
python | realpython__materials | duck-typing-python/vehicles_abc.py | {
"start": 515,
"end": 711
} | class ____(Vehicle):
def start(self):
print("The car is starting")
def stop(self):
print("The car is stopping")
def drive(self):
print("The car is driving")
| Car |
python | google__jax | jax/experimental/colocated_python/serialization.py | {
"start": 1112,
"end": 12301
} | class ____(threading.local):
"""Tracks repeated objects within a single `_serialize()` or `_deserialize()`.
It is common for `_serialize(x)` to be called with `x` being a nested
container or capturing other objects in a closure, with many references
pointing to only a few unique objects. The logic below
(`_m... | _CommonObjectState |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 714703,
"end": 715266
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "created_at", "database_id", "deleted_comment_author")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
created_at = sgqlc.types.Field(
sgqlc.type... | CommentDeletedEvent |
python | coleifer__peewee | playhouse/sqlite_udf.py | {
"start": 10860,
"end": 11317
} | class ____(object):
name = 'range'
def __init__(self):
self._min = self._max = None
def step(self, value):
if self._min is None or value < self._min:
self._min = value
if self._max is None or value > self._max:
self._max = value
def finalize(self):
... | _range |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 2194,
"end": 2510
} | class ____(RequestError):
"""Raised when an existing pool gets a request for a foreign host."""
def __init__(self, pool, url, retries=3):
message = "Tried to open a foreign host with url: %s" % url
RequestError.__init__(self, pool, url, message)
self.retries = retries
| HostChangedError |
python | celery__celery | t/unit/events/test_state.py | {
"start": 356,
"end": 1180
} | class ____:
def __init__(self, state):
self.state = state
self.rewind()
self.setup()
self.current_clock = 0
def setup(self):
pass
def next_event(self):
ev = self.events[next(self.position)]
ev['local_received'] = ev['timestamp']
try:
... | replay |
python | jmcnamara__XlsxWriter | xlsxwriter/test/table/test_table06.py | {
"start": 481,
"end": 2114
} | class ____(unittest.TestCase):
"""
Test assembling a complete Table file.
"""
def test_assemble_xml_file(self):
"""Test writing a table"""
self.maxDiff = None
worksheet = Worksheet()
worksheet.worksheet_meta = WorksheetMeta()
worksheet.str_table = SharedStringT... | TestAssembleTable |
python | fastapi__sqlmodel | sqlmodel/sql/_expression_select_cls.py | {
"start": 1483,
"end": 1546
} | class ____(SelectBase[_T]):
inherit_cache = True
| SelectOfScalar |
python | django__django | django/core/files/storage/memory.py | {
"start": 977,
"end": 2322
} | class ____(ContentFile, TimingMixin):
"""
Helper class representing an in-memory file node.
Handle unicode/bytes conversion during I/O operations and record creation,
modification, and access times.
"""
def __init__(self, content="", name=None):
super().__init__(content, name)
... | InMemoryFileNode |
python | tensorflow__tensorflow | tensorflow/python/framework/composite_tensor_test.py | {
"start": 2935,
"end": 2967
} | class ____(CTSpec):
pass
| CTSpec2 |
python | django__django | tests/admin_views/tests.py | {
"start": 80812,
"end": 85510
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True)
def setUp(self):
... | SaveAsTests |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 46824,
"end": 49626
} | class ____(ElectraPreTrainedModel):
config_class = ElectraConfig
base_model_prefix = "electra"
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.electra = ElectraModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config... | ElectraForQuestionAnswering |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 20944,
"end": 21144
} | class ____(DataBlob):
"""
SlackDataBlob is a specific type that represents the data blob for a Slack notification action.
"""
tags: str = ""
notes: str = ""
@dataclass
| SlackDataBlob |
python | facebook__pyre-check | client/commands/statistics.py | {
"start": 3417,
"end": 3569
} | class ____(SuppressionCountCollector):
def __init__(self) -> None:
super().__init__(r".*# *pyre-fixme(\[(\d* *,? *)*\])?")
| FixmeCountCollector |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/natural_language.py | {
"start": 10919,
"end": 13753
} | class ____(GoogleCloudBaseOperator):
"""
Classifies a document into categories.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageClassifyTextOperator`
:param document: Input document.
If a dict is ... | CloudNaturalLanguageClassifyTextOperator |
python | keras-team__keras | examples/demo_custom_jax_workflow.py | {
"start": 278,
"end": 858
} | class ____(layers.Layer):
def __init__(self, units, name=None):
super().__init__(name=name)
self.units = units
def build(self, input_shape):
input_dim = input_shape[-1]
w_shape = (input_dim, self.units)
w_value = initializers.GlorotUniform()(w_shape)
self.w = bac... | MyDense |
python | apache__airflow | providers/redis/tests/unit/redis/operators/test_redis_publish.py | {
"start": 1066,
"end": 1854
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
self.mock_context = MagicMock()
@patch("airflow.providers.redis.hooks.redis.RedisHook.get_conn")
def test_execute_operator(se... | TestRedisPublishOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict24.py | {
"start": 132,
"end": 199
} | class ____(TypedDict):
a: str
T1 = TypeVar("T1", bound=TD1)
| TD1 |
python | rapidsai__cudf | python/cudf/cudf_pandas_tests/third_party_integration_tests/tests/test_pytorch.py | {
"start": 983,
"end": 1874
} | class ____(torch.utils.data.Dataset):
def __init__(self, x1, x2, y):
self.x1 = x1
self.x2 = x2
self.y = y
def __getitem__(self, idx):
x1 = self.x1[idx]
x2 = self.x2[idx]
y = self.y[idx]
return (x1, x2), y
def __len__(self):
return len(self.x1... | Dataset |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_flakiness.py | {
"start": 1018,
"end": 4827
} | class ____(Exception):
pass
def test_fails_only_once_is_flaky():
first_call = True
@given(integers())
def rude(x):
nonlocal first_call
if first_call:
first_call = False
raise Nope
with pytest.raises(FlakyFailure, match="Falsified on the first call but") as... | Nope |
python | getsentry__sentry | src/sentry/uptime/endpoints/serializers.py | {
"start": 1031,
"end": 1275
} | class ____(TypedDict):
url: str
method: str
body: str | None
headers: Sequence[tuple[str, str]]
intervalSeconds: int
timeoutMs: int
traceSampling: bool
@register(UptimeSubscription)
| UptimeSubscriptionSerializerResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator1.py | {
"start": 2894,
"end": 3011
} | class ____(Protocol):
def __next__(self, /) -> int: ...
def generator15() -> IntIterator:
yield 0
| IntIterator |
python | PrefectHQ__prefect | tests/server/models/test_block_types.py | {
"start": 453,
"end": 2636
} | class ____:
async def test_create_block_type(self, session):
block_type = await models.block_types.create_block_type(
session=session,
block_type=schemas.actions.BlockTypeCreate(
name="x",
slug="x",
logo_url="http://example.com/logo.png... | TestCreateBlockType |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-weaviate/unit_tests/destination_test.py | {
"start": 325,
"end": 3650
} | class ____(unittest.TestCase):
def setUp(self):
self.config = {
"processing": {"text_fields": ["str_col"], "metadata_fields": [], "chunk_size": 1000},
"embedding": {"mode": "openai", "openai_key": "mykey"},
"indexing": {"host": "https://my-cluster.weaviate.network", "auth... | TestDestinationWeaviate |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 13867,
"end": 16268
} | class ____(StepInputSource):
"""This step input source is configuration to be passed to a type loader.
A None node_handle implies the inputs were provided at the root graph level.
"""
node_handle: Optional[NodeHandle]
input_name: str
def get_associated_input_def(self, job_def: JobDefinition) ... | FromConfig |
python | dask__distributed | distributed/diagnostics/plugin.py | {
"start": 25336,
"end": 26253
} | class ____(WorkerPlugin):
"""A WorkerPlugin to upload a local file to workers.
Parameters
----------
filepath: str
A path to the file (.py, egg, or zip) to upload
Examples
--------
>>> from distributed.diagnostics.plugin import UploadFile
>>> client.register_plugin(UploadFile(... | UploadFile |
python | django__django | tests/model_package/models/article.py | {
"start": 103,
"end": 304
} | class ____(models.Model):
sites = models.ManyToManyField(Site)
headline = models.CharField(max_length=100)
publications = models.ManyToManyField("model_package.Publication", blank=True)
| Article |
python | fastai__fastai | fastai/layers.py | {
"start": 3386,
"end": 3565
} | class ____(Module):
"Reshape `x` to `size`"
def __init__(self, *size): self.size = size
def forward(self, x): return x.view(self.size)
# %% ../nbs/01_layers.ipynb 19
| View |
python | kamyu104__LeetCode-Solutions | Python/minimum-removals-to-balance-array.py | {
"start": 54,
"end": 429
} | class ____(object):
def minRemoval(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
left = 0
for right in xrange(len(nums)):
if nums[left]*k < nums[right]:
left += 1
return left
# ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/remove-nth-node-from-end-of-list.py | {
"start": 280,
"end": 653
} | class ____(object):
# @return a ListNode
def removeNthFromEnd(self, head, n):
dummy = ListNode(-1)
dummy.next = head
slow, fast = dummy, dummy
for i in xrange(n):
fast = fast.next
while fast.next:
slow, fast = slow.next, fast.next
slow.n... | Solution |
python | PrefectHQ__prefect | tests/test_task_engine.py | {
"start": 44618,
"end": 56276
} | class ____:
async def test_sync_task_sets_start_time_on_running(
self, prefect_client, events_pipeline
):
@task
def foo():
return TaskRunContext.get().task_run.id
task_run_id = run_task_sync(foo)
await events_pipeline.process_events()
run = await pre... | TestTaskTimeTracking |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 5623,
"end": 6203
} | class ____(nn.Module):
def __init__(self, embed_dim, kernel_size, padding, stride, projection_method="dw_bn"):
super().__init__()
if projection_method == "dw_bn":
self.convolution_projection = CvtSelfAttentionConvProjection(embed_dim, kernel_size, padding, stride)
self.linear_pro... | CvtSelfAttentionProjection |
python | dabeaz-course__practical-python | Solutions/7_11/portfolio.py | {
"start": 47,
"end": 1208
} | class ____:
def __init__(self):
self._holdings = []
@classmethod
def from_csv(cls, lines, **opts):
self = cls()
portdicts = fileparse.parse_csv(lines,
select=['name','shares','price'],
types=[str,int,f... | Portfolio |
python | kamyu104__LeetCode-Solutions | Python/minimum-size-subarray-in-infinite-array.py | {
"start": 801,
"end": 1464
} | class ____(object):
def minSizeSubarray(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
INF = float("inf")
q, target = divmod(target, sum(nums))
if not target:
return q*len(nums)
result = INF
... | Solution2 |
python | doocs__leetcode | solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/Solution2.py | {
"start": 0,
"end": 290
} | class ____:
def longestSemiRepetitiveSubstring(self, s: str) -> int:
n = len(s)
cnt = l = 0
for i in range(1, n):
cnt += s[i] == s[i - 1]
if cnt > 1:
cnt -= s[l] == s[l + 1]
l += 1
return n - l
| Solution |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 389422,
"end": 399565
} | class ____:
""" Tests __array_finalize__ """
def test_receives_base(self):
# gh-11237
class SavesBase(np.ndarray):
def __array_finalize__(self, obj):
self.saved_base = self.base
a = np.array(1).view(SavesBase)
assert_(a.saved_base is a.base)
def... | TestArrayFinalize |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 5226,
"end": 6323
} | class ____(Operation):
def __init__(self, threshold=0.5, *, name=None):
super().__init__(name=name)
self.threshold = threshold
def call(self, x):
return backend.nn.soft_shrink(x, self.threshold)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
... | SoftShrink |
python | pappasam__jedi-language-server | jedi_language_server/initialization_options.py | {
"start": 591,
"end": 730
} | class ____:
name_extract_variable: str = "jls_extract_var"
name_extract_function: str = "jls_extract_def"
@light_dataclass
| CodeAction |
python | pytorch__pytorch | test/profiler/test_profiler_tree.py | {
"start": 2763,
"end": 8565
} | class ____:
@staticmethod
def test(f):
"""Mark unit test that will be using ProfilerTree to test traces.
This decorator serves two purposes. First, it provides a method name
that `format` can use to tell where the test runner (which is
environment specific) ends and the unit tes... | ProfilerTree |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/AllowedHosts.py | {
"start": 186,
"end": 567
} | class ____(BaseModel):
class Config:
extra = Extra.allow
hosts: Optional[List[str]] = Field(
None,
description="An array of hosts that this connector can connect to. AllowedHosts not being present for the source or destination means that access to all hosts is allowed. An empty list h... | AllowedHosts |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/adls2/io_manager.py | {
"start": 8626,
"end": 11707
} | class ____(ADLS2PickleIOManager):
"""Renamed to ADLS2PickleIOManager. See ADLS2PickleIOManager for documentation."""
pass
@dagster_maintained_io_manager
@io_manager(
config_schema=ADLS2PickleIOManager.to_config_schema(),
required_resource_keys={"adls2"},
)
def adls2_pickle_io_manager(init_context: In... | ConfigurablePickledObjectADLS2IOManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/streams.py | {
"start": 15200,
"end": 21197
} | class ____(DateSlicesMixin, IncrementalMixpanelStream):
"""Export event data as it is received and stored within Mixpanel, complete with all event properties
(including distinct_id) and the exact timestamp the event was fired.
API Docs: https://developer.mixpanel.com/reference/export
Endpoint: https:/... | Export |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required_Numpy.py | {
"start": 3957,
"end": 9359
} | class ____: # [multiple-constructor-doc, missing-param-doc, missing-type-doc]
"""test_constr_params_in_class_and_init_numpy
Example of a class with missing constructor parameter documentation
in both the init docstring and the class docstring
(Numpy style)
Everything is completely analogous to fun... | ClassFoo |
python | pytorch__pytorch | test/dynamo/test_compile.py | {
"start": 236,
"end": 480
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear = torch.nn.Linear(10, 10)
self.relu = torch.nn.ReLU()
def forward(self, x):
return self.relu(self.linear(x))
| ToyModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_hourly_reports.py | {
"start": 7725,
"end": 15350
} | class ____(HourlyReportsTestWithStateChangesAfterMigration):
stream_name = "account_impression_performance_report_hourly"
report_file = "account_impression_performance_report_hourly"
records_number = 24
state_file = "hourly_reports_state"
incremental_report_file = "account_impression_performance_rep... | TestAccountImpressionPerformanceReportHourlyStream |
python | mlflow__mlflow | tests/pytorch/iris_data_module.py | {
"start": 1040,
"end": 1344
} | class ____(IrisDataModuleBase):
def train_dataloader(self):
return DataLoader(self.train_set, batch_size=4)
def val_dataloader(self):
return DataLoader(self.val_set, batch_size=4)
def test_dataloader(self):
return DataLoader(self.test_set, batch_size=4)
| IrisDataModule |
python | sympy__sympy | sympy/polys/puiseux.py | {
"start": 1533,
"end": 2351
} | class ____(Protocol[K, V]):
"""A dict mapping from keys to values."""
def items(self) -> Iterable[tuple[K, V]]: ...
def __iter__(self) -> Iterator[K]: ...
MonI = tuple[int, ...]
MonQ = tuple[MPQ, ...]
def puiseux_ring(
symbols: str | list[Expr],
domain: Domain[Er],
/,
) -> tuple[PuiseuxRing... | Map |
python | django__django | django/contrib/gis/geos/prototypes/io.py | {
"start": 7580,
"end": 10184
} | class ____(IOBase):
_constructor = wkb_writer_create
ptr_type = WKB_WRITE_PTR
destructor = wkb_writer_destroy
geos_version = geos_version_tuple()
def __init__(self, dim=2):
super().__init__()
self.outdim = dim
def _handle_empty_point(self, geom):
from django.contrib.gis... | WKBWriter |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 7206,
"end": 8636
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
if config.feat_extract_norm == "group":
conv_layers = [HubertGroupNormConvLayer(config, layer_id=0)] + [
HubertNoLayerNormConvLayer(config, lay... | HubertFeatureEncoder |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_reaching.py | {
"start": 120,
"end": 3306
} | class ____:
"""Unit tests for the global reaching centrality function."""
def test_non_positive_weights(self):
with pytest.raises(nx.NetworkXError):
G = nx.DiGraph()
nx.global_reaching_centrality(G, weight="weight")
def test_negatively_weighted(self):
with pytest.ra... | TestGlobalReachingCentrality |
python | tensorflow__tensorflow | tensorflow/python/distribute/strategy_test_lib.py | {
"start": 29562,
"end": 32889
} | class ____(DistributionTestBase):
"""Tests for a Remote single worker."""
def _get_num_gpus(self):
pass
def _testNumReplicasInSync(self, distribution):
self.assertEqual(self._get_num_gpus(), distribution.num_replicas_in_sync)
def _testMinimizeLoss(self, distribution):
if context.executing_eagerly... | RemoteSingleWorkerMirroredStrategyBase |
python | django__django | tests/nested_foreign_keys/tests.py | {
"start": 997,
"end": 7043
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.director = Person.objects.create(name="Terry Gilliam / Terry Jones")
cls.movie = Movie.objects.create(
title="Monty Python and the Holy Grail", director=cls.director
)
# This test failed in #16715 because in ... | NestedForeignKeysTests |
python | pytorch__pytorch | test/dynamo/test_guard_manager.py | {
"start": 34175,
"end": 43557
} | class ____(RecursiveDictTagTests):
def setUp(self):
self._prev = torch._dynamo.config.use_recursive_dict_tags_for_guards
torch._dynamo.config.use_recursive_dict_tags_for_guards = True
def tearDown(self):
torch._dynamo.config.use_recursive_dict_tags_for_guards = self._prev
def test_... | TagSafetyChecks |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 53666,
"end": 58482
} | class ____(TestCase):
fixtures = ["base_data.json", "bulk_data.json"]
def setUp(self):
super().setUp()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = ElasticsearchAutocompleteMockModelSearchIndex()
sel... | LiveElasticsearchAutocompleteTestCase |
python | pytorch__pytorch | .github/scripts/trymerge_explainer.py | {
"start": 647,
"end": 3259
} | class ____:
force: bool
labels: list[str]
pr_num: int
org: str
project: str
ignore_current: bool
has_trunk_label: bool
has_ciflow_label: bool
def __init__(
self,
force: bool,
labels: list[str],
pr_num: int,
org: str,
project: str,
... | TryMergeExplainer |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 22497,
"end": 24275
} | class ____(TypedDict, total=False):
type: Required[Literal['int']]
multiple_of: int
le: int
ge: int
lt: int
gt: int
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def int_schema(
*,
multiple_of: int | None = None,
le: int | None = None,
... | IntSchema |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-netsuite/source_netsuite/streams.py | {
"start": 12088,
"end": 12244
} | class ____(IncrementalNetsuiteStream):
@property
def cursor_field(self) -> str:
return CUSTOM_INCREMENTAL_CURSOR
| CustomIncrementalNetsuiteStream |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 915561,
"end": 916265
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Ref."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("RefEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Fi... | RefConnection |
python | davidhalter__jedi | jedi/inference/value/iterable.py | {
"start": 6373,
"end": 6508
} | class ____:
def _get_generics(self):
return tuple(c_set.py__class__() for c_set in self.get_mapping_item_values())
| _DictMixin |
python | lazyprogrammer__machine_learning_examples | airline/ann.py | {
"start": 965,
"end": 5556
} | class ____(object):
def __init__(self, hidden_layer_sizes):
self.hidden_layer_sizes = hidden_layer_sizes
def fit(self, X, Y, activation=T.tanh, learning_rate=1e-3, mu=0.5, reg=0, epochs=5000, batch_sz=None, print_period=100, show_fig=True):
X = X.astype(np.float32)
Y = Y.astype(np.float... | ANN |
python | joke2k__faker | faker/providers/phone_number/hu_HU/__init__.py | {
"start": 49,
"end": 284
} | class ____(PhoneNumberProvider):
formats = (
"+36 ## ###-####",
"(06)##/###-####",
"(##)/###-####",
"##/###-####",
"##/### ####",
"06-#/### ####",
"06-##/### ####",
)
| Provider |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 328176,
"end": 332532
} | class ____(Response):
"""
Response of tasks.enqueue_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
:param queue_watched: Returns Trueif there are workers or autscalers working
with the queue
:type queue_watched: bool
... | EnqueueManyResponse |
python | mlflow__mlflow | dev/clint/src/clint/linter.py | {
"start": 4012,
"end": 8682
} | class ____:
code: str
range: Range
def _get_indent(s: str) -> int:
return len(s) - len(s.lstrip())
_CODE_BLOCK_HEADER_REGEX = re.compile(r"^\.\.\s+code-block::\s*py(thon)?")
_CODE_BLOCK_OPTION_REGEX = re.compile(r"^:\w+:")
def _get_header_indent(s: str) -> int | None:
if _CODE_BLOCK_HEADER_REGEX.m... | CodeBlock |
python | Pylons__pyramid | src/pyramid/config/views.py | {
"start": 1922,
"end": 7493
} | class ____:
def __init__(self, name):
self.name = name
self.media_views = {}
self.views = []
self.accepts = []
def __discriminator__(self, context, request):
# used by introspection systems like so:
# view = adapters.lookup(....)
# view.__discriminator__(... | MultiView |
python | python-attrs__attrs | tests/test_slots.py | {
"start": 923,
"end": 9605
} | class ____:
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
def my_class(self):
return _... | C1Slots |
python | django__django | tests/m2m_recursive/models.py | {
"start": 1118,
"end": 1312
} | class ____(models.Model):
first = models.ForeignKey(Person, models.CASCADE)
second = models.ForeignKey(Person, models.CASCADE, related_name="+")
first_meet = models.DateField()
| Colleague |
python | django__django | django/db/models/fields/reverse_related.py | {
"start": 578,
"end": 8013
} | class ____(FieldCacheMixin):
"""
Used by ForeignObject to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
# Field flags
auto_created = True
concrete = False
editable = False
is_re... | ForeignObjectRel |
python | prabhupant__python-ds | data_structures/graphs/topological_sort.py | {
"start": 38,
"end": 671
} | class ____:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def topo_sort_util(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False... | Graph |
python | kamyu104__LeetCode-Solutions | Python/minimum-edge-weight-equilibrium-queries-in-a-tree.py | {
"start": 6160,
"end": 6892
} | class ____(object):
def minOperationsQueries(self, n, edges, queries):
"""
:type n: int
:type edges: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
adj = [[] for _ in xrange(n)]
for u, v, w in edges:
w -= 1
... | Solution2 |
python | falconry__falcon | tests/test_request_media.py | {
"start": 831,
"end": 1071
} | class ____:
def on_post(self, req, resp, **kwargs):
self.captured_req_media = req.media
# NOTE(kgriffs): Ensure that the media object is cached
assert self.captured_req_media is req.get_media()
| ResourceCachedMedia |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 13162,
"end": 13353
} | class ____:
inner: sympy.Symbol
# the original symbolic expression represented by inner
inner_expr: sympy.Expr
def __str__(self):
return str(self.inner)
| SymbolicCallArg |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.