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 | src/transformers/models/sam/processing_sam.py | {
"start": 1572,
"end": 11069
} | class ____(ProcessorMixin):
r"""
Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a
single processor.
[`SamProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of
[`~SamImageProcessor.__call__`] for more ... | SamProcessor |
python | ray-project__ray | rllib/models/tf/layers/skip_connection.py | {
"start": 252,
"end": 1653
} | class ____(tf.keras.layers.Layer if tf else object):
"""Skip connection layer.
Adds the original input to the output (regular residual layer) OR uses
input as hidden state input to a given fan_in_layer.
"""
def __init__(self, layer: Any, fan_in_layer: Optional[Any] = None, **kwargs):
"""In... | SkipConnection |
python | ray-project__ray | python/ray/serve/_private/test_utils.py | {
"start": 4482,
"end": 4545
} | class ____:
def remote(self):
pass
| FakeRemoteFunction |
python | google__pytype | pytype/abstract/_function_base.py | {
"start": 10140,
"end": 15792
} | class ____(Generic[_SomeFunction], _base.BaseValue):
"""An function type which has had an argument bound into it."""
underlying: _SomeFunction
def __init__(
self, callself: "cfg.Variable", underlying: _SomeFunction
) -> None:
super().__init__(underlying.name, underlying.ctx)
self.cls = _classes.... | BoundFunction |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 10867,
"end": 11375
} | class ____(BaseConfig):
future_state_path: Optional[str] = Field(description="Path to a state file with values in far future")
missing_streams: List[EmptyStreamConfiguration] = Field(default=[], description="List of missing streams with valid bypass reasons.")
bypass_reason: Optional[str]
cursor_format:... | FutureStateConfig |
python | catalyst-team__catalyst | catalyst/contrib/losses/triplet.py | {
"start": 7090,
"end": 9015
} | class ____(nn.Module):
"""TripletPairwiseEmbeddingLoss – proof of concept criterion.
Still work in progress.
@TODO: Docs. Contribution is welcome.
"""
def __init__(self, margin: float = 0.3, reduction: str = "mean"):
"""
Args:
margin: margin parameter
reduc... | TripletPairwiseEmbeddingLoss |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 53698,
"end": 55825
} | class ____(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else... | BertForTokenClassification |
python | viewflow__viewflow | viewflow/workflow/flow/views/actions.py | {
"start": 4203,
"end": 5731
} | class ____(mixins.ProcessViewTemplateNames, generic.DetailView):
context_object_name = "process"
flow_class = None
pk_url_kwarg = "process_pk"
template_filename = "process_cancel.html"
def get_queryset(self):
"""Flow processes."""
return self.flow_class.process_class._default_manage... | CancelProcessView |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/serdes/serdes.py | {
"start": 2968,
"end": 3950
} | class ____(Mapping[_K, _V]):
"""Wrapper class for non-scalar key mappings, used to performantly type check when serializing
without impacting the performance of serializing the more common scalar key dicts.
May be replaceable with a different clever scheme.
"""
def __init__(self, mapping: Mapping[_... | SerializableNonScalarKeyMapping |
python | nedbat__coveragepy | coverage/templite.py | {
"start": 540,
"end": 644
} | class ____(ValueError):
"""Raised when a template has a syntax error."""
pass
| TempliteSyntaxError |
python | tornadoweb__tornado | tornado/httpclient.py | {
"start": 24608,
"end": 28784
} | class ____:
"""HTTP Response object.
Attributes:
* ``request``: HTTPRequest object
* ``code``: numeric HTTP status code, e.g. 200 or 404
* ``reason``: human-readable reason phrase describing the status code
* ``headers``: `tornado.httputil.HTTPHeaders` object
* ``effective_url``: final... | HTTPResponse |
python | bokeh__bokeh | tests/unit/bokeh/util/test_hex.py | {
"start": 2045,
"end": 2751
} | class ____:
def test_default_aspect_pointytop(self) -> None:
x = np.array([0, -2, 2, -1.5, -1.5, 1.5, 1.5])
y = np.array([0, 0, 0, 1.5, -1.5, 1.5, -1.5])
q, r = buh.cartesian_to_axial(x, y, 1, "pointytop")
assert list(zip(q, r)) == [
(0,0), (-1, 0), (1,0), (0,-1), (-1, ... | Test_cartesian_to_axial |
python | spack__spack | lib/spack/spack/test/cray_manifest.py | {
"start": 2218,
"end": 15417
} | class ____:
def __init__(self, *, name, version, arch=None, executables=None, prefix=None):
self.name = name
self.version = version
self.arch = arch or JsonArchEntry("anyplatform", "anyos", "anytarget")
self.executables = executables or {"cc": "cc", "cxx": "cxx", "fc": "fc"}
... | JsonCompilerEntry |
python | django__django | django/db/models/lookups.py | {
"start": 21058,
"end": 22430
} | class ____(BuiltinLookup):
param_pattern = "%%%s%%"
prepare_rhs = False
def get_rhs_op(self, connection, rhs):
# Assume we are in startswith. We need to produce SQL like:
# col LIKE %s, ['thevalue%']
# For python values we can (and should) do that directly in Python,
# b... | PatternLookup |
python | apache__airflow | providers/sftp/tests/unit/sftp/operators/test_sftp.py | {
"start": 2085,
"end": 27958
} | class ____:
def setup_method(self):
hook = SSHHook(ssh_conn_id="ssh_default")
hook.no_host_key_check = True
self.hook = hook
sftp_hook = SFTPHook(ssh_conn_id="ssh_default")
sftp_hook.no_host_key_check = True
self.sftp_hook = sftp_hook
self.test_dir = "/tmp"
... | TestSFTPOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 974446,
"end": 974842
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("SponsorsActivity", graphq... | SponsorsActivityEdge |
python | pypa__hatch | tests/cli/version/test_version.py | {
"start": 174,
"end": 11485
} | class ____:
def test_random_directory(self, hatch, temp_dir, helpers):
with temp_dir.as_cwd():
result = hatch("version")
assert result.exit_code == 1, result.output
assert result.output == helpers.dedent(
"""
No project detected
"""
)
... | TestNoProject |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_primitive.py | {
"start": 13590,
"end": 15148
} | class ____:
def test_valid(self) -> None:
prop = bcpp.String()
assert prop.is_valid("")
assert prop.is_valid("6")
def test_invalid(self) -> None:
prop = bcpp.String()
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_vali... | Test_String |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 2990,
"end": 3205
} | class ____(MetaflowCardComponent):
type = "subtitle"
def __init__(self, text=None):
self._text = text
def render(self):
return dict(type=self.type, text=str(self._text))
| SubTitleComponent |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flow_run_states.py | {
"start": 99,
"end": 961
} | class ____:
async def test_read_flow_run_state(self, flow_run, client, session):
# create a flow run state to read
result = await models.flow_runs.set_flow_run_state(
session=session,
flow_run_id=flow_run.id,
state=schemas.states.Running(),
)
await... | TestReadFlowRunStateById |
python | apache__airflow | providers/opensearch/tests/unit/opensearch/log/test_os_json_formatter.py | {
"start": 1031,
"end": 3305
} | class ____:
JSON_FIELDS = ["asctime", "filename", "lineno", "levelname", "message", "exc_text"]
EXTRA_FIELDS = {
"dag_id": "dag1",
"task_id": "task1",
"execution_date": "2023-11-17",
"try_number": "1",
"log_id": "Some_log_id",
}
@pytest.fixture
def os_json_fo... | TestOpensearchJSONFormatter |
python | numba__numba | numba/cuda/tests/cudapy/test_complex.py | {
"start": 2459,
"end": 4588
} | class ____(CUDATestCase):
def basic_values(self):
reals = [-0.0, +0.0, 1, -1, +1.5, -3.5,
float('-inf'), float('+inf'), float('nan')]
return [complex(x, y) for x, y in itertools.product(reals, reals)]
def more_values(self):
reals = [0.0, +0.0, 1, -1, -math.pi, +math.pi... | BaseComplexTest |
python | plotly__plotly.py | plotly/graph_objs/surface/contours/z/_project.py | {
"start": 233,
"end": 5178
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "surface.contours.z"
_path_str = "surface.contours.z.project"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
Determines whether or not these contour lines are projected on
the x plane. If `highlight` is set t... | Project |
python | has2k1__plotnine | plotnine/geoms/geom_density_2d.py | {
"start": 77,
"end": 494
} | class ____(geom_path):
"""
2D density estimate
{usage}
This is a 2d version of [](`~plotnine.geoms.geom_density`).
Parameters
----------
{common_parameters}
See Also
--------
plotnine.stat_density_2d : The default `stat` for this `geom`.
"""
DEFAULT_PARAMS = {
... | geom_density_2d |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 10833,
"end": 14126
} | class ____(ModelOutput):
"""
Base class for model's outputs that also contains a pooling of the last hidden states.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model... | BaseModelOutputWithPoolingAndCrossAttentions |
python | viewflow__viewflow | viewflow/workflow/nodes/handle.py | {
"start": 1461,
"end": 2808
} | class ____(mixins.NextNodeMixin, Node):
"""
Task to be executed outside of the flow.
"""
task_type = "FUNCTION"
activation_class = HandleActivation
shape = {
"width": 150,
"height": 100,
"text-align": "middle",
"svg": """
<rect class="task" width="15... | Handle |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 5201,
"end": 5358
} | class ____(DataContextError):
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message)
| InvalidConfigError |
python | kamyu104__LeetCode-Solutions | Python/create-binary-tree-from-descriptions.py | {
"start": 36,
"end": 611
} | class ____(object):
def createBinaryTree(self, descriptions):
"""
:type descriptions: List[List[int]]
:rtype: Optional[TreeNode]
"""
nodes = {}
children = set()
for p, c, l in descriptions:
parent = nodes.setdefault(p, TreeNode(p))
chil... | Solution |
python | django__django | tests/signals/models.py | {
"start": 536,
"end": 701
} | class ____(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(Author)
def __str__(self):
return self.name
| Book |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_config.py | {
"start": 198,
"end": 9374
} | class ____:
@pytest.mark.parametrize(
"raw_config, expected_output_config, expected_error",
[
pytest.param(
{"connector_image": "foo", "tests": {"spec": [{"spec_path": "my-spec-path"}]}},
config.Config(
connector_image="foo",
... | TestConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 11366,
"end": 13775
} | class ____(
NamedTuple(
"_ListRepositoriesResponse",
[
("repository_symbols", Sequence[LoadableRepositorySymbol]),
("executable_path", Optional[str]),
("repository_code_pointer_dict", Mapping[str, CodePointer]),
("entry_point", Optional[Sequence[str]])... | ListRepositoriesResponse |
python | kamyu104__LeetCode-Solutions | Python/count-sub-islands.py | {
"start": 33,
"end": 780
} | class ____(object):
def countSubIslands(self, grid1, grid2):
"""
:type grid1: List[List[int]]
:type grid2: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def dfs(grid1, grid2, i, j):
if not (0 <= i < len(grid2) and
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-kvdb/destination_kvdb/client.py | {
"start": 143,
"end": 2729
} | class ____:
base_url = "https://kvdb.io"
PAGE_SIZE = 1000
def __init__(self, bucket_id: str, secret_key: str = None):
self.secret_key = secret_key
self.bucket_id = bucket_id
def write(self, key: str, value: Mapping[str, Any]):
return self.batch_write([(key, value)])
def ba... | KvDbClient |
python | sphinx-doc__sphinx | sphinx/builders/linkcheck.py | {
"start": 12082,
"end": 26528
} | class ____(Thread):
"""A worker class for checking the availability of hyperlinks."""
def __init__(
self,
config: Config,
rqueue: Queue[CheckResult],
wqueue: Queue[CheckRequest],
rate_limits: dict[str, RateLimit],
) -> None:
self.rate_limits = rate_limits
... | HyperlinkAvailabilityCheckWorker |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 11926,
"end": 12181
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
uri: str
language_id: str
version: int
text: str
def document_uri(self) -> DocumentUri:
return DocumentUri.parse(self.uri)
@dataclasses.dataclass(frozen=True)
| TextDocumentItem |
python | openai__openai-python | src/openai/types/containers/file_create_params.py | {
"start": 230,
"end": 412
} | class ____(TypedDict, total=False):
file: FileTypes
"""The File object (not file name) to be uploaded."""
file_id: str
"""Name of the file to create."""
| FileCreateParams |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 4664,
"end": 4834
} | class ____:
@overload
def m1(self, x: int) -> int: ...
@overload
def m1(self, x: str) -> str: ...
def m1(self, x: int | str) -> int | str: ...
| Parent5 |
python | kamyu104__LeetCode-Solutions | Python/check-if-a-string-contains-all-binary-codes-of-size-k.py | {
"start": 309,
"end": 787
} | class ____(object):
def hasAllCodes(self, s, k):
"""
:type s: str
:type k: int
:rtype: bool
"""
lookup = set()
base = 2**k
if base > len(s):
return False
num = 0
for i in xrange(len(s)):
num = (num << 1) + (s[i] ... | Solution2 |
python | RaRe-Technologies__gensim | gensim/models/doc2vec.py | {
"start": 52959,
"end": 54756
} | class ____:
def __init__(self, source):
"""Iterate over a file that contains documents:
one line = :class:`~gensim.models.doc2vec.TaggedDocument` object.
Words are expected to be already preprocessed and separated by whitespace. Document tags are constructed
automatically from the d... | TaggedLineDocument |
python | ray-project__ray | python/ray/tests/test_autoscaling_policy.py | {
"start": 1514,
"end": 2045
} | class ____:
def __init__(
self,
duration: float,
bundles: List[Dict[str, float]],
strategy: int,
start_callback: Callable[[None], None] = None,
done_callback: Callable[[None], None] = None,
):
self.duration = duration
self.bundles = bundles
... | PlacementGroup |
python | apache__airflow | providers/yandex/src/airflow/providers/yandex/links/yq.py | {
"start": 1115,
"end": 1545
} | class ____(BaseOperatorLink):
"""Web link to query in Yandex Query UI."""
name = "Yandex Query"
def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey):
return XCom.get_value(key=XCOM_WEBLINK_KEY, ti_key=ti_key) or "https://yq.cloud.yandex.ru"
@staticmethod
def persist(cont... | YQLink |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-opendal/llama_index/readers/opendal/gcs/base.py | {
"start": 318,
"end": 2075
} | class ____(BaseReader):
"""General reader for any Gcs file or directory."""
def __init__(
self,
bucket: str,
path: str = "/",
endpoint: str = "",
credentials: str = "",
file_extractor: Optional[Dict[str, Union[str, BaseReader]]] = None,
) -> None:
"""... | OpendalGcsReader |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_accounts.py | {
"start": 2104,
"end": 3331
} | class ____(TestCase):
@HttpMocker()
def test_full_refresh(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
_create_accounts_request().with_limit(100).build(),
_create_response().with_record(record=_create_record()).build(),
)
source = get_source(config=_C... | AccountsTest |
python | gevent__gevent | src/gevent/tests/test__core_fork.py | {
"start": 644,
"end": 2738
} | class ____(unittest.TestCase):
def test(self):
self.assertEqual(hub.threadpool.size, 0)
# Use a thread to make us multi-threaded
hub.threadpool.apply(lambda: None)
self.assertEqual(hub.threadpool.size, 1)
# Not all platforms use fork by default, so we want to force it,
... | Test |
python | pdm-project__pdm | src/pdm/resolver/base.py | {
"start": 493,
"end": 887
} | class ____(t.NamedTuple):
"""The resolution result."""
packages: t.Iterable[Package]
"""The list of pinned packages with dependencies."""
collected_groups: set[str]
"""The list of collected groups."""
@property
def candidates(self) -> dict[str, Candidate]:
return {entry.candidate.i... | Resolution |
python | pytorch__pytorch | torchgen/model.py | {
"start": 99081,
"end": 103577
} | class ____:
base: str
inplace: bool
dunder_method: bool
# Note [Overload Ambiguity With Functional Variants]
# A handful of operators have both a "mutable" and a "functional" variant.
# (native_batch_norm is a good example, although this isn't the case today).
# For those operators, the muta... | BaseOperatorName |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/tableau/customize-tableau-asset-defs.py | {
"start": 715,
"end": 1673
} | class ____(DagsterTableauTranslator):
def get_asset_spec(self, data: TableauTranslatorData) -> dg.AssetSpec:
# We create the default asset spec using super()
default_spec = super().get_asset_spec(data)
# We customize the metadata and asset key prefix for all assets, including sheets,
... | MyCustomTableauTranslator |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/sourceware.py | {
"start": 198,
"end": 768
} | class ____(PackageBase):
sourceware_mirror_path: Optional[str] = None
base_mirrors = [
"https://sourceware.org/pub/",
"https://mirrors.kernel.org/sourceware/",
"https://ftp.gwdg.de/pub/linux/sources.redhat.com/",
]
@property
def urls(self):
if self.sourceware_mirror_... | SourcewarePackage |
python | getsentry__sentry | tests/sentry/api/test_base.py | {
"start": 14017,
"end": 17050
} | class ____(APITestCase):
@mock.patch("rest_framework.views.APIView.handle_exception", return_value=Response(status=500))
def test_handle_exception_when_super_returns_response(
self, mock_super_handle_exception: MagicMock
):
mock_endpoint = DummyErroringEndpoint.as_view(error=Exception("nope"... | EndpointHandleExceptionTest |
python | streamlit__streamlit | lib/streamlit/components/v2/component_path_utils.py | {
"start": 1180,
"end": 8706
} | class ____:
"""Utility class for component path operations and security validation."""
@staticmethod
def has_glob_characters(path: str) -> bool:
"""Check if a path contains glob pattern characters.
Parameters
----------
path : str
The path to check
Retu... | ComponentPathUtils |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 53884,
"end": 55876
} | class ____(_FilterInvalids):
# Need test for intermediate precisions
def test_logaddexp2_values(self):
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
z = [6, 6, 6, 6, 6]
for dt, dec_ in zip(['f', 'd', 'g'], [6, 15, 15]):
xf = np.log2(np.array(x, dtype=dt))
yf = n... | TestLogAddExp2 |
python | wandb__wandb | wandb/vendor/pygments/lexers/sql.py | {
"start": 6878,
"end": 7827
} | class ____(PostgresBase, RegexLexer):
"""
Handle the extra syntax in Pl/pgSQL language.
.. versionadded:: 1.5
"""
name = 'PL/pgSQL'
aliases = ['plpgsql']
mimetypes = ['text/x-plpgsql']
flags = re.IGNORECASE
tokens = dict((k, l[:]) for (k, l) in iteritems(PostgresLexer.tokens))
... | PlPgsqlLexer |
python | neetcode-gh__leetcode | python/1020-number-of-enclaves.py | {
"start": 0,
"end": 762
} | class ____:
def numEnclaves(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
def dfs(grid, row, col):
if 0 <= row < ROWS and 0 <= col < COLS:
if grid[row][col] == 1:
grid[row][col] = 0
dfs(grid, row + 1, c... | Solution |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session_test.py | {
"start": 24358,
"end": 26673
} | class ____(test.TestCase):
"""_WrappedSession tests."""
@test_util.run_deprecated_v1
def test_properties(self):
with self.cached_session() as sess:
constant_op.constant(0.0)
wrapped_sess = monitored_session._WrappedSession(sess)
self.assertEqual(sess.graph, wrapped_sess.graph)
self.as... | WrappedSessionTest |
python | doocs__leetcode | solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/Solution.py | {
"start": 0,
"end": 233
} | class ____:
def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:
f = {0}
for row in mat:
f = set(a + b for a in f for b in row)
return min(abs(v - target) for v in f)
| Solution |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 9579,
"end": 9751
} | class ____(scale_y_continuous):
"""
Continuous y position reverse transformed scale
"""
trans: TransUser = "reverse"
@dataclass(kw_only=True)
| scale_y_reverse |
python | tensorflow__tensorflow | tensorflow/python/ops/control_flow_ops_test.py | {
"start": 6713,
"end": 7956
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_deprecated_v1
def testTupleDependencies(self):
counter = variable_scope.get_variable(
"my_counter", shape=[], initializer=init_ops.zeros_initializer())
increment_counter = state_ops.assign_add(counter, 1)
const_with_dep = control_flow_ops... | WithDependenciesTestCase |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 292166,
"end": 294025
} | class ____(Response):
"""
Response of tasks.stopped endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "stopped"
_version = "2.9"
_schema = {
... | StoppedResponse |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_R.py | {
"start": 3700,
"end": 5193
} | class ____(Benchmark):
r"""
Ratkowsky02 objective function.
This class defines the Ratkowsky 2 [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Ratkowsky02}}(x) = \sum_{m=1}^{9}(a_m - x[0] / (1 + exp(x[1]
- b_m x[2]... | Ratkowsky02 |
python | django__django | tests/generic_views/views.py | {
"start": 7029,
"end": 7260
} | class ____:
model = BookSigning
date_field = "event_date"
# use the same templates as for books
def get_template_names(self):
return ["generic_views/book%s.html" % self.template_name_suffix]
| BookSigningConfig |
python | pytorch__pytorch | torch/_inductor/fx_passes/split_cat.py | {
"start": 17792,
"end": 22820
} | class ____(CallFunction):
"""
Matches a call to torch.split if it is in a normalized form. Ensures that all users of
splits are unique getitems.
"""
def __init__(self, arg, sizes, func=torch.split) -> None:
# using KeywordArg("dim") for `dim` checks they all match
super().__init__(f... | TorchSplit |
python | tensorflow__tensorflow | tensorflow/python/framework/op_def_util_test.py | {
"start": 1249,
"end": 5808
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.parameters([
("any", "Foo", "Foo"),
("any", 12, 12),
("any", {2: 3}, {2: 3}),
("string", "Foo", "Foo"),
("string", b"Foo", b"Foo"),
("int", 12, 12),
("int", 12.3, 12),
("float", 12, 12.0),... | OpDefUtilTest |
python | sphinx-doc__sphinx | sphinx/domains/index.py | {
"start": 775,
"end": 2041
} | class ____(Domain):
"""Index domain."""
name = 'index'
label = 'index'
@property
def entries(self) -> dict[str, list[tuple[str, str, str, str, str | None]]]:
return self.data.setdefault('entries', {})
def clear_doc(self, docname: str) -> None:
self.entries.pop(docname, None)
... | IndexDomain |
python | huggingface__transformers | src/transformers/models/qwen3_moe/modeling_qwen3_moe.py | {
"start": 27492,
"end": 31948
} | class ____(Qwen3MoePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Qwen... | Qwen3MoeForCausalLM |
python | huggingface__transformers | examples/pytorch/text-generation/run_generation.py | {
"start": 8792,
"end": 17060
} | class ____(GenerationMixin):
__slots__ = ("_optimized", "_default")
def __init__(self, optimized, default):
self._optimized = optimized
self._default = default
def __call__(self, *args, **kwargs):
if kwargs["past_key_values"] is None and self._default.config.use_cache:
... | _ModelFallbackWrapper |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_cell.py | {
"start": 336,
"end": 2060
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_cell() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_cell_number(self):
"""Test the _write_cell() method for numbers... | TestWriteCell |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/digitalocean.py | {
"start": 286,
"end": 739
} | class ____(CloudProvider):
"""Checks if a configuration file has been passed or fixtures are going to be used for testing"""
def __init__(self, args: IntegrationConfig) -> None:
super().__init__(args)
self.uses_config = True
def setup(self) -> None:
"""Setup the cloud resource bef... | DigitalOceanCloudProvider |
python | doocs__leetcode | solution/0000-0099/0053.Maximum Subarray/Solution2.py | {
"start": 0,
"end": 845
} | class ____:
def maxSubArray(self, nums: List[int]) -> int:
def crossMaxSub(nums, left, mid, right):
lsum = rsum = 0
lmx = rmx = -inf
for i in range(mid, left - 1, -1):
lsum += nums[i]
lmx = max(lmx, lsum)
for i in range(mid + 1,... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess24.py | {
"start": 449,
"end": 499
} | class ____(UnknownX):
y: Desc
| DerivesFromUnknown |
python | matplotlib__matplotlib | lib/matplotlib/figure.py | {
"start": 91566,
"end": 143754
} | class ____(FigureBase):
"""
The top level container for all the plot elements.
See `matplotlib.figure` for an index of class methods.
Attributes
----------
patch
The `.Rectangle` instance representing the figure background patch.
suppressComposite
For multiple images, the ... | Figure |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_container_upload_block.py | {
"start": 201,
"end": 300
} | class ____(BaseModel):
file_id: str
type: Literal["container_upload"]
| BetaContainerUploadBlock |
python | huggingface__transformers | src/transformers/models/video_llama_3/modular_video_llama_3.py | {
"start": 46486,
"end": 46735
} | class ____(Qwen2VLProcessorKwargs):
_defaults = {
"text_kwargs": {
"padding": False,
"return_mm_token_type_ids": False,
},
"videos_kwargs": {"return_metadata": True},
}
| VideoLlama3ProcessorKwargs |
python | tiangolo__fastapi | fastapi/dependencies/models.py | {
"start": 521,
"end": 638
} | class ____:
security_scheme: SecurityBase
scopes: Optional[Sequence[str]] = None
@dataclass
| SecurityRequirement |
python | networkx__networkx | networkx/algorithms/tests/test_cluster.py | {
"start": 16297,
"end": 17600
} | class ____:
@classmethod
def setup_class(cls):
pytest.importorskip("numpy")
def test_empty(self):
G = nx.Graph()
with pytest.raises(ZeroDivisionError):
nx.average_clustering(G)
def test_average_clustering(self):
G = nx.cycle_graph(3)
G.add_edge(2, 3)... | TestAverageClustering |
python | bokeh__bokeh | src/bokeh/models/annotations/geometry.py | {
"start": 3348,
"end": 4694
} | class ____(Model):
""" Defines interaction handles for box-like annotations.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
all = Required(Instance(AreaVisuals)) # move, resize
move ... | BoxInteractionHandles |
python | walkccc__LeetCode | solutions/3498. Reverse Degree of a String/3498.py | {
"start": 0,
"end": 151
} | class ____:
def reverseDegree(self, s: str) -> int:
return sum((26 - (ord(c) - ord('a'))) * (i + 1)
for i, c in enumerate(s))
| Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/data_adapter.py | {
"start": 27424,
"end": 31644
} | class ____(DataAdapter):
"""Adapter that handles python generators and iterators."""
@staticmethod
def can_handle(x, y=None):
return ((hasattr(x, "__next__") or hasattr(x, "next"))
and hasattr(x, "__iter__")
and not isinstance(x, data_utils.Sequence))
def __init__(self,
... | GeneratorDataAdapter |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 15692,
"end": 18422
} | class ____(BaseDataset):
"""
Feature: Datasets can be created by manually specifying chunks
"""
def test_create_chunks(self):
""" Create via chunks tuple """
dset = self.f.create_dataset(make_name(), shape=(100,), chunks=(10,))
self.assertEqual(dset.chunks, (10,))
def ... | TestCreateChunked |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 122819,
"end": 122903
} | class ____(Unicode):
"""The SQL NCHAR type."""
__visit_name__ = "NCHAR"
| NCHAR |
python | spyder-ide__spyder | spyder/plugins/projects/api.py | {
"start": 6094,
"end": 6396
} | class ____(BaseProjectType):
ID = 'empty-project-type'
@staticmethod
def get_name():
return _("Empty project")
def create_project(self):
return True, ""
def open_project(self):
return True, ""
def close_project(self):
return True, ""
| EmptyProject |
python | matplotlib__matplotlib | galleries/examples/misc/demo_ribbon_box.py | {
"start": 1148,
"end": 2788
} | class ____(AxesImage):
zorder = 1
def __init__(self, ax, bbox, color, *, extent=(0, 1, 0, 1), **kwargs):
super().__init__(ax, extent=extent, **kwargs)
self._bbox = bbox
self._ribbonbox = RibbonBox(color)
self.set_transform(BboxTransformTo(bbox))
def draw(self, renderer):
... | RibbonBoxImage |
python | apache__airflow | airflow-core/tests/unit/models/test_variable.py | {
"start": 1336,
"end": 16447
} | class ____:
@pytest.fixture(autouse=True)
def setup_test_cases(self):
db.clear_db_variables()
SecretCache.reset()
with conf_vars({("secrets", "use_cache"): "true"}):
SecretCache.init()
with mock.patch("airflow.models.variable.mask_secret", autospec=True) as m:
... | TestVariable |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/sensors.py | {
"start": 7680,
"end": 7812
} | class ____(graphene.ObjectType):
results = non_null_list(GrapheneSensor)
class Meta:
name = "Sensors"
| GrapheneSensors |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image09.py | {
"start": 315,
"end": 847
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | ApeWorX__ape | src/ape/utils/os.py | {
"start": 4094,
"end": 11697
} | class ____:
"""
A context manager to manage injecting and removing paths from
a user's sys paths without permanently modifying it.
"""
def __init__(self, path: Path, exclude: Optional[list[Path]] = None):
self.temp_path = str(path)
self.exclude = [str(p) for p in exclude or []]
... | use_temp_sys_path |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 40606,
"end": 41024
} | class ____(MultiThreadedTestCase):
@property
def world_size(self):
return DEVICE_COUNT
def setUp(self):
super().setUp()
self._spawn_threads()
def run_subtests(self, *args, **kwargs):
return run_subtests(self, *args, **kwargs)
def perThreadSetUp(self):
torch... | FSDPTestMultiThread |
python | langchain-ai__langchain | libs/langchain/langchain_classic/memory/summary_buffer.py | {
"start": 536,
"end": 5678
} | class ____(BaseChatMemory, SummarizerMixin):
"""Buffer with summarizer for storing conversation memory.
Provides a running summary of the conversation together with the most recent
messages in the conversation under the constraint that the total number of
tokens in the conversation does not exceed a ce... | ConversationSummaryBufferMemory |
python | RaRe-Technologies__gensim | gensim/utils.py | {
"start": 35871,
"end": 41126
} | class ____(SaveLoad):
"""Wrap `corpus` and return a slice of it."""
def __init__(self, corpus, slice_):
"""
Parameters
----------
corpus : iterable of iterable of (int, numeric)
Input corpus.
slice_ : slice or iterable
Slice for `corpus`.
... | SlicedCorpus |
python | wandb__wandb | wandb/vendor/pygments/lexers/dotnet.py | {
"start": 21059,
"end": 21757
} | class ____(DelegatingLexer):
"""
Lexer for highlighting Visual Basic.net within ASP.NET pages.
"""
name = 'aspx-vb'
aliases = ['aspx-vb']
filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
mimetypes = []
def __init__(self, **options):
super(VbNetAspxLexer, ... | VbNetAspxLexer |
python | walkccc__LeetCode | solutions/1634. Add Two Polynomials Represented as Linked Lists/1634.py | {
"start": 183,
"end": 1125
} | class ____:
def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode':
dummy = PolyNode()
curr = dummy
p = poly1 # poly1's pointer
q = poly2 # poly2's pointer
while p and q:
if p.power > q.power:
curr.next = PolyNode(p.coefficient, p.power)
curr = curr.next
... | Solution |
python | walkccc__LeetCode | solutions/1231. Divide Chocolate/1231.py | {
"start": 0,
"end": 611
} | class ____:
def maximizeSweetness(self, sweetness: list[int], k: int) -> int:
l = len(sweetness) // (k + 1)
r = sum(sweetness) // (k + 1)
def canEat(m: int) -> bool:
"""
Returns True if can eat m sweetness (the minimum sweetness of each piece).
"""
pieces = 0
summ = 0 # the... | Solution |
python | eth-brownie__brownie | brownie/project/build.py | {
"start": 947,
"end": 7260
} | class ____:
"""Methods for accessing and manipulating a project's contract build data."""
def __init__(self, sources: Sources) -> None:
self._sources: Final = sources
self._contracts: Final[Dict[ContractName, ContractBuildJson]] = {}
self._interfaces: Final[Dict[ContractName, InterfaceB... | Build |
python | sanic-org__sanic | sanic/signals.py | {
"start": 4114,
"end": 14827
} | class ____(BaseRouter):
"""A `BaseRouter` that is used to dispatch signals to handlers"""
def __init__(self) -> None:
super().__init__(
delimiter=".",
route_class=Signal,
group_class=SignalGroup,
stacking=True,
)
self.allow_fail_builtin = ... | SignalRouter |
python | getsentry__sentry | src/sentry/deletions/defaults/sentry_app_installation_token.py | {
"start": 289,
"end": 787
} | class ____(ModelDeletionTask[SentryAppInstallationToken]):
def get_child_relations(self, instance: SentryAppInstallationToken) -> list[BaseRelation]:
from sentry.models.apitoken import ApiToken
return [
ModelRelation(ApiToken, {"id": instance.api_token_id}, task=ModelApiTokenDeletionTas... | SentryAppInstallationTokenDeletionTask |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py | {
"start": 29127,
"end": 33343
} | class ____:
"""Comprehensive tests for the PrefixTree"""
def test_tree_structure_multiple_insertions(self, tree: PrefixTree) -> None:
"""Test tree structure after multiple insertions."""
tree.add_tenants(["tenant_1", "tenant_2"], 0)
tree.insert("helloworld", "tenant_1", 1)
tree.... | TestPrefixTreeComprehensive |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/units.py | {
"start": 3011,
"end": 3163
} | class ____(UnitMetadata):
"""
Represents the unit metadata of a QueryExpression with no unit.
"""
pass
@dataclass(frozen=True)
| WithNoUnit |
python | huggingface__transformers | src/transformers/models/textnet/modeling_textnet.py | {
"start": 12706,
"end": 15087
} | class ____(TextNetPreTrainedModel, BackboneMixin):
has_attentions = False
def __init__(self, config):
super().__init__(config)
super()._init_backbone(config)
self.textnet = TextNetModel(config)
self.num_features = config.hidden_sizes
# initialize weights and apply fina... | TextNetBackbone |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 2010,
"end": 3149
} | class ____(ModelOutput):
r"""
text_features (`torch.FloatTensor` of shape `(batch_size, text_sequence_length, hidden_size)`):
Sequence of hidden-states at the text output of the last layer of the model.
image_features (`torch.FloatTensor` of shape `(batch_size, image_sequence_length, hidden_size)`):... | BridgeTowerModelOutput |
python | spack__spack | lib/spack/spack/bootstrap/core.py | {
"start": 2945,
"end": 4923
} | class ____:
"""Interface for "core" software bootstrappers"""
config_scope_name = ""
def __init__(self, conf: ConfigDictionary) -> None:
self.conf = conf
self.name = conf["name"]
self.metadata_dir = spack.util.path.canonicalize_path(conf["metadata"])
# Check for relative p... | Bootstrapper |
python | django__django | tests/admin_inlines/tests.py | {
"start": 55235,
"end": 59163
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(
"testing", password="password", is_staff=True
)
cls.user.user_permissions.add(
Permission.objects.get(
codename="view_poll",
content_typ... | TestReadOnlyChangeViewInlinePermissions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.