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/audit_log/events.py | {
"start": 2784,
"end": 3398
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=7, name="MEMBER_LEAVE_TEAM", api_name="member.leave-team")
def render(self, audit_log_entry: AuditLogEntry) -> str:
if audit_log_entry.target_user == audit_log_entry.actor:
return "left team {team_slug}... | MemberLeaveTeamAuditLogEvent |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 58133,
"end": 58207
} | class ____(_TestNormBase):
dt = np.int64
dec = 12
| _TestNormInt64Base |
python | spyder-ide__spyder | spyder/plugins/console/widgets/shell.py | {
"start": 34013,
"end": 36108
} | class ____(ShellBaseWidget):
"""
Terminal widget
"""
COM = 'rem' if os.name == 'nt' else '#'
INITHISTORY = ['%s *** Spyder Terminal History Log ***' % COM, COM,]
SEPARATOR = '%s%s ---(%s)---' % (os.linesep*2, COM, time.ctime())
# This signal emits a parsed error traceback text so we can the... | TerminalWidget |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_strategy_test.py | {
"start": 4358,
"end": 8961
} | class ____(test.TestCase):
# In this case, the entire computation in foo is compiled using JIT
# compilation.
def test_single_tpu_jit_compile(self):
with ops.device("/device:TPU:0"):
a = variables.Variable(1)
def get_a_plus_one():
return a + 1
@def_function.function(
input_signa... | TPUTest |
python | getsentry__sentry | src/sentry/models/groupassignee.py | {
"start": 1343,
"end": 9467
} | class ____(BaseManager["GroupAssignee"]):
def get_assigned_to_data(
self,
assigned_to: Team | RpcUser | User,
assignee_type: str,
extra: dict[str, str] | None = None,
) -> dict[str, Any]:
data = {
"assignee": str(assigned_to.id),
"assigneeEmail": g... | GroupAssigneeManager |
python | pypa__pipenv | pipenv/patched/pip/_internal/network/download.py | {
"start": 5192,
"end": 10668
} | class ____:
def __init__(
self,
session: PipSession,
progress_bar: str,
resume_retries: int,
) -> None:
assert (
resume_retries >= 0
), "Number of max resume retries must be bigger or equal to zero"
self._session = session
self._progres... | Downloader |
python | getsentry__sentry | src/sentry/incidents/action_handlers.py | {
"start": 4288,
"end": 6069
} | class ____(ActionHandler):
def fire(
self,
action: AlertRuleTriggerAction,
incident: Incident,
project: Project,
metric_value: int | float | None,
new_status: IncidentStatus,
notification_uuid: str | None = None,
) -> None:
if not RuleSnooze.object... | DefaultActionHandler |
python | scipy__scipy | scipy/integrate/_ode.py | {
"start": 27922,
"end": 30140
} | class ____:
runner = None # runner is None => integrator is not available
success = None # success==1 if integrator was called successfully
istate = None # istate > 0 means success, istate < 0 means failure
supports_run_relax = None
supports_step = None
supports_solout = False
integrator_... | IntegratorBase |
python | pdm-project__pdm | src/pdm/project/config.py | {
"start": 18867,
"end": 19575
} | class ____(Mapping[str, Any]):
def __init__(self, config_items: Mapping[str, ConfigItem]) -> None:
self._config_map = config_items
def __repr__(self) -> str:
return repr(dict(self))
def __getitem__(self, k: str) -> Any:
try:
item = self._config_map[k]
if ite... | EnvMap |
python | python__mypy | mypy/options.py | {
"start": 2351,
"end": 26238
} | class ____:
"""Options collected from flags."""
def __init__(self) -> None:
# Cache for clone_for_module()
self._per_module_cache: dict[str, Options] | None = None
# -- build options --
self.build_type = BuildType.STANDARD
self.python_version: tuple[int, int] = sys.vers... | Options |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofit02.py | {
"start": 315,
"end": 835
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofit02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_fil... | TestCompareXLSXFiles |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 101127,
"end": 101795
} | class ____(TestCase):
def setUp(self):
self.model = ModelWithMultipleNoDBIndex
self.history_model = self.model.history.model
def test_field_indices(self):
for field in ["name", "fk"]:
# dropped index
self.assertTrue(self.model._meta.get_field(field).db_index)
... | ModelWithMultipleNoDBIndexTest |
python | streamlit__streamlit | lib/tests/streamlit/runtime/connection_factory_test.py | {
"start": 1499,
"end": 10700
} | class ____(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
# st.secrets modifies os.environ, so we save it here and
# restore in tearDown.
self._prev_environ = dict(os.environ)
# Caching functions rely on an active script run ctx
add_script_run_ctx(thre... | ConnectionFactoryTest |
python | has2k1__plotnine | plotnine/scales/limits.py | {
"start": 3660,
"end": 3739
} | class ____(_lim):
"""
Fill limits
"""
aesthetic = "fill"
| filllim |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 43122,
"end": 45149
} | class ____(Drag, RegionSelectTool):
''' *toolbar icon*: |box_select_icon|
The box selection tool allows users to make selections on a Plot by showing
a rectangular region by dragging the mouse or a finger over the plot area.
The end of the drag event indicates the selection region is ready.
See :r... | BoxSelectTool |
python | pytorch__pytorch | torch/_inductor/autotune_process.py | {
"start": 18735,
"end": 22144
} | class ____(BenchmarkRequest):
# Important: Instances of this class have to be serializable
# across process boundaries. Do not put CUDA Tensors in here!
def __init__(
self,
kernel_name: str,
input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
output_tensor_meta: Union[Ten... | TritonBenchmarkRequest |
python | sympy__sympy | sympy/physics/quantum/piab.py | {
"start": 1668,
"end": 1912
} | class ____(Bra):
"""Particle in a box eigenbra."""
@classmethod
def _eval_hilbert_space(cls, label):
return L2(Interval(S.NegativeInfinity, S.Infinity))
@classmethod
def dual_class(self):
return PIABKet
| PIABBra |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 32575,
"end": 32978
} | class ____(__TestCase):
thetype = SetSubclassWithSlots
test_pickling = _TestJointOps.test_pickling
def setUp(self):
self.word = word = 'simsalabim'
self.otherword = 'madagascar'
self.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
self.s = self.thetype(word)... | TestSetSubclassWithSlots |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 13870,
"end": 14701
} | class ____(ASTLiteral):
def __init__(self, value: bool) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTBooleanLiteral):
return NotImplemented
return self.value == other.value
def __hash__(self) -> int:
return has... | ASTBooleanLiteral |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-contextual/llama_index/llms/contextual/base.py | {
"start": 491,
"end": 6520
} | class ____(OpenAILike):
"""
Generate a response using Contextual's Grounded Language Model (GLM), an LLM engineered specifically to prioritize faithfulness to in-context retrievals over parametric knowledge to reduce hallucinations in Retrieval-Augmented Generation.
The total request cannot exceed 32,000 t... | Contextual |
python | huggingface__transformers | src/transformers/models/paligemma/processing_paligemma.py | {
"start": 2868,
"end": 15061
} | class ____(ProcessorMixin):
r"""
Constructs a PaliGemma processor which wraps a PaliGemma image processor and a PaliGemma tokenizer into a single processor.
[`PaliGemmaProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GemmaTokenizerFast`]. See the
[`~PaliGemmaProcessor.__call... | PaliGemmaProcessor |
python | pytorch__pytorch | test/distributed/argparse_util_test.py | {
"start": 390,
"end": 5389
} | class ____(unittest.TestCase):
def setUp(self):
# remove any lingering environment variables
for e in os.environ.keys(): # noqa: SIM118
if e.startswith("PET_"):
del os.environ[e]
def test_env_string_arg_no_env(self):
parser = ArgumentParser()
parser.... | ArgParseUtilTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 9944,
"end": 10070
} | class ____(Base1):
def submit(self, fn: Callable[..., _T2], *args: Any, **kwargs: Any) -> list[_T2]:
return []
| Base2 |
python | pytorch__pytorch | test/distributed/pipelining/test_stage.py | {
"start": 10127,
"end": 13524
} | class ____(MultiProcessTestCase):
@property
def world_size(self) -> int:
return torch.get_device_module(device_type).device_count()
@property
def device(self) -> torch.device:
return torch.device(device_type, self.rank)
def setUp(self):
super().setUp()
self._spawn_p... | StageNegativeTest |
python | google__jax | tests/pallas/export_pallas_test.py | {
"start": 1010,
"end": 3021
} | class ____(jtu.JaxTestCase):
def setUp(self):
if sys.platform == "win32":
self.skipTest("Only works on non-Windows platforms")
self.enter_context(pallas_call_lib._PALLAS_USE_MOSAIC_GPU(False))
super().setUp()
def _check_cuda_export(self, exp):
self.assertRegex(
exp.mlir_module(),
... | ExportTestWithTriton |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_event_grouping_info.py | {
"start": 643,
"end": 9954
} | class ____(APITestCase, PerformanceIssueTestCase):
def setUp(self) -> None:
self.login_as(user=self.user)
self.team = self.create_team(
organization=self.organization, slug="tiger-team", members=[self.user]
)
self.project = self.create_project(
organization=... | EventGroupingInfoEndpointTestCase |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-tencentvectordb/llama_index/vector_stores/tencentvectordb/base.py | {
"start": 4984,
"end": 20557
} | class ____(BasePydanticVectorStore):
"""
Tencent Vector Store.
In this vector store, embeddings and docs are stored within a Collection.
If the Collection does not exist, it will be automatically created.
In order to use this you need to have a database instance.
See the following documentatio... | TencentVectorDB |
python | huggingface__transformers | src/transformers/models/idefics2/modeling_idefics2.py | {
"start": 15941,
"end": 16954
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`Idefics2EncoderLayer`].
Args:
config: Idefics2Config
"""
def __init__(self, config: Idefics2Config):
super().__init__()
self.config = config
... | Idefics2Encoder |
python | pypa__pip | src/pip/_internal/self_outdated_check.py | {
"start": 4432,
"end": 8466
} | class ____:
old: str
new: str
def __rich__(self) -> Group:
if WINDOWS:
pip_cmd = f"{get_best_invocation_for_this_python()} -m pip"
else:
pip_cmd = get_best_invocation_for_this_pip()
notice = "[bold][[reset][blue]notice[reset][bold]][reset]"
return Gr... | UpgradePrompt |
python | django__django | tests/prefetch_related/models.py | {
"start": 6072,
"end": 6418
} | class ____(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=255)
owner = models.ForeignKey("Person", models.SET_NULL, null=True)
main_room = models.OneToOneField(
"Room", models.SET_NULL, related_name="main_room_of", null=True
)
class Meta:
... | House |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 46462,
"end": 48662
} | class ____(__TestCase):
def setUp(self):
self.values = ["a", "b", "c"]
self.set = set(self.values)
super().setUp()
def test_add_present(self):
self.set.add("c")
self.assertEqual(self.set, set("abc"))
def test_add_absent(self):
self.set.add("d")
self.... | TestMutate |
python | getsentry__sentry | src/sentry/processing/backpressure/topology.py | {
"start": 180,
"end": 1289
} | class ____(Enum):
AttachmentsStore = "attachments-store"
ProcessingStore = "processing-store"
ProcessingStoreTransactions = "processing-store-transactions"
ProcessingLocks = "processing-locks"
PostProcessLocks = "post-process-locks"
def get_all_services() -> list[str]:
return [item.value for i... | ProcessingServices |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_dynamic/_mock.py | {
"start": 3720,
"end": 6403
} | class ____(MetaPathFinder):
"""A finder for mocking."""
def __init__(self, modnames: Sequence[str]) -> None:
super().__init__()
self.modnames = modnames
self.loader = MockLoader(self)
self.mocked_modules: list[str] = []
def find_spec(
self,
fullname: str,
... | MockFinder |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_base_monitor_environment_details.py | {
"start": 342,
"end": 4811
} | class ____(MonitorTestCase):
__test__ = False
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_simple(self) -> None:
monitor = self._create_monitor(status=MonitorStatus.ACTIVE)
monitor_environment = self._create_monitor_environment(monitor)
... | BaseUpdateMonitorEnvironmentTest |
python | apache__avro | lang/py/avro/test/test_tether_task_runner.py | {
"start": 1071,
"end": 6675
} | class ____(unittest.TestCase):
"""unit test for a tethered task runner."""
def test1(self):
# set the logging level to debug so that debug messages are printed
logging.basicConfig(level=logging.DEBUG)
proc = None
try:
# launch the server in a separate process
... | TestTetherTaskRunner |
python | kamyu104__LeetCode-Solutions | Python/maximum-white-tiles-covered-by-a-carpet.py | {
"start": 817,
"end": 1546
} | class ____(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
result = left = gap = 0
for right in xrange(len(tiles)):
if right-1 >= 0:
... | Solution2 |
python | joke2k__faker | faker/providers/phone_number/bg_BG/__init__.py | {
"start": 49,
"end": 390
} | class ____(PhoneNumberProvider):
formats = (
"+359(0)#########",
"+359(0)### ######",
"+359(0)### ### ###",
"+359#########",
"0#########",
"0### ######",
"0### ### ###",
"0### ###-###",
"(0###) ######",
"(0###) ### ###",
"(0###)... | Provider |
python | pennersr__django-allauth | allauth/socialaccount/migrations/0005_socialtoken_nullable_app.py | {
"start": 126,
"end": 597
} | class ____(migrations.Migration):
dependencies = [
("socialaccount", "0004_app_provider_id_settings"),
]
operations = [
migrations.AlterField(
model_name="socialtoken",
name="app",
field=models.ForeignKey(
blank=True,
null=... | Migration |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/transport/common/producer.py | {
"start": 920,
"end": 4327
} | class ____(object):
"""Base implementation of a v3.0 compilant language server client."""
CONTENT_LENGTH = 'Content-Length: {0}\r\n\r\n'
def __init__(self, zmq_in_port=7000, zmq_out_port=7001):
self.zmq_in_port = zmq_in_port
self.zmq_out_port = zmq_out_port
self.context = None
... | LanguageServerClient |
python | getsentry__sentry | src/sentry/issues/endpoints/project_events.py | {
"start": 1291,
"end": 4437
} | class ____(ProjectEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(limit=60, window=60, concurrent_li... | ProjectEventsEndpoint |
python | gevent__gevent | _setuputils.py | {
"start": 12388,
"end": 14159
} | class ____(build_ext):
# CFFI subclasses this class with its own, that overrides run()
# and invokes a `pre_run` method, if defined. The run() method is
# called only once from setup.py (this class is only instantiated
# once per invocation of setup()); run() in turn calls
# `build_extension` for e... | ConfiguringBuildExt |
python | getsentry__sentry | src/sentry/core/endpoints/organization_projects_experiment.py | {
"start": 2401,
"end": 9169
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
permission_classes = (OrgProjectPermission,)
logger = logging.getLogger("team-project.create")
owner = ApiOwner.ENTERPRISE
def should_add_creator_to_team(self, user: User | AnonymousUser) -> Ty... | OrganizationProjectsExperimentEndpoint |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_reflection.py | {
"start": 42215,
"end": 45768
} | class ____(fixtures.TestBase):
__only_on__ = "oracle"
__sparse_driver_backend__ = True
def _run_test(self, metadata, connection, specs, attributes):
columns = [Column("c%i" % (i + 1), t[0]) for i, t in enumerate(specs)]
m = metadata
Table("oracle_types", m, *columns)
m.creat... | TypeReflectionTest |
python | pytorch__pytorch | tools/nightly.py | {
"start": 6538,
"end": 41807
} | class ____:
"""Virtual environment manager"""
AGGRESSIVE_UPDATE_PACKAGES = (
"uv",
"pip",
"setuptools",
"packaging",
"wheel",
"build[uv]",
)
def __init__(
self,
prefix: Path | str,
pip_source: PipSource,
*,
base_ex... | Venv |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py | {
"start": 60802,
"end": 64807
} | class ____(TestTaskInstanceEndpoint):
def setup_method(self):
clear_db_runs()
def teardown_method(self):
clear_db_runs()
def test_should_respond_empty_non_scheduled(self, test_client, session):
self.create_task_instances(session)
response = test_client.get(
"/da... | TestGetTaskDependencies |
python | kamyu104__LeetCode-Solutions | Python/rotate-array.py | {
"start": 29,
"end": 590
} | class ____(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
def reverse(nums, start, end):
while start < end:
nums[start], nums[end - 1] = nums[end - 1], nums[star... | Solution |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/explorer.py | {
"start": 63579,
"end": 69477
} | class ____(DirView):
"""
File/directory explorer tree widget.
"""
sig_dir_opened = Signal(str, str)
"""
This signal is emitted when the current directory of the explorer tree
has changed.
Parameters
----------
new_root_directory: str
The new root directory path.
ser... | ExplorerTreeWidget |
python | huggingface__transformers | src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py | {
"start": 6450,
"end": 32089
} | class ____:
def __init__(self, original_model: nn.Module, config: MaskFormerConfig):
self.original_model = original_model
self.config = config
def pop_all(self, renamed_keys: list[tuple[str, str]], dst_state_dict: StateDict, src_state_dict: StateDict):
for src_key, dst_key in renamed_ke... | OriginalMaskFormerCheckpointToOursConverter |
python | PyCQA__pylint | tests/functional/d/duplicate/duplicate_bases.py | {
"start": 95,
"end": 155
} | class ____(str, str): # [duplicate-bases]
pass
| Duplicates |
python | GoogleCloudPlatform__python-docs-samples | compute/managed-instances/demo/app.py | {
"start": 5042,
"end": 5923
} | class ____:
"""
Object to asynchronously burn CPU cycles to simulate high CPU load.
Burns CPU in a separate process and can be toggled on and off.
"""
def __init__(self):
self._toggle = Value(c_bool, False, lock=True)
self._process = Process(target=self._burn_cpu)
self._proc... | CpuBurner |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 52800,
"end": 53060
} | class ____(themeable):
"""
Plot Margin on the left
Parameters
----------
theme_element : float
Must be in the [0, 1] range. It is specified
as a fraction of the figure width and figure
height.
"""
| plot_margin_left |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 10370,
"end": 11571
} | class ____(object):
backends = {'tbb': skip_no_tbb,
'omp': skip_no_omp,
'workqueue': unittest.skipIf(False, '')}
def run_cmd(self, cmdline, env):
popen = subprocess.Popen(cmdline,
stdout=subprocess.PIPE,
s... | TestInSubprocess |
python | getsentry__sentry | src/sentry/seer/endpoints/seer_rpc.py | {
"start": 4764,
"end": 4823
} | class ____(TypedDict):
name: str
type: str
| ColumnDict |
python | PyCQA__pylint | tests/functional/i/inherit_non_class.py | {
"start": 1700,
"end": 1811
} | class ____:
def __class_getitem__(cls, item): # pylint: disable=unused-argument
return cls
| ParentGood |
python | openai__openai-python | src/openai/types/beta/function_tool_param.py | {
"start": 285,
"end": 471
} | class ____(TypedDict, total=False):
function: Required[FunctionDefinition]
type: Required[Literal["function"]]
"""The type of tool being defined: `function`"""
| FunctionToolParam |
python | getsentry__sentry | src/sentry/deletions/defaults/group.py | {
"start": 3879,
"end": 6904
} | class ____(BaseDeletionTask[Group]):
"""
Base class to delete events associated to groups and its related models.
"""
# Number of events fetched from eventstore per chunk() call.
DEFAULT_CHUNK_SIZE = EVENT_CHUNK_SIZE
referrer = "deletions.group"
dataset: Dataset
def __init__(
s... | EventsBaseDeletionTask |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 113791,
"end": 116068
} | class ____(test.TestCase):
_WRITE_VERSION = saver_pb2.SaverDef.V1
def testDebugString(self):
# Builds a graph.
v0 = variable_v1.VariableV1([[1, 2, 3], [4, 5, 6]],
dtype=dtypes.float32,
name="v0")
v1 = variable_v1.VariableV1([[[1], [2]], [... | CheckpointReaderTest |
python | walkccc__LeetCode | solutions/1136. Parallel Courses/1136.py | {
"start": 85,
"end": 755
} | class ____:
def minimumSemesters(self, n: int, relations: list[list[int]]) -> int:
graph = [[] for _ in range(n)]
states = [State.INIT] * n
depth = [1] * n
for u, v in relations:
graph[u - 1].append(v - 1)
def hasCycle(u: int) -> bool:
if states[u] == State.VISITING:
return T... | Solution |
python | ray-project__ray | python/ray/air/tests/mocked_wandb_integration.py | {
"start": 2284,
"end": 3420
} | class ____(WandbLoggerCallback):
"""Wandb logger with mocked Wandb API gateway (one per trial)."""
_logger_actor_cls = _MockWandbLoggingActor
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._saved_actor_states: Dict["Trial", LoggingActorState] = {}
def _cle... | WandbTestExperimentLogger |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 1387,
"end": 1541
} | class ____(TestModel):
student = ForeignKeyField(Student)
course = ForeignKeyField(Course)
StudentCourseProxy.set_model(StudentCourse)
| StudentCourse |
python | spyder-ide__spyder | spyder/plugins/plots/widgets/figurebrowser.py | {
"start": 2281,
"end": 11111
} | class ____(
QWidget, SpyderWidgetMixin, ShellConnectWidgetForStackMixin
):
"""
Widget to browse the figures that were sent by the kernel to the IPython
console to be plotted inline.
"""
sig_figure_loaded = Signal()
"""This signal is emitted when a new figure is loaded."""
sig_figure_me... | FigureBrowser |
python | arrow-py__arrow | arrow/parser.py | {
"start": 779,
"end": 1332
} | class ____(ValueError):
"""
A custom exception class for handling parsing errors in the parser.
Notes:
This class inherits from the built-in `ValueError` class and is used to raise exceptions
when an error occurs during the parsing process.
"""
pass
# Allows for ParserErrors to b... | ParserError |
python | wandb__wandb | wandb/vendor/pygments/lexers/varnish.py | {
"start": 6488,
"end": 7265
} | class ____(VCLLexer):
"""
For Varnish Configuration Language snippets.
.. versionadded:: 2.2
"""
name = 'VCLSnippets'
aliases = ['vclsnippets', 'vclsnippet']
mimetypes = ['text/x-vclsnippet']
filenames = []
def analyse_text(text):
# override method inherited from VCLLexer
... | VCLSnippetLexer |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 158478,
"end": 184386
} | class ____(Runnable[Input, Output]):
"""`RunnableLambda` converts a python callable into a `Runnable`.
Wrapping a callable in a `RunnableLambda` makes the callable usable
within either a sync or async context.
`RunnableLambda` can be composed as any other `Runnable` and provides
seamless integrati... | RunnableLambda |
python | pydantic__pydantic | tests/typechecking/fields.py | {
"start": 135,
"end": 290
} | class ____(BaseModel):
_private_field: str = PrivateAttr()
m = ModelWithPrivateAttr()
def new_list() -> list[int]:
return []
| ModelWithPrivateAttr |
python | getsentry__sentry | src/sentry/backup/comparators.py | {
"start": 30744,
"end": 43576
} | class ____(IgnoredComparator):
"""
DataSource.source_id is a dynamic foreign key that gets remapped during import via the
normalize_before_relocation_import method. Since the remapping is handled there, we just
need to verify that both sides have a valid source_id value, without comparing the actual val... | DataSourceComparator |
python | ZoranPandovski__al-go-rithms | games/Python/Blackjack.py | {
"start": 599,
"end": 1250
} | class ____:
def __init__(self):
self.deck = [] # start with an empty list
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit,rank)) # build Card objects and add them to the list
def __str__(self):
deck_comp = '' # start with an empty... | Deck |
python | apache__airflow | providers/postgres/tests/unit/postgres/hooks/test_postgres.py | {
"start": 21916,
"end": 24018
} | class ____:
"""PostgresHookConn tests that are specific to psycopg3."""
def setup_method(self):
self.connection = Connection(login="login", password="password", host="host", schema="database")
class UnitTestPostgresHook(PostgresHook):
conn_name_attr = "test_conn_id"
self.d... | TestPostgresHookConnPPG3 |
python | spack__spack | lib/spack/spack/solver/asp.py | {
"start": 137987,
"end": 138441
} | class ____:
"""ASP functions used to express spec clauses in the HEAD of a rule"""
node = fn.attr("node")
namespace = fn.attr("namespace_set")
virtual_node = fn.attr("virtual_node")
node_platform = fn.attr("node_platform_set")
node_os = fn.attr("node_os_set")
node_target = fn.attr("node_tar... | _Head |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py | {
"start": 32039,
"end": 43197
} | class ____(TestDagEndpoint):
"""Unit tests for DAG Details."""
@pytest.mark.parametrize(
(
"query_params",
"dag_id",
"expected_status_code",
"dag_display_name",
"start_date",
"owner_links",
"last_parse_duration",
... | TestDagDetails |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 47491,
"end": 49212
} | class ____(SageMakerBaseOperator):
"""
Creates a model in Amazon SageMaker.
In the request, you name the model and describe a primary container. For the
primary container, you specify the Docker image that contains inference code,
artifacts (from prior training), and a custom environment map that t... | SageMakerModelOperator |
python | doocs__leetcode | solution/0700-0799/0754.Reach a Number/Solution.py | {
"start": 0,
"end": 244
} | class ____:
def reachNumber(self, target: int) -> int:
target = abs(target)
s = k = 0
while 1:
if s >= target and (s - target) % 2 == 0:
return k
k += 1
s += k
| Solution |
python | readthedocs__readthedocs.org | readthedocs/audit/migrations/0002_add_organization.py | {
"start": 183,
"end": 1328
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("organizations", "0006_add_assets_cleaned"),
("audit", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="auditlog",
name="log_organization_id",
fie... | Migration |
python | gevent__gevent | src/greentest/3.14/test_urllib.py | {
"start": 21004,
"end": 24473
} | class ____(unittest.TestCase):
"""Test urlopen() opening a data URL."""
def setUp(self):
# clear _opener global variable
self.addCleanup(urllib.request.urlcleanup)
# text containing URL special- and unicode-characters
self.text = "test data URLs :;,%=& \u00f6 \u00c4 "
#... | urlopen_DataTests |
python | django__django | tests/admin_filters/models.py | {
"start": 1609,
"end": 1699
} | class ____(models.Model):
book = models.OneToOneField(Book, models.CASCADE)
| ImprovedBook |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/alloy_db.py | {
"start": 12127,
"end": 17439
} | class ____(AlloyDBWriteBaseOperator):
"""
Update an Alloy DB cluster.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:AlloyDBUpdateClusterOperator`
:param cluster_id: Required. ID of the cluster to update.
:param cluster... | AlloyDBUpdateClusterOperator |
python | wandb__wandb | wandb/vendor/pygments/lexers/shell.py | {
"start": 24413,
"end": 28513
} | class ____(RegexLexer):
"""
For Windows PowerShell code.
.. versionadded:: 1.5
"""
name = 'PowerShell'
aliases = ['powershell', 'posh', 'ps1', 'psm1']
filenames = ['*.ps1', '*.psm1']
mimetypes = ['text/x-powershell']
flags = re.DOTALL | re.IGNORECASE | re.MULTILINE
keywords = ... | PowerShellLexer |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/benchmarks/matching_files_benchmark.py | {
"start": 921,
"end": 2558
} | class ____(benchmark_base.DatasetBenchmarkBase):
"""Benchmark for the experimental `MatchingFilesDataset`."""
def benchmark_nested_directories(self):
tmp_dir = tempfile.mkdtemp()
width = 500
depth = 10
for i in range(width):
for j in range(depth):
new_base = os.path.join(tmp_dir, str(... | MatchingFilesBenchmark |
python | scipy__scipy | scipy/fftpack/tests/test_pseudo_diffs.py | {
"start": 11764,
"end": 13733
} | class ____:
"""Check input overwrite behavior """
real_dtypes = (np.float32, np.float64)
dtypes = real_dtypes + (np.complex64, np.complex128)
def _check(self, x, routine, *args, **kwargs):
x2 = x.copy()
routine(x2, *args, **kwargs)
sig = routine.__name__
if args:
... | TestOverwrite |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_timeseries_spans.py | {
"start": 2003,
"end": 2130
} | class ____:
def __eq__(self, o: object):
return o in ["high", "low"]
any_confidence = AnyConfidence()
| AnyConfidence |
python | doocs__leetcode | solution/0800-0899/0899.Orderly Queue/Solution.py | {
"start": 0,
"end": 270
} | class ____:
def orderlyQueue(self, s: str, k: int) -> str:
if k == 1:
ans = s
for _ in range(len(s) - 1):
s = s[1:] + s[0]
ans = min(ans, s)
return ans
return "".join(sorted(s))
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter10.py | {
"start": 315,
"end": 1554
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/core.py | {
"start": 11540,
"end": 13461
} | class ____(keras_layers.Flatten, base.Layer):
"""Flattens an input tensor while preserving the batch axis (axis 0).
Args:
data_format: A string, one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
... | Flatten |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-anthropic/llama_index/llms/anthropic/base.py | {
"start": 2914,
"end": 41517
} | class ____(FunctionCallingLLM):
"""
Anthropic LLM.
Examples:
`pip install llama-index-llms-anthropic`
```python
from llama_index.llms.anthropic import Anthropic
llm = Anthropic(model="claude-instant-1")
resp = llm.stream_complete("Paul Graham is ")
for r in... | Anthropic |
python | sanic-org__sanic | sanic/application/constants.py | {
"start": 39,
"end": 416
} | class ____(str, Enum): # no cov
def _generate_next_value_(name: str, *args) -> str: # type: ignore
return name.lower()
def __eq__(self, value: object) -> bool:
value = str(value).upper()
return super().__eq__(value)
def __hash__(self) -> int:
return hash(self.value)
... | StrEnum |
python | ray-project__ray | python/ray/tune/search/sample.py | {
"start": 4545,
"end": 4634
} | class ____(Sampler):
def __str__(self):
return "Base"
@DeveloperAPI
| BaseSampler |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 85944,
"end": 145984
} | class ____(EdgeTamVideoPreTrainedModel):
input_modalities = ("video", "text")
_can_record_outputs = {"mask_decoder_attentions": OutputRecorder(EdgeTamVideoTwoWayAttentionBlock, index=2)}
_keys_to_ignore_on_load_unexpected = []
_tied_weights_keys = {
"prompt_encoder.shared_embedding.positional_em... | EdgeTamVideoModel |
python | davidhalter__jedi | test/completion/stdlib.py | {
"start": 2626,
"end": 2667
} | class ____(object):
def say(self): pass
| A |
python | tensorflow__tensorflow | tensorflow/compiler/tests/jit_test.py | {
"start": 3176,
"end": 9811
} | class ____(test.TestCase):
# Evaluates 'fn' on 'args' both directly and as a compiled XLA kernel.
# Verifies that the outputs match and that XLA was invoked. 'fn' must take
# the same number of tensors as arguments that are in 'args', and must return
# a tuple of output tensors.
#
# If 'require_kernel_laun... | JitLaunchTest |
python | ray-project__ray | python/ray/tune/search/concurrency_limiter.py | {
"start": 285,
"end": 6325
} | class ____(Searcher):
"""A wrapper algorithm for limiting the number of concurrent trials.
Certain Searchers have their own internal logic for limiting
the number of concurrent trials. If such a Searcher is passed to a
``ConcurrencyLimiter``, the ``max_concurrent`` of the
``ConcurrencyLimiter`` wil... | ConcurrencyLimiter |
python | pytorch__pytorch | torch/_inductor/codegen/simd_kernel_features.py | {
"start": 22903,
"end": 23781
} | class ____:
"""Memory usage stats collected for each generated kernel"""
persistent: StatsForKernelType
looped: StatsForKernelType
def get(self, persistent: bool) -> StatsForKernelType:
return self.persistent if persistent else self.looped
@classmethod
def compute(cls, estimator: Memo... | MemoryStats |
python | Pylons__pyramid | tests/test_util.py | {
"start": 25287,
"end": 25465
} | class ____(unittest.TestCase):
def test_repr(self):
from pyramid.util import Sentinel
r = repr(Sentinel('ABC'))
self.assertEqual(r, 'ABC')
| TestSentinel |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 7476,
"end": 7769
} | class ____:
def __init__(self, size: int, generate_dtype_str: Callable[..., str]):
self.size = size
self._generate_dtype_str = generate_dtype_str
def generate_dtype_str(self) -> str:
return self._generate_dtype_str()
@dataclasses.dataclass
| TritonScratchWorkspace |
python | ionelmc__pytest-benchmark | tests/test_elasticsearch_storage.py | {
"start": 1801,
"end": 7699
} | class ____(BenchmarkSession):
def __init__(self):
self.verbose = False
self.quiet = False
self.histogram = True
self.benchmarks = []
self.performance_regressions = []
self.sort = 'min'
self.compare = '0001'
self.logger = logging.getLogger(__name__)
... | MockSession |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 9283,
"end": 9472
} | class ____(object):
def comprehension_definition(self):
return [1 for self.b in [1]]
#? int()
Foo().b
# -----------------
# default arguments
# -----------------
default = ''
| Foo |
python | PyCQA__pycodestyle | tests/test_shell.py | {
"start": 127,
"end": 7880
} | class ____(unittest.TestCase):
"""Test the usual CLI options and output."""
def setUp(self):
self._saved_argv = sys.argv
self._saved_stdout = sys.stdout
self._saved_stderr = sys.stderr
self._saved_pconfig = pycodestyle.PROJECT_CONFIG
self._saved_cpread = configparser.Raw... | ShellTestCase |
python | google__pytype | pytype/rewrite/frame_test.py | {
"start": 18114,
"end": 19232
} | class ____(FrameTestBase):
"""Test accumulating results in a comprehension."""
def test_list_append(self):
frame = self.run_block(
"""
BUILD_LIST 0
LOAD_CONST 0
LOAD_CONST 1
LIST_APPEND 2
""",
consts=[1, 2],
)
target_var = frame._stack.peek(2)
target = ab... | ComprehensionAccumulatorTest |
python | kamyu104__LeetCode-Solutions | Python/right-triangles.py | {
"start": 57,
"end": 689
} | class ____(object):
def numberOfRightTriangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def get(i, j):
return grid[i][j] if n < m else grid[j][i]
n, m = len(grid), len(grid[0])
result = 0
cnt1 = [sum(get(i, j) for j in ... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_build.py | {
"start": 1318,
"end": 1506
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Build link."""
name = "Cloud Build Details"
key = "cloud_build_key"
format_str = BUILD_LINK
| CloudBuildLink |
python | ray-project__ray | rllib/utils/typing.py | {
"start": 9270,
"end": 9960
} | class ____:
"""Data type that is fed into and yielded from agent connectors.
Args:
env_id: ID of the environment.
agent_id: ID to help identify the agent from which the data is received.
data: A payload (``data``). With RLlib's default sampler, the payload
is a dictionary of... | AgentConnectorDataType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.