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 | tensorflow__tensorflow | tensorflow/python/client/timeline.py | {
"start": 12955,
"end": 30057
} | class ____(object):
"""A class for visualizing execution timelines of TensorFlow steps."""
def __init__(
self, step_stats: step_stats_pb2.StepStats, graph: Optional[Any] = None
) -> None:
"""Constructs a new Timeline.
A 'Timeline' is used for visualizing the execution of a TensorFlow
computati... | Timeline |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 20839,
"end": 21558
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MegatronBertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hi... | MegatronBertLMPredictionHead |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/asset_decorator.py | {
"start": 18040,
"end": 19236
} | class ____(NamedTuple):
required_resource_keys: AbstractSet[str]
name: Optional[str]
key_prefix: Optional[CoercibleToAssetKeyPrefix]
ins: Mapping[str, AssetIn]
deps: Iterable[AssetDep]
metadata: Optional[ArbitraryMetadataMapping]
tags: Optional[Mapping[str, str]]
description: Optional[st... | AssetDecoratorArgs |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 31299,
"end": 32319
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("hu_HU")
Faker.seed(0)
def test_ssn(self):
for _ in range(100):
ssn = self.fake.ssn()
assert ssn.isdigit()
assert len(ssn) >= 10
assert len(ssn) <= 12
for _ in rang... | TestHuHU |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 584838,
"end": 585197
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("errors",)
errors = sgqlc.types.Field(
sgqlc.types.non_null(
sgqlc.types.list_of(sgqlc.types.non_null("RepositoryCodeownersError"))
),
graphql_... | RepositoryCodeowners |
python | pytorch__pytorch | torch/fx/proxy.py | {
"start": 2224,
"end": 3541
} | class ____:
"""A context manager to track the Scope of Node during symbolic tracing.
When entering a forward function of a Module, we'll update the scope information of
the current module, and when we exit, we'll restore the previous scope information.
"""
def __init__(
self,
scope:... | ScopeContextManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 465394,
"end": 465862
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AddLabelsToLabelable"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "labelable")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the... | AddLabelsToLabelablePayload |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_insights_tree.py | {
"start": 352,
"end": 5505
} | class ____(
OrganizationEventsEndpointTestBase, SnubaTestCase, SpanTestCase
):
url_name = "sentry-api-0-organization-insights-tree"
FEATURES = ["organizations:trace-spans-format"]
def setUp(self) -> None:
super().setUp()
self.ten_mins_ago = before_now(minutes=10)
self.features =... | OrganizationInsightsTreeEndpointTest |
python | walkccc__LeetCode | solutions/2097. Valid Arrangement of Pairs/2097.py | {
"start": 0,
"end": 705
} | class ____:
def validArrangement(self, pairs: list[list[int]]) -> list[list[int]]:
ans = []
graph = collections.defaultdict(list)
outDegree = collections.Counter()
inDegrees = collections.Counter()
for start, end in pairs:
graph[start].append(end)
outDegree[start] += 1
inDegrees... | Solution |
python | scipy__scipy | scipy/stats/_sensitivity_analysis.py | {
"start": 4366,
"end": 25123
} | class ____:
first_order: np.ndarray
total_order: np.ndarray
_indices_method: Callable
_f_A: np.ndarray
_f_B: np.ndarray
_f_AB: np.ndarray
_A: np.ndarray | None = None
_B: np.ndarray | None = None
_AB: np.ndarray | None = None
_bootstrap_result: BootstrapResult | None = None
... | SobolResult |
python | ansible__ansible | lib/ansible/modules/mount_facts.py | {
"start": 8553,
"end": 26018
} | class ____:
mount_point: str
line: str
fields: dict[str, str | dict[str, str]]
def replace_octal_escapes(value: str) -> str:
return re.sub(r"(\\[0-7]{3})", lambda m: codecs.decode(m.group(0), "unicode_escape"), value)
@functools.lru_cache(maxsize=None)
def get_device_by_uuid(module: AnsibleModule, u... | MountInfoOptions |
python | pypa__pipenv | pipenv/vendor/tomlkit/toml_file.py | {
"start": 303,
"end": 1627
} | class ____:
"""
Represents a TOML file.
:param path: path to the TOML file
"""
def __init__(self, path: _StrPath) -> None:
self._path = path
self._linesep = os.linesep
def read(self) -> TOMLDocument:
"""Read the file content as a :class:`tomlkit.toml_document.TOMLDocum... | TOMLFile |
python | pydata__xarray | xarray/tests/test_units.py | {
"start": 187021,
"end": 190824
} | class ____(PlotTestCase):
@pytest.mark.parametrize(
"coord_unit, coord_attrs",
[
(1, {"units": "meter"}),
pytest.param(
unit_registry.m,
{},
marks=pytest.mark.xfail(reason="indexes don't support units"),
),
]... | TestPlots |
python | ApeWorX__ape | src/ape_node/provider.py | {
"start": 18131,
"end": 27762
} | class ____(EthereumNodeProvider, TestProviderAPI, SubprocessProvider):
_process: Optional[GethDevProcess] = None
name: str = "node"
@property
def process_name(self) -> str:
if self._process:
return self._process.process_name
elif exec_cfg := self.config.executable:
... | GethDev |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias3.py | {
"start": 445,
"end": 1043
} | class ____(Generic[T]):
def __new__(cls, value: T) -> "ClassA[T]": ...
TypeAliasA1 = ClassA[T]
a1 = ClassA(3.0)
reveal_type(a1, expected_text="ClassA[float]")
a2 = TypeAliasA1(3)
reveal_type(a2, expected_text="ClassA[Unknown]")
a3 = TypeAliasA1[int](3)
reveal_type(a3, expected_text="ClassA[int]")
TypeAliasA2... | ClassA |
python | doocs__leetcode | solution/2300-2399/2312.Selling Pieces of Wood/Solution.py | {
"start": 0,
"end": 515
} | class ____:
def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
@cache
def dfs(h: int, w: int) -> int:
ans = d[h].get(w, 0)
for i in range(1, h // 2 + 1):
ans = max(ans, dfs(i, w) + dfs(h - i, w))
for i in range(1, w // 2 + 1):
... | Solution |
python | doocs__leetcode | solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.py | {
"start": 0,
"end": 527
} | class ____:
def minRefuelStops(
self, target: int, startFuel: int, stations: List[List[int]]
) -> int:
pq = []
ans = pre = 0
stations.append([target, 0])
for pos, fuel in stations:
dist = pos - pre
startFuel -= dist
while startFuel < 0 ... | Solution |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 11704,
"end": 11948
} | class ____(desc_sig_element, _sig_element=True):
"""Node for a character literal in a signature."""
classes = ['sc']
###############################################################
# new admonition-like constructs
| desc_sig_literal_char |
python | pytorch__pytorch | torch/_dynamo/variables/torch_function.py | {
"start": 11615,
"end": 19510
} | class ____(VariableTracker):
"""Fake VT to use as a dummy object, indicating the presence of torch function mode stack mutation"""
# singleton value representing the global torch function mode stack
# singleton (it exists in C++)
stack_value_singleton = object()
# offset is used to track if we hav... | TorchFunctionModeStackVariable |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/model_parallel.py | {
"start": 14057,
"end": 14351
} | class ____(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager:
"""Blocks gradient synchronization inside the FSDP2 modules."""
return _FSDPNoSync(module=module, enabled=enabled)
| _ParallelBackwardSyncControl |
python | tiangolo__fastapi | docs_src/encoder/tutorial001.py | {
"start": 177,
"end": 461
} | class ____(BaseModel):
title: str
timestamp: datetime
description: Union[str, None] = None
app = FastAPI()
@app.put("/items/{id}")
def update_item(id: str, item: Item):
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
| Item |
python | kamyu104__LeetCode-Solutions | Python/design-a-todo-list.py | {
"start": 2231,
"end": 3918
} | class ____(object):
def __init__(self):
self.__tasks = []
self.__user_task_ids = collections.defaultdict(SortedList)
def addTask(self, userId, taskDescription, dueDate, tags):
"""
:type userId: int
:type taskDescription: str
:type dueDate: int
:type tags... | TodoList2 |
python | Textualize__textual | src/textual/widgets/_data_table.py | {
"start": 7924,
"end": 8111
} | class ____(NamedTuple):
"""Container for a row, which contains an optional label and some data cells."""
label: RenderableType | None
cells: list[RenderableType]
| RowRenderables |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_workflows.py | {
"start": 1924,
"end": 10056
} | class ____:
def setup_method(self, _):
with mock.patch(BASE_PATH.format("GoogleBaseHook.__init__"), new=mock_init):
self.hook = WorkflowsHook(gcp_conn_id="test")
@mock.patch(BASE_PATH.format("WorkflowsHook.get_credentials"))
@mock.patch(BASE_PATH.format("WorkflowsClient"))
def test_... | TestWorkflowsHook |
python | pypa__pipenv | pipenv/vendor/click/_termui_impl.py | {
"start": 843,
"end": 15625
} | class ____(t.Generic[V]):
def __init__(
self,
iterable: t.Optional[t.Iterable[V]],
length: t.Optional[int] = None,
fill_char: str = "#",
empty_char: str = " ",
bar_template: str = "%(bar)s",
info_sep: str = " ",
show_eta: bool = True,
show_per... | ProgressBar |
python | Netflix__metaflow | test/test_config/mutable_flow.py | {
"start": 6411,
"end": 8403
} | class ____(FlowSpec):
trigger_param = Parameter(
"trigger_param",
default="",
)
config = Config("config", default_value=default_config)
def _check(self, step_decorators):
for p in self.config.parameters:
assert hasattr(self, p["name"]), "Missing parameter"
a... | ConfigMutableFlow |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/chains/test_base.py | {
"start": 496,
"end": 1048
} | class ____(BaseMemory):
"""Fake memory class for testing purposes."""
@property
def memory_variables(self) -> list[str]:
"""Return baz variable."""
return ["baz"]
@override
def load_memory_variables(
self,
inputs: dict[str, Any] | None = None,
) -> dict[str, str... | FakeMemory |
python | python-visualization__folium | folium/features.py | {
"start": 7030,
"end": 14959
} | class ____(MacroElement):
"""
Creates a Vega-Lite chart element.
Parameters
----------
data: JSON-like str or object
The Vega-Lite description of the chart.
It can also be any object that has a method `to_json`,
so that you can (for instance) provide an `Altair` chart.
w... | VegaLite |
python | joke2k__faker | faker/providers/currency/fr_CA/__init__.py | {
"start": 46,
"end": 279
} | class ____(CurrencyProvider):
price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"]
def pricetag(self) -> str:
return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}$"
| Provider |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 2292,
"end": 5832
} | class ____(str, Enum):
"""The available vectorization modules in Weaviate.
These modules encode binary data into lists of floats called vectors.
See the [docs](https://weaviate.io/developers/weaviate/modules/retriever-vectorizer-modules) for more details.
Attributes:
NONE: No vectorizer.
... | Vectorizers |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1485031,
"end": 1486458
} | class ____(sgqlc.types.Type, Node):
"""An event related to sponsorship activity."""
__schema__ = github_schema
__field_names__ = ("action", "previous_sponsors_tier", "sponsor", "sponsorable", "sponsors_tier", "timestamp", "via_bulk_sponsorship")
action = sgqlc.types.Field(sgqlc.types.non_null(SponsorsA... | SponsorsActivity |
python | HypothesisWorks__hypothesis | hypothesis-python/examples/example_hypothesis_entrypoint/example_hypothesis_entrypoint.py | {
"start": 624,
"end": 928
} | class ____:
def __init__(self, x: int):
assert x >= 0, f"got {x}, but only positive numbers are allowed"
self.x = x
def _hypothesis_setup_hook():
import hypothesis.strategies as st
st.register_type_strategy(MyCustomType, st.integers(min_value=0).map(MyCustomType))
| MyCustomType |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_indexing.py | {
"start": 22662,
"end": 23259
} | class ____:
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
def test_get_slice_bounds_within(self, side, expected):
index = Index(range(6))
result = index.get_slice_bound(4, side=side)
assert result == expected
@pytest.mark.parametrize("side", ["left", "right... | TestGetSliceBounds |
python | coleifer__peewee | tests/manytomany.py | {
"start": 21131,
"end": 21232
} | class ____(TestModel):
name = TextField()
DeniedThroughDeferred = DeferredThroughModel()
| Permission |
python | django__django | django/contrib/syndication/apps.py | {
"start": 91,
"end": 203
} | class ____(AppConfig):
name = "django.contrib.syndication"
verbose_name = _("Syndication")
| SyndicationConfig |
python | scipy__scipy | scipy/stats/_distribution_infrastructure.py | {
"start": 12230,
"end": 20310
} | class ____(_Domain):
r""" Representation of an interval defined by two endpoints.
Each endpoint may be a finite scalar, positive or negative infinity, or
be given by a single parameter. The domain may include the endpoints or
not.
This class still does not provide an implementation of the __str__ ... | _Interval |
python | palantir__python-language-server | versioneer.py | {
"start": 52511,
"end": 68611
} | class ____(Exception):
"""The project root directory is unknown or missing key files."""
def get_versions(verbose=False):
"""Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'.
"""
if "versioneer" in sys.modules:
# see the discussio... | VersioneerBadRootError |
python | ipython__ipython | tests/test_magic.py | {
"start": 1258,
"end": 10137
} | class ____(magic.Magics):
pass
def test_extract_code_ranges():
instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
expected = [
(0, 1),
(2, 3),
(4, 6),
(6, 9),
(9, 14),
(16, None),
(None, 9),
(9, None),
(None, 13),
(None, None),
... | DummyMagics |
python | ApeWorX__ape | src/ape/managers/compilers.py | {
"start": 903,
"end": 14504
} | class ____(BaseManager, ExtraAttributesMixin):
"""
The singleton that manages :class:`~ape.api.compiler.CompilerAPI` instances.
Each compiler plugin typically contains a single :class:`~ape.api.compiler.CompilerAPI`.
**NOTE**: Typically, users compile their projects using the CLI via ``ape compile``,
... | CompilerManager |
python | pypa__pip | src/pip/_internal/metadata/base.py | {
"start": 24938,
"end": 25159
} | class ____(Wheel):
def __init__(self, location: str) -> None:
self.location = location
def as_zipfile(self) -> zipfile.ZipFile:
return zipfile.ZipFile(self.location, allowZip64=True)
| FilesystemWheel |
python | walkccc__LeetCode | solutions/1037. Valid Boomerang/1037.py | {
"start": 0,
"end": 226
} | class ____:
def isBoomerang(self, points: list[list[int]]) -> bool:
return ((points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) !=
(points[1][1] - points[0][1]) * (points[2][0] - points[1][0]))
| Solution |
python | scipy__scipy | benchmarks/benchmarks/signal.py | {
"start": 6517,
"end": 6762
} | class ____(Benchmark):
param_names = ['n', 'edges']
params = [
[21, 101, 1001, 2001],
[(0.1, 0.9), (0.01, 0.99)],
]
def time_firls(self, n, edges):
signal.firls(n, (0,) + edges + (1,), [1, 1, 0, 0])
| FIRLS |
python | nryoung__algorithms | algorithms/random/mersenne_twister.py | {
"start": 340,
"end": 1594
} | class ____:
def __init__(self):
self.state = []
self.index = 0
def seed(self, seed):
"""
Initialize generator.
:param seed: An integer value to seed the generator with
"""
self.state = []
self.index = 0
self.state.append(seed)
for... | MersenneTwister |
python | readthedocs__readthedocs.org | readthedocs/search/api/v3/tests/test_api.py | {
"start": 13365,
"end": 19572
} | class ____(SearchAPITest):
host = "project.readthedocs.io"
def get(self, *args, **kwargs):
return self.client.get(*args, HTTP_HOST=self.host, **kwargs)
def test_search_project_number_of_queries(self):
# Default version
with self.assertNumQueries(11):
resp = self.get(sel... | ProxiedSearchAPITest |
python | sympy__sympy | sympy/matrices/common.py | {
"start": 92107,
"end": 95395
} | class ____:
"""Wrapper class providing the minimum functionality for a matrix-like
object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
math operations should work on matrix-like objects. This one is intended for
matrix-like objects which use the same indexing format as SymPy with r... | _MatrixWrapper |
python | rq__rq | rq/cli/helpers.py | {
"start": 8435,
"end": 11527
} | class ____(Enum):
PLAIN_TEXT = 0
JSON = 1
LITERAL_EVAL = 2
def _parse_json_value(value, keyword, arg_pos):
"""Parse value as JSON with error handling."""
try:
return loads(value)
except JSONDecodeError:
raise click.BadParameter('Unable to parse %s as JSON.' % (keyword or '%s. n... | ParsingMode |
python | numba__numba | numba/tests/test_record_dtype.py | {
"start": 31915,
"end": 34872
} | class ____(TestCase):
# Test getitem when index is Literal[str]
def test_literal_variable(self):
arr = np.array([1, 2], dtype=recordtype2)
pyfunc = get_field1
jitfunc = njit(pyfunc)
self.assertEqual(pyfunc(arr[0]), jitfunc(arr[0]))
def test_literal_unroll(self):
ar... | TestRecordArrayGetItem |
python | kubernetes-client__python | kubernetes/client/models/v1_rule_with_operations.py | {
"start": 383,
"end": 9436
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1RuleWithOperations |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 115769,
"end": 128685
} | class ____(Response):
"""
Response of datasets.get_all endpoint.
:param datasets: List of datasets
:type datasets: Sequence[Dataset]
:param scroll_id: Scroll ID that can be used with the next calls to get_all to
retrieve more data
:type scroll_id: str
"""
_service = "datasets"
... | GetAllResponse |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 2283,
"end": 4468
} | class ____(list):
"""
This list calls on_add or on_remove whenever the list is modified.
"""
on_add = on_remove = None
name = None
def __init__(self, *args, **kw):
on_add = on_remove = name = None
if 'on_add' in kw:
on_add = kw.pop('on_add')
if 'on_remove' in ... | _LiveList |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-coins-for-fruits-ii.py | {
"start": 67,
"end": 788
} | class ____(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
dq = collections.deque()
j = 0
for i in xrange(len(prices)):
while dq and dp[dq[-1]]+price... | Solution |
python | wandb__wandb | wandb/sdk/launch/runner/local_process.py | {
"start": 440,
"end": 2665
} | class ____(AbstractRunner):
"""Runner class, uses a project to create a LocallySubmittedRun.
LocalProcessRunner is very similar to a LocalContainerRunner, except it does not
run the command inside a docker container. Instead, it runs the
command specified as a process directly on the bare metal machine... | LocalProcessRunner |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 44657,
"end": 44919
} | class ____(sgqlc.types.Enum):
"""Properties by which enterprise owners can be ordered.
Enumeration Choices:
* `LOGIN`: Order enterprise owners by login.
"""
__schema__ = github_schema
__choices__ = ("LOGIN",)
| OrgEnterpriseOwnerOrderField |
python | astropy__astropy | astropy/units/tests/test_format.py | {
"start": 12472,
"end": 12861
} | class ____(RoundtripBase):
format_ = u_format.VOUnit
@pytest.mark.parametrize(
"unit",
[u for u in u_format.VOUnit._units.values() if not isinstance(u, PrefixUnit)],
ids=str,
)
def test_roundtrip(self, unit):
self.check_roundtrip(unit)
if unit not in (u.mag, u.dB... | TestRoundtripVOUnit |
python | sympy__sympy | sympy/stats/joint_rv_types.py | {
"start": 26091,
"end": 28364
} | class ____(JointDistribution):
_argnames = ('n', 'p')
is_Continuous=False
is_Discrete = True
@staticmethod
def check(n, p):
_value_check(n > 0,
"number of trials must be a positive integer")
for p_k in p:
_value_check((p_k >= 0, p_k <= 1),
... | MultinomialDistribution |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 419,
"end": 544
} | class ____(Enum):
black = "black hair"
brown = "brown hair"
blond = "blond hair"
red = "red hair"
| HairColorEnum |
python | Netflix__metaflow | metaflow/plugins/env_escape/client.py | {
"start": 958,
"end": 25066
} | class ____(object):
def __init__(
self, modules, python_executable, pythonpath, max_pickle_version, config_dir
):
# Wrap with ImportError so that if users are just using the escaped module
# as optional, the typical logic of catching ImportError works properly
try:
se... | Client |
python | kamyu104__LeetCode-Solutions | Python/find-the-k-th-character-in-string-game-i.py | {
"start": 40,
"end": 273
} | class ____(object):
def kthCharacter(self, k):
"""
:type k: int
:rtype: str
"""
def popcount(x):
return bin(x)[2:].count('1')
return chr(ord('a')+popcount(k-1)%26)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/step-by-step-directions-from-a-binary-tree-node-to-another.py | {
"start": 1515,
"end": 2307
} | class ____(object):
def getDirections(self, root, startValue, destValue):
"""
:type root: Optional[TreeNode]
:type startValue: int
:type destValue: int
:rtype: str
"""
def dfs(node, val, path):
if node.val == val:
return True
... | Solution2 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-slack/components.py | {
"start": 3401,
"end": 3792
} | class ____(DpathExtractor):
"""
Transform response from a list of strings to list dicts:
from: ['aa', 'bb']
to: [{'member_id': 'aa'}, {{'member_id': 'bb'}]
"""
def extract_records(self, response: requests.Response) -> List[Record]:
records = super().extract_records(response)
ret... | ChannelMembersExtractor |
python | tornadoweb__tornado | tornado/ioloop.py | {
"start": 1701,
"end": 1876
} | class ____(Protocol):
def fileno(self) -> int:
pass
def close(self) -> None:
pass
_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)
| _Selectable |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 235297,
"end": 239152
} | class ____(OrganizationEventsEndpointTestBase):
@mock.patch("sentry.search.events.builder.base.raw_snql_query")
def test_profiles_dataset_simple(self, mock_snql_query: mock.MagicMock) -> None:
mock_snql_query.side_effect = [
{
"data": [
{
... | OrganizationEventsProfilesDatasetEndpointTest |
python | getsentry__sentry | src/sentry/similarity/backends/metrics.py | {
"start": 110,
"end": 1767
} | class ____(AbstractIndexBackend):
def __init__(self, backend, template="similarity.{}", scope_tag_name="scope"):
self.backend = backend
self.template = template
self.scope_tag_name = scope_tag_name
def __getattr__(self, name):
return getattr(self.backend, name)
def __instru... | MetricsWrapper |
python | kubernetes-client__python | kubernetes/client/models/v1alpha3_device_selector.py | {
"start": 383,
"end": 3394
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1alpha3DeviceSelector |
python | scikit-learn__scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | {
"start": 438,
"end": 16022
} | class ____(TransformerMixin, BaseEstimator):
"""Transforms lists of feature-value mappings to vectors.
This transformer turns lists of mappings (dict-like objects) of feature
names to feature values into Numpy arrays or scipy.sparse matrices for use
with scikit-learn estimators.
When feature value... | DictVectorizer |
python | walkccc__LeetCode | solutions/781. Rabbits in Forest/781.py | {
"start": 0,
"end": 252
} | class ____:
def numRabbits(self, answers: list[int]) -> int:
ans = 0
count = collections.Counter()
for answer in answers:
if count[answer] % (answer + 1) == 0:
ans += answer + 1
count[answer] += 1
return ans
| Solution |
python | falconry__falcon | tests/test_sinks.py | {
"start": 149,
"end": 339
} | class ____:
def __init__(self):
self._proxy = Proxy()
def __call__(self, req, resp, **kwargs):
resp.status = self._proxy.forward(req)
self.kwargs = kwargs
| Sink |
python | getsentry__sentry | src/sentry/analytics/events/repo_linked.py | {
"start": 68,
"end": 268
} | class ____(analytics.Event):
user_id: int | None = None
default_user_id: int
organization_id: int
repository_id: int
provider: str
analytics.register(RepoLinkedEvent)
| RepoLinkedEvent |
python | kamyu104__LeetCode-Solutions | Python/sequential-digits.py | {
"start": 78,
"end": 560
} | class ____(object):
def sequentialDigits(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
result = []
q = collections.deque(range(1, 9))
while q:
num = q.popleft()
if num > high:
continu... | Solution |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 221658,
"end": 221727
} | class ____(_NonCanonicalCSMixin, TestCSC):
pass
| TestCSCNonCanonical |
python | dask__dask | dask/dataframe/dask_expr/_cumulative.py | {
"start": 326,
"end": 1185
} | class ____(Expr):
_parameters = ["frame", "axis", "skipna"]
_defaults = {"axis": None}
chunk_operation = None
aggregate_operation: Callable | None = None
neutral_element: int | None = None
def _divisions(self):
return self.frame._divisions()
@functools.cached_property
def _met... | CumulativeAggregations |
python | cython__cython | Cython/Plex/Regexps.py | {
"start": 2237,
"end": 5118
} | class ____:
"""RE is the base class for regular expression constructors.
The following operators are defined on REs:
re1 + re2 is an RE which matches |re1| followed by |re2|
re1 | re2 is an RE which matches either |re1| or |re2|
"""
nullable = 1 # True if this RE can... | RE |
python | skorch-dev__skorch | skorch/exceptions.py | {
"start": 474,
"end": 541
} | class ____(UserWarning):
"""Base skorch warning."""
| SkorchWarning |
python | pytorch__pytorch | torch/_inductor/index_propagation.py | {
"start": 1629,
"end": 2396
} | class ____:
"""A SymPy expression with associated type"""
expr: _ExprType
dtype: torch.dtype
def is_constant(self):
return _is_constant(self.expr)
def __post_init__(self):
if _is_constant(self.expr):
expr = self.expr
if isinstance(expr, sympy.Expr):
... | TypedExpr |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 112819,
"end": 112961
} | class ____(MaybeAlignPartitions):
_parameters = ["frame", "other", "join", "axis", "fill_value"]
_expr_cls = _Align
| AlignAlignPartitions |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1044115,
"end": 1044676
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "block_duration", "created_at", "subject")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
block_duration = sgqlc.types.Field(
sgqlc.types.non_nu... | UserBlockedEvent |
python | astropy__astropy | astropy/io/fits/tests/test_core.py | {
"start": 976,
"end": 20244
} | class ____(FitsTestCase):
def test_missing_file(self):
with pytest.raises(OSError):
fits.open(self.temp("does-not-exist.fits"))
def test_naxisj_check(self):
with fits.open(self.data("o4sp040b0_raw.fits")) as hdulist:
hdulist[1].header["NAXIS3"] = 500
assert ... | TestCore |
python | python-openxml__python-docx | src/docx/shared.py | {
"start": 2670,
"end": 2885
} | class ____(Length):
"""Convenience value class for specifying a length in points."""
def __new__(cls, points: float):
emu = int(points * Length._EMUS_PER_PT)
return Length.__new__(cls, emu)
| Pt |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 24673,
"end": 26249
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global t1, t2
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(10... | PolymorphicSynonymTest |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 7272,
"end": 7510
} | class ____(WeaviateQueryError):
"""Is raised if a gRPC batch query to Weaviate fails in any way."""
def __init__(self, message: str):
super().__init__(message, "GRPC batch")
self.message = message
| WeaviateBatchError |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-cohere-citation-chat/llama_index/packs/cohere_citation_chat/citations_context_chat_engine.py | {
"start": 8549,
"end": 9951
} | class ____(VectorStoreIndex):
"""Vector Store Index with Citations Chat."""
def set_embed_model_input_type(self, input_type: str) -> None:
try:
from llama_index.embeddings.cohere import CohereEmbedding
except ImportError:
raise ImportError(
"Please run `p... | VectorStoreIndexWithCitationsChat |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 72436,
"end": 76399
} | class ____(system_info):
notfounderror = BlasNotFoundError
# List of all known BLAS libraries, in the default order
blas_order = ['armpl', 'mkl', 'ssl2', 'blis', 'openblas',
'accelerate', 'atlas', 'blas']
order_env_var_name = 'NPY_BLAS_ORDER'
def _calc_info_armpl(self):
... | blas_opt_info |
python | walkccc__LeetCode | solutions/63. Unique Paths II/63.py | {
"start": 0,
"end": 485
} | class ____:
def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# dp[i][j] := the number of unique paths from (0, 0) to (i, j)
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # Can also set dp[1][0] = 1.
for i in ra... | Solution |
python | rapidsai__cudf | cpp/scripts/gdb-pretty-printers.py | {
"start": 1000,
"end": 1914
} | class ____(gdb.printing.PrettyPrinter):
"""Print a cudf::device_span"""
def __init__(self, val):
self.val = val
self.pointer = val["_data"]
self.size = int(val["_size"])
def children(self):
return DeviceIterator(self.pointer, self.size)
def to_string(self):
ret... | CudfDeviceSpanPrinter |
python | google__pytype | pytype/tests/test_classes2.py | {
"start": 7844,
"end": 16438
} | class ____(test_base.BaseTest):
"""Tests for classes."""
def test_class_starargs(self):
ty = self.Infer("""
class Foo: pass
class Bar: pass
bases = (Foo, Bar)
class Baz(*bases): pass
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Tuple, Type
... | ClassesTestPython3Feature |
python | django__django | tests/serializers/models/data.py | {
"start": 3260,
"end": 3333
} | class ____(models.Model):
data = models.ManyToManyField(Anchor)
| M2MData |
python | django__django | tests/backends/tests.py | {
"start": 11537,
"end": 11591
} | class ____(EscapingChecks):
pass
| EscapingChecksDebug |
python | pennersr__django-allauth | allauth/idp/oidc/admin.py | {
"start": 1191,
"end": 1415
} | class ____(admin.ModelAdmin):
raw_id_fields = ("client", "user")
list_display = (
"client",
"type",
"user",
"created_at",
"expires_at",
)
list_filter = ("type",)
| TokenAdmin |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/launchers/subprocess_script.py | {
"start": 1322,
"end": 7015
} | class ____(_Launcher):
r"""A process launcher that invokes the current script as many times as desired in a single node.
This launcher needs to be invoked on each node.
In its default behavior, the main process in each node then spawns N-1 child processes via :func:`subprocess.Popen`,
where N is the nu... | _SubprocessScriptLauncher |
python | huggingface__transformers | src/transformers/models/switch_transformers/modular_switch_transformers.py | {
"start": 11265,
"end": 11342
} | class ____(T5LayerSelfAttention):
pass
| SwitchTransformersLayerSelfAttention |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 59783,
"end": 60142
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["SearchMatrixOffsetsResponse"] = Field(default=... | InlineResponse20024 |
python | gevent__gevent | src/greentest/3.11/test_signal.py | {
"start": 6974,
"end": 9057
} | class ____(unittest.TestCase):
def test_valid_signals(self):
s = signal.valid_signals()
self.assertIsInstance(s, set)
self.assertGreaterEqual(len(s), 6)
self.assertIn(signal.Signals.SIGINT, s)
self.assertNotIn(0, s)
self.assertNotIn(signal.NSIG, s)
self.asser... | WindowsSignalTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/parameter_server_strategy_test.py | {
"start": 3959,
"end": 22723
} | class ____(
multi_worker_test_base.MultiWorkerTestBase):
def setUp(self):
self._result = 0
self._lock = threading.Lock()
self._init_condition = threading.Condition()
self._init_reached = 0
self._finish_condition = threading.Condition()
self._finish_reached = 0
self._sess_config = conf... | ParameterServerStrategyTestBase |
python | openai__openai-python | src/openai/types/realtime/realtime_transcription_session_create_response.py | {
"start": 861,
"end": 1551
} | class ____(BaseModel):
format: Optional[RealtimeAudioFormats] = None
"""The PCM audio format. Only a 24kHz sample rate is supported."""
noise_reduction: Optional[AudioInputNoiseReduction] = None
"""Configuration for input audio noise reduction."""
transcription: Optional[AudioTranscription] = None... | AudioInput |
python | getsentry__sentry | src/sentry/web/frontend/csv.py | {
"start": 336,
"end": 411
} | class ____:
def write(self, value: str) -> str:
return value
| Echo |
python | jackfrued__Python-100-Days | Day31-35/code/example07.py | {
"start": 114,
"end": 1285
} | class ____():
"""摘要生成器"""
def __init__(self, algorithm='md5', size=4096):
"""初始化方法
@params:
algorithm - 哈希摘要算法
size - 每次读取数据的大小
"""
self.size = size
cls = getattr(__import__('hashlib'), algorithm.lower())
self.hasher = cls()
def ... | StreamHasher |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-perplexity/llama_index/llms/perplexity/base.py | {
"start": 826,
"end": 19102
} | class ____(LLM):
"""
Perplexity LLM.
Examples:
`pip install llama-index-llms-perplexity`
```python
from llama_index.llms.perplexity import Perplexity
from llama_index.core.llms import ChatMessage
pplx_api_key = "your-perplexity-api-key"
llm = Perplexity(
... | Perplexity |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/_legendgrouptitle.py | {
"start": 233,
"end": 2975
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar"
_path_str = "scatterpolar.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may ... | Legendgrouptitle |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/utils/connection_wrapper.py | {
"start": 1419,
"end": 2608
} | class ____:
"""
Connection metadata data-class.
This class implements main :ref:`~airflow.models.connection.Connection` attributes
and use in AwsConnectionWrapper for avoid circular imports.
Only for internal usage, this class might change or removed in the future.
"""
conn_id: str | None... | _ConnectionMetadata |
python | scipy__scipy | scipy/signal/_ltisys.py | {
"start": 9045,
"end": 14862
} | class ____(LinearTimeInvariant):
r"""
Discrete-time linear time invariant system base class.
Parameters
----------
*system: arguments
The `dlti` class can be instantiated with either 2, 3 or 4 arguments.
The following gives the number of arguments and the corresponding
discr... | dlti |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.