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 | chroma-core__chroma | chromadb/api/types.py | {
"start": 60318,
"end": 100435
} | class ____:
defaults: ValueTypes
keys: Dict[str, ValueTypes]
def __init__(self) -> None:
# Initialize the dataclass fields first
self.defaults = ValueTypes()
self.keys: Dict[str, ValueTypes] = {}
# Populate with sensible defaults automatically
self._initialize_defau... | Schema |
python | dask__dask | dask/array/_array_expr/_collection.py | {
"start": 896,
"end": 51412
} | class ____(DaskMethodsMixin):
__dask_scheduler__ = staticmethod(
named_schedulers.get("threads", named_schedulers["sync"])
)
__dask_optimize__ = staticmethod(lambda dsk, keys, **kwargs: dsk)
def __init__(self, expr):
self._expr = expr
@property
def expr(self) -> ArrayExpr:
... | Array |
python | tornadoweb__tornado | demos/websocket/chatdemo.py | {
"start": 1536,
"end": 3013
} | class ____(tornado.websocket.WebSocketHandler):
waiters = set()
cache = []
cache_size = 200
def get_compression_options(self):
# Non-None enables compression with default options.
return {}
def open(self):
ChatSocketHandler.waiters.add(self)
def on_close(self):
... | ChatSocketHandler |
python | numba__numba | numba/core/callwrapper.py | {
"start": 2855,
"end": 8450
} | class ____(object):
def __init__(self, context, module, func, fndesc, env, call_helper,
release_gil):
self.context = context
self.module = module
self.func = func
self.fndesc = fndesc
self.env = env
self.release_gil = release_gil
def build(self):... | PyCallWrapper |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/gradients_test.py | {
"start": 22706,
"end": 27689
} | class ____(test.Benchmark):
def _run(self, targets, iters, name=None):
def _done(t):
# Note that we don't use tf.control_dependencies since that will not make
# sure that the computation on GPU has actually finished. So we fetch the
# first element of the output, and assume that this will not ... | GradientsBenchmarks |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py | {
"start": 149,
"end": 797
} | class ____(object):
__slots__ = 'kind', 'start', 'end', 'value'
def __init__(self, kind, start, end, value=None):
self.kind = kind
self.start = start
self.end = end
self.value = value
def __repr__(self):
return u'<Token kind={} at {}..{} value={}>'.format(
... | Token |
python | automl__auto-sklearn | test/test_pipeline/components/classification/test_random_forest.py | {
"start": 169,
"end": 992
} | class ____(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris"] = 0.96
res["iris_n_calls"] = 9
res["default_iris_iterative"] = res["default_iris"]
res["default_iris_proba"] = 0.0996785324703419
res["default_iris_sparse"] = 0.85999999999999999
res["default_... | RandomForestComponentTest |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 82914,
"end": 83484
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING
# override to give better return typehint
@classmethod
def from_pretrained(
cls: type["AutoModelForCausalLM"],
pretrained_model_name_or_path: Union[str, os.PathLike[str]],
*model_args,
**kwargs... | AutoModelForCausalLM |
python | Pylons__pyramid | tests/test_view.py | {
"start": 25523,
"end": 28935
} | class ____(BaseTest, unittest.TestCase):
def _callFUT(self, context, request):
from pyramid.view import append_slash_notfound_view
return append_slash_notfound_view(context, request)
def _registerMapper(self, reg, match=True):
from pyramid.interfaces import IRoutesMapper
class... | Test_append_slash_notfound_view |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 11736,
"end": 13068
} | class ____(Warning):
"""
Warning raised when reading a file that doesn't use the default 'c' parser.
Raised by `pd.read_csv` and `pd.read_table` when it is necessary to change
parsers, generally from the default 'c' parser to 'python'.
It happens due to a lack of support or functionality for parsi... | ParserWarning |
python | doocs__leetcode | solution/2300-2399/2351.First Letter to Appear Twice/Solution2.py | {
"start": 0,
"end": 217
} | class ____:
def repeatedCharacter(self, s: str) -> str:
mask = 0
for c in s:
i = ord(c) - ord('a')
if mask >> i & 1:
return c
mask |= 1 << i
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/edx/provider.py | {
"start": 213,
"end": 408
} | class ____(ProviderAccount):
def get_profile_url(self):
if self.account.extra_data["profile_image"]["has_image"]:
return self.account.extra_data["image_url_full"]
| EdxAccount |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/padding.py | {
"start": 2160,
"end": 2854
} | class ____(MGF):
def __init__(self, algorithm: hashes.HashAlgorithm):
if not isinstance(algorithm, hashes.HashAlgorithm):
raise TypeError("Expected instance of hashes.HashAlgorithm.")
self._algorithm = algorithm
def calculate_max_pss_salt_length(
key: rsa.RSAPrivateKey | rsa.RSAPu... | MGF1 |
python | astropy__astropy | astropy/modeling/polynomial.py | {
"start": 51507,
"end": 54905
} | class ____(Model):
"""
Simple Imaging Polynomial (SIP) model.
The SIP convention is used to represent distortions in FITS image headers.
See [1]_ for a description of the SIP convention.
Parameters
----------
crpix : list or (2,) ndarray
CRPIX values
a_order : int
SIP p... | SIP |
python | wandb__wandb | wandb/vendor/pygments/lexers/actionscript.py | {
"start": 513,
"end": 6405
} | class ____(RegexLexer):
"""
For ActionScript source code.
.. versionadded:: 0.9
"""
name = 'ActionScript'
aliases = ['as', 'actionscript']
filenames = ['*.as']
mimetypes = ['application/x-actionscript', 'text/x-actionscript',
'text/actionscript']
flags = re.DOTALL... | ActionScriptLexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/properties.py | {
"start": 3090,
"end": 16154
} | class ____(
_DataclassDefaultsDontSet,
_MapsColumns[_T],
StrategizedProperty[_T],
_IntrospectsAnnotations,
log.Identified,
):
"""Describes an object attribute that corresponds to a table column
or other column expression.
Public constructor is the :func:`_orm.column_property` function.
... | ColumnProperty |
python | pytorch__pytorch | torch/nn/utils/prune.py | {
"start": 19069,
"end": 21488
} | class ____(BasePruningMethod):
r"""Prune (currently unpruned) units in a tensor at random.
Args:
name (str): parameter name within ``module`` on which pruning
will act.
amount (int or float): quantity of parameters to prune.
If ``float``, should be between 0.0 and 1.0 an... | RandomUnstructured |
python | pytorch__pytorch | torch/_guards.py | {
"start": 39397,
"end": 40308
} | class ____:
def is_dict_key(self) -> bool:
return False
def is_ephemeral(self) -> bool:
return False
def reconstruct(self, codegen: PyCodegen) -> None:
raise NotImplementedError
def guard_source(self) -> GuardSource:
raise NotImplementedError
def name(self) -> str... | Source |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_raise.py | {
"start": 8339,
"end": 10183
} | class ____(__TestCase):
def raiser(self):
raise ValueError
def test_attrs(self):
try:
self.raiser()
except Exception as exc:
tb = exc.__traceback__
self.assertIsInstance(tb.tb_next, types.TracebackType)
self.assertIs(tb.tb_frame, sys._getframe()... | TestTracebackType |
python | kamyu104__LeetCode-Solutions | Python/eliminate-maximum-number-of-monsters.py | {
"start": 33,
"end": 463
} | class ____(object):
def eliminateMaximum(self, dist, speed):
"""
:type dist: List[int]
:type speed: List[int]
:rtype: int
"""
for i in xrange(len(dist)):
dist[i] = (dist[i]-1)//speed[i]
dist.sort()
result = 0
for i in xrange(len(dis... | Solution |
python | encode__django-rest-framework | tests/test_relations_hyperlink.py | {
"start": 11088,
"end": 18995
} | class ____(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
new_target = ForeignKeyTarget(name='target-2')
new_target.save()
for idx in range(1, 4):
source = ForeignKeySource(name='source-%d' % idx, target=target)
so... | HyperlinkedForeignKeyTests |
python | sympy__sympy | sympy/functions/elementary/complexes.py | {
"start": 25365,
"end": 27314
} | class ____(DefinedFunction):
"""
Returns the *complex conjugate* [1]_ of an argument.
In mathematics, the complex conjugate of a complex number
is given by changing the sign of the imaginary part.
Thus, the conjugate of the complex number
:math:`a + ib` (where $a$ and $b$ are real numbers) is :... | conjugate |
python | ray-project__ray | rllib/algorithms/appo/torch/appo_torch_learner.py | {
"start": 1253,
"end": 9029
} | class ____(APPOLearner, IMPALATorchLearner):
"""Implements APPO loss / update logic on top of IMPALATorchLearner."""
@override(IMPALATorchLearner)
def compute_loss_for_module(
self,
*,
module_id: ModuleID,
config: APPOConfig,
batch: Dict,
fwd_out: Dict[str, T... | APPOTorchLearner |
python | aimacode__aima-python | deep_learning4e.py | {
"start": 4368,
"end": 5146
} | class ____(Layer):
"""
1D convolution layer of in neural network.
:param kernel_size: convolution kernel size
"""
def __init__(self, size=3, kernel_size=3):
super().__init__(size)
# init convolution kernel as gaussian kernel
for node in self.nodes:
node.weights =... | ConvLayer1D |
python | getsentry__sentry | tests/sentry/web/frontend/test_shared_group_details.py | {
"start": 250,
"end": 3130
} | class ____(TestCase):
def setUp(self) -> None:
self.group = self.create_group(project=self.project)
self.org_domain = f"{self.organization.slug}.testserver"
def share_group(self) -> GroupShare:
with assume_test_silo_mode(SiloMode.REGION):
return GroupShare.objects.create(
... | SharedGroupDetailsTest |
python | dask__dask | dask/dataframe/dask_expr/_describe.py | {
"start": 3362,
"end": 3579
} | class ____(DescribeNumericAggregate):
_parameters = ["name"]
_defaults = {}
@staticmethod
def operation(name, *stats):
return describe_nonnumeric_aggregate(stats, name)
| DescribeNonNumericAggregate |
python | pytorch__pytorch | torch/_inductor/compiler_bisector.py | {
"start": 399,
"end": 455
} | class ____(Subsystem):
pass
@dataclass
| BisectSubsystem |
python | python__mypy | mypyc/irbuild/mapper.py | {
"start": 1097,
"end": 9604
} | class ____:
"""Keep track of mappings from mypy concepts to IR concepts.
For example, we keep track of how the mypy TypeInfos of compiled
classes map to class IR objects.
This state is shared across all modules being compiled in all
compilation groups.
"""
def __init__(self, group_map: di... | Mapper |
python | rq__rq | rq/queue.py | {
"start": 1796,
"end": 58619
} | class ____:
job_class: type['Job'] = Job
death_penalty_class: type[BaseDeathPenalty] = UnixSignalDeathPenalty
DEFAULT_TIMEOUT: int = 180 # Default timeout seconds.
redis_queue_namespace_prefix: str = 'rq:queue:'
redis_queues_keys: str = 'rq:queues'
@classmethod
def all(
cls,
... | Queue |
python | huggingface__transformers | src/transformers/models/wavlm/modular_wavlm.py | {
"start": 22755,
"end": 22799
} | class ____(Wav2Vec2Model):
pass
| WavLMModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/trino_to_gcs.py | {
"start": 1229,
"end": 5043
} | class ____:
"""
An adapter that adds additional feature to the Trino cursor.
The implementation of cursor in the trino library is not sufficient.
The following changes have been made:
* The poke mechanism for row. You can look at the next row without consuming it.
* The description attribute i... | _TrinoToGCSTrinoCursorAdapter |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_index.py | {
"start": 244,
"end": 2590
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-index"
def setUp(self) -> None:
super().setUp()
self.superuser = self.create_user("bar@example.com", is_superuser=True)
self.normal_user = self.create_user("foo@example.com", is_superuser=False)
self.login_as(user=self.supe... | UserListTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 61897,
"end": 64045
} | class ____(Response):
"""
Response of workers.get_metric_keys endpoint.
:param categories: List of unique metric categories found in the statistics of
the requested workers.
:type categories: Sequence[MetricsCategory]
"""
_service = "workers"
_action = "get_metric_keys"
_versio... | GetMetricKeysResponse |
python | PyCQA__pylint | pylint/extensions/_check_docs_utils.py | {
"start": 15376,
"end": 17035
} | class ____(SphinxDocstring):
"""Epytext is similar to Sphinx.
See the docs:
http://epydoc.sourceforge.net/epytext.html
http://epydoc.sourceforge.net/fields.html#fields
It's used in PyCharm:
https://www.jetbrains.com/help/pycharm/2016.1/creating-documentation-comments.html#d848203e3... | EpytextDocstring |
python | celery__celery | t/unit/app/test_amqp.py | {
"start": 6560,
"end": 7193
} | class ____:
def test_kwargs_must_be_mapping(self):
with pytest.raises(TypeError):
self.app.amqp.as_task_v1(uuid(), 'foo', kwargs=[1, 2])
def test_args_must_be_list(self):
with pytest.raises(TypeError):
self.app.amqp.as_task_v1(uuid(), 'foo', args='abc')
def test_co... | test_AMQP_proto1 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/totalOrdering1.py | {
"start": 413,
"end": 459
} | class ____:
val1: int
@total_ordering
| ClassB |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/exceptions.py | {
"start": 1130,
"end": 1258
} | class ____(AirflowException):
"""Raised when an error is encountered while trying access Kubernetes API."""
| KubernetesApiError |
python | python-pillow__Pillow | src/PIL/ImageShow.py | {
"start": 6061,
"end": 6555
} | class ____(UnixViewer):
"""
The freedesktop.org ``xdg-open`` command.
"""
def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:
command = executable = "xdg-open"
return command, executable
def show_file(self, path: str, **options: Any) -> int:
"""
... | XDGViewer |
python | pandas-dev__pandas | pandas/tests/arrays/categorical/test_api.py | {
"start": 17243,
"end": 19778
} | class ____:
def test_codes_immutable(self):
# Codes should be read only
c = Categorical(["a", "b", "c", "a", np.nan])
exp = np.array([0, 1, 2, 0, -1], dtype="int8")
tm.assert_numpy_array_equal(c.codes, exp)
# Assignments to codes should raise
msg = "property 'codes' ... | TestPrivateCategoricalAPI |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 783,
"end": 1744
} | class ____(unittest.TestCase):
@contextlib.contextmanager
def expect_error(self, **kwargs):
[(key, msg)] = kwargs.items()
with self.assertRaises(UnexpectedError) as cm:
yield
if isinstance(msg, re.Pattern):
self.assertRegex(str(cm.exception), f'^{key}="{msg.patter... | TestCase |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 5811,
"end": 6263
} | class ____(CtrlNode):
"""Gaussian smoothing filter."""
nodeName = 'GaussianFilter'
uiTemplate = [
('sigma', 'doubleSpin', {'min': 0, 'max': 1000000})
]
def processData(self, data):
sigma = self.ctrls['sigma'].value()
try:
import scipy.ndimage
retu... | Gaussian |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1051983,
"end": 1052739
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for VerifiableDomain."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("VerifiableDomainEdge"), graphql_name="edges")
"""A list of edges."""
... | VerifiableDomainConnection |
python | doocs__leetcode | solution/0200-0299/0230.Kth Smallest Element in a BST/Solution2.py | {
"start": 841,
"end": 983
} | class ____:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
bst = BST(root)
return bst.kthSmallest(k)
| Solution |
python | huggingface__transformers | src/transformers/models/got_ocr2/configuration_got_ocr2.py | {
"start": 1288,
"end": 5502
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GotOcr2VisionModel`]. It is used to instantiate a GOT_OCR2
vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
defaults will yield a simila... | GotOcr2VisionConfig |
python | Pylons__pyramid | docs/quick_tutorial/logging/tutorial/views.py | {
"start": 155,
"end": 500
} | class ____:
def __init__(self, request):
self.request = request
@view_config(route_name='home')
def home(self):
log.debug('In home view')
return {'name': 'Home View'}
@view_config(route_name='hello')
def hello(self):
log.debug('In hello view')
return {'name'... | TutorialViews |
python | coleifer__peewee | tests/schema.py | {
"start": 29746,
"end": 30297
} | class ____(BaseTestCase):
def test_set_table_name(self):
class Foo(TestModel):
pass
self.assertEqual(Foo._meta.table_name, 'foo')
self.assertEqual(Foo._meta.table.__name__, 'foo')
# Writing the attribute directly does not update the cached Table name.
Foo._meta.... | TestModelSetTableName |
python | allegroai__clearml | clearml/backend_api/session/datamodel.py | {
"start": 1257,
"end": 4917
} | class ____(object):
"""Data Model"""
_schema = None
_data_props_list = None
@classmethod
def _get_data_props(cls) -> Dict[str, str]:
props = cls._data_props_list
if props is None:
props = {}
for c in cls.__mro__:
props.update({k: getattr(v, "... | DataModel |
python | ray-project__ray | release/ray_release/tests/test_buildkite.py | {
"start": 1976,
"end": 28730
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.buildkite = {}
self.buildkite_mock = MockBuildkiteAgent(self.buildkite)
def testSplitRayRepoStr(self):
url, branch = split_ray_repo_str("https://github.com/ray-project/ray.git")
self.assertEqual(url, "https://github.co... | BuildkiteSettingsTest |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/linux/mkl/set-build-env.py | {
"start": 3560,
"end": 3993
} | class ____(IntelPlatform):
def __init__(self):
IntelPlatform.__init__(self, 4, 8)
def get_bazel_gcc_flags(self):
NEHALEM_ARCH_OLD = "corei7"
NEHALEM_ARCH_NEW = "nehalem"
if self.use_old_arch_names(4, 9):
return self.BAZEL_PREFIX_ + self.ARCH_PREFIX_ + \
NEHALEM_ARCH_OLD + " "
... | NehalemPlatform |
python | agronholm__apscheduler | src/apscheduler/datastores/base.py | {
"start": 678,
"end": 1163
} | class ____(BaseDataStore, RetryMixin):
"""
Base class for data stores using an external service such as a database.
:param serializer: the serializer used to (de)serialize tasks, schedules and jobs
for storage
:param start_from_scratch: erase all existing data during startup (useful for test
... | BaseExternalDataStore |
python | django-guardian__django-guardian | guardian/testapp/models.py | {
"start": 3636,
"end": 3902
} | class ____(AbstractBaseUser, GuardianUserMixin):
email = models.EmailField(max_length=100, unique=True)
USERNAME_FIELD = "email"
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
| CustomUsernameUser |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/schemas/role_and_permission_schema.py | {
"start": 2251,
"end": 2526
} | class ____(Schema):
"""List of roles."""
roles = fields.List(fields.Nested(RoleSchema))
total_entries = fields.Int()
role_schema = RoleSchema()
role_collection_schema = RoleCollectionSchema()
action_collection_schema = ActionCollectionSchema()
| RoleCollectionSchema |
python | protocolbuffers__protobuf | python/google/protobuf/internal/field_mask.py | {
"start": 5322,
"end": 10438
} | class ____(object):
"""Represents a FieldMask in a tree structure.
For example, given a FieldMask "foo.bar,foo.baz,bar.baz",
the FieldMaskTree will be:
[_root] -+- foo -+- bar
| |
| +- baz
|
+- bar --- baz
In the tree, each leaf node represents ... | _FieldMaskTree |
python | modin-project__modin | modin/config/envvars.py | {
"start": 13373,
"end": 21667
} | class ____(EnvironmentVariableDisallowingExecutionAndBackendBothSet, type=str):
"""
An alias for execution, i.e. the combination of StorageFormat and Engine.
Setting backend may change StorageFormat and/or Engine to the corresponding
respective values, and setting Engine or StorageFormat may change Bac... | Backend |
python | joke2k__faker | faker/providers/currency/en_US/__init__.py | {
"start": 46,
"end": 261
} | class ____(CurrencyProvider):
price_formats = ["#.##", "%#.##", "%##.##", "%,###.##", "%#,###.##"]
def pricetag(self) -> str:
return "$" + self.numerify(self.random_element(self.price_formats))
| Provider |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/gcs_upload.py | {
"start": 1692,
"end": 1772
} | class ____(NamedTuple):
uploaded: bool
blob_id: str
@dataclass
| MaybeUpload |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 37967,
"end": 46036
} | class ____(Colormap):
"""
Colormap objects based on lookup tables using linear segments.
The lookup table is generated using linear interpolation for each
primary color, with the 0-1 domain divided into any number of
segments.
"""
def __init__(self, name, segmentdata, N=256, gamma=1.0, *,
... | LinearSegmentedColormap |
python | openai__openai-python | src/openai/types/beta/chatkit/chatkit_thread_user_message_item.py | {
"start": 1395,
"end": 2153
} | class ____(BaseModel):
id: str
"""Identifier of the thread item."""
attachments: List[ChatKitAttachment]
"""Attachments associated with the user message. Defaults to an empty list."""
content: List[Content]
"""Ordered content elements supplied by the user."""
created_at: int
"""Unix t... | ChatKitThreadUserMessageItem |
python | encode__starlette | tests/test_authentication.py | {
"start": 875,
"end": 2511
} | class ____(AuthenticationBackend):
async def authenticate(
self,
request: HTTPConnection,
) -> tuple[AuthCredentials, SimpleUser] | None:
if "Authorization" not in request.headers:
return None
auth = request.headers["Authorization"]
try:
scheme, c... | BasicAuth |
python | django__django | tests/indexes/models.py | {
"start": 862,
"end": 1282
} | class ____(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
published = models.BooleanField(default=False)
# Add virtual relation to the ArticleTranslation model.
translation = CurrentTranslation(
ArticleTranslation, models.CASCADE, ["id"], ["arti... | Article |
python | jazzband__django-waffle | waffle/tests/test_templates.py | {
"start": 660,
"end": 2378
} | class ____(TestCase):
def test_django_tags(self):
request = get()
response = process_request(request, views.flag_in_django)
self.assertContains(response, 'flag off')
self.assertContains(response, 'switch off')
self.assertContains(response, 'sample')
self.assertContain... | WaffleTemplateTests |
python | spack__spack | lib/spack/spack/util/web.py | {
"start": 1015,
"end": 1912
} | class ____(HTTPError):
def __init__(
self, req: Request, code: int, msg: str, hdrs: email.message.Message, fp: Optional[IO]
) -> None:
self.req = req
super().__init__(req.get_full_url(), code, msg, hdrs, fp)
def __str__(self):
# Note: HTTPError, is actually a kind of non-see... | DetailedHTTPError |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_weekday.py | {
"start": 948,
"end": 1921
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.weekday"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, col... | ColumnValuesToBeWeekday |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 1835,
"end": 3193
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testAssertIntegerForm(self):
# This should only be detected as an integer.
x = array_ops.placeholder(dtypes.float32)
y = array_ops.placeholder(dtypes.float32)
# First component isn't less than float32.eps = 1e-7
z = array_ops.placehold... | AssertCloseTest |
python | wandb__wandb | wandb/sdk/lib/lazyloader.py | {
"start": 69,
"end": 1891
} | class ____(types.ModuleType):
"""Lazily import a module, mainly to avoid pulling in large dependencies.
We use this for tensorflow and other optional libraries primarily at the
top module level.
"""
# The lint error here is incorrect.
def __init__(
self,
local_name, # pylint: ... | LazyLoader |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_airbyte_utils.py | {
"start": 458,
"end": 2735
} | class ____(AirbyteCloudWorkspace):
@cached_method
def fetch_airbyte_workspace_data(
self,
) -> AirbyteWorkspaceData:
"""Retrieves all Airbyte content from the workspace and returns it as a AirbyteWorkspaceData object.
Returns:
AirbyteWorkspaceData: A snapshot of the Airb... | MockAirbyteWorkspace |
python | django__django | django/views/generic/list.py | {
"start": 315,
"end": 5177
} | class ____(ContextMixin):
"""A mixin for views manipulating multiple objects."""
allow_empty = True
queryset = None
model = None
paginate_by = None
paginate_orphans = 0
context_object_name = None
paginator_class = Paginator
page_kwarg = "page"
ordering = None
def get_querys... | MultipleObjectMixin |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 27886,
"end": 32626
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: DetrConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = DetrAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_heads,
dropout=config.attention... | DetrDecoderLayer |
python | getsentry__sentry | tests/sentry/integrations/api/serializers/rest_framework/test_data_forwarder.py | {
"start": 608,
"end": 20189
} | class ____(TestCase):
def setUp(self) -> None:
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
def test_basic_field_validation(self) -> None:
serializer = DataForwarderSerializer(
data={
"organ... | DataForwarderSerializerTest |
python | spack__spack | lib/spack/spack/vendor/attr/validators.py | {
"start": 7760,
"end": 9232
} | class ____:
options = attrib()
def __call__(self, inst, attr, value):
try:
in_options = value in self.options
except TypeError: # e.g. `1 in "abc"`
in_options = False
if not in_options:
raise ValueError(
"'{name}' must be in {options... | _InValidator |
python | django__django | tests/custom_managers/models.py | {
"start": 6353,
"end": 6518
} | class ____(models.Model):
abstract_persons = models.Manager()
objects = models.CharField(max_length=30)
class Meta:
abstract = True
| AbstractPerson |
python | mkdocs__mkdocs | mkdocs/tests/config/config_tests.py | {
"start": 360,
"end": 11000
} | class ____(unittest.TestCase):
def test_missing_config_file(self):
with self.assertRaises(ConfigurationError):
config.load_config(config_file='bad_filename.yaml')
def test_missing_site_name(self):
conf = defaults.MkDocsConfig()
conf.load_dict({})
errors, warnings = c... | ConfigTests |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_circulant.py | {
"start": 6876,
"end": 28766
} | class ____(linear_operator.LinearOperator):
"""Base class for circulant operators. Not user facing.
`LinearOperator` acting like a [batch] [[nested] block] circulant matrix.
"""
def __init__(self,
spectrum: tensor.Tensor,
block_depth: int,
input_output_dtype=dtype... | _BaseLinearOperatorCirculant |
python | pytorch__pytorch | torch/_dynamo/variables/torch.py | {
"start": 90506,
"end": 91734
} | class ____(BaseTorchVariable):
"""represents torch.DispatchKeySet"""
@staticmethod
def create(value, **kwargs):
return DispatchKeySetVariable(value, **kwargs)
@classmethod
def create_with_source(cls, value, source):
install_guard(source.make_guard(GuardBuilder.DISPATCH_KEY_SET_MATC... | DispatchKeySetVariable |
python | getsentry__sentry | tests/sentry/data_export/test_tasks.py | {
"start": 47420,
"end": 47603
} | class ____(TestCase, SnubaTestCase):
def test_task_persistent_name(self) -> None:
assert merge_export_blobs.name == "sentry.data_export.tasks.merge_blobs"
| MergeExportBlobsTest |
python | streamlit__streamlit | lib/tests/streamlit/runtime/metrics_util_test.py | {
"start": 5716,
"end": 18343
} | class ____(DeltaGeneratorTestCase):
def setUp(self):
super().setUp()
ctx = get_script_run_ctx()
assert ctx is not None
ctx.reset()
ctx.gather_usage_stats = True
@parameterized.expand(
[
(10, "int"),
(0.01, "float"),
(True, "bo... | PageTelemetryTest |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/combining.py | {
"start": 15224,
"end": 17765
} | class ____(IterDataPipe):
r"""
Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``).
A list of the child DataPipes is returned from this operation.
Args:
datapipe: Iterable DataPipe being filtered
num_instances: n... | DemultiplexerIterDataPipe |
python | encode__django-rest-framework | tests/test_relations_pk.py | {
"start": 1807,
"end": 2005
} | class ____(serializers.ModelSerializer):
class Meta:
model = NullableForeignKeySource
fields = ('id', 'name', 'target')
# Nullable UUIDForeignKey
| NullableForeignKeySourceSerializer |
python | getsentry__sentry | src/sentry/runner/decorators.py | {
"start": 224,
"end": 2680
} | class ____(click.Choice[str]):
def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str:
self.choices = [choice.upper() for choice in self.choices]
return super().convert(value.upper(), param, ctx)
def configuration(f: Callable[P, R]) -> Callable[P, R]:
"L... | CaseInsensitiveChoice |
python | pytorch__pytorch | torch/_dynamo/guards.py | {
"start": 33276,
"end": 36049
} | class ____:
# Represents where is the attr name is present in the nn module attribute
# access
# Tells that the attribute can be accessed via __dict__
present_in_generic_dict: bool = False
# Either the actual name or _parameters/_buffers/_modules
l1_key: Optional[str] = None
# Actual para... | NNModuleAttrAccessorInfo |
python | doocs__leetcode | solution/1600-1699/1649.Create Sorted Array through Instructions/Solution.py | {
"start": 357,
"end": 729
} | class ____:
def createSortedArray(self, instructions: List[int]) -> int:
m = max(instructions)
tree = BinaryIndexedTree(m)
ans = 0
mod = 10**9 + 7
for i, x in enumerate(instructions):
cost = min(tree.query(x - 1), i - tree.query(x))
ans += cost
... | Solution |
python | python-openxml__python-docx | src/docx/oxml/text/parfmt.py | {
"start": 11632,
"end": 12221
} | class ____(BaseOxmlElement):
"""``<w:tabs>`` element, container for a sorted sequence of tab stops."""
tab = OneOrMore("w:tab", successors=())
def insert_tab_in_order(self, pos, align, leader):
"""Insert a newly created `w:tab` child element in `pos` order."""
new_tab = self._new_tab()
... | CT_TabStops |
python | google__jax | jax/_src/util.py | {
"start": 11312,
"end": 16136
} | class ____:
# Stands for an arg/kwarg that was replaced with a weakref
pass
_multi_weakref_placeholder = MultiWeakRefPlaceholder()
# The types of arguments for which `multi_weakref_lru_cache` should keep
# weak references.
weakref_cache_key_types: set[Type] = set()
def is_weakref_cache_key_type(v):
return callab... | MultiWeakRefPlaceholder |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/unit_tests.py | {
"start": 2203,
"end": 2795
} | class ____(dg.Config):
my_int: int
@dg.op
def op_requires_config(config: MyOpConfig):
return config.my_int * 2
# end_op_requires_config
# start_op_invocation_config
def test_op_with_config():
assert op_requires_config(MyOpConfig(my_int=5)) == 10
# end_op_invocation_config
# start_op_requires_cont... | MyOpConfig |
python | mlflow__mlflow | mlflow/tracking/fluent.py | {
"start": 8394,
"end": 129860
} | class ____(Run):
"""Wrapper around :py:class:`mlflow.entities.Run` to enable using Python ``with`` syntax."""
def __init__(self, run):
Run.__init__(self, run.info, run.data)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
active_run_stack = _act... | ActiveRun |
python | bokeh__bokeh | src/bokeh/core/property/datetime.py | {
"start": 4859,
"end": 6071
} | class ____(Property[datetime.timedelta]):
""" Accept TimeDelta values.
"""
def __init__(self, default: Init[datetime.timedelta] = datetime.timedelta(), *, help: str | None = None) -> None:
super().__init__(default=default, help=help)
def transform(self, value: Any) -> Any:
value = sup... | TimeDelta |
python | realpython__materials | intro-to-threading/prodcom_lock.py | {
"start": 118,
"end": 2195
} | class ____:
"""
Class to allow a single element pipeline
between producer and consumer.
"""
def __init__(self):
self.message = 0
self.producer_lock = threading.Lock()
self.consumer_lock = threading.Lock()
self.consumer_lock.acquire()
def get_message(self, name):... | Pipeline |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 82141,
"end": 83283
} | class ____(Response):
"""
Response of projects.make_public endpoint.
:param updated: Number of projects updated
:type updated: int
"""
_service = "projects"
_action = "make_public"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"updated"... | MakePublicResponse |
python | vyperlang__vyper | vyper/semantics/analysis/data_positions.py | {
"start": 3940,
"end": 15193
} | class ____:
"""
Keep track of which storage slots have been used. If there is a collision of
storage slots, this will raise an error and fail to compile
"""
def __init__(self):
self.occupied_slots: dict[int, str] = {}
def reserve_slot_range(self, first_slot: int, n_slots: int, var_name... | OverridingStorageAllocator |
python | yaml__pyyaml | lib/yaml/cyaml.py | {
"start": 2995,
"end": 3851
} | class ____(CEmitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=False,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
... | CDumper |
python | openai__openai-python | src/openai/resources/evals/runs/output_items.py | {
"start": 11468,
"end": 11842
} | class ____:
def __init__(self, output_items: AsyncOutputItems) -> None:
self._output_items = output_items
self.retrieve = _legacy_response.async_to_raw_response_wrapper(
output_items.retrieve,
)
self.list = _legacy_response.async_to_raw_response_wrapper(
outp... | AsyncOutputItemsWithRawResponse |
python | sympy__sympy | sympy/codegen/cnodes.py | {
"start": 2753,
"end": 3044
} | class ____(Basic):
""" Represents the post-increment operator
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cnodes import PostIncrement
>>> from sympy import ccode
>>> ccode(PostIncrement(x))
'(x)++'
"""
nargs = 1
| PostIncrement |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_stats.py | {
"start": 114628,
"end": 118519
} | class ____(APITestCase, SnubaTestCase, OurLogTestCase):
# This is implemented almost exactly the same as spans, add a simple test case for a sanity check
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.day_ago = before_now(days=1).replace(hour=10, minute=0, s... | OrganizationEventsStatsTopNEventsLogs |
python | OmkarPathak__pygorithm | pygorithm/data_structures/trie.py | {
"start": 228,
"end": 3224
} | class ____:
def __init__(self):
self.root = Node('') #The root of the trie is always empty
def insert(self, word):
"""
Inserts a word in the trie. Starting from the root, move down the trie
following the path of characters in the word. If the nodes for the word
character... | Trie |
python | getsentry__sentry | src/sentry/seer/sentry_data_models.py | {
"start": 466,
"end": 771
} | class ____(BaseModel):
span_id: str | None = None
parent_span_id: str | None = None
timestamp: float | None = None
op: str | None = None
description: str | None = None
exclusive_time: float | None = None # duration in milliseconds
data: dict[str, Any] | None = None
| EvidenceSpan |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_type_check.py | {
"start": 1892,
"end": 3983
} | class ____(TestCase):
def test_default_1(self):
for itype in "1bcsuwil":
assert_equal(mintypecode(itype), "d")
assert_equal(mintypecode("f"), "f")
assert_equal(mintypecode("d"), "d")
assert_equal(mintypecode("F"), "F")
assert_equal(mintypecode("D"), "D")
def ... | TestMintypecode |
python | wandb__wandb | tools/graphql_codegen/plugin_utils.py | {
"start": 5003,
"end": 5168
} | class ____(ParsedConstraints):
min: int | None = Field(None, serialization_alias="ge")
max: int | None = Field(None, serialization_alias="le")
| NumericConstraints |
python | gevent__gevent | src/gevent/_config.py | {
"start": 16415,
"end": 16901
} | class ____(FloatSettingMixin, Setting):
name = 'memory_monitor_period'
environment_key = 'GEVENT_MONITOR_MEMORY_PERIOD'
default = 5
desc = """\
If `monitor_thread` is enabled, this is approximately how long
(in seconds) we will go between checking the processes memory usage.
Checking the ... | MonitorMemoryPeriod |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table18.py | {
"start": 315,
"end": 1233
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table18.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | redis__redis-py | redis/commands/timeseries/commands.py | {
"start": 560,
"end": 47147
} | class ____:
"""RedisTimeSeries Commands."""
def create(
self,
key: KeyT,
retention_msecs: Optional[int] = None,
uncompressed: Optional[bool] = False,
labels: Optional[Dict[str, str]] = None,
chunk_size: Optional[int] = None,
duplicate_policy: Optional[str... | TimeSeriesCommands |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.