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 | lazyprogrammer__machine_learning_examples | rl3/a2c/neural_network.py | {
"start": 723,
"end": 1824
} | class ____:
def __init__(self, sess, ob_space, ac_space, nenv, nsteps, nstack, reuse=False):
gain = np.sqrt(2)
nbatch = nenv * nsteps
nh, nw, nc = ob_space.shape
ob_shape = (nbatch, nh, nw, nc * nstack)
X = tf.placeholder(tf.uint8, ob_shape) # obs
X_normal = tf.cast... | CNN |
python | python-poetry__poetry | tests/types.py | {
"start": 3327,
"end": 3429
} | class ____(Protocol):
def __call__(self, name: str) -> NormalizedName: ...
| NormalizedNameTransformer |
python | django__django | tests/backends/base/test_features.py | {
"start": 74,
"end": 228
} | class ____(SimpleTestCase):
def test_nonexistent_feature(self):
self.assertFalse(hasattr(connection.features, "nonexistent"))
| TestDatabaseFeatures |
python | run-llama__llama_index | docs/examples/output_parsing/directory.py | {
"start": 247,
"end": 1112
} | class ____(BaseModel):
"""
Class representing a single node in a filesystem. Can be either a file or a folder.
Note that a file cannot have children, but a folder can.
Args:
name (str): The name of the node.
children (List[Node]): The list of child nodes (if any).
node_type (Nod... | Node |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 15040,
"end": 15151
} | class ____(MysqlConnectionPool, TpoolConnectionPool, tests.LimitedTestCase):
__test__ = True
| Test01MysqlTpool |
python | kamyu104__LeetCode-Solutions | Python/bulb-switcher-iv.py | {
"start": 29,
"end": 328
} | class ____(object):
def minFlips(self, target):
"""
:type target: str
:rtype: int
"""
result, curr = 0, '0'
for c in target:
if c == curr:
continue
curr = c
result += 1
return result
| Solution |
python | pypa__setuptools | setuptools/_static.py | {
"start": 138,
"end": 2332
} | class ____:
"""
Wrapper for built-in object types that are allow setuptools to identify
static core metadata (in opposition to ``Dynamic``, as defined :pep:`643`).
The trick is to mark values with :class:`Static` when they come from
``pyproject.toml`` or ``setup.cfg``, so if any plugin overwrite th... | Static |
python | Textualize__textual | docs/examples/guide/reactivity/dynamic_watch.py | {
"start": 172,
"end": 544
} | class ____(Widget):
DEFAULT_CSS = "Counter { height: auto; }"
counter = reactive(0) # (1)!
def compose(self) -> ComposeResult:
yield Label()
yield Button("+10")
def on_button_pressed(self) -> None:
self.counter += 10
def watch_counter(self, counter_value: int):
se... | Counter |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 13690,
"end": 14018
} | class ____(LocalizableStreamlitException):
"""Exception raised when a page_link is created without a label."""
def __init__(self) -> None:
super().__init__(
"The `label` param is required for external links used with `st.page_link` - please provide a `label`."
)
| StreamlitMissingPageLabelError |
python | getsentry__sentry | tests/sentry/api/serializers/test_project.py | {
"start": 11688,
"end": 12381
} | class ____(TestCase):
def test_simple(self) -> None:
user = self.create_user(username="foo")
organization = self.create_organization(owner=user)
team = self.create_team(organization=organization)
project = self.create_project(teams=[team], organization=organization, name="foo")
... | ProjectWithTeamSerializerTest |
python | agronholm__apscheduler | tests/triggers/test_combining.py | {
"start": 447,
"end": 6431
} | class ____:
@pytest.mark.parametrize("threshold", [1, 0])
def test_two_datetriggers(self, timezone, serializer, threshold):
date1 = datetime(2020, 5, 16, 14, 17, 30, 254212, tzinfo=timezone)
date2 = datetime(2020, 5, 16, 14, 17, 31, 254212, tzinfo=timezone)
trigger = AndTrigger(
... | TestAndTrigger |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py | {
"start": 52000,
"end": 57660
} | class ____:
def setup_method(self):
clear_db_runs()
def teardown_method(self):
clear_db_runs()
@pytest.mark.parametrize(
("hostname", "pid", "expected_status_code", "expected_detail"),
[
# Case: Successful heartbeat
("random-hostname", 1789, 204, Non... | TestTIHealthEndpoint |
python | numba__numba | numba/tests/test_heapq.py | {
"start": 14343,
"end": 14456
} | class ____(_TestHeapq, TestCase):
"""Test heapq with typed lists"""
listimpl = typed.List
| TestHeapqTypedList |
python | python-markdown__markdown | tests/test_syntax/extensions/test_md_in_html.py | {
"start": 961,
"end": 1545
} | class ____(TestCase):
""" Ensure any remaining elements in HTML stash are properly serialized. """
def test_stash_to_string(self):
# There should be no known cases where this actually happens so we need to
# forcefully pass an `etree` `Element` to the method to ensure proper behavior.
e... | TestMarkdownInHTMLPostProcessor |
python | allegroai__clearml | examples/distributed/pytorch_distributed_example.py | {
"start": 521,
"end": 1209
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.L... | Net |
python | graphql-python__graphene | graphene/types/tests/test_json.py | {
"start": 96,
"end": 2347
} | class ____(ObjectType):
json = JSONString(input=JSONString())
def resolve_json(self, info, input):
return input
schema = Schema(query=Query)
def test_jsonstring_query():
json_value = '{"key": "value"}'
json_value_quoted = json_value.replace('"', '\\"')
result = schema.execute("""{ json... | Query |
python | astropy__astropy | astropy/io/fits/card.py | {
"start": 916,
"end": 50087
} | class ____(_Verify):
length = CARD_LENGTH
"""The length of a Card image; should always be 80 for valid FITS files."""
# String for a FITS standard compliant (FSC) keyword.
_keywd_FSC_RE = re.compile(r"^[A-Z0-9_-]{0,%d}$" % KEYWORD_LENGTH) # noqa: UP031, RUF100
# This will match any printable ASCII... | Card |
python | python-poetry__poetry | src/poetry/inspection/info.py | {
"start": 1264,
"end": 1544
} | class ____(ValueError):
def __init__(self, path: Path, *reasons: BaseException | str) -> None:
reasons = (f"Unable to determine package info for path: {path!s}", *reasons)
super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg))
| PackageInfoError |
python | conda__conda | tests/plugins/test_reporter_backends.py | {
"start": 410,
"end": 696
} | class ____(ReporterRendererBase):
"""Dummy reporter backend class only for tests"""
def detail_view(self, data: dict[str, str | int | bool], **kwargs) -> str:
return str(data)
def envs_list(self, data, **kwargs) -> str:
return str(data)
| DummyReporterRenderer |
python | django-extensions__django-extensions | django_extensions/management/commands/create_template_tags.py | {
"start": 178,
"end": 2957
} | class ____(AppCommand):
help = "Creates a Django template tags directory structure for the given app name "
"in the apps's directory"
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--name",
"-n",
action="store",
... | Command |
python | joke2k__faker | faker/providers/automotive/el_GR/__init__.py | {
"start": 59,
"end": 555
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``el_GR`` locale."""
uppercase_letters = "ABEZHIKMNOPTYX"
license_formats = (
"??? ####",
"?? ####",
)
def license_plate(self) -> str:
"""Generate a license plate."""
temp = re.sub(
r"... | Provider |
python | spyder-ide__spyder | spyder/widgets/collectionseditor.py | {
"start": 24939,
"end": 25998
} | class ____(QHeaderView):
"""
A header view for the BaseTableView that emits a signal when the width of
one of its sections is resized by the user.
"""
sig_user_resized_section = Signal(int, int, int)
def __init__(self, parent=None):
super().__init__(Qt.Horizontal, parent)
self._... | BaseHeaderView |
python | walkccc__LeetCode | solutions/3098. Find the Sum of Subsequence Powers/3098.py | {
"start": 0,
"end": 920
} | class ____:
def sumOfPowers(self, nums: list[int], k: int) -> int:
MOD = 1_000_000_007
nums.sort()
@functools.lru_cache(None)
def dp(
i: int,
k: int,
lastPickedIndex: int,
firstIndex: int,
secondIndex: int
) -> int:
if k == 0:
return nums[seco... | Solution |
python | pytorch__pytorch | test/jit/test_freezing.py | {
"start": 1148,
"end": 66969
} | class ____(JitTestCase):
def test_freeze_module(self):
class M(nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = 1 # folded
self.b = 1.2 # folded
self.c = "hello" # folded
self.c2 = "hi\xa1" # n... | TestFreezing |
python | arrow-py__arrow | arrow/locales.py | {
"start": 18155,
"end": 19477
} | class ____(Locale):
names = ["sv", "sv-se"]
past = "för {0} sen"
future = "om {0}"
and_word = "och"
timeframes = {
"now": "just nu",
"second": "en sekund",
"seconds": "{0} sekunder",
"minute": "en minut",
"minutes": "{0} minuter",
"hour": "en timme",... | SwedishLocale |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | {
"start": 1327,
"end": 4050
} | class ____(expression.ColumnElement[_T]):
"""Represent a PostgreSQL aggregate order by expression.
E.g.::
from sqlalchemy.dialects.postgresql import aggregate_order_by
expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
stmt = select(expr)
would represent the e... | aggregate_order_by |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 121691,
"end": 127697
} | class ____(test.TestCase):
def _npBias(self, inputs, bias):
assert len(bias.shape) == 1
assert inputs.shape[-1] == bias.shape[0]
return inputs + bias.reshape(
([1] * (len(inputs.shape) - 1)) + [bias.shape[0]]
)
def testNpBias(self):
self.assertAllClose(
np.array([[11, 22, 33], ... | BiasAddTestBase |
python | django__django | django/contrib/auth/backends.py | {
"start": 1700,
"end": 9259
} | class ____(BaseBackend):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
if username is None or password is None:
... | ModelBackend |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/snippets/expect_column_values_to_equal_three.py | {
"start": 4997,
"end": 15950
} | class ____(ColumnMapExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/expect_column_values_to_equal_three.py docstring">
"""Expect values in this column to equal 3."""
# </snippet>
# These examples will be shown in the public gallery.
# They will also be executed as unit... | ExpectColumnValuesToEqualThree |
python | dagster-io__dagster | python_modules/dagster/dagster/_cli/workspace/cli_target.py | {
"start": 12098,
"end": 25631
} | class ____:
repository: Optional[str] = None
location: Optional[str] = None
@classmethod
def extract_from_cli_options(cls, cli_options: dict[str, object]) -> Self:
return cls(
repository=check.opt_inst(cli_options.pop("repository"), str),
location=check.opt_inst(cli_opti... | RepositoryOpts |
python | lepture__authlib | authlib/oauth2/rfc7523/token.py | {
"start": 90,
"end": 3384
} | class ____:
"""A JSON Web Token formatted bearer token generator for jwt-bearer grant type.
This token generator can be registered into authorization server::
authorization_server.register_token_generator(
"urn:ietf:params:oauth:grant-type:jwt-bearer",
JWTBearerTokenGenerator(pr... | JWTBearerTokenGenerator |
python | pypa__pip | src/pip/_vendor/pkg_resources/__init__.py | {
"start": 8510,
"end": 9372
} | class ____(ResolutionError):
"""
An already-installed version conflicts with the requested version.
Should be initialized with the installed Distribution and the requested
Requirement.
"""
_template = "{self.dist} is installed but {self.req} is required"
@property
def dist(self) -> Di... | VersionConflict |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py | {
"start": 11469,
"end": 11802
} | class ____(BaseModel):
"""Schema for response with previous successful DagRun information for Task Template Context."""
data_interval_start: UtcDateTime | None = None
data_interval_end: UtcDateTime | None = None
start_date: UtcDateTime | None = None
end_date: UtcDateTime | None = None
| PrevSuccessfulDagRunResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/specialization1.py | {
"start": 150,
"end": 202
} | class ____(A):
pass
_T1 = TypeVar("_T1", A, B)
| C |
python | getsentry__sentry | src/sentry/models/projectcodeowners.py | {
"start": 855,
"end": 6567
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
# no db constraint to prevent locks on the Project table
project = FlexibleForeignKey("sentry.Project", db_constraint=False)
# repository_project_path_config ⇒ use this to transform CODEOWNERS paths to stacktrace paths
repository_pr... | ProjectCodeOwners |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/prediction_loop.py | {
"start": 2101,
"end": 18725
} | class ____(_Loop):
"""Top-level loop where prediction starts."""
def __init__(self, trainer: "pl.Trainer", inference_mode: bool = True) -> None:
super().__init__(trainer)
self.inference_mode = inference_mode
# dataloaders x batches x samples. used by PredictionWriter
self.epoch_... | _PredictionLoop |
python | doocs__leetcode | solution/3300-3399/3377.Digit Operations to Make Two Integers Equal/Solution.py | {
"start": 15,
"end": 1534
} | class ____:
def __init__(self):
self.sieve = []
def run_sieve(self):
self.sieve = [True] * 100000
self.sieve[0], self.sieve[1] = False, False
for i in range(2, 100000):
if self.sieve[i]:
for j in range(2 * i, 100000, i):
self.sieve... | Solution |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/organization_integration_serverless_functions.py | {
"start": 724,
"end": 887
} | class ____(CamelSnakeSerializer):
action = serializers.ChoiceField(ACTIONS)
target = serializers.CharField()
@region_silo_endpoint
| ServerlessActionSerializer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1235767,
"end": 1236390
} | class ____(sgqlc.types.Type, Node):
"""A GitHub Enterprise Importer (GEI) migration source."""
__schema__ = github_schema
__field_names__ = ("name", "type", "url")
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
"""The migration source name."""
type = sgqlc.types.Fi... | MigrationSource |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/client/utils.py | {
"start": 657,
"end": 1475
} | class ____(NamedTuple):
"""This class gives information about the result of reloading
a Dagster repository location with a GraphQL mutation.
Args:
status (ReloadRepositoryLocationStatus): The status of the reload repository location mutation
failure_type: (Optional[str], optional): the fail... | ReloadRepositoryLocationInfo |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 56711,
"end": 56788
} | class ____(TestMaskedArrayRepr, QuantitySetup):
pass
| TestMaskedQuantityRepr |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/hybrid.py | {
"start": 43380,
"end": 43589
} | class ____(Protocol[_T_con]):
def __call__(
s,
cls: Any,
value: Union[_T_con, _ColumnExpressionArgument[_T_con]],
) -> List[Tuple[_DMLColumnArgument, Any]]: ...
| _HybridUpdaterType |
python | doocs__leetcode | solution/1400-1499/1419.Minimum Number of Frogs Croaking/Solution.py | {
"start": 0,
"end": 580
} | class ____:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
if len(croakOfFrogs) % 5 != 0:
return -1
idx = {c: i for i, c in enumerate('croak')}
cnt = [0] * 5
ans = x = 0
for i in map(idx.get, croakOfFrogs):
cnt[i] += 1
if i == 0:
... | Solution |
python | walkccc__LeetCode | solutions/2280. Minimum Lines to Represent a Line Chart/2280.py | {
"start": 0,
"end": 598
} | class ____:
def minimumLines(self, stockPrices: list[list[int]]) -> int:
ans = 0
stockPrices.sort()
def getSlope(p: list[int], q: list[int]) -> tuple[int, int]:
dx = p[0] - q[0]
dy = p[1] - q[1]
if dx == 0:
return (0, p[0])
if dy == 0:
return (p[1], 0)
d = g... | Solution |
python | huggingface__transformers | tests/generation/test_utils.py | {
"start": 129866,
"end": 235108
} | class ____(unittest.TestCase):
# TODO joao, manuel: remove in v4.62.0
@slow
def test_diverse_beam_search(self):
article = """Justin Timberlake and Jessica Biel, welcome to parenthood.
The celebrity couple announced the arrival of their son, Silas Randall Timberlake, in statements to People.
... | GenerationIntegrationTests |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 62191,
"end": 64990
} | class ____(T5PreTrainedModel):
def __init__(self, config: T5Config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = T5EncoderModel(config)
self.dropout = nn.Dropout(config.classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, co... | T5ForTokenClassification |
python | streamlit__streamlit | lib/streamlit/runtime/runtime.py | {
"start": 2955,
"end": 4724
} | class ____:
"""Config options for StreamlitRuntime."""
# The filesystem path of the Streamlit script to run.
script_path: str
# DEPRECATED: We need to keep this field around for compatibility reasons, but we no
# longer use this anywhere.
command_line: str | None
# The storage backend for... | RuntimeConfig |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/fetchers.py | {
"start": 2807,
"end": 5105
} | class ____(_DataFetcher):
"""This class is used to control batch fetching flow.
Args:
prefetch_batches: Number of batches to pre-fetch. Pre-fetching at least 1 batch is necessary to properly track
whether a batch is the last one (available with :attr:`self.done`) when the length is not avai... | _PrefetchDataFetcher |
python | getsentry__sentry | tests/sentry/integrations/aws_lambda/test_utils.py | {
"start": 4056,
"end": 7837
} | class ____(TestCase):
node_fn = {
"Runtime": "nodejs10.x",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaB",
}
python_fn = {
"Runtime": "python3.6",
"FunctionArn": "arn:aws:lambda:us-east-2:599817902985:function:lambdaC",
}
cache_value = {
... | GetOptionValueTest |
python | streamlit__streamlit | lib/tests/streamlit/connections/sql_connection_test.py | {
"start": 1312,
"end": 8474
} | class ____(unittest.TestCase):
def tearDown(self) -> None:
st.cache_data.clear()
@patch("sqlalchemy.engine.make_url", MagicMock(return_value="some_sql_conn_string"))
@patch(
"streamlit.connections.sql_connection.SQLConnection._secrets",
PropertyMock(return_value=AttrDict({"url": "so... | SQLConnectionTest |
python | google__jax | jax/_src/pallas/mosaic/sc_core.py | {
"start": 1215,
"end": 2047
} | class ____(pallas_core.MemoryRef):
"""A MemoryRef for SparseCore."""
tiling: Tiling | None = None
def __init__(
self,
shape: Sequence[int],
dtype: jax.typing.DTypeLike,
memory_space: tpu_core.MemorySpace,
tiling: Tiling | None = None,
):
super().__init__(jax_core.ShapedArray(... | MemoryRef |
python | PrefectHQ__prefect | src/prefect/server/concurrency/lease_storage/filesystem.py | {
"start": 548,
"end": 695
} | class ____(TypedDict):
id: str
resource_ids: list[str]
metadata: dict[str, Any] | None
expiration: str
created_at: str
| _LeaseFile |
python | huggingface__transformers | src/transformers/models/phimoe/modeling_phimoe.py | {
"start": 39857,
"end": 40066
} | class ____(GenericForSequenceClassification, PhimoePreTrainedModel): ...
__all__ = ["PhimoePreTrainedModel", "PhimoeModel", "PhimoeForCausalLM", "PhimoeForSequenceClassification"]
| PhimoeForSequenceClassification |
python | getsentry__sentry | src/sentry/users/api/endpoints/user_password.py | {
"start": 748,
"end": 2137
} | class ____(serializers.Serializer[User]):
password = serializers.CharField(required=True, trim_whitespace=False)
passwordNew = serializers.CharField(required=True, trim_whitespace=False)
passwordVerify = serializers.CharField(required=True, trim_whitespace=False)
def validate_password(self, value: str)... | UserPasswordSerializer |
python | pytorch__pytorch | torch/_inductor/dependencies.py | {
"start": 13757,
"end": 13925
} | class ____:
index: sympy.Expr # type: ignore[assignment]
var_names: tuple[sympy.Symbol, ...]
size: tuple[sympy.Expr, ...]
@dataclasses.dataclass
| IndexExprDep |
python | python__mypy | mypyc/namegen.py | {
"start": 75,
"end": 4934
} | class ____:
"""Utility for generating distinct C names from Python names.
Since C names can't use '.' (or unicode), some care is required to
make C names generated from Python names unique. Also, we want to
avoid generating overly long C names since they make the generated
code harder to read.
... | NameGenerator |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py | {
"start": 1130,
"end": 16052
} | class ____(ReleaseValidator):
APACHE_RAT_JAR_DOWNLOAD_URL = (
"https://downloads.apache.org/creadur/apache-rat-0.17/apache-rat-0.17-bin.tar.gz"
)
def __init__(
self,
version: str,
svn_path: Path,
airflow_repo_root: Path,
task_sdk_version: str | None = None,
... | AirflowReleaseValidator |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_schema_enforcement.py | {
"start": 2525,
"end": 3909
} | class ____(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
assert isinstance(params, dict)
assert isinstance(params["str_param"], str)
assert isinstance(params["int_param"], int)
assert isinstance(params["bool_param"], bool)
assert isinstance... | PythonModelWithBasicParams |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 41694,
"end": 41873
} | class ____(BaseModel, extra="forbid"):
formula: "Expression" = Field(..., description="")
defaults: Optional[Dict[str, Any]] = Field(default={}, description="")
| FormulaQuery |
python | numpy__numpy | benchmarks/benchmarks/bench_creation.py | {
"start": 74,
"end": 623
} | class ____(Benchmark):
""" Benchmark meshgrid generation
"""
params = [[16, 32],
[2, 3, 4],
['ij', 'xy'], TYPES1]
param_names = ['size', 'ndims', 'ind', 'ndtype']
timeout = 10
def setup(self, size, ndims, ind, ndtype):
rnd = np.random.RandomState(1864768776)
... | MeshGrid |
python | ApeWorX__ape | src/ape_ethereum/multicall/exceptions.py | {
"start": 557,
"end": 681
} | class ____(MulticallException):
def __init__(self):
super().__init__("Multicall not executed yet.")
| NotExecutedError |
python | python__mypy | mypyc/test/test_misc.py | {
"start": 253,
"end": 690
} | class ____(unittest.TestCase):
def test_debug_op(self) -> None:
block = BasicBlock()
builder = LowLevelIRBuilder(errors=None, options=CompilerOptions())
builder.activate_block(block)
builder.debug_print("foo")
names = generate_names_for_ir([], [block])
code = format_... | TestMisc |
python | getsentry__sentry | src/sentry/integrations/repository/notification_action.py | {
"start": 1622,
"end": 1810
} | class ____(NotificationActionNotificationMessageValidationError):
message = "both action and group need to exist together with a reference"
@dataclass
| ActionAndGroupActionValidationError |
python | huggingface__transformers | src/transformers/models/layoutlmv3/modeling_layoutlmv3.py | {
"start": 37315,
"end": 41582
} | class ____(LayoutLMv3PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.layoutlmv3 = LayoutLMv3Model(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
if config.num_labels < 10:
self.classif... | LayoutLMv3ForTokenClassification |
python | fastai__fastai | fastai/callback/tensorboard.py | {
"start": 3505,
"end": 7389
} | class ____(TensorBoardBaseCallback):
"Extracts and exports image featuers for tensorboard projector during inference"
def __init__(self, log_dir=None, layer=None):
super().__init__()
store_attr()
def before_fit(self):
self.run = not hasattr(self.learn, 'lr_finder') and hasattr(s... | TensorBoardProjectorCallback |
python | django__django | django/core/exceptions.py | {
"start": 1718,
"end": 1835
} | class ____(Exception):
"""The request was closed before it was completed, or timed out."""
pass
| RequestAborted |
python | wandb__wandb | wandb/sdk/internal/job_builder.py | {
"start": 913,
"end": 2014
} | class ____:
def __init__(self, major: int, minor: int, patch: int):
self._major = major
self._minor = minor
self._patch = patch
def __repr__(self) -> str:
return f"{self._major}.{self._minor}.{self._patch}"
def __lt__(self, other: "Version") -> bool:
if self._major ... | Version |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/tfr_gen.py | {
"start": 20488,
"end": 21722
} | class ____(object):
"""Symbol Table for python code."""
def __init__(self):
self.symbols = []
self.enter_scope()
self.scf_scope = 0
# reserved key words
self.insert_symbol('len', 'len', TFRTypes.PY_BUILTIN_FUNC)
def enter_scope(self, scf_scope=False):
"""Enter a new scope - at function l... | SymbolTable |
python | kamyu104__LeetCode-Solutions | Python/faulty-keyboard.py | {
"start": 58,
"end": 452
} | class ____(object):
def finalString(self, s):
"""
:type s: str
:rtype: str
"""
dq = collections.deque()
parity = 0
for x in s:
if x == 'i':
parity ^= 1
else:
dq.appendleft(x) if parity else dq.append(x)
... | Solution |
python | encode__django-rest-framework | tests/browsable_api/test_browsable_nested_api.py | {
"start": 793,
"end": 1294
} | class ____(TestCase):
"""Tests correct dropdown behavior with Auth views enabled."""
@override_settings(ROOT_URLCONF='tests.browsable_api.test_browsable_nested_api')
def test_login(self):
response = self.client.get('/api/')
assert 200 == response.status_code
content = response.conte... | DropdownWithAuthTests |
python | tensorflow__tensorflow | tensorflow/python/training/input_test.py | {
"start": 3708,
"end": 5983
} | class ____(test_lib.TestCase):
def testNoShuffle(self):
with ops.Graph().as_default(), self.cached_session():
input_tensor = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
num_epochs = 2
queue = inp.input_producer(
input_tensor, num_epochs=nu... | InputProducerTest |
python | getsentry__sentry | src/sentry/runner/commands/repair.py | {
"start": 286,
"end": 1787
} | class ____(Exception):
pass
@contextmanager
def catchable_atomic() -> Generator[None]:
try:
with transaction.atomic("default"):
yield
except RollbackLocally:
pass
@region_silo_function
def create_missing_dsns() -> None:
from sentry.models.project import Project
from s... | RollbackLocally |
python | ansible__ansible | lib/ansible/module_utils/facts/system/fips.py | {
"start": 373,
"end": 784
} | class ____(BaseFactCollector):
name = 'fips'
_fact_ids = set() # type: t.Set[str]
def collect(self, module=None, collected_facts=None):
# NOTE: this is populated even if it is not set
fips_facts = {
'fips': False
}
if get_file_content('/proc/sys/crypto/fips_enab... | FipsFactCollector |
python | gwtw__py-sorting | test/radix_sort_test.py | {
"start": 278,
"end": 513
} | class ____(unittest.TestCase,
BasePositiveIntegerSortTest,
BaseNegativeIntegerSortTest):
def setUp(self):
self.sort = radix_sort.sort
if __name__ == '__main__':
unittest.main()
| RadixSortTest |
python | huggingface__transformers | src/transformers/models/biogpt/modeling_biogpt.py | {
"start": 29180,
"end": 34283
} | class ____(BioGptPreTrainedModel):
def __init__(self, config: BioGptConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.biogpt = BioGptModel(config)
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply ... | BioGptForSequenceClassification |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 5018,
"end": 10612
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | BartAttention |
python | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 39087,
"end": 40608
} | class ____(LogFormatter):
"""
Format values for log axis using ``exponent = log_base(value)``.
"""
def _non_decade_format(self, sign_string, base, fx, usetex):
"""Return string for non-decade locations."""
return r'$\mathdefault{%s%s^{%.2f}}$' % (sign_string, base, fx)
def __call__... | LogFormatterMathtext |
python | matplotlib__matplotlib | lib/matplotlib/patheffects.py | {
"start": 7002,
"end": 7832
} | class ____(AbstractPathEffect):
"""A line based PathEffect which re-draws a stroke."""
def __init__(self, offset=(0, 0), **kwargs):
"""
The path will be stroked with its gc updated with the given
keyword arguments, i.e., the keyword arguments should be valid
gc parameter values.... | Stroke |
python | lazyprogrammer__machine_learning_examples | unsupervised_class2/autoencoder.py | {
"start": 1042,
"end": 4337
} | class ____(object):
def __init__(self, M, an_id):
self.M = M
self.id = an_id
def fit(self, X, learning_rate=0.5, mu=0.99, epochs=1, batch_sz=100, show_fig=False):
# cast to float
mu = np.float32(mu)
learning_rate = np.float32(learning_rate)
N, D = X.shape
... | AutoEncoder |
python | plotly__plotly.py | plotly/graph_objs/_candlestick.py | {
"start": 215,
"end": 64788
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "candlestick"
_valid_props = {
"close",
"closesrc",
"customdata",
"customdatasrc",
"decreasing",
"high",
"highsrc",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
... | Candlestick |
python | fluentpython__example-code-2e | 15-more-types/protocol/random/randompop.py | {
"start": 73,
"end": 140
} | class ____(Protocol):
def pop_random(self) -> Any: ...
| RandomPopper |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 184376,
"end": 184774
} | class ____:
_col_type = INT8RANGE
_col_str = "INT8RANGE"
def _data_str(self):
return "[9223372036854775306,9223372036854775800)"
def _data_obj(self):
return Range(9223372036854775306, 9223372036854775800)
_epsilon = 1
def _step_value_up(self, value):
return value + 5
... | _Int8RangeTests |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/check_numerics_callback_test.py | {
"start": 4914,
"end": 17582
} | class ____(test_util.TensorFlowTestCase):
"""Test for cases in which enable_check_numerics() catches infs or nans."""
def tearDown(self):
check_numerics_callback.disable_check_numerics()
super(CheckNumericsCallbackUnhealthyTest, self).tearDown()
def _assertRaisesInvalidArgumentErrorAndGetMessage(self, f... | CheckNumericsCallbackUnhealthyTest |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/selected/_textfont.py | {
"start": 233,
"end": 2456
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl.selected"
_path_str = "scatterpolargl.selected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and may be s... | Textfont |
python | walkccc__LeetCode | solutions/2862. Maximum Element-Sum of a Complete Subset of Indices/2862-2.py | {
"start": 0,
"end": 330
} | class ____:
def maximumSum(self, nums: list[int]) -> int:
ans = 0
for oddPower in range(1, len(nums) + 1):
summ = 0
for num in range(1, len(nums) + 1):
if num * num * oddPower > len(nums):
break
summ += nums[oddPower * num * num - 1]
ans = max(ans, summ)
retur... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 33357,
"end": 36948
} | class ____(ShopifyBulkQuery):
"""
{
customers(query: "updated_at:>='2024-01-20T00:00:00+00:00' AND updated_at:<'2024-01-24T00:00:00+00:00'", sortKey:UPDATED_AT) {
edges {
node {
__typename
customerId: id
defaultAddre... | CustomerAddresses |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 4795,
"end": 4912
} | class ____(SecurityWarning):
"""Warned when making an unverified HTTPS request."""
pass
| InsecureRequestWarning |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/window.py | {
"start": 2229,
"end": 2537
} | class ____(OutlineExplorerWidget):
sig_collapse_requested = Signal()
@Slot()
def close_dock(self):
"""
Reimplemented to preserve the widget's visible state when shown in an
editor window.
"""
self.sig_collapse_requested.emit()
| OutlineExplorerInEditorWindow |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 26640,
"end": 26834
} | class ____(BasenameTestCase, TestCase):
def setUp(self):
self.router = DefaultRouter()
self.router.root_view_name = 'nameable-root'
| TestDuplicateBasenameDefaultRouterRootViewName |
python | readthedocs__readthedocs.org | readthedocs/sso/admin.py | {
"start": 383,
"end": 1636
} | class ____(admin.ModelAdmin):
"""Admin configuration for SSOIntegration."""
list_display = ("organization", "provider")
search_fields = ("organization__slug", "organization__name", "domains__domain")
list_filter = ("provider",)
raw_id_fields = ("organization",)
actions = [
"resync_sso_... | SSOIntegrationAdmin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 3154,
"end": 3232
} | class ____(Variadic[T_co]): ...
# This should generate an error.
| VariadicChildCo |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_grad_test.py | {
"start": 9151,
"end": 9680
} | class ____(test.TestCase):
def testSwishGrad(self):
features = constant_op.constant([[-2, -1, 1, 3]],
dtype=dtypes.float32)
beta = constant_op.constant(0.25, dtype=dtypes.float32)
with self.cached_session():
theoretical, numerical = gradient_checker_v2.compute_g... | SwishGradOpTest |
python | agronholm__apscheduler | examples/gui/qt_executor.py | {
"start": 505,
"end": 1269
} | class ____(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("APScheduler demo")
self.clock = QLabel()
font = self.clock.font()
font.setPointSize(30)
self.clock.setFont(font)
self.update_time()
self.setCentralWidget(self.clock... | MainWindow |
python | kubernetes-client__python | kubernetes/client/models/v1_env_from_source.py | {
"start": 383,
"end": 5214
} | 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... | V1EnvFromSource |
python | ray-project__ray | python/ray/serve/tests/test_list_outbound_deployments.py | {
"start": 258,
"end": 357
} | class ____:
def __call__(self, x: int) -> int:
return x * 2
@serve.deployment
| DownstreamA |
python | numba__numba | numba/core/ir.py | {
"start": 30126,
"end": 30810
} | class ____(EqualityCheckMixin, AbstractRHS):
def __init__(self, value, loc, use_literal_type=True):
assert isinstance(loc, Loc)
self.value = value
self.loc = loc
# Note: need better way to tell if this is a literal or not.
self.use_literal_type = use_literal_type
def __r... | Const |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 1997,
"end": 2448
} | class ____(BaseModel):
data = IntegerField()
misc = IntegerField()
text = TextField(index=True)
user = ForeignKeyField(column_name='user_id', field='username', model=User)
class Meta:
table_name = 'note'
indexes = (
(('user', 'data', 'misc'), False),
(('user'... | Note |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 8709,
"end": 10823
} | class ____(VirtualMachineError):
"""
Raised when there is a contract-defined revert,
such as from an assert/require statement.
"""
def __init__(
self,
revert_message: Optional[str] = None,
txn: Optional[FailedTxn] = None,
trace: _TRACE_ARG = None,
contract_ad... | ContractLogicError |
python | wandb__wandb | wandb/vendor/pygments/lexers/automation.py | {
"start": 475,
"end": 10167
} | class ____(RegexLexer):
"""
For `autohotkey <http://www.autohotkey.com/>`_ source code.
.. versionadded:: 1.4
"""
name = 'autohotkey'
aliases = ['ahk', 'autohotkey']
filenames = ['*.ahk', '*.ahkl']
mimetypes = ['text/x-autohotkey']
tokens = {
'root': [
(r'^(\s*)... | AutohotkeyLexer |
python | sympy__sympy | sympy/assumptions/assume.py | {
"start": 10738,
"end": 14588
} | class ____(Predicate):
"""
Predicate without handler.
Explanation
===========
This predicate is generated by using ``Predicate`` directly for
construction. It does not have a handler, and evaluating this with
arguments is done by SAT solver.
Examples
========
>>> from sympy i... | UndefinedPredicate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.