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 | pytorch__pytorch | torch/distributions/relaxed_categorical.py | {
"start": 552,
"end": 3825
} | class ____(Distribution):
r"""
Creates a ExpRelaxedCategorical parameterized by
:attr:`temperature`, and either :attr:`probs` or :attr:`logits` (but not both).
Returns the log of a point in the simplex. Based on the interface to
:class:`OneHotCategorical`.
Implementation based on [1].
See ... | ExpRelaxedCategorical |
python | PyCQA__pylint | tests/functional/n/none_dunder_protocols.py | {
"start": 435,
"end": 507
} | class ____(metaclass=MetaContainer):
__iter__ = None
| NonContainerClass |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/nosource_bundle/package.py | {
"start": 223,
"end": 411
} | class ____(BundlePackage):
"""Simple bundle package with one dependency"""
homepage = "http://www.example.com"
version("1.0")
depends_on("dependency-install")
| NosourceBundle |
python | getsentry__sentry | src/sentry/preprod/api/models/project_preprod_build_details_models.py | {
"start": 1910,
"end": 2282
} | class ____(BaseModel):
state: Literal[PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED] = (
PreprodArtifactSizeMetrics.SizeAnalysisState.COMPLETED
)
# Deprecated, use size_metrics instead
install_size_bytes: int
# Deprecated, use size_metrics instead
download_size_bytes: int
si... | SizeInfoCompleted |
python | sphinx-doc__sphinx | sphinx/builders/latex/transforms.py | {
"start": 16475,
"end": 17376
} | class ____(SphinxPostTransform):
"""Replace pending_xref nodes for citation by citation_reference.
To handle citation reference easily on LaTeX writer, this converts
pending_xref nodes to citation_reference.
"""
default_priority = 5 # before ReferencesResolver
formats = ('latex',)
def ru... | CitationReferenceTransform |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_heapq.py | {
"start": 10979,
"end": 11123
} | class ____(_TestHeap, __TestCase):
module = c_heapq
#==============================================================================
| TestHeapC |
python | RaRe-Technologies__gensim | gensim/models/callbacks.py | {
"start": 5406,
"end": 9093
} | class ____(Metric):
"""Metric class for coherence evaluation.
See Also
--------
:class:`~gensim.models.coherencemodel.CoherenceModel`
"""
def __init__(self, corpus=None, texts=None, dictionary=None, coherence=None,
window_size=None, topn=10, logger=None, viz_env=None, title=No... | CoherenceMetric |
python | jazzband__django-polymorphic | src/polymorphic/admin/inlines.py | {
"start": 9983,
"end": 10291
} | class ____(PolymorphicInlineModelAdmin):
"""
Stacked inline for django-polymorphic models.
Since tabular doesn't make much sense with changed fields, just offer this one.
"""
#: The default template to use.
template = "admin/polymorphic/edit_inline/stacked.html"
| StackedPolymorphicInline |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 881,
"end": 962
} | class ____:
def __init__(self):
self.registry = dummy_registry
| DummyApp |
python | pytorch__pytorch | test/distributed/test_symmetric_memory.py | {
"start": 1885,
"end": 10713
} | class ____(MultiProcContinuousTest):
@property
def device(self) -> torch.device:
return torch.device(device_type, self.rank)
def _init_process(self):
torch.cuda.set_device(self.device)
torch.manual_seed(42 + self.rank)
def test_has_multicast_support(self) -> None:
# val... | SymmetricMemoryTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_managed_kafka.py | {
"start": 2990,
"end": 3320
} | class ____:
def test_class_attributes(self):
assert ApacheKafkaTopicLink.key == EXPECTED_MANAGED_KAFKA_TOPIC_LINK_KEY
assert ApacheKafkaTopicLink.name == EXPECTED_MANAGED_KAFKA_TOPIC_LINK_NAME
assert ApacheKafkaTopicLink.format_str == EXPECTED_MANAGED_KAFKA_TOPIC_LINK_FORMAT_STR
| TestApacheKafkaTopicLink |
python | django__django | django/contrib/admin/templatetags/log.py | {
"start": 61,
"end": 2030
} | class ____(template.Node):
def __init__(self, limit, varname, user):
self.limit = limit
self.varname = varname
self.user = user
def __repr__(self):
return "<GetAdminLog Node>"
def render(self, context):
entries = context["log_entries"]
if self.user is not No... | AdminLogNode |
python | django__django | django/db/models/functions/math.py | {
"start": 394,
"end": 491
} | class ____(NumericOutputFieldMixin, Transform):
function = "ACOS"
lookup_name = "acos"
| ACos |
python | skorch-dev__skorch | skorch/tests/callbacks/test_lr_scheduler.py | {
"start": 671,
"end": 9743
} | class ____:
@pytest.mark.parametrize('policy', [StepLR, 'StepLR'])
def test_simulate_lrs_epoch_step(self, policy):
lr_sch = LRScheduler(policy, step_size=2)
lrs = lr_sch.simulate(6, 1)
expected = np.array([1.0, 1.0, 0.1, 0.1, 0.01, 0.01])
assert np.allclose(expected, lrs)
@... | TestLRCallbacks |
python | coleifer__peewee | playhouse/sqliteq.py | {
"start": 10392,
"end": 10819
} | class ____(ThreadHelper):
__slots__ = ()
def event(self): return GEvent()
def queue(self, max_size=None):
max_size = max_size if max_size is not None else self.queue_max_size
return GQueue(maxsize=max_size or 0)
def thread(self, fn, *args, **kwargs):
def wrap(*a, **k):
... | GreenletHelper |
python | apache__airflow | providers/oracle/tests/unit/oracle/operators/test_oracle.py | {
"start": 1161,
"end": 3531
} | class ____:
@mock.patch.object(OracleHook, "run", autospec=OracleHook.run)
def test_execute(self, mock_run):
procedure = "test"
oracle_conn_id = "oracle_default"
parameters = {"parameter": "value"}
context = "test_context"
task_id = "test_task_id"
operator = Orac... | TestOracleStoredProcedureOperator |
python | doocs__leetcode | solution/0800-0899/0845.Longest Mountain in Array/Solution.py | {
"start": 0,
"end": 460
} | class ____:
def longestMountain(self, arr: List[int]) -> int:
n = len(arr)
f = [1] * n
g = [1] * n
for i in range(1, n):
if arr[i] > arr[i - 1]:
f[i] = f[i - 1] + 1
ans = 0
for i in range(n - 2, -1, -1):
if arr[i] > arr[i + 1]:
... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/gcs.py | {
"start": 4562,
"end": 8992
} | class ____(BaseTrigger):
"""
A trigger that makes an async call to GCS to check whether the object is updated in a bucket.
:param bucket: google cloud storage bucket name cloud storage where the objects are residing.
:param object_name: the file or folder present in the bucket
:param target_date: c... | GCSCheckBlobUpdateTimeTrigger |
python | pytorch__pytorch | torch/nn/modules/loss.py | {
"start": 43572,
"end": 47823
} | class ____(_Loss):
r"""Creates a criterion that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise.
It is less sensitive to outliers than :class:`torch.nn.MSELoss` and in some cases
prevents exploding gradients (e.g. see the paper `Fast R-CNN`_ by Ross Girsh... | SmoothL1Loss |
python | joerick__pyinstrument | pyinstrument/renderers/speedscope.py | {
"start": 3075,
"end": 8606
} | class ____(FrameRenderer):
"""
Outputs a tree of JSON conforming to the speedscope schema documented at
wiki: https://github.com/jlfwong/speedscope/wiki/Importing-from-custom-sources
schema: https://www.speedscope.app/file-format-schema.json
spec: https://github.com/jlfwong/speedscope/blob/main/src... | SpeedscopeRenderer |
python | simonw__datasette | datasette/views/special.py | {
"start": 18302,
"end": 19354
} | class ____(BaseView):
name = "permission_check"
has_json_alternate = False
async def get(self, request):
await self.ds.ensure_permission(action="permissions-debug", actor=request.actor)
as_format = request.url_vars.get("format")
if not as_format:
return await self.rende... | PermissionCheckView |
python | pypa__setuptools | setuptools/tests/config/test_setupcfg.py | {
"start": 496,
"end": 2046
} | class ____(ConfigHandler[Target]):
"""Erroneous handler. Fails to implement required methods."""
section_prefix = "**err**"
def make_package_dir(name, base_dir, ns=False):
dir_package = base_dir
for dir_name in name.split('/'):
dir_package = dir_package.mkdir(dir_name)
init_file = None
... | ErrConfigHandler |
python | huggingface__transformers | tests/models/siglip2/test_modeling_siglip2.py | {
"start": 6770,
"end": 10235
} | class ____:
def __init__(
self,
parent,
batch_size=12,
num_patches=16,
image_num_patches=24,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=64,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=3... | Siglip2VisionModelTester |
python | django__django | tests/admin_autodiscover/models.py | {
"start": 31,
"end": 102
} | class ____(models.Model):
title = models.CharField(max_length=10)
| Story |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 22097,
"end": 22513
} | class ____(graphene.Union):
"""The output from shutting down a code location server."""
class Meta:
types = (
GrapheneShutdownRepositoryLocationSuccess,
GrapheneRepositoryLocationNotFound,
GrapheneUnauthorizedError,
GraphenePythonError,
)
... | GrapheneShutdownRepositoryLocationMutationResult |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 8980,
"end": 9153
} | class ____(BaseModel):
"""
Response for task breadcrumbs.
"""
breadcrumbs: Annotated[list[dict[str, Any]], Field(title="Breadcrumbs")]
| TaskBreadcrumbsResponse |
python | getsentry__sentry | src/sentry/integrations/messaging/spec.py | {
"start": 7277,
"end": 9495
} | class ____(DefaultActionHandler):
def __init__(self, spec: MessagingIntegrationSpec):
super().__init__()
self._spec = spec
@property
def provider(self) -> str:
return self._spec.provider_slug
def send_alert(
self,
action: AlertRuleTriggerAction,
incident... | MessagingActionHandler |
python | sqlalchemy__sqlalchemy | test/aaa_profiling/test_orm.py | {
"start": 19939,
"end": 24542
} | class ____(NoCache, fixtures.MappedTest):
__requires__ = ("python_profiling_backend",)
__backend__ = True
@classmethod
def define_tables(cls, metadata):
def make_some_columns():
return [Column("c%d" % i, Integer) for i in range(10)]
Table(
"a",
metad... | JoinedEagerLoadTest |
python | numba__numba | numba/tests/test_tuples.py | {
"start": 18191,
"end": 19119
} | class ____(TestCase):
"""
Test implicit conversions between tuple types.
"""
def check_conversion(self, fromty, toty, val):
pyfunc = identity
cfunc = njit(toty(fromty))(pyfunc)
res = cfunc(val)
self.assertEqual(res, val)
def test_conversions(self):
check = s... | TestConversions |
python | doocs__leetcode | solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/Solution.py | {
"start": 0,
"end": 348
} | class ____:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
l = 0
cnt = Counter()
for c in s:
cnt[c] += 1
if len(cnt) > k:
cnt[s[l]] -= 1
if cnt[s[l]] == 0:
del cnt[s[l]]
l += 1
... | Solution |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 3808,
"end": 4377
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.bbox_sinusoid_emb = BrosPositionalEmbedding2D(config)
self.bbox_projection = nn.Linear(config.dim_bbox_sinusoid_emb_2d, config.dim_bbox_projection, bias=False)
def forward(self, bbox: torch.Tensor):
bbox_... | BrosBboxEmbeddings |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 45611,
"end": 48839
} | class ____(TestCase):
def test_array_equal(self):
res = np.array_equal(np.array([1, 2]), np.array([1, 2]))
assert_(res)
assert_(type(res) is bool)
res = np.array_equal(np.array([1, 2]), np.array([1, 2, 3]))
assert_(not res)
assert_(type(res) is bool)
res = np.... | TestArrayComparisons |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink27.py | {
"start": 315,
"end": 991
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink27.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | matplotlib__matplotlib | lib/matplotlib/_api/__init__.py | {
"start": 887,
"end": 969
} | class ____:
def __repr__(self):
return "<UNSET>"
UNSET = _Unset()
| _Unset |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 41229,
"end": 44605
} | class ____(unittest.TestCase):
@staticmethod
def create_history_model(model, inherited):
custom_model_name_prefix = f"Mock{HistoricalRecords.DEFAULT_MODEL_NAME_PREFIX}"
records = HistoricalRecords(
# Provide a custom history model name, to prevent name collisions
# with e... | CreateHistoryModelTests |
python | python__mypy | mypyc/irbuild/prepare.py | {
"start": 30611,
"end": 35925
} | class ____(NamedTuple):
singledispatch_func: FuncDef
dispatch_type: TypeInfo
def get_singledispatch_register_call_info(
decorator: Expression, func: FuncDef
) -> RegisteredImpl | None:
# @fun.register(complex)
# def g(arg): ...
if (
isinstance(decorator, CallExpr)
and len(decor... | RegisteredImpl |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 13344,
"end": 13688
} | class ____(HTTPSuccessful):
"""
subclass of :class:`~HTTPSuccessful`
This indicates that the request has been accepted for processing, but the
processing has not been completed.
code: 202, title: Accepted
"""
code = 202
title = 'Accepted'
explanation = 'The request is accepted for... | HTTPAccepted |
python | mlflow__mlflow | mlflow/models/evaluation/artifacts.py | {
"start": 413,
"end": 846
} | class ____(EvaluationArtifact):
def _save(self, output_artifact_path):
self._content.save(output_artifact_path)
def _load_content_from_file(self, local_artifact_path):
from PIL.Image import open as open_image
self._content = open_image(local_artifact_path)
self._content.load() ... | ImageEvaluationArtifact |
python | walkccc__LeetCode | solutions/304. Range Sum Query 2D - Immutable/304.py | {
"start": 0,
"end": 671
} | class ____:
def __init__(self, matrix: list[list[int]]):
if not matrix:
return
m = len(matrix)
n = len(matrix[0])
# prefix[i][j] := the sum of matrix[0..i)[0..j)
self.prefix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
self.prefix[i + 1][j... | NumMatrix |
python | coleifer__peewee | tests/db_tests.py | {
"start": 13473,
"end": 14348
} | class ____(BaseTestCase):
def test_deferred_database(self):
deferred_db = SqliteDatabase(None)
self.assertTrue(deferred_db.deferred)
class DeferredModel(Model):
class Meta:
database = deferred_db
self.assertRaises(Exception, deferred_db.connect)
... | TestDeferredDatabase |
python | doocs__leetcode | solution/3500-3599/3539.Find Sum of Array Product of Magical Sequences/Solution.py | {
"start": 232,
"end": 971
} | class ____:
def magicalSum(self, m: int, k: int, nums: List[int]) -> int:
@cache
def dfs(i: int, j: int, k: int, st: int) -> int:
if k < 0 or (i == len(nums) and j > 0):
return 0
if i == len(nums):
while st:
k -= st & 1
... | Solution |
python | numba__numba | numba/tests/test_hashing.py | {
"start": 5554,
"end": 8037
} | class ____(TestCase):
def setUp(self):
self.cfunc = jit(nopython=True)(hash_usecase)
def check_hash_values(self, values):
cfunc = self.cfunc
for val in list(values):
nb_hash = cfunc(val)
self.assertIsInstance(nb_hash, int)
try:
self.a... | BaseTest |
python | ray-project__ray | python/ray/autoscaler/v2/metrics_reporter.py | {
"start": 403,
"end": 4423
} | class ____:
def __init__(self, prom_metrics: AutoscalerPrometheusMetrics) -> None:
self._prom_metrics = prom_metrics
def report_instances(
self,
instances: List[IMInstance],
node_type_configs: Dict[NodeType, NodeTypeConfig],
):
"""
Record autoscaler metrics f... | AutoscalerMetricsReporter |
python | Farama-Foundation__Gymnasium | tests/utils/test_play.py | {
"start": 830,
"end": 7625
} | class ____:
def __init__(self, callback: Callable):
self.data_callback = callback
self.cumulative_reward = 0
self.last_observation = None
def callback(self, obs_t, obs_tp1, action, rew, terminated, truncated, info):
_, obs_tp1, _, rew, _, _, _ = self.data_callback(
o... | PlayStatus |
python | celery__celery | t/unit/worker/test_consumer.py | {
"start": 30075,
"end": 32072
} | class ____(ConsumerTestCase):
def test_perform_pending_operations_all_success(self):
"""
Test that all pending operations are processed successfully when `once=False`.
"""
c = self.get_consumer(no_hub=True)
# Create mock operations
mock_operation_1 = Mock()
... | test_Consumer_PerformPendingOperations |
python | dateutil__dateutil | tests/test_tz.py | {
"start": 48522,
"end": 59540
} | class ____(unittest.TestCase, TzFoldMixin):
# POSIX string indicating change to summer time on the 2nd Sunday in March
# at 2AM, and ending the 1st Sunday in November at 2AM. (valid >= 2007)
TZ_EST = 'EST+5EDT,M3.2.0/2,M11.1.0/2'
# POSIX string for AEST/AEDT (valid >= 2008)
TZ_AEST = 'AEST-10AEDT,M... | TZStrTest |
python | tensorflow__tensorflow | tensorflow/python/ops/variables.py | {
"start": 3496,
"end": 5160
} | class ____(enum.Enum):
"""Indicates how a distributed variable will be aggregated.
`tf.distribute.Strategy` distributes a model by making multiple copies
(called "replicas") acting on different elements of the input batch in a
data parallel model. When performing some variable-update operation,
for example `... | VariableAggregationV2 |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 5184,
"end": 5506
} | class ____(str, _Action, Enum):
CREATE = "create_replicate"
READ = "read_replicate"
UPDATE = "update_replicate"
DELETE = "delete_replicate"
@staticmethod
def values() -> List[str]:
return [action.value for action in ReplicateAction]
ActionT = TypeVar("ActionT", bound=Enum)
| ReplicateAction |
python | openai__openai-python | src/openai/types/chat/chat_completion_function_message_param.py | {
"start": 262,
"end": 591
} | class ____(TypedDict, total=False):
content: Required[Optional[str]]
"""The contents of the function message."""
name: Required[str]
"""The name of the function to call."""
role: Required[Literal["function"]]
"""The role of the messages author, in this case `function`."""
| ChatCompletionFunctionMessageParam |
python | great-expectations__great_expectations | tests/core/test__docs_decorators.py | {
"start": 18922,
"end": 19383
} | class ____:
"""Docstring summary.
Longer description.
Args:
some_arg: some_arg description.
other_arg: other_arg description.
"""
def __init__(self, some_arg, other_arg) -> None:
self.some_arg = some_arg
self.other_arg = other_arg
@deprecated_method_or_class(vers... | _ClassFullDocstringPublicAPI |
python | huggingface__transformers | src/transformers/models/got_ocr2/convert_got_ocr2_weights_to_hf.py | {
"start": 6149,
"end": 9642
} | class ____(TikTokenConverter):
def __init__(
self,
vocab_file,
special_tokens: list[str],
pattern: str,
model_max_length: int,
chat_template: Optional[str] = None,
**kwargs,
):
super().__init__(vocab_file, pattern=pattern)
self.additional_s... | GotOcr2Converter |
python | apache__airflow | airflow-core/tests/unit/utils/log/test_log_reader.py | {
"start": 1822,
"end": 16201
} | class ____:
DAG_ID = "dag_log_reader"
TASK_ID = "task_log_reader"
DEFAULT_DATE = timezone.datetime(2017, 9, 1)
FILENAME_TEMPLATE = "{{ ti.dag_id }}/{{ ti.task_id }}/{{ ts | replace(':', '.') }}/{{ try_number }}.log"
@pytest.fixture(autouse=True)
def log_dir(self):
with tempfile.Temporar... | TestLogView |
python | gabrielfalcao__HTTPretty | httpretty/core.py | {
"start": 37526,
"end": 41758
} | class ____(BaseClass):
"""Internal representation of `URIs <https://en.wikipedia.org/wiki/Uniform_Resource_Identifier>`_
.. tip:: all arguments are optional
:param username:
:param password:
:param hostname:
:param port:
:param path:
:param query:
:param fragment:
:param scheme... | URIInfo |
python | getsentry__sentry | src/sentry/users/api/bases/user.py | {
"start": 3955,
"end": 4889
} | class ____(Endpoint):
"""
The base endpoint for APIs that deal with Users. Inherit from this class to
get permission checks and to automatically convert user ID "me" to the
currently logged in user's ID.
"""
permission_classes: tuple[type[BasePermission], ...] = (UserPermission,)
def conve... | UserEndpoint |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 21406,
"end": 21622
} | class ____:
"""Record for errors encountered during Dg config validation."""
@property
@abstractmethod
def message(self) -> str:
"""The error message to display."""
@record
| _DgConfigErrorRecord |
python | getsentry__sentry | tests/sentry/models/test_groupassignee.py | {
"start": 704,
"end": 15648
} | class ____(TestCase):
def test_constraints(self) -> None:
# Can't both be assigned
with pytest.raises(AssertionError):
GroupAssignee.objects.create(
group=self.group, project=self.group.project, user_id=self.user.id, team=self.team
)
# Can't have nobo... | GroupAssigneeTestCase |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_output_block_param.py | {
"start": 233,
"end": 379
} | class ____(TypedDict, total=False):
file_id: Required[str]
type: Required[Literal["code_execution_output"]]
| BetaCodeExecutionOutputBlockParam |
python | plotly__plotly.py | plotly/graph_objs/mesh3d/_lighting.py | {
"start": 233,
"end": 7753
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "mesh3d"
_path_str = "mesh3d.lighting"
_valid_props = {
"ambient",
"diffuse",
"facenormalsepsilon",
"fresnel",
"roughness",
"specular",
"vertexnormalsepsilon",
}
@property
def ambient... | Lighting |
python | wandb__wandb | wandb/vendor/pygments/lexer.py | {
"start": 29818,
"end": 31054
} | class ____(RegexLexer):
"""Drop-in replacement for RegexLexer that does profiling of its regexes."""
_prof_data = []
_prof_sort_index = 4 # defaults to time per call
def get_tokens_unprocessed(self, text, stack=('root',)):
# this needs to be a stack, since using(this) will produce nested call... | ProfilingRegexLexer |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 31518,
"end": 31786
} | class ____(VOTableSpecWarning):
"""The root element should specify a namespace.
The ``VOTABLE`` namespace is::
http://www.ivoa.net/xml/VOTable/vX.X
where "X.X" is the version number.
"""
message_template = "No XML namespace specified"
| W42 |
python | kamyu104__LeetCode-Solutions | Python/range-addition.py | {
"start": 33,
"end": 509
} | class ____(object):
def getModifiedArray(self, length, updates):
"""
:type length: int
:type updates: List[List[int]]
:rtype: List[int]
"""
result = [0] * length
for update in updates:
result[update[0]] += update[2]
if update[1]+1 < len... | Solution |
python | PrefectHQ__prefect | tests/server/models/test_task_runs.py | {
"start": 25720,
"end": 27452
} | class ____:
async def test_delete_task_run(self, task_run, session):
assert await models.task_runs.delete_task_run(
session=session, task_run_id=task_run.id
)
# make sure the task run is deleted
assert (
await models.task_runs.read_task_run(
s... | TestDeleteTaskRun |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-numbers-non-positive.py | {
"start": 57,
"end": 681
} | class ____(object):
def minOperations(self, nums, x, y):
"""
:type nums: List[int]
:type x: int
:type y: int
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
def check(total):
return sum(ceil_divide(max(v-min(ceil_divid... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_stateful.py | {
"start": 4545,
"end": 5686
} | class ____(RuleBasedStateMachine):
b1 = Bundle("b1")
b2 = Bundle("b2")
def __init__(self):
self.created_counter = 0
self.consumed_counter = 0
super().__init__()
@invariant()
def bundle_length(self):
assert len(self.bundle("b1")) == self.created_counter - self.consum... | MachineWithConsumingRule |
python | huggingface__transformers | tests/models/bit/test_image_processing_bit.py | {
"start": 1050,
"end": 3252
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_center_crop=True,
crop_size=None,
do_normalize=True,
image... | BitImageProcessingTester |
python | mlflow__mlflow | mlflow/genai/scheduled_scorers.py | {
"start": 348,
"end": 3649
} | class ____:
"""
A scheduled scorer configuration for automated monitoring of generative AI applications.
Scheduled scorers are used to automatically evaluate traces logged to MLflow experiments
by production applications. They are part of `Databricks Lakehouse Monitoring for GenAI
<https://docs.dat... | ScorerScheduleConfig |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 10309,
"end": 10511
} | class ____(BinOp):
cases = [signature(types.boolean, types.boolean, types.boolean)]
cases += list(integer_binop_cases)
unsafe_casting = False
@infer_global(operator.and_)
| BitwiseLogicOperation |
python | ray-project__ray | python/ray/data/datasource/file_based_datasource.py | {
"start": 2547,
"end": 18370
} | class ____(Datasource):
"""File-based datasource for reading files.
Don't use this class directly. Instead, subclass it and implement `_read_stream()`.
"""
# If `_WRITE_FILE_PER_ROW` is `True`, this datasource calls `_write_row` and writes
# each row to a file. Otherwise, this datasource calls `_w... | FileBasedDatasource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 83455,
"end": 84020
} | class ____(sgqlc.types.Enum):
"""The reasons a piece of content can be reported or minimized.
Enumeration Choices:
* `ABUSE`: An abusive or harassing piece of content
* `DUPLICATE`: A duplicated piece of content
* `OFF_TOPIC`: An irrelevant piece of content
* `OUTDATED`: An outdated piece of c... | ReportedContentClassifiers |
python | getsentry__sentry | src/sentry/grouping/fingerprinting/rules.py | {
"start": 530,
"end": 1067
} | class ____(TypedDict):
# Each matcher is a list of [<name of event attribute to match>, <value to match>]
matchers: list[list[str]]
fingerprint: list[str]
attributes: NotRequired[FingerprintRuleAttributes]
is_builtin: NotRequired[bool]
# This is just `FingerprintRuleConfig` with an extra `text` en... | FingerprintRuleConfig |
python | scipy__scipy | scipy/special/tests/test_erfinv.py | {
"start": 119,
"end": 3059
} | class ____:
def test_compliment(self):
# Test erfcinv(1 - x) == erfinv(x)
x = np.linspace(-1, 1, 101)
assert_allclose(sc.erfcinv(1 - x), sc.erfinv(x), rtol=0, atol=1e-15)
def test_literal_values(self):
# The expected values were calculated with mpmath:
#
# impo... | TestInverseErrorFunction |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/sql_database/query.py | {
"start": 552,
"end": 633
} | class ____(TypedDict):
"""Input for a SQL Chain."""
question: str
| SQLInput |
python | Netflix__metaflow | metaflow/plugins/env_escape/communication/bytestream.py | {
"start": 0,
"end": 1866
} | class ____(object):
"""Basic interface that reads and writes bytes"""
def read(self, count, timeout=None):
"""
Reads exactly count bytes from the stream. This call is blocking until count bytes
are read or an error happens
This call returns a byte array or EOFError if there was... | ByteStream |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/xla_control_flow_ops_test.py | {
"start": 1651,
"end": 4907
} | class ____(PForTestCase):
def __init__(self, method_name="runTest"):
super(PForTest, self).__init__(method_name)
context.context().enable_xla_devices()
def test_xla_einsum(self):
num_loop = 10
x_series = random_ops.random_uniform([num_loop, 9, 9])
y_series = random_ops.random_uniform([num_loop... | PForTest |
python | facelessuser__soupsieve | tests/test_level3/test_first_of_type.py | {
"start": 58,
"end": 1997
} | class ____(util.TestCase):
"""Test first of type selectors."""
def test_first_of_type_at_start(self):
"""Test first of type which is also the first sibling."""
markup = """
<body>
<p id="0"></p>
<p id="1"></p>
<span id="2"></span>
<span id="3"></span>
... | TestFirstOfType |
python | numba__numba | numba/typed/listobject.py | {
"start": 1800,
"end": 2179
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('size', types.intp), # the size of the iteration space
('parent', fe_type.parent), # the parent list
('index', types.EphemeralPointer(types.intp)), # current index
]
super(ListI... | ListIterModel |
python | cookiecutter__cookiecutter | tests/test-extensions/local_extension/local_extensions/main.py | {
"start": 176,
"end": 613
} | class ____(Extension):
"""Simple jinja2 extension for cookiecutter test purposes."""
def __init__(self, environment: Environment) -> None:
"""Foobar Extension Constructor."""
super().__init__(environment)
environment.filters['foobar'] = lambda v: v * 2
@simple_filter
def simplefiltere... | FoobarExtension |
python | walkccc__LeetCode | solutions/1504. Count Submatrices With All Ones/1504.py | {
"start": 0,
"end": 477
} | class ____:
def numSubmat(self, mat: list[list[int]]) -> int:
m = len(mat)
n = len(mat[0])
ans = 0
for baseRow in range(m):
row = [1] * n
for i in range(baseRow, m):
for j in range(n):
row[j] &= mat[i][j]
ans += self._count(row)
return ans
def _count(self... | Solution |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 55825,
"end": 58789
} | class ____(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply... | BertForQuestionAnswering |
python | kamyu104__LeetCode-Solutions | Python/set-mismatch.py | {
"start": 1103,
"end": 1454
} | class ____(object):
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
N = len(nums)
x_minus_y = sum(nums) - N*(N+1)//2
x_plus_y = (sum(x*x for x in nums) - N*(N+1)*(2*N+1)/6) // x_minus_y
return (x_plus_y+x_minus_y) // 2, (... | Solution3 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 931344,
"end": 931623
} | class ____(
sgqlc.types.Type,
Node,
AuditEntry,
RepositoryAuditEntryData,
OrganizationAuditEntryData,
TopicAuditEntryData,
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ()
| RepoAddTopicAuditEntry |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 15552,
"end": 16634
} | class ____(ThreadedTCPSocketTest):
"""Socket tests for client-server connection.
self.cli_conn is a client socket connected to the server. The
setUp() method guarantees that it is connected to the server.
"""
def __init__(self, methodName='runTest'):
ThreadedTCPSocketTest.__init__(self, m... | SocketConnectedTest |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 27807,
"end": 28554
} | class ____(ModelOutput):
r"""
object_ids (`list[int]`, *optional*):
List of object IDs being tracked in the current frame.
pred_masks (`torch.FloatTensor` of shape `(batch_size, num_masks, height, width)`):
The predicted masks stored at the model's resolution.
object_score_logits (`torch... | Sam2VideoSegmentationOutput |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datastore.py | {
"start": 10197,
"end": 12624
} | class ____(GoogleCloudBaseOperator):
"""
Allocate IDs for incomplete keys. Return list of keys.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDatastoreAllocateIdsOperator`
.. seealso::
https://cloud.google.com... | CloudDatastoreAllocateIdsOperator |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib_type_spec_test.py | {
"start": 23819,
"end": 31293
} | class ____(test.TestCase,
parameterized.TestCase):
@combinations.generate(
combinations.combine(
mode=["eager"],
tf_api_version=2,
distribution=[
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strateg... | RaggedTensorDistributedIteratorTest |
python | coleifer__peewee | tests/dataset.py | {
"start": 518,
"end": 670
} | class ____(TestModel):
user = ForeignKeyField(User)
content = TextField()
timestamp = DateTimeField()
status = IntegerField(default=1)
| Note |
python | ansible__ansible | lib/ansible/module_utils/facts/network/hurd.py | {
"start": 2962,
"end": 3066
} | class ____(NetworkCollector):
_platform = 'GNU'
_fact_class = HurdPfinetNetwork
| HurdNetworkCollector |
python | django-extensions__django-extensions | tests/test_admin_widgets.py | {
"start": 149,
"end": 1559
} | class ____(TestCase):
def test_widget_works(self):
name = models.Name.objects.create(name="Name")
person = models.Person.objects.create(
name=name,
age=30,
)
club = models.Club.objects.create(
name="Club",
)
membership = models.Memb... | ForeignKeySearchInputTestCase |
python | facebook__pyre-check | pyre_extensions/type_variable_operators.py | {
"start": 525,
"end": 612
} | class ____(metaclass=ParameterSpecificationComponentMeta):
pass
| PositionalArgumentsOf |
python | ray-project__ray | python/ray/dashboard/modules/reporter/tests/test_gpu_providers.py | {
"start": 3958,
"end": 15311
} | class ____(unittest.TestCase):
"""Test NvidiaGpuProvider class."""
def setUp(self):
"""Set up test fixtures."""
self.provider = NvidiaGpuProvider()
def test_get_provider_name(self):
"""Test provider name."""
self.assertEqual(self.provider.get_provider_name(), GpuProviderTyp... | TestNvidiaGpuProvider |
python | keras-team__keras | keras/src/layers/preprocessing/index_lookup.py | {
"start": 347,
"end": 42991
} | class ____(Layer):
"""Maps values from a vocabulary to integer indices.
This layer translates a set of arbitrary hashables into an integer output
via a table-based lookup, with optional out-of-vocabulary handling. This is
the basis layer for both IntegerLookup and StringLookup; it holds the common
... | IndexLookup |
python | ansible__ansible | lib/ansible/modules/group.py | {
"start": 16460,
"end": 18035
} | class ____(Group):
"""
This is a OpenBSD Group manipulation class.
This overrides the following methods from the generic class:-
- group_del()
- group_add()
- group_mod()
"""
platform = 'OpenBSD'
distribution = None
GROUPFILE = '/etc/group'
def group_del(self):
... | OpenBsdGroup |
python | walkccc__LeetCode | solutions/2352. Equal Row and Column Pairs/2352.py | {
"start": 0,
"end": 328
} | class ____:
def equalPairs(self, grid: list[list[int]]) -> int:
n = len(grid)
ans = 0
for i in range(n):
for j in range(n):
k = 0
while k < n:
if grid[i][k] != grid[k][j]:
break
k += 1
if k == n: # R[i] == C[j]
ans += 1
return ... | Solution |
python | gevent__gevent | src/greentest/3.12/test_threading.py | {
"start": 51452,
"end": 57599
} | class ____(BaseTestCase):
def pipe(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
if hasattr(os, 'set_blocking'):
os.set_blocking(r, False)
return (r, w)
def test_threads_join(self):
# Non-daemon threads should be jo... | SubinterpThreadingTests |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 4734,
"end": 5101
} | class ____(models.Model):
fk = TreeForeignKey(Category, related_name="+", on_delete=models.CASCADE)
one = TreeOneToOneField(Category, related_name="+", on_delete=models.CASCADE)
m2m = TreeManyToManyField(Category, related_name="+")
# for testing various types of inheritance:
# 1. multi-table inheritance,... | ReferencingModel |
python | huggingface__transformers | src/transformers/models/mpt/configuration_mpt.py | {
"start": 807,
"end": 4577
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`MptAttention`] class. It is used to instantiate
attention layers according to the specified arguments, defining the layers architecture. Instantiating a
configuration with the defaults will yield a simila... | MptAttentionConfig |
python | kubernetes-client__python | kubernetes/client/api/storagemigration_v1alpha1_api.py | {
"start": 543,
"end": 125245
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | StoragemigrationV1alpha1Api |
python | numpy__numpy | benchmarks/benchmarks/bench_core.py | {
"start": 2635,
"end": 3094
} | class ____(Benchmark):
def setup(self):
self.amid = np.ones(50000)
self.bmid = np.ones(50000)
self.alarge = np.ones(1000000)
self.blarge = np.ones(1000000)
def time_mid(self):
(self.amid * 2) + self.bmid
def time_mid2(self):
(self.amid + self.bmid) - 2
... | Temporaries |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 529400,
"end": 530037
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ProjectV2ViewEdge"), graphql_name="edges"
)
nodes = sgqlc... | ProjectV2ViewConnection |
python | openai__openai-python | src/openai/types/conversations/conversation_item.py | {
"start": 3752,
"end": 4085
} | class ____(BaseModel):
input_schema: object
"""The JSON schema describing the tool's input."""
name: str
"""The name of the tool."""
annotations: Optional[object] = None
"""Additional annotations about the tool."""
description: Optional[str] = None
"""The description of the tool."""
... | McpListToolsTool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.