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 | getsentry__sentry | src/sentry/utils/prompts.py | {
"start": 2252,
"end": 3579
} | class ____:
"""
Used to configure available 'prompts' (frontend modals or UI that may be
dismissed or have some other action recorded about it). This config
declares what prompts are available And what fields may be required.
required_fields available: [organization_id, project_id]
"""
def... | PromptsConfig |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 30914,
"end": 35212
} | class ____(BaseDataset):
"""
Feature: Datasets can use the scale/offset filter
Note: loss of precision caused by scaleoffset only becomes visible
when closing and reopening the File.
Can't close/reopen the shared self.f in pytest-run-parallel.
"""
def test_float_fails_without_options(se... | TestCreateScaleOffset |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 129501,
"end": 131113
} | class ____(WrapHigherOrderVariable):
def __init__(self, hop, source) -> None:
super().__init__(hop, source)
def _call_function(
self,
tx: "InstructionTranslator",
args: list[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
func_var ... | DynamoBypassingWrapperHigherOrderVariable |
python | django__django | tests/forms_tests/tests/test_formsets.py | {
"start": 72027,
"end": 72088
} | class ____(FormsetAsTagTests):
pass
| Jinja2FormsetAsTagTests |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 775897,
"end": 776379
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "created_at", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), gra... | HeadRefRestoredEvent |
python | huggingface__transformers | tests/kernels/test_kernels.py | {
"start": 1499,
"end": 8953
} | class ____(TestCasePlus):
@classmethod
def setUpClass(cls):
cls.model_id = "unsloth/Llama-3.2-1B-Instruct"
cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_id)
cls.model_kernelized = AutoModelForCausalLM.from_pretrained(
cls.model_id, use_kernels=True, device_map=torch... | TestHubKernels |
python | wandb__wandb | wandb/automations/_generated/enums.py | {
"start": 149,
"end": 239
} | class ____(str, Enum):
INFO = "INFO"
WARN = "WARN"
ERROR = "ERROR"
| AlertSeverity |
python | spack__spack | lib/spack/spack/environment/depfile.py | {
"start": 1153,
"end": 1787
} | class ____:
"""Contains a spec, a subset of its dependencies, and a flag whether it should be
buildcache only/never/auto."""
def __init__(
self, target: spack.spec.Spec, prereqs: List[spack.spec.Spec], buildcache: UseBuildCache
):
self.target = MakefileSpec(target)
self.prereqs ... | DepfileNode |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 153881,
"end": 154284
} | class ____:
scalar_testcase = 4.
testcase = [1., 2., 3., 4.]
testmathworks = [1.165, 0.6268, 0.0751, 0.3516, -0.6965]
def test_empty_1d(self, xp):
x = xp.asarray([])
with eager_warns(SmallSampleWarning, match=too_small_1d_not_omit, xp=xp):
res = self.stat_fun(x)
xp_... | SkewKurtosisTest |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/function_type_utils.py | {
"start": 6093,
"end": 17425
} | class ____(object):
"""Specification of how to bind arguments to a function.
Deprecated. Please use FunctionType instead.
"""
@classmethod
def from_function_and_signature(
cls, python_function, input_signature, is_pure=False, jit_compile=None
):
"""Creates a FunctionSpec instance given a python ... | FunctionSpec |
python | huggingface__transformers | src/transformers/pipelines/pt_utils.py | {
"start": 129,
"end": 502
} | class ____(Dataset):
def __init__(self, dataset, process, params):
self.dataset = dataset
self.process = process
self.params = params
def __len__(self):
return len(self.dataset)
def __getitem__(self, i):
item = self.dataset[i]
processed = self.process(item, ... | PipelineDataset |
python | getsentry__sentry | src/sentry/integrations/msteams/actions/form.py | {
"start": 377,
"end": 1961
} | class ____(forms.Form):
team = forms.ChoiceField(choices=(), widget=forms.Select())
channel = forms.CharField(widget=forms.TextInput())
channel_id = forms.HiddenInput()
def __init__(self, *args, **kwargs):
self._team_list = [(i.id, i.name) for i in kwargs.pop("integrations")]
super()._... | MsTeamsNotifyServiceForm |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0067_change_max_length_feature_id.py | {
"start": 149,
"end": 542
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0066_make_imported_file_slug_nullable"),
]
operations = [
migrations.AlterField(
model_name="feature",
name="feature_id",
field=models.CharField(max_length=255... | Migration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py | {
"start": 4241,
"end": 4642
} | class ____(SubsetAutomationCondition):
@property
def name(self) -> str:
return "run_in_progress"
async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride]
return await context.asset_graph_view.compute_run_in_progress_sub... | RunInProgressAutomationCondition |
python | getsentry__sentry | tests/sentry/lang/dart/test_plugin_logic.py | {
"start": 129,
"end": 5686
} | class ____(TestCase):
def setUp(self) -> None:
self.plugin = DartPlugin()
self.data = {
"project": self.project.id,
"sdk": {"name": "sentry.dart.flutter"},
"debug_meta": {"images": [{"debug_id": "b8e43a-f242-3d73-a453-aeb6a777ef75"}]},
"exception": {
... | DartPluginTest |
python | numba__numba | numba/cuda/tests/cudapy/test_gufunc_scalar.py | {
"start": 366,
"end": 5382
} | class ____(CUDATestCase):
def test_gufunc_scalar_output(self):
# function type:
# - has no void return type
# - array argument is one dimension fewer than the source array
# - scalar output is passed as a 1-element array.
#
# signature: (n)-... | TestGUFuncScalar |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 36289,
"end": 36530
} | class ____(_SizedIntType):
""" Represents a signed integer type. """
__slots__ = ()
@property
def min(self):
return -2**(self.nbits-1)
@property
def max(self):
return 2**(self.nbits-1) - 1
| SignedIntType |
python | numpy__numpy | numpy/distutils/fcompiler/none.py | {
"start": 129,
"end": 758
} | class ____(FCompiler):
compiler_type = 'none'
description = 'Fake Fortran compiler'
executables = {'compiler_f77': None,
'compiler_f90': None,
'compiler_fix': None,
'linker_so': None,
'linker_exe': None,
'archiv... | NoneFCompiler |
python | django__django | tests/gis_tests/gdal_tests/test_srs.py | {
"start": 8393,
"end": 15785
} | class ____(SimpleTestCase):
def test01_wkt(self):
"Testing initialization on valid OGC WKT."
for s in srlist:
SpatialReference(s.wkt)
def test02_bad_wkt(self):
"Testing initialization on invalid WKT."
for bad in bad_srlist:
try:
srs = Spat... | SpatialRefTest |
python | google__jax | jax/experimental/mosaic/gpu/utils.py | {
"start": 31306,
"end": 35827
} | class ____:
base_address: ir.Value
offset: ir.Value
phases: ir.Value
num_barriers: int
@staticmethod
def initialize(
barrier_memref: ir.Value, arrival_count: int = 1
) -> "BarrierRef":
barrier_ty = ir.MemRefType(barrier_memref.type)
[num_barriers] = barrier_ty.shape
if num_barriers > 32... | BarrierRef |
python | getsentry__sentry | src/sentry/web/frontend/analytics.py | {
"start": 79,
"end": 337
} | class ____(analytics.Event):
organization_id: int
project_id: int
is_lazy: bool
has_performance: bool
has_replay: bool
has_debug: bool
sdk_version: str | None
tmpl: str
analytics.register(JsSdkLoaderRendered)
| JsSdkLoaderRendered |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_redirects.py | {
"start": 416,
"end": 3386
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.pip = Project.objects.create(
**{
"repo_type": "git",
"name": "Pip",
"default_branch": "",
"project_url": "http://pip.rtfd.org",
"repo": "https://git... | CustomRedirectTests |
python | geekcomputers__Python | turtle_shapes_made.py | {
"start": 16,
"end": 1269
} | class ____:
def __init__(self, color, pensize):
self.turtle = turtle.Turtle()
self.turtle.color(color)
self.turtle.pensize(pensize)
def draw_rectangle(self, width, height):
for _ in range(2):
self.turtle.forward(width)
self.turtle.left(90)
sel... | ShapeDrawer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar13.py | {
"start": 595,
"end": 884
} | class ____: ...
_T3 = TypeVar("_T3", A, B, C)
_P = ParamSpec("_P")
_Ts = TypeVarTuple("_Ts")
def func1(val1: _T1) -> _T1:
if isinstance(val1, str):
return ""
return 0
def func2(val1: _T1) -> list[_T1]:
if isinstance(val1, str):
return [""]
return [0]
| C |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 22912,
"end": 36098
} | class ____:
def test_invalid_cursor(self):
request = Request(factory.get('/', {'cursor': '123'}))
with pytest.raises(exceptions.NotFound):
self.pagination.paginate_queryset(self.queryset, request)
def test_use_with_ordering_filter(self):
class MockView:
filter_b... | CursorPaginationTestsMixin |
python | mahmoud__glom | glom/core.py | {
"start": 12494,
"end": 13544
} | class ____(GlomError):
"""This :exc:`GlomError` subtype is raised when an assignment fails,
stemming from an :func:`~glom.assign` call or other
:class:`~glom.Assign` usage.
One example would be assigning to an out-of-range position in a list::
>>> assign(["short", "list"], Path(5), 'too far') #... | PathAssignError |
python | getsentry__sentry | tests/sentry/workflow_engine/detectors/test_error_detector.py | {
"start": 446,
"end": 4778
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.environment = Environment.objects.create(
organization_id=self.project.organization_id, name="production"
)
self.context = {
"organization": self.p... | TestErrorDetectorValidator |
python | walkccc__LeetCode | solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py | {
"start": 0,
"end": 391
} | class ____:
def maximumLengthOfRanges(self, nums: list[int]) -> list[int]:
ans = [0] * len(nums)
stack = [] # a decreasing stack
for i in range(len(nums) + 1):
while stack and (i == len(nums) or nums[stack[-1]] < nums[i]):
index = stack.pop()
left = stack[-1] if stack else -1
... | Solution |
python | xlwings__xlwings | xlwings/_xlwindows.py | {
"start": 53983,
"end": 54602
} | class ____(base_classes.Collection):
def __init__(self, xl):
self.xl = xl
@property
def api(self):
return self.xl
def __call__(self, key):
try:
return self._wrap(xl=self.xl.Item(key))
except pywintypes.com_error:
raise KeyError(key)
def __le... | Collection |
python | run-llama__llama_index | llama-index-integrations/callbacks/llama-index-callbacks-promptlayer/llama_index/callbacks/promptlayer/base.py | {
"start": 453,
"end": 4905
} | class ____(BaseCallbackHandler):
"""Callback handler for sending to promptlayer.com."""
pl_tags: Optional[List[str]]
return_pl_id: bool = False
def __init__(self, pl_tags: List[str] = [], return_pl_id: bool = False) -> None:
try:
from promptlayer.utils import get_api_key, promptlay... | PromptLayerHandler |
python | doocs__leetcode | solution/2000-2099/2070.Most Beautiful Item for Each Query/Solution2.py | {
"start": 0,
"end": 445
} | class ____:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort()
prices = [p for p, _ in items]
n = len(items)
mx = [items[0][1]]
for i in range(1, n):
mx.append(max(mx[i - 1], items[i][1]))
ans = []
for q ... | Solution |
python | simonw__datasette | datasette/utils/__init__.py | {
"start": 31499,
"end": 34298
} | class ____(Exception):
pass
@documented
def parse_metadata(content: str) -> dict:
"Detects if content is JSON or YAML and parses it appropriately."
# content can be JSON or YAML
try:
return json.loads(content)
except json.JSONDecodeError:
try:
return yaml.safe_load(cont... | BadMetadataError |
python | huggingface__transformers | tests/models/deepseek_vl/test_image_processing_deepseek_vl.py | {
"start": 2961,
"end": 6119
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = DeepseekVLImageProcessor if is_vision_available() else None
fast_image_processing_class = DeepseekVLImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_proces... | DeepseekVLImageProcessingTest |
python | altair-viz__altair | altair/utils/selection.py | {
"start": 281,
"end": 1599
} | class ____:
"""
Represents the state of an alt.selection_point() when neither the fields nor encodings arguments are specified.
The value field is a list of zero-based indices into the
selected dataset.
Note: These indices only apply to the input DataFrame
for charts that do not include aggreg... | IndexSelection |
python | gevent__gevent | src/greentest/3.14/test__interpreters.py | {
"start": 26671,
"end": 31449
} | class ____(TestBase):
def setUp(self):
super().setUp()
self.id = _interpreters.create()
def add_module(self, modname, text):
import tempfile
tempdir = tempfile.mkdtemp()
self.addCleanup(lambda: os_helper.rmtree(tempdir))
_interpreters.run_string(self.id, dedent(... | RunFailedTests |
python | doocs__leetcode | solution/2700-2799/2707.Extra Characters in a String/Solution2.py | {
"start": 0,
"end": 161
} | class ____:
__slots__ = ['children', 'is_end']
def __init__(self):
self.children: List[Node | None] = [None] * 26
self.is_end = False
| Node |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 4015,
"end": 4923
} | class ____:
id: ID
data: bytes | memoryview
@property
def ref(self) -> Ref:
return Ref(id=self.id)
def to_bytes(self) -> bytes:
return self.data.tobytes() if isinstance(self.data, memoryview) else self.data
def to_compressed_bytes(self) -> bytes:
level = settings.compr... | Buffer |
python | spack__spack | lib/spack/spack/config.py | {
"start": 73036,
"end": 75256
} | class ____(spack.error.ConfigError):
"""Raised when a configuration format does not match its schema."""
def __init__(
self,
validation_error,
data: YamlConfigDict,
filename: Optional[str] = None,
line: Optional[int] = None,
) -> None:
# spack yaml has its ow... | ConfigFormatError |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 83985,
"end": 84499
} | class ____:
def __init__(self, sync_debug_mode):
self.mode = sync_debug_mode
def __enter__(self):
self.debug_mode_restore = torch.cuda.get_sync_debug_mode()
torch.cuda.set_sync_debug_mode(self.mode)
def __exit__(self, exception_type, exception_value, traceback):
torch.cuda.... | CudaSyncGuard |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-days-to-disconnect-island.py | {
"start": 7630,
"end": 9080
} | class ____(object):
def minDays(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def floodfill(grid, i, j, lookup):
stk = [(i, j)]
lookup[i][j] = 1
while stk:
... | Solution3 |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 25002,
"end": 29588
} | class ____:
"""DependencySpecs represent an edge in the DAG, and contain dependency types
and information on the virtuals being provided.
Dependencies can be one (or more) of several types:
- build: needs to be in the PATH at build time.
- link: is linked to and added to compiler flags.
- run:... | DependencySpec |
python | ipython__ipython | IPython/core/prefilter.py | {
"start": 18206,
"end": 19761
} | class ____(PrefilterChecker):
priority = Integer(1000).tag(config=True)
function_name_regexp = CRegExp(re_fun_name,
help="RegExp to identify potential function names."
).tag(config=True)
exclude_regexp = CRegExp(re_exclude_auto,
help="RegExp to exclude strings with this start from ... | AutocallChecker |
python | ray-project__ray | python/ray/serve/tests/test_config_files/get_multi_deployment_signal_app.py | {
"start": 110,
"end": 385
} | class ____:
def __init__(self, b: DeploymentHandle):
self.b = b
self.signal = ray.get_actor("signal_A", namespace="default_test_namespace")
async def __call__(self):
await self.signal.wait.remote()
return os.getpid()
@serve.deployment
| A |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scanner.py | {
"start": 76040,
"end": 82103
} | class ____:
def __init__(self):
# type: (Any) -> None
self.comments = {} # type: ignore
self.unused = [] # type: ignore
def add_eol_comment(self, comment, column, line):
# type: (Any, Any, Any) -> Any
# info = inspect.getframeinfo(inspect.stack()[1][0])
if comm... | ScannedComments |
python | pytorch__pytorch | test/functorch/test_eager_transforms.py | {
"start": 79794,
"end": 81783
} | class ____(TestCase):
def _test_against_reference(self, f, inputs):
def foo(inputs):
return f(*inputs)
expected = torch.autograd.functional.hessian(f, inputs)
result = hessian(foo)(inputs)
self.assertEqual(result, expected)
def test_hessian_vectorize_correctness_sim... | TestHessian |
python | PrefectHQ__prefect | src/prefect/events/filters.py | {
"start": 7870,
"end": 9195
} | class ____(EventDataFilter):
occurred: EventOccurredFilter = Field(
default_factory=lambda: EventOccurredFilter(),
description="Filter criteria for when the events occurred",
)
event: Optional[EventNameFilter] = Field(
default=None,
description="Filter criteria for the event ... | EventFilter |
python | tensorflow__tensorflow | tensorflow/compiler/tests/eager_test.py | {
"start": 10983,
"end": 23715
} | class ____(xla_test.XLATestCase):
def testBasic(self):
with self.test_scope():
matmul = def_function.function(math_ops.matmul)
t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]])
sq = matmul(t, t, transpose_a=True)
self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20])
def testCo... | EagerFunctionTest |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 20010,
"end": 23414
} | class ____(nn.Module):
def __init__(self, config, grid_size):
super().__init__()
self.num_stages = len(config.depths)
self.config = config
self.stages = nn.ModuleList(
[
FocalNetStage(
config=config,
index=i_layer,
... | FocalNetEncoder |
python | django-compressor__django-compressor | compressor/css.py | {
"start": 104,
"end": 2362
} | class ____(Compressor):
output_mimetypes = {"text/css"}
def split_contents(self):
if self.split_content:
return self.split_content
self.media_nodes = []
for elem in self.parser.css_elems():
data = None
elem_name = self.parser.elem_name(elem)
... | CssCompressor |
python | getsentry__sentry | src/sentry/testutils/fixtures.py | {
"start": 2849,
"end": 34347
} | class ____:
@cached_property
def session(self):
return Factories.create_session()
@cached_property
def projectkey(self):
return self.create_project_key(project=self.project)
@cached_property
def user(self) -> User:
try:
return self.create_user(
... | Fixtures |
python | keras-team__keras | keras/src/backend/torch/export.py | {
"start": 246,
"end": 4909
} | class ____:
def _track_layer(self, layer):
raise NotImplementedError(
"`track` is not supported for `Layer`s and `Model`s in the torch "
"backend. Use `track_and_add_endpoint` instead."
)
def add_endpoint(self, name, fn, input_signature, **kwargs):
raise NotImple... | TorchExportArchive |
python | walkccc__LeetCode | solutions/931. Minimum Falling Path Sum/931.py | {
"start": 0,
"end": 298
} | class ____:
def minFallingPathSum(self, A: list[list[int]]) -> int:
n = len(A)
for i in range(1, n):
for j in range(n):
mn = math.inf
for k in range(max(0, j - 1), min(n, j + 2)):
mn = min(mn, A[i - 1][k])
A[i][j] += mn
return min(A[-1])
| Solution |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-grid-with-obstacles-elimination.py | {
"start": 76,
"end": 1479
} | class ____(object):
def shortestPath(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def dot(a, b):
return a[0]*b[0]+a[1]*b[1]
def g(a, b):
return abs... | Solution |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/deepspeed.py | {
"start": 3014,
"end": 42084
} | class ____(DDPStrategy):
strategy_name = "deepspeed"
DEEPSPEED_ENV_VAR = "PL_DEEPSPEED_CONFIG_PATH"
def __init__(
self,
accelerator: Optional["pl.accelerators.Accelerator"] = None,
zero_optimization: bool = True,
stage: int = 2,
remote_device: Optional[str] = None,
... | DeepSpeedStrategy |
python | mkdocs__mkdocs | mkdocs/tests/search_tests.py | {
"start": 10571,
"end": 24300
} | class ____(unittest.TestCase):
def test_html_stripping(self):
stripper = search_index.ContentParser()
stripper.feed("<h1>Testing</h1><p>Content</p>")
self.assertEqual(stripper.stripped_html, "Testing\nContent")
def test_content_parser(self):
parser = search_index.ContentParser... | SearchIndexTests |
python | boto__boto3 | boto3/dynamodb/transform.py | {
"start": 930,
"end": 1333
} | class ____(dict):
"""A dictionary that discards any items set on it. For use as `memo` in
`copy.deepcopy()` when every instance of a repeated object in the deepcopied
data structure should result in a separate copy.
"""
def __setitem__(self, key, value):
pass
def copy_dynamodb_params(para... | _ForgetfulDict |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/antlr_asset_selection/generated/AssetSelectionListener.py | {
"start": 251,
"end": 10558
} | class ____(ParseTreeListener):
# Enter a parse tree produced by AssetSelectionParser#start.
def enterStart(self, ctx: AssetSelectionParser.StartContext):
pass
# Exit a parse tree produced by AssetSelectionParser#start.
def exitStart(self, ctx: AssetSelectionParser.StartContext):
pass
... | AssetSelectionListener |
python | kubernetes-client__python | kubernetes/client/models/v1_device_toleration.py | {
"start": 383,
"end": 8723
} | 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... | V1DeviceToleration |
python | streamlit__streamlit | lib/tests/streamlit/elements/lib/options_selector_utils_test.py | {
"start": 13118,
"end": 15119
} | class ____:
"""Test class for create_mappings utility function."""
def test_create_mappings_with_default_format_func(self):
# Using default str format_func
options = ["apple", "banana", "cherry"]
formatted_options, mapping = create_mappings(options)
# Check formatted options
... | TestCreateMappings |
python | falconry__falcon | tests/asgi/test_buffered_reader.py | {
"start": 1387,
"end": 9348
} | class ____:
def __init__(self):
self._sink = io.BytesIO()
async def write(self, data):
self._sink.write(data)
@property
def accumulated(self):
return self._sink.getvalue()
@pytest.fixture()
def reader1():
return reader.BufferedReader(async_iter(SOURCE1), chunk_size=8)
@... | AsyncSink |
python | apache__airflow | airflow-core/tests/unit/utils/test_process_utils.py | {
"start": 8807,
"end": 9450
} | class ____:
@mock.patch("os.setpgid")
def test_not_session_leader(self, mock_set_pid):
pid = os.getpid()
with mock.patch("os.getsid", autospec=True) as mock_get_sid:
mock_get_sid.return_value = pid + 1
set_new_process_group()
assert mock_set_pid.call_count == ... | TestSetNewProcessGroup |
python | getsentry__sentry | tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py | {
"start": 291,
"end": 2686
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(is_staff=True, is_superuser=True)
self.canary_environment = Environment.objects.create(
organization_id=self.organization.id, name="canary"
)
self.production_environmen... | ReleaseThresholdDetailsGETTest |
python | walkccc__LeetCode | solutions/260. Single Number III/260.py | {
"start": 0,
"end": 331
} | class ____:
def singleNumber(self, nums: list[int]) -> list[int]:
xors = functools.reduce(operator.xor, nums)
lowbit = xors & -xors
ans = [0, 0]
# Seperate `nums` into two groups by `lowbit`.
for num in nums:
if num & lowbit:
ans[0] ^= num
else:
ans[1] ^= num
retu... | Solution |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py | {
"start": 1573,
"end": 1837
} | class ____(BaseModel):
token: str
"""The token that was used to generate the log probability."""
bytes: List[int]
"""The bytes that were used to generate the log probability."""
logprob: float
"""The log probability of the token."""
| Logprob |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/time.py | {
"start": 3400,
"end": 3974
} | class ____(NamedConfig[Literal["numpy.timedelta64"], TimeConfig]):
"""
The JSON representation of the ``TimeDelta64`` data type in Zarr V3.
References
----------
This representation is defined in the numpy.timedelta64
[specification document](https://zarr-specs.readthedocs.io/en/latest/spec/v3/... | TimeDelta64JSON_V3 |
python | doocs__leetcode | solution/3200-3299/3254.Find the Power of K-Size Subarrays I/Solution.py | {
"start": 0,
"end": 304
} | class ____:
def resultsArray(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1] * n
for i in range(1, n):
if nums[i] == nums[i - 1] + 1:
f[i] = f[i - 1] + 1
return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]
| Solution |
python | fluentpython__example-code-2e | 10-dp-1class-func/classic_strategy.py | {
"start": 1309,
"end": 1468
} | class ____(NamedTuple):
product: str
quantity: int
price: Decimal
def total(self) -> Decimal:
return self.price * self.quantity
| LineItem |
python | sqlalchemy__sqlalchemy | test/orm/test_collection.py | {
"start": 3226,
"end": 52868
} | class ____(OrderedDictFixture, fixtures.ORMTest):
class Entity:
def __init__(self, a=None, b=None, c=None):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return str((id(self), self.a, self.b, self.c))
class SimpleComparableEntity:
... | CollectionsTest |
python | django__django | django/db/backends/mysql/base.py | {
"start": 3467,
"end": 16345
} | class ____(BaseDatabaseWrapper):
vendor = "mysql"
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings;
# they'll be interpolated against the values of Field.__dict__ before being
# output. If a column type is set t... | DatabaseWrapper |
python | huggingface__transformers | src/transformers/models/hubert/modular_hubert.py | {
"start": 11526,
"end": 11573
} | class ____(Wav2Vec2ForCTC):
pass
| HubertForCTC |
python | django-import-export__django-import-export | tests/core/tests/resources.py | {
"start": 871,
"end": 1002
} | class ____(resources.ModelResource):
class Meta:
model = Book
store_instance = True
| BookResourceWithStoreInstance |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 8186,
"end": 8268
} | class ____(UUIDProject):
artist = models.CharField(max_length=30)
| UUIDArtProject |
python | getsentry__sentry | tests/sentry/core/endpoints/test_project_details.py | {
"start": 59056,
"end": 67152
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-details"
method = "put"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.options_dict = {
"sentry:resolve_age": 1,
"sentry:scrub_data": False,
"sentry:scrub_defa... | CopyProjectSettingsTest |
python | viewflow__viewflow | viewflow/workflow/admin.py | {
"start": 1648,
"end": 2443
} | class ____(admin.ModelAdmin):
"""List all of viewflow tasks."""
icon = '<i class="material-icons">assignment_turned_in</i>'
actions = None
date_hierarchy = "created"
list_display = [
"pk",
"created",
"process",
"status",
"owner",
"owner_permission",
... | TaskAdmin |
python | huggingface__transformers | src/transformers/models/camembert/modeling_camembert.py | {
"start": 23653,
"end": 25041
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden stat... | CamembertPooler |
python | catalyst-team__catalyst | catalyst/contrib/data/dataset_ml.py | {
"start": 119,
"end": 645
} | class ____(Dataset, ABC):
"""
Base class for datasets adapted for
metric learning train stage.
"""
@abstractmethod
def get_labels(self) -> List[int]:
"""
Dataset for metric learning must provide
label of each sample for forming positive
and negative pairs during ... | MetricLearningTrainDataset |
python | django-mptt__django-mptt | mptt/forms.py | {
"start": 1993,
"end": 2656
} | class ____(forms.ChoiceField):
"""A ChoiceField for specifying position relative to another node."""
FIRST_CHILD = "first-child"
LAST_CHILD = "last-child"
LEFT = "left"
RIGHT = "right"
DEFAULT_CHOICES = (
(FIRST_CHILD, _("First child")),
(LAST_CHILD, _("Last child")),
(... | TreeNodePositionField |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 153085,
"end": 153540
} | class ____:
_col_type = None
"The concrete range class these tests are for."
_col_str = None
"The corresponding PG type name."
_epsilon = None
"""A small value used to generate range variants"""
def _data_str(self):
"""return string form of a sample range"""
raise NotImple... | _RangeTests |
python | eth-brownie__brownie | brownie/network/contract.py | {
"start": 66795,
"end": 67575
} | class ____(_ContractMethod):
"""
A public payable or non-payable contract method.
Attributes
----------
abi : dict
Contract ABI specific to this method.
signature : str
Bytes4 method signature.
"""
def __call__(self, *args: Any, silent: bool = False) -> TransactionRecei... | ContractTx |
python | astropy__astropy | astropy/samp/tests/test_hub_proxy.py | {
"start": 181,
"end": 1183
} | class ____:
def setup_method(self, method):
self.hub = SAMPHubServer(web_profile=False, mode="multiple", pool_size=1)
self.hub.start()
self.proxy = SAMPHubProxy()
self.proxy.connect(hub=self.hub, pool_size=1)
def teardown_method(self, method):
if self.proxy.is_connected... | TestHubProxy |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/unary.py | {
"start": 2316,
"end": 22246
} | class ____(Expr):
"""Class representing unary functions of an expression."""
__slots__ = ("name", "options")
_non_child = ("dtype", "name", "options")
# Note: log, and pow are handled via translation to binops
_OP_MAPPING: ClassVar[dict[str, plc.unary.UnaryOperator]] = {
"sin": plc.unary.U... | UnaryFunction |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator/create_python_api.py | {
"start": 3355,
"end": 33441
} | class ____(object):
"""Builds a map from module name to imports included in that module."""
def __init__(self,
output_package,
api_version,
lazy_loading=_LAZY_LOADING,
use_relative_imports=False):
self._output_package = output_package
# Maps API m... | _ModuleInitCodeBuilder |
python | ray-project__ray | python/ray/train/torch/xla/config.py | {
"start": 422,
"end": 4242
} | class ____(TorchConfig):
"""
Configuration for torch XLA setup.
See https://pytorch.org/xla/release/1.13/index.html for more info.
Currently, only "neuron_cores" accelerator (AwsNeuronXLABackend)
is supported with xrt runtime.
"""
neuron_parallel_compile: bool = False
@property
def... | TorchXLAConfig |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py | {
"start": 939,
"end": 1746
} | class ____(Scaffolder[SimplePipesScriptScaffoldParams]):
@classmethod
def get_scaffold_params(cls) -> type[SimplePipesScriptScaffoldParams]:
return SimplePipesScriptScaffoldParams
def scaffold(self, request: ScaffoldRequest[SimplePipesScriptScaffoldParams]) -> None:
scaffold_component(reque... | SimplePipesScriptScaffolder |
python | pytorch__pytorch | torch/distributed/elastic/timer/local_timer.py | {
"start": 1381,
"end": 2141
} | class ____(RequestQueue):
"""
A ``RequestQueue`` backed by python ``multiprocessing.Queue``
"""
def __init__(self, mp_queue: mp.Queue):
super().__init__()
self._mp_queue = mp_queue
def size(self) -> int:
return self._mp_queue.qsize()
def get(self, size, timeout: float)... | MultiprocessingRequestQueue |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/hybrid.py | {
"start": 44019,
"end": 44128
} | class ____(Protocol[_T]):
def __call__(self, cls: Any) -> Comparator[_T]: ...
| _HybridComparatorCallableType |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/multi_modal/retriever.py | {
"start": 1046,
"end": 15301
} | class ____(MultiModalRetriever):
"""
Multi Modal Vector index retriever.
Args:
index (MultiModalVectorStoreIndex): Multi Modal vector store index for images and texts.
similarity_top_k (int): number of top k results to return.
vector_store_query_mode (str): vector store query mode
... | MultiModalVectorIndexRetriever |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 4505,
"end": 4720
} | class ____(BaseModel):
x: int
y: str
class Config:
alias_generator = None
frozen = True
extra = Extra.forbid
frozenmodel = FrozenModel(x=1, y='b')
frozenmodel.y = 'a'
| FrozenModel |
python | readthedocs__readthedocs.org | readthedocs/invitations/apps.py | {
"start": 137,
"end": 344
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "readthedocs.invitations"
def ready(self):
import readthedocs.invitations.signals # noqa
| InvitationsConfig |
python | sphinx-doc__sphinx | sphinx/writers/text.py | {
"start": 14529,
"end": 45229
} | class ____(SphinxTranslator):
builder: TextBuilder
def __init__(self, document: nodes.document, builder: TextBuilder) -> None:
super().__init__(document, builder)
newlines = self.config.text_newlines
if newlines == 'windows':
self.nl = '\r\n'
elif newlines == 'nativ... | TextTranslator |
python | django-haystack__django-haystack | test_haystack/mocks.py | {
"start": 700,
"end": 807
} | class ____(BaseRouter):
def for_write(self, **hints):
return ["multi1", "multi2"]
| MockMultiRouter |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/impl.py | {
"start": 2840,
"end": 3145
} | class ____:
"""This represents a user error encountered during the IPC call. This indicates a business
logic error, rather than a protocol. Consider this a "task failed successfully"
use case.
"""
serializable_error_info: SerializableErrorInfo
message: Optional[str]
| IPCErrorMessage |
python | wandb__wandb | wandb/vendor/pygments/lexers/ruby.py | {
"start": 805,
"end": 16899
} | class ____(ExtendedRegexLexer):
"""
For `Ruby <http://www.ruby-lang.org>`_ source code.
"""
name = 'Ruby'
aliases = ['rb', 'ruby', 'duby']
filenames = ['*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec',
'*.rbx', '*.duby', 'Gemfile']
mimetypes = ['text/x-ruby', 'application... | RubyLexer |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 7158,
"end": 7284
} | class ____:
def process_spider_output(self, response, result):
yield from result
| ProcessSpiderOutputSimpleMiddleware |
python | chardet__chardet | chardet/big5prober.py | {
"start": 1309,
"end": 1697
} | class ____(MultiByteCharSetProber):
def __init__(self) -> None:
super().__init__()
self.coding_sm = CodingStateMachine(BIG5_SM_MODEL)
self.distribution_analyzer = Big5DistributionAnalysis()
self.reset()
@property
def charset_name(self) -> str:
return "Big5"
@pro... | Big5Prober |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_pgf.py | {
"start": 6776,
"end": 13573
} | class ____:
"""
The LatexManager opens an instance of the LaTeX application for
determining the metrics of text elements. The LaTeX environment can be
modified by setting fonts and/or a custom preamble in `.rcParams`.
"""
@staticmethod
def _build_latex_header():
latex_header = [
... | LatexManager |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 79430,
"end": 87042
} | class ____(PallasBaseTest):
INTERPRET = False
def test_basic_runtime_assert(self):
# TODO(justinfu): Move to non-interpret checkify class.
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Runtime check only implemented on TPU.")
# Run this test manually, since we cannot recover from a halt... | PallasCheckifyTest |
python | pytorch__pytorch | benchmarks/gpt_fast/mixtral_moe_model.py | {
"start": 7275,
"end": 8233
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.w1 = nn.Parameter(
torch.empty(config.num_experts, config.intermediate_size, config.dim)
)
self.w2 = nn.Parameter(
torch.empty(config.num_experts, config.dim, config.intermediate_size)
... | ConditionalFeedForward |
python | langchain-ai__langchain | libs/core/langchain_core/outputs/chat_generation.py | {
"start": 391,
"end": 2296
} | class ____(Generation):
"""A single chat generation output.
A subclass of `Generation` that represents the response from a chat model
that generates chat messages.
The `message` attribute is a structured representation of the chat message.
Most of the time, the message will be of type `AIMessage`.... | ChatGeneration |
python | apache__airflow | dev/breeze/src/airflow_breeze/global_constants.py | {
"start": 8885,
"end": 8972
} | class ____(SelectiveTestType):
AIRFLOW_CTL = "AirflowCTL"
| SelectiveAirflowCtlTestType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.