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 | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 223338,
"end": 223576
} | class ____(VegaLiteSchema):
"""ConditionalAxisString schema wrapper."""
_schema = {"$ref": "#/definitions/ConditionalAxisString"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ConditionalAxisString |
python | scipy__scipy | scipy/interpolate/_fitpack2.py | {
"start": 32281,
"end": 42119
} | class ____:
""" Base class for Bivariate spline s(x,y) interpolation on the rectangle
[xb,xe] x [yb, ye] calculated from a given set of data points
(x,y,z).
See Also
--------
bisplrep :
a function to find a bivariate B-spline representation of a surface
bisplev :
a function ... | _BivariateSplineBase |
python | kamyu104__LeetCode-Solutions | Python/find-bottom-left-tree-value.py | {
"start": 908,
"end": 1259
} | class ____(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
last_node, q = None, collections.deque([root])
while q:
last_node = q.popleft()
q.extend([n for n in [last_node.right, last_node.left] if n])
... | Solution2 |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 46324,
"end": 56057
} | class ____(BaseTestCase):
def _get_width(self, data, input_arg):
xlsx_content = data.export('xlsx', column_width=input_arg)
wb = load_workbook(filename=BytesIO(xlsx_content))
ws = wb.active
return ws.column_dimensions['A'].width
def _xlsx_cell_values_data(self, cls):
xls... | XLSXTests |
python | kamyu104__LeetCode-Solutions | Python/insert-into-a-binary-search-tree.py | {
"start": 749,
"end": 1182
} | class ____(object):
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
if not root:
root = TreeNode(val)
else:
if val <= root.val:
root.left = self.insertIntoBST(root.left, v... | Solution2 |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_current_flow_closeness.py | {
"start": 98,
"end": 1327
} | class ____:
def test_K4(self):
"""Closeness centrality: K4"""
G = nx.complete_graph(4)
b = nx.current_flow_closeness_centrality(G)
b_answer = {0: 2.0 / 3, 1: 2.0 / 3, 2: 2.0 / 3, 3: 2.0 / 3}
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
... | TestFlowClosenessCentrality |
python | great-expectations__great_expectations | tests/expectations/metrics/conftest.py | {
"start": 930,
"end": 1561
} | class ____(SqlAlchemyExecutionEngine):
def __init__(self, create_temp_table: bool = True, *args, **kwargs):
self.engine = MockSaEngine(dialect=Dialect("sqlite")) # type: ignore[assignment] # FIXME CoP
self._create_temp_table = create_temp_table
self._connection = MockConnection()
s... | MockSqlAlchemyExecutionEngine |
python | MongoEngine__mongoengine | mongoengine/base/metaclasses.py | {
"start": 8999,
"end": 17656
} | class ____(DocumentMetaclass):
"""Metaclass for top-level documents (i.e. documents that have their own
collection in the database.
"""
def __new__(mcs, name, bases, attrs):
flattened_bases = mcs._get_bases(bases)
super_new = super().__new__
# Set default _meta data if base cla... | TopLevelDocumentMetaclass |
python | google__jax | jax/_src/clusters/cluster.py | {
"start": 779,
"end": 6017
} | class ____:
"""Interface for defining a cluster environment.
To enable auto bootstrapping (aka :func:`jax.distributed.initialize()`),
cluster environments need to derive from :class:`ClusterEnv` and implement
:func:`is_env_present`, :func:`get_coordinator_address`,
:func:`get_process_count`, and :func:`get_p... | ClusterEnv |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/slides/base.py | {
"start": 754,
"end": 14100
} | class ____(BaseReader):
"""
Enhanced PowerPoint parser.
Extract text, tables, charts, speaker notes, and optionally caption images.
Supports multithreaded processing and LLM-based content consolidation.
Always returns one Document per slide.
"""
def __init__(
self,
extract_... | PptxReader |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 8412,
"end": 8570
} | class ____(AtomicRule):
"""integrate(1/x, x) -> ln(x)"""
base: Expr
def eval(self) -> Expr:
return log(self.base)
@dataclass
| ReciprocalRule |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 1521,
"end": 1828
} | class ____(OAuth2Error):
error = "insecure_transport"
description = "OAuth 2 MUST utilize https."
@classmethod
def check(cls, uri):
"""Check and raise InsecureTransportError with the given URI."""
if not is_secure_transport(uri):
raise cls()
| InsecureTransportError |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 10170,
"end": 10572
} | class ____(BaseSafeMigrationTest):
app = "bad_flow_delete_model_double_pending_app"
migrate_from = "0001"
migrate_to = "0003"
def test(self) -> None:
with pytest.raises(
LookupError,
match="App 'bad_flow_delete_model_double_pending_app' doesn't have a 'TestTable' model",... | DeletionModelBadDeleteDoublePendingTest |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 19303,
"end": 19510
} | class ____(BaseModel):
consensus_thread_status: Literal[
"working",
] = Field(..., description="")
last_update: Union[datetime, date] = Field(..., description="")
| ConsensusThreadStatusOneOf |
python | sqlalchemy__sqlalchemy | test/sql/test_quote.py | {
"start": 34071,
"end": 35219
} | class ____(fixtures.TestBase):
dialect = default.DefaultDialect()
@testing.combinations(
("NAME", "name", False),
("NA ME", "NA ME", False),
("NaMe", "NaMe", False),
("姓名", "姓名", False),
("name", "name", True), # an all-lower case name needs quote forced
)
def t... | NameNormalizeTest |
python | Lightning-AI__lightning | examples/pytorch/domain_templates/reinforce_learn_ppo.py | {
"start": 2868,
"end": 4026
} | class ____(nn.Module):
"""Policy network, for continuous action spaces, which returns a distribution and an action given an
observation."""
def __init__(self, actor_net, act_dim):
"""
Args:
input_shape: observation shape of the environment
n_actions: number of discre... | ActorContinuous |
python | optuna__optuna | optuna/search_space/intersection.py | {
"start": 1470,
"end": 5386
} | class ____:
"""A class to calculate the intersection search space of a :class:`~optuna.study.Study`.
Intersection search space contains the intersection of parameter distributions that have been
suggested in the completed trials of the study so far.
If there are multiple parameters that have the same n... | IntersectionSearchSpace |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called_extensions_py310.py | {
"start": 143,
"end": 258
} | class ____(ExtensionProtocol):
"""A protocol without __init__ using Protocol from typing_extensions."""
| TestProto |
python | google__pytype | pytype/tests/test_fiddle_overlay.py | {
"start": 397,
"end": 649
} | class ____(Generic[T], Buildable[T]):
def __call__(self, *args, **kwargs): ...
"""
_DATACLASS_NESTED_ANNOTATED_METHOD_SNIPPET = """
import dataclasses
import class_with_annotated_method as cwam
import fiddle
@dataclasses.dataclass(frozen=True)
| Partial |
python | readthedocs__readthedocs.org | readthedocs/projects/views/base.py | {
"start": 359,
"end": 1401
} | class ____:
"""Add project onboard context data to project object views."""
def get_context_data(self, **kwargs):
"""Add onboard context data."""
context = super().get_context_data(**kwargs)
# If more than 1 project, don't show onboarding at all. This could
# change in the futur... | ProjectOnboardMixin |
python | openai__openai-python | src/openai/types/responses/response_input_message_item.py | {
"start": 310,
"end": 1029
} | class ____(BaseModel):
id: str
"""The unique ID of the message input."""
content: ResponseInputMessageContentList
"""
A list of one or many input items to the model, containing different content
types.
"""
role: Literal["user", "system", "developer"]
"""The role of the message inpu... | ResponseInputMessageItem |
python | huggingface__transformers | src/transformers/models/ijepa/configuration_ijepa.py | {
"start": 714,
"end": 5262
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`IJepaModel`]. It is used to instantiate an IJEPA
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configur... | IJepaConfig |
python | mlflow__mlflow | mlflow/utils/credentials.py | {
"start": 529,
"end": 8050
} | class ____(NamedTuple):
username: str | None
password: str | None
def _get_credentials_path() -> str:
return os.path.expanduser("~/.mlflow/credentials")
def _read_mlflow_creds_from_file() -> tuple[str | None, str | None]:
path = _get_credentials_path()
if not os.path.exists(path):
return... | MlflowCreds |
python | h5py__h5py | h5py/tests/test_file.py | {
"start": 28505,
"end": 29623
} | class ____:
def test_mpio(self, mpi_file_name):
""" MPIO driver and options """
from mpi4py import MPI
with File(mpi_file_name, 'w', driver='mpio', comm=MPI.COMM_WORLD) as f:
assert f
assert f.driver == 'mpio'
def test_mpio_append(self, mpi_file_name):
"... | TestMPI |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 8921,
"end": 9810
} | class ____(RecordTransformation):
"""
Makes request to provided endpoint and updates record with retrieved data.
requester: Requester
record_selector: HttpSelector
"""
requester: Requester
record_selector: HttpSelector
def transform(
self,
record: Dict[str, Any],
... | AddFieldsFromEndpointTransformation |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 42350,
"end": 43878
} | class ____(SemiIncrementalMixin, GitHubGraphQLStream):
"""
API docs: https://docs.github.com/en/graphql/reference/objects#projectv2
"""
is_sorted = "asc"
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
repository = response.json()["data"]["repository"]... | ProjectsV2 |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0056_add_disable_analytics.py | {
"start": 149,
"end": 724
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0055_change_help_text_description"),
]
operations = [
migrations.AddField(
model_name="project",
name="analytics_disabled",
field=models.BooleanField(
... | Migration |
python | walkccc__LeetCode | solutions/2156. Find Substring With Given Hash Value/2156.py | {
"start": 0,
"end": 521
} | class ____:
def subStrHash(
self,
s: str,
power: int,
modulo: int,
k: int,
hashValue: int,
) -> str:
maxPower = pow(power, k, modulo)
hash = 0
def val(c: str) -> int:
return ord(c) - ord('a') + 1
for i, c in reversed(list(enumerate(s))):
hash = (hash... | Solution |
python | eth-brownie__brownie | brownie/utils/docopt.py | {
"start": 13854,
"end": 14360
} | class ____(_BranchPattern):
def match(self, left: list[_Pattern], collected: list[_Pattern] | None = None) -> Any:
collected = [] if collected is None else collected
outcomes = []
for pattern in self.children:
matched, _, _ = outcome = pattern.match(left, collected)
i... | _Either |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_doc_integration_details.py | {
"start": 4541,
"end": 12654
} | class ____(DocIntegrationDetailsTest):
method = "PUT"
payload: dict[str, Any] = {
"name": "Enemy",
"author": "Imagine Dragons",
"description": "An opening theme song 👀",
"url": "https://github.com/getsentry/sentry/",
"popularity": 5,
"resources": [{"title": "Docs... | PutDocIntegrationDetailsTest |
python | PyCQA__pylint | tests/functional/u/unpacking/unpacking_non_sequence.py | {
"start": 967,
"end": 1098
} | class ____(type):
"metaclass that makes classes that use it iterables"
def __iter__(cls):
return iter((1, 2))
| MetaIter |
python | chroma-core__chroma | chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py | {
"start": 213,
"end": 4579
} | class ____(EmbeddingFunction[Documents]):
# Since we do dynamic imports we have to type this as Any
models: Dict[str, Any] = {}
# If you have a beefier machine, try "gtr-t5-large".
# for a full list of options: https://huggingface.co/sentence-transformers, https://www.sbert.net/docs/pretrained_models.h... | SentenceTransformerEmbeddingFunction |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 1382,
"end": 1469
} | class ____(Item):
name = Field()
url = Field()
price = Field()
@attr.s
| MyItem |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/llms/types.py | {
"start": 7435,
"end": 10595
} | class ____(BaseModel):
"""A representation of video data to directly pass to/from the LLM."""
block_type: Literal["video"] = "video"
video: bytes | IOBase | None = None
path: FilePath | None = None
url: AnyUrl | str | None = None
video_mimetype: str | None = None
detail: str | None = None
... | VideoBlock |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/metadata_checks_component.py | {
"start": 3443,
"end": 3784
} | class ____(Component, Resolvable):
checks: Sequence[MetadataCheck]
def build_defs(self, context: ComponentLoadContext) -> Definitions:
return Definitions(
asset_checks=[
check for metadata_check in self.checks for check in metadata_check.build_checks()
]
... | MetadataChecksComponent |
python | coleifer__peewee | tests/fields.py | {
"start": 50685,
"end": 51313
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [InvalidTypes]
def test_invalid_data_types(self):
it = InvalidTypes.create(tfield=100, ifield='five', ffield='pi')
it_db1 = InvalidTypes.get(InvalidTypes.tfield == 100)
it_db2 = InvalidTypes.get(InvalidTypes.ifield ... | TestSqliteInvalidDataTypes |
python | django__django | tests/utils_tests/test_timezone.py | {
"start": 330,
"end": 9650
} | class ____(SimpleTestCase):
def test_default_timezone_is_zoneinfo(self):
self.assertIsInstance(timezone.get_default_timezone(), zoneinfo.ZoneInfo)
def test_now(self):
with override_settings(USE_TZ=True):
self.assertTrue(timezone.is_aware(timezone.now()))
with override_settin... | TimezoneTests |
python | kamyu104__LeetCode-Solutions | Python/fraction-to-recurring-decimal.py | {
"start": 76,
"end": 856
} | class ____(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
result = ""
if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
result = "-"
... | Solution |
python | numpy__numpy | numpy/polynomial/tests/test_symbol.py | {
"start": 1533,
"end": 2095
} | class ____:
p = poly.Polynomial([1, 2, 3], symbol='z')
def test_neg(self):
n = -self.p
assert_equal(n.symbol, 'z')
def test_scalarmul(self):
out = self.p * 10
assert_equal(out.symbol, 'z')
def test_rscalarmul(self):
out = 10 * self.p
assert_equal(out.sy... | TestUnaryOperators |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 33370,
"end": 36567
} | class ____(FlavaPreTrainedModel):
config: FlavaImageConfig
# This override allows us to load FlavaImageModel from FlavaModel/FlavaForPreTraining checkpoints.
base_model_prefix = "flava.image_model"
main_input_name = "pixel_values"
input_modalities = ("image",)
def __init__(self, config: FlavaIm... | FlavaImageModel |
python | pytest-dev__pytest | src/_pytest/config/__init__.py | {
"start": 34587,
"end": 79178
} | class ____:
"""Access to configuration values, pluginmanager and plugin hooks.
:param PytestPluginManager pluginmanager:
A pytest PluginManager.
:param InvocationParams invocation_params:
Object containing parameters regarding the :func:`pytest.main`
invocation.
"""
@final... | Config |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1503787,
"end": 1505267
} | class ____(sgqlc.types.Type, Node):
"""Represents the rollup for both the check runs and status for a
commit.
"""
__schema__ = github_schema
__field_names__ = ("commit", "contexts", "state")
commit = sgqlc.types.Field(Commit, graphql_name="commit")
"""The commit the status and check runs ar... | StatusCheckRollup |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 23119,
"end": 23567
} | class ____(MarkdownBlock):
"""A list item Markdown block."""
DEFAULT_CSS = """
MarkdownListItem {
layout: horizontal;
margin-right: 1;
height: auto;
}
MarkdownListItem > Vertical {
width: 1fr;
height: auto;
}
"""
def __init__(self, markdown: Mar... | MarkdownListItem |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolModule3.py | {
"start": 140,
"end": 247
} | class ____(Protocol[Y]):
def __call__(self, y: Y) -> None: ...
def x(x: Fn[int]) -> None:
print(x)
| Fn |
python | kamyu104__LeetCode-Solutions | Python/wildcard-matching.py | {
"start": 2657,
"end": 3151
} | class ____(object):
# @return a boolean
def isMatch(self, s, p):
if not p or not s:
return not s and not p
if p[0] != '*':
if p[0] == s[0] or p[0] == '?':
return self.isMatch(s[1:], p[1:])
else:
return False
else:
... | Solution4 |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 114593,
"end": 114739
} | class ____(BaseModel):
pairs: List["SearchMatrixPair"] = Field(..., description="List of pairs of points with scores")
| SearchMatrixPairsResponse |
python | pytorch__pytorch | torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py | {
"start": 4692,
"end": 40498
} | class ____:
r"""
Store both the algorithm's hyperparameters and internal state for all gradients during training.
Particularly, ``matrix_approximation_rank`` and ``start_powerSGD_iter`` are the main hyperparameters that should be tuned by the user.
For performance, we suggest to keep binary hyperparame... | PowerSGDState |
python | great-expectations__great_expectations | great_expectations/render/renderer/observed_value_renderer.py | {
"start": 343,
"end": 2212
} | class ____:
name: str
value: str
def _prepare_params_for_list_comparison(
params: "_RendererValueBase",
expected_prefix: str,
observed_prefix: str,
) -> str:
"""
This function mutates the `params` argument to set the render_state of each variable entry.
Return:
A template strin... | TemplateStrVariable |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 395879,
"end": 396312
} | class ____(sgqlc.types.Interface):
"""An individual line of a hovercard"""
__schema__ = github_schema
__field_names__ = ("message", "octicon")
message = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="message")
"""A string describing this context"""
octicon = sgqlc.types.Field(sg... | HovercardContext |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image22.py | {
"start": 315,
"end": 847
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image22.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-drive/source_google_drive/stream_reader.py | {
"start": 2645,
"end": 3219
} | class ____(RemoteFile):
id: str
# The mime type of the file as returned by the Google Drive API
# This is not the same as the mime type when opened by the parser (e.g. google docs is exported as docx)
original_mime_type: str
view_link: str
# Only populated for items in shared drives.
drive_i... | GoogleDriveRemoteFile |
python | walkccc__LeetCode | solutions/3105. Longest Strictly Increasing or Strictly Decreasing Subarray/3105.py | {
"start": 0,
"end": 489
} | class ____:
# Similar to 978. Longest Turbulent Subarray
def longestMonotonicSubarray(self, nums: list[int]) -> int:
ans = 1
increasing = 1
decreasing = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
increasing += 1
decreasing = 1
elif nums[i] < nums[i - 1]:
... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass7.py | {
"start": 243,
"end": 342
} | class ____(type):
def __call__(cls, **kwargs):
return object.__new__(**kwargs)
| MetaClass1 |
python | coleifer__peewee | tests/fields.py | {
"start": 17097,
"end": 17233
} | class ____(ModelTestCase):
requires = [Composite]
def test_composite_primary_key(self):
pass
| TestCompositePrimaryKeyField |
python | mlflow__mlflow | tests/pyfunc/test_responses_agent.py | {
"start": 2857,
"end": 3307
} | class ____(ResponsesAgent):
def predict(self, request: ResponsesAgentRequest) -> ResponsesAgentResponse:
mock_response = get_mock_response(request)
return ResponsesAgentResponse(**mock_response)
def predict_stream(
self, request: ResponsesAgentRequest
) -> Generator[ResponsesAgentSt... | SimpleResponsesAgent |
python | wandb__wandb | wandb/sdk/internal/file_pusher.py | {
"start": 612,
"end": 6023
} | class ____:
"""Parallel file upload class.
This manages uploading multiple files in parallel. It will restart a given file's
upload job if it receives a notification that that file has been modified. The
finish() method will block until all events have been processed and all uploads are
complete.
... | FilePusher |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/definition/asset_dep.py | {
"start": 1057,
"end": 6488
} | class ____(
NamedTuple(
"_AssetDep",
[
("asset_key", PublicAttr[AssetKey]),
("partition_mapping", PublicAttr[Optional[PartitionMapping]]),
],
)
):
"""Specifies a dependency on an upstream asset.
Args:
asset (Union[AssetKey, str, AssetSpec, AssetsD... | AssetDep |
python | pyparsing__pyparsing | examples/booleansearchparser.py | {
"start": 10746,
"end": 15486
} | class ____(BooleanSearchParser):
"""Tests the parser with some search queries
tests contains a dictionary with tests and expected results.
"""
def Test(self):
# fmt: off
exprs = {
"0": "help",
"1": "help or hulp",
"2": "help and hulp",
"3"... | ParserTest |
python | PrefectHQ__prefect | tests/server/models/test_concurrency_limits.py | {
"start": 4296,
"end": 6033
} | class ____:
async def test_reading_concurrency_limits_by_id(self, session):
concurrency_limit = await models.concurrency_limits.create_concurrency_limit(
session=session,
concurrency_limit=schemas.core.ConcurrencyLimit(
tag="hide and seek", concurrency_limit=4242
... | TestReadingSingleConcurrencyLimits |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hide01.py | {
"start": 315,
"end": 880
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hide01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filena... | TestCompareXLSXFiles |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/12_Proximal_Policy_Optimization/discrete_DPPO.py | {
"start": 1196,
"end": 4814
} | class ____(object):
def __init__(self):
self.sess = tf.Session()
self.tfs = tf.placeholder(tf.float32, [None, S_DIM], 'state')
# critic
w_init = tf.random_normal_initializer(0., .1)
lc = tf.layers.dense(self.tfs, 200, tf.nn.relu, kernel_initializer=w_init, name='lc')
... | PPONet |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/test_error/package.py | {
"start": 217,
"end": 659
} | class ____(Package):
"""This package has a test method that fails in a subprocess."""
homepage = "http://www.example.com/test-failure"
url = "http://www.test-failure.test/test-failure-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
def install(self, spec, prefix):
mkdir... | TestError |
python | run-llama__llama_index | llama-index-core/llama_index/core/data_structs/data_structs.py | {
"start": 4433,
"end": 4908
} | class ____(IndexStruct):
"""A list of documents."""
nodes: List[str] = field(default_factory=list)
def add_node(self, node: BaseNode) -> None:
"""Add text to table, return current position in list."""
# don't worry about child indices for now, nodes are all in order
self.nodes.appe... | IndexList |
python | getsentry__sentry | src/sentry/core/endpoints/team_projects.py | {
"start": 5052,
"end": 5330
} | class ____(TeamPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin"],
"POST": ["project:write", "project:admin"],
"PUT": ["project:write", "project:admin"],
"DELETE": ["project:admin"],
}
| TeamProjectPermission |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 46333,
"end": 47201
} | class ____(nn.Module):
"""Learned Augmented Residual Layer"""
def __init__(self, config: Gemma3nTextConfig):
super().__init__()
self.config = config
self.linear_left = nn.Linear(self.config.hidden_size, self.config.laurel_rank, bias=False)
self.linear_right = nn.Linear(self.con... | Gemma3nTextLaurelBlock |
python | jschneier__django-storages | tests/test_dropbox.py | {
"start": 6685,
"end": 7916
} | class ____(TestCase):
def test_jailed(self, *args):
self.storage = dropbox.DropboxStorage("foo", root_path="/bar")
dirs, files = self.storage.listdir("/")
self.assertFalse(dirs)
self.assertFalse(files)
@mock.patch("dropbox.Dropbox.files_upload", return_value="foo")
@mock.pat... | DropboxRootPathTest |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 11598,
"end": 11920
} | class ____(BaseManager["AlertRuleTriggerAction"]):
"""
A manager that excludes trigger actions that are pending to be deleted
"""
def get_queryset(self) -> BaseQuerySet[AlertRuleTriggerAction]:
return super().get_queryset().exclude(status=ObjectStatus.PENDING_DELETION)
| AlertRuleTriggerActionManager |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datafusion.py | {
"start": 6387,
"end": 7445
} | class ____:
@mock.patch(HOOK_STR)
def test_execute_check_hook_call_should_execute_successfully(self, mock_hook):
mock_hook.return_value.get_instance.return_value = {
"apiEndpoint": INSTANCE_URL,
"serviceEndpoint": INSTANCE_URL,
}
op = CloudDataFusionCreatePipeline... | TestCloudDataFusionCreatePipelineOperator |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 14059,
"end": 14468
} | class ____(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
def forward(self, hidden_states):
hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
hidden_... | Emu3VQVAEEncoderConvUpsample |
python | django__django | tests/model_fields/test_imagefield.py | {
"start": 11598,
"end": 12321
} | class ____(ImageFieldTwoDimensionsTests):
"""
Tests behavior of an ImageField with no dimension fields.
"""
PersonModel = Person
def test_post_init_not_connected(self):
person_model_id = id(self.PersonModel)
self.assertNotIn(
person_model_id,
[sender_id for ... | ImageFieldNoDimensionsTests |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 16101,
"end": 19155
} | class ____(graphene.ObjectType):
dynamicPartitionsRequests = graphene.List(graphene.NonNull(GrapheneDynamicPartitionsRequest))
runRequests = graphene.List(lambda: graphene.NonNull(GrapheneRunRequest))
skipReason = graphene.String()
error = graphene.Field(GraphenePythonError)
cursor = graphene.String... | GrapheneTickEvaluation |
python | pypa__pip | src/pip/_vendor/rich/traceback.py | {
"start": 7787,
"end": 7948
} | class ____:
offset: int
filename: str
line: str
lineno: int
msg: str
notes: List[str] = field(default_factory=list)
@dataclass
| _SyntaxError |
python | PyCQA__flake8 | example-plugin/src/flake8_example_plugin/on_by_default.py | {
"start": 69,
"end": 243
} | class ____:
"""First Example Plugin."""
def __init__(self, tree):
self.tree = tree
def run(self):
"""Do nothing."""
yield from []
| ExampleOne |
python | walkccc__LeetCode | solutions/3147. Taking Maximum Energy From the Mystic Dungeon/3147.py | {
"start": 0,
"end": 240
} | class ____:
def maximumEnergy(self, energy: list[int], k: int) -> int:
# dp[i] := the sum of energy starting at i
dp = energy.copy()
for i in range(len(energy) - 1 - k, -1, -1):
dp[i] += dp[i + k]
return max(dp)
| Solution |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 41702,
"end": 44410
} | class ____:
"""
Test functions that are similar to gufuncs
"""
def test_cross(self):
q1 = np.arange(6.0).reshape(2, 3) * u.m
q2 = np.array([4.0, 5.0, 6.0]) / u.s
o = np.cross(q1, q2)
expected = np.cross(q1.value, q2.value) * u.m / u.s
assert np.all(o == expected)... | TestVariousProductFunctions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 33404,
"end": 33562
} | class ____:
inside_results_array: bool = False
array_nesting_depth: int = 0
expecting_results_array_start: bool = False
@dataclass
| ResultsArrayState |
python | pypa__setuptools | setuptools/unicode_utils.py | {
"start": 2296,
"end": 3189
} | class ____(SetuptoolsDeprecationWarning):
_SUMMARY = """
`encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`.
"""
_DETAILS = """
Fallback behavior for UTF-8 is considered **deprecated** and future versions of
`setuptools` may not implement it.
Please encode {fil... | _Utf8EncodingNeeded |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/PlotItem/PlotItem.py | {
"start": 752,
"end": 61869
} | class ____(GraphicsWidget):
"""
GraphicsWidget implementing a standard 2D plotting area with axes.
**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
This class provides the ViewBox-plus-axes that appear when using
:func:`pg.plot() <pyqtgraph.plot>`, :class:`PlotWidget <pyqtgraph.Pl... | PlotItem |
python | ray-project__ray | python/ray/train/v2/_internal/execution/checkpoint/sync_actor.py | {
"start": 1004,
"end": 8732
} | class ____:
"""A Ray actor that synchronizes the workers in a distributed training job.
This actor forms a synchronization barrier on a group of processes.
Every time a worker calls the broadcast_from_rank_zero method,
the counter is incremented. When the counter equals to the world size,
the actor... | SynchronizationActor |
python | viewflow__viewflow | tests/components/__init__.py | {
"start": 198,
"end": 1447
} | class ____(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
geckodriver_path = shutil.which("geckodriver")
cls.assertTrue(geckodriver_path, "`geckodriver` not found")
driver_service = webdriver.FirefoxService(executable_path=geckodriver_path)
... | LiveTestCase |
python | conda__conda | conda/plugins/reporter_backends/json.py | {
"start": 2855,
"end": 3552
} | class ____(SpinnerBase):
"""
This class for a JSONSpinner does nothing because we do not want to include this output.
"""
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
@hookimpl(
tryfirst=True
) # make sure the default json reporter backend ca... | JSONSpinner |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/instance/runs/run_domain.py | {
"start": 2714,
"end": 47486
} | class ____:
"""Domain object encapsulating run-related operations.
This class holds a reference to a DagsterInstance and provides methods
for creating, managing, and querying runs.
"""
def __init__(self, instance: "DagsterInstance") -> None:
self._instance = instance
def create_run(
... | RunDomain |
python | getsentry__sentry | tests/acceptance/test_onboarding.py | {
"start": 284,
"end": 5064
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.member =... | OrganizationOnboardingTest |
python | django__django | tests/postgres_tests/test_array.py | {
"start": 27498,
"end": 28358
} | class ____(PostgreSQLTestCase):
@classmethod
def setUpTestData(cls):
now = timezone.now()
cls.datetimes = [now]
cls.dates = [now.date()]
cls.times = [now.time()]
cls.objs = [
DateTimeArrayModel.objects.create(
datetimes=cls.datetimes, dates=cls... | TestDateTimeExactQuerying |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-matching-indices-after-right-shifts.py | {
"start": 45,
"end": 344
} | class ____(object):
def maximumMatchingIndices(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
return max(sum(nums2[j] == nums1[(i+j)%len(nums1)] for j in xrange(len(nums2))) for i in xrange(len(nums1)))
| Solution |
python | marshmallow-code__apispec | src/apispec/exceptions.py | {
"start": 508,
"end": 616
} | class ____(APISpecError):
"""Raised when parameter doesn't contains required keys"""
| InvalidParameterError |
python | EpistasisLab__tpot | tpot/search_spaces/pipelines/graph.py | {
"start": 35333,
"end": 36496
} | class ____():
'''
A class that can be used as a key for a graph.
Parameters
----------
graph : (nx.Graph)
The graph to use as a key. Node Attributes are used for the hash.
matched_label : (str)
The node attribute to consider for the hash.
'''
def __init__(self, graph, m... | GraphKey |
python | pypa__pipenv | pipenv/exceptions.py | {
"start": 8229,
"end": 8628
} | class ____(VirtualenvException):
def __init__(self, message=None, **kwargs):
if not message:
message = (
"activate_this.py not found. Your environment is most certainly "
"not activated. Continuing anyway..."
)
self.message = message
Vi... | VirtualenvActivationException |
python | boto__boto3 | tests/functional/test_resource.py | {
"start": 1430,
"end": 1770
} | class ____(unittest.TestCase):
def test_has_good_error_message_when_no_resource(self):
bad_resource_name = 'doesnotexist'
err_regex = f'{bad_resource_name}.*resource does not exist.'
with pytest.raises(ResourceNotExistsError, match=err_regex):
boto3.resource(bad_resource_name)
| TestSessionErrorMessages |
python | kamyu104__LeetCode-Solutions | Python/sum-of-prefix-scores-of-strings.py | {
"start": 144,
"end": 771
} | class ____(object):
def sumPrefixScores(self, words):
"""
:type words: List[str]
:rtype: List[int]
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for w in words:
curr = trie
for c in w:
curr = curr[c]
... | Solution |
python | google__jax | jax/_src/pallas/fuser/block_spec.py | {
"start": 20633,
"end": 21088
} | class ____(Protocol):
def __call__(
self,
ctx: KernelEvalContext,
*args: Any,
**params: Any,
) -> Sequence[Any]:
...
eval_rules: dict[core.Primitive, EvalRuleFn] = {}
def register_eval_rule(
prim: core.Primitive,
) -> Callable[[EvalRuleFn], EvalRuleFn]:
def wrapper(
f: E... | EvalRuleFn |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/input.py | {
"start": 12828,
"end": 13618
} | class ____(
NamedTuple(
"_FanInInputPointer", [("node_name", str), ("input_name", str), ("fan_in_index", int)]
)
):
def __new__(cls, node_name: str, input_name: str, fan_in_index: int):
return super().__new__(
cls,
check.str_param(node_name, "node_name"),
... | FanInInputPointer |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/73_class_generic.py | {
"start": 0,
"end": 23
} | class ____[T]:
x: T
| Foo |
python | geekcomputers__Python | CliYoutubeDownloader.py | {
"start": 34,
"end": 2513
} | class ____:
def __init__(self):
self.url = str(input("Enter the url of video : "))
self.youtube = YouTube(
self.url, on_progress_callback=YouTubeDownloder.onProgress
)
self.showTitle()
def showTitle(self):
print("title : {0}\n".format(self.youtube.title))
... | YouTubeDownloder |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/types.py | {
"start": 1621,
"end": 2739
} | class ____(ArgNotSet):
"""Sentinel type for annotations, useful when a value is dynamic and set during Execution but not parsing."""
@staticmethod
def serialize() -> str:
return "DYNAMIC (set during execution)"
SET_DURING_EXECUTION = SetDuringExecution()
"""Sentinel value for argument default. Se... | SetDuringExecution |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 16661,
"end": 16730
} | class ____(AugmentedAssignment):
binop = '*'
| MulAugmentedAssignment |
python | openai__openai-python | src/openai/types/realtime/response_mcp_call_completed.py | {
"start": 201,
"end": 563
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the MCP tool call item."""
output_index: int
"""The index of the output item in the response."""
type: Literal["response.mcp_call.completed"]
"""The event type, must be `response.mc... | ResponseMcpCallCompleted |
python | numba__numba | numba/tests/test_dictimpl.py | {
"start": 395,
"end": 4647
} | class ____(object):
"""A wrapper around the C-API to provide a minimal dictionary object for
testing.
"""
def __init__(self, tc, keysize, valsize):
"""
Parameters
----------
tc : TestCase instance
keysize : int
byte size for the key
valsize : i... | Dict |
python | pytest-dev__pluggy | src/pluggy/_hooks.py | {
"start": 20826,
"end": 22481
} | class ____(HookCaller):
"""A proxy to another HookCaller which manages calls to all registered
plugins except the ones from remove_plugins."""
# This class is unusual: in inhertits from `HookCaller` so all of
# the *code* runs in the class, but it delegates all underlying *data*
# to the original H... | _SubsetHookCaller |
python | gevent__gevent | src/gevent/_ffi/watcher.py | {
"start": 18065,
"end": 18119
} | class ____(object):
_watcher_type = 'fork'
| ForkMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.