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
microsoft__pyright
packages/pyright-internal/src/tests/samples/namedTuple8.py
{ "start": 116, "end": 183 }
class ____(NamedTuple, Generic[AnyStr]): scheme: AnyStr
GenericNT
python
pytorch__pytorch
test/distributed/checkpoint/_experimental/test_checkpointer.py
{ "start": 1560, "end": 16273 }
class ____(TestCase): """Parameterized tests that work with both sync and async checkpointers.""" def setUp(self): super().setUp() # Create a temporary directory for checkpoints self.temp_dir = tempfile.mkdtemp() # Create real objects for testing self.rank_info = RankIn...
TestCheckpointer
python
astropy__astropy
astropy/cosmology/_src/tests/io/base.py
{ "start": 2913, "end": 4604 }
class ____(IOTestBase): """Directly test Cosmology I/O functions. These functions are not public API and are discouraged from public use, in favor of the I/O methods on |Cosmology|. They are tested b/c they are used internally and because some tests for the methods on |Cosmology| don't need to be r...
IODirectTestBase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 27648, "end": 27777 }
class ____(sgqlc.types.Scalar): """A string containing HTML code.""" __schema__ = github_schema ID = sgqlc.types.ID
HTML
python
python-pillow__Pillow
Tests/test_image_resample.py
{ "start": 1429, "end": 8436 }
class ____: def make_case(self, mode: str, size: tuple[int, int], color: int) -> Image.Image: """Makes a sample image with two dark and two bright squares. For example: e0 e0 1f 1f e0 e0 1f 1f 1f 1f e0 e0 1f 1f e0 e0 """ case = Image.new("L", size, 255...
TestImagingCoreResampleAccuracy
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_system_message.py
{ "start": 27614, "end": 31828 }
class ____: """Test middleware that accepts SystemMessage return types.""" def test_middleware_can_return_system_message(self) -> None: """Test that middleware can return a SystemMessage with dynamic content.""" def dynamic_system_prompt_middleware(request: ModelRequest) -> SystemMessage: ...
TestDynamicSystemPromptMiddleware
python
scipy__scipy
scipy/io/arff/_arffread.py
{ "start": 6807, "end": 9703 }
class ____(Attribute): def __init__(self, name, date_format, datetime_unit): super().__init__(name) self.date_format = date_format self.datetime_unit = datetime_unit self.type_name = 'date' self.range = date_format self.dtype = np.datetime64(0, self.datetime_unit) ...
DateAttribute
python
dask__distributed
distributed/broker.py
{ "start": 905, "end": 3140 }
class ____: _scheduler: Scheduler _topics: defaultdict[str, Topic] def __init__(self, maxlen: int, scheduler: Scheduler) -> None: self._scheduler = scheduler self._topics = defaultdict(partial(Topic, maxlen=maxlen)) def subscribe(self, topic: str, subscriber: str) -> None: self...
Broker
python
google__flatbuffers
python/flatbuffers/reflection/Schema.py
{ "start": 179, "end": 7978 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = Schema() x.Init(buf, n + offset) return x @classmethod def GetRootAsSchema(cls, buf, offset=0): "...
Schema
python
langchain-ai__langchain
libs/partners/groq/langchain_groq/chat_models.py
{ "start": 2333, "end": 61216 }
class ____(BaseChatModel): r"""Groq Chat large language models API. To use, you should have the environment variable `GROQ_API_KEY` set with your API key. Any parameters that are valid to be passed to the groq.create call can be passed in, even if not explicitly saved on this class. Setup: ...
ChatGroq
python
PrefectHQ__prefect
src/prefect/server/schemas/core.py
{ "start": 37278, "end": 37831 }
class ____(ORMBaseModel): """An ORM representation of an agent""" name: str = Field( default_factory=lambda: generate_slug(2), description=( "The name of the agent. If a name is not provided, it will be" " auto-generated." ), ) work_queue_id: UUID = Field...
Agent
python
geekcomputers__Python
Checker_game_by_dz/modules/checker.py
{ "start": 132, "end": 1967 }
class ____: def __init__(self, window): self._init() self.window = window # to update the position def update(self): self.board.draw(self.window) self.draw_moves(self.valid_moves) pg.display.update() def _init(self): self.select = None self.board...
checker
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/tests/llama_index/conftest.py
{ "start": 2450, "end": 9213 }
class ____(BaseModel): """Table configuration for test parameterization. :param existing: Whether the table should be created before running a test. :param schema_name: Schema where the table resides. :param table_name: Name of the table. :param id_column: Primary key column name (uuid). :param...
Table
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/cascade_delete_relationships/tutorial003_py39.py
{ "start": 120, "end": 361 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str heroes: list["Hero"] = Relationship(back_populates="team", passive_deletes="all")
Team
python
django__django
django/template/defaulttags.py
{ "start": 29381, "end": 29677 }
class ____(Literal): def __init__(self, value, text): self.value = value self.text = text # for better error messages def display(self): return self.text def eval(self, context): return self.value.resolve(context, ignore_failures=True)
TemplateLiteral
python
huggingface__transformers
src/transformers/models/visual_bert/modeling_visual_bert.py
{ "start": 59524, "end": 67402 }
class ____(VisualBertPreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "visual_bert.embeddings.word_embeddings.weight", } def __init__(self, config): super().__init__(config) self.visual_bert =...
VisualBertForRegionToPhraseAlignment
python
getsentry__sentry
tests/sentry/middleware/test_access_log_middleware.py
{ "start": 2802, "end": 3399 }
class ____(Endpoint): permission_classes = (AllowAny,) enforce_rate_limit = True rate_limits = RateLimitConfig( group="foo", limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=20, window=1, concurrent_limit=1), RateLimitCategory.USER:...
ConcurrentRateLimitedEndpoint
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 95577, "end": 98201 }
class ____: items = [ {"foo": "bar1", "egg": "spam1"}, {"foo": "bar2", "egg": "spam2", "baz": "quux2"}, {"foo": "bar3", "baz": "quux3"}, ] with tempfile.NamedTemporaryFile(suffix="json") as tmp: settings = { "FEEDS": { f"file:///{tmp.name}": { ...
TestFeedExporterSignals
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 10689, "end": 10842 }
class ____(_NumberBoundError): code = 'number.not_ge' msg_template = 'ensure this value is greater than or equal to {limit_value}'
NumberNotGeError
python
kamyu104__LeetCode-Solutions
Python/make-the-prefix-sum-non-negative.py
{ "start": 75, "end": 481 }
class ____(object): def makePrefSumNonNegative(self, nums): """ :type nums: List[int] :rtype: int """ result = prefix = 0 min_heap = [] for x in nums: heapq.heappush(min_heap, x) prefix += x if prefix < 0: pr...
Solution
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/examples/reinforcement_learning_rpc_test.py
{ "start": 8075, "end": 9268 }
class ____(RpcAgentTestFixture): @dist_init(setup_rpc=False) def test_rl_rpc(self): if self.rank == 0: # Rank 0 is the agent. rpc.init_rpc( name=worker_name(self.rank), backend=self.rpc_backend, rank=self.rank, world...
ReinforcementLearningRpcTest
python
pandas-dev__pandas
pandas/tests/arithmetic/test_datetime64.py
{ "start": 64300, "end": 73796 }
class ____: def test_empty_series_add_sub(self, box_with_array): # GH#13844 a = Series(dtype="M8[ns]") b = Series(dtype="m8[ns]") a = box_with_array(a) b = box_with_array(b) tm.assert_equal(a, a + b) tm.assert_equal(a, a - b) tm.assert_equal(a, b + a) ...
TestTimestampSeriesArithmetic
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 26738, "end": 27118 }
class ____(LinearOperator): def __init__(self, A): super().__init__(A.dtype, A.shape) self.A = A self.__adj = None self.args = (A,) def _matmat(self, X): return self.A.dot(X) def _adjoint(self): if self.__adj is None: self.__adj = _AdjointMatrixO...
MatrixLinearOperator
python
scipy__scipy
benchmarks/benchmarks/optimize_milp.py
{ "start": 1764, "end": 2630 }
class ____(Benchmark): # TODO: look at 5,6 - timing out and disabled in Apr'24 (5) and Aug'23 (6) # see gh-19389 for details params = [[3, 4]] param_names = ['size'] def setup(self, n): A_eq, b_eq, self.c, self.numbers, self.M = magic_square(n) self.constraints = (A_eq, b_eq,...
MilpMagicSquare
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/git_url_svn_top_level/package.py
{ "start": 217, "end": 557 }
class ____(Package): """Mock package that uses git for fetching.""" homepage = "http://www.git-fetch-example.com" # can't have two VCS fetchers. url = "https://example.com/some/tarball-1.0.tar.gz" git = "https://example.com/some/git/repo" svn = "https://example.com/some/svn/repo" version(...
GitUrlSvnTopLevel
python
pandas-dev__pandas
pandas/tests/frame/methods/test_tz_convert.py
{ "start": 175, "end": 4984 }
class ____: def test_tz_convert(self, frame_or_series): rng = date_range( "1/1/2011", periods=200, freq="D", tz=zoneinfo.ZoneInfo("US/Eastern") ) obj = DataFrame({"a": 1}, index=rng) obj = tm.get_obj(obj, frame_or_series) berlin = zoneinfo.ZoneInfo("Europe/Berli...
TestTZConvert
python
sqlalchemy__sqlalchemy
test/dialect/mysql/test_types.py
{ "start": 1091, "end": 15246 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mysql.dialect() @testing.combinations( # column type, args, kwargs, expected ddl # e.g. Column(Integer(10, unsigned=True)) == # 'INTEGER(10) UNSIGNED' (mysql.MSNumeric, [], {}, "NUMERIC"), (mysql.MSNumeric,...
TypeCompileTest
python
huggingface__transformers
src/transformers/utils/quantization_config.py
{ "start": 6800, "end": 9718 }
class ____(QuantizationConfigMixin): """This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded AutoRound quantization. Args: bits (`int`, *optional*, defaults to 4): The number of bits to quantize to, supported numbers are ...
AutoRoundConfig
python
numba__numba
numba/core/registry.py
{ "start": 355, "end": 1167 }
class ____(TargetDescriptor): options = cpu.CPUTargetOptions @cached_property def _toplevel_target_context(self): # Lazily-initialized top-level target context, for all threads return cpu.CPUContext(self.typing_context, self._target_name) @cached_property def _toplevel_typing_conte...
CPUTarget
python
sphinx-doc__sphinx
sphinx/domains/c/__init__.py
{ "start": 23885, "end": 24818 }
class ____(XRefRole): def process_link( self, env: BuildEnvironment, refnode: Element, has_explicit_title: bool, title: str, target: str, ) -> tuple[str, str]: refnode.attributes.update(env.ref_context) if not has_explicit_title: # maj...
CXRefRole
python
django__django
tests/admin_views/models.py
{ "start": 24269, "end": 24421 }
class ____(models.Model): def __str__(self): return "PK=%d" % self.pk pk_gt_1 = _Manager() objects = models.Manager()
FilteredManager
python
pytest-dev__pytest
src/_pytest/python.py
{ "start": 12491, "end": 21051 }
class ____(PyobjMixin, nodes.Collector, abc.ABC): def funcnamefilter(self, name: str) -> bool: return self._matches_prefix_or_glob_option("python_functions", name) def isnosetest(self, obj: object) -> bool: """Look for the __test__ attribute, which is applied by the @nose.tools.istest d...
PyCollector
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/timestamp.py
{ "start": 539, "end": 651 }
class ____(NamedTuple): timestamp: float # Seconds since the Unix epoch timezone: str
TimestampWithTimezone
python
pypa__pipenv
pipenv/patched/pip/_internal/vcs/versioncontrol.py
{ "start": 2854, "end": 4288 }
class ____: """ Encapsulates a VCS-specific revision to install, along with any VCS install options. Args: vc_class: a VersionControl subclass. rev: the name of the revision to install. extra_args: a list of extra options. """ vc_class: Type["VersionControl"] rev: O...
RevOptions
python
ansible__ansible
test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py
{ "start": 84, "end": 680 }
class ____(ActionBase): def run(self, tmp=None, task_vars=None): """ handler for file transfer operations """ if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if result.get('skipped'): return result mo...
ActionModule
python
PyCQA__pylint
tests/regrtest_data/descriptor_crash.py
{ "start": 45, "end": 358 }
class ____(object): _urlOpen = staticmethod(urllib.urlopen) def getPage(self, url): handle = self._urlOpen(url) data = handle.read() handle.close() return data #_getPage #Page if __name__ == "__main__": import sys p = Page() print p.getPage(sys.argv[1])
Page
python
lazyprogrammer__machine_learning_examples
unsupervised_class3/dcgan_tf.py
{ "start": 719, "end": 2129 }
class ____: def __init__(self, name, mi, mo, apply_batch_norm, filtersz=5, stride=2, f=tf.nn.relu): # mi = input feature map size # mo = output feature map size # self.W = tf.Variable(0.02*tf.random_normal(shape=(filtersz, filtersz, mi, mo))) # self.b = tf.Variable(np.zeros(mo, dtype=np.float32)) ...
ConvLayer
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/conv_test.py
{ "start": 168, "end": 1299 }
class ____(op_bench.TorchBenchmarkBase): def init(self, IC, OC, kernel, stride, N, L, device): self.inputs = { "input": torch.rand(N, IC, L, device=device, requires_grad=self.auto_set()) } self.conv1d = nn.Conv1d(IC, OC, kernel, stride=stride).to(device=device) self.set_m...
Conv1dBenchmark
python
pytorch__pytorch
torch/autograd/profiler_util.py
{ "start": 32763, "end": 39132 }
class ____(FormattedTimesMixin): """Averaged profiling statistics over multiple FunctionEvent objects. FunctionEventAvg aggregates statistics from multiple FunctionEvent objects with the same key (typically same operation name). This is useful for getting average performance metrics across multiple inv...
FunctionEventAvg
python
spack__spack
lib/spack/spack/test/installer_tui.py
{ "start": 445, "end": 564 }
class ____: """Mock multiprocessing.Connection for testing""" def fileno(self): return -1
MockConnection
python
getsentry__sentry
tests/sentry/workflow_engine/handlers/condition/test_existing_high_priority_issue_handler.py
{ "start": 495, "end": 3368 }
class ____(ConditionTestCase): condition = Condition.EXISTING_HIGH_PRIORITY_ISSUE payload = {"id": ExistingHighPriorityIssueCondition.id} def setUp(self) -> None: super().setUp() self.event_data = WorkflowEventData( event=self.group_event, group=self.group_event.grou...
TestExistingHighPriorityIssueCondition
python
ansible__ansible
test/units/module_utils/datatag/test_datatag.py
{ "start": 1976, "end": 3660 }
class ____(t.Protocol): def copy(self) -> t.Any: """Copy this instance.""" message_instances = [ _messages.Event(msg="bla", formatted_source_context="sc"), _messages.EventChain(msg_reason="a", traceback_reason="b", event=_messages.Event(msg="c")), _messages.ErrorSummary(event=_messages.Event(m...
CopyProtocol
python
doocs__leetcode
lcci/08.04.Power Set/Solution2.py
{ "start": 0, "end": 308 }
class ____: def subsets(self, nums: List[int]) -> List[List[int]]: ans = [] for mask in range(1 << len(nums)): t = [] for i, v in enumerate(nums): if (mask >> i) & 1: t.append(v) ans.append(t) return ans
Solution
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 57844, "end": 58091 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) alert_id: str = Field(..., description="The canonical identifier of the SQL alert.")
SqlTaskAlert
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 224589, "end": 224692 }
class ____(suite.JSONTest): __requires__ = ("postgresql_jsonb",) datatype = JSONB
JSONBSuiteTest
python
PyCQA__pylint
tests/functional/m/method_hidden.py
{ "start": 237, "end": 314 }
class ____: """dummy""" def __init__(self): self.abcd = 1
Abcd
python
walkccc__LeetCode
solutions/2616. Minimize the Maximum Difference of Pairs/2616.py
{ "start": 0, "end": 573 }
class ____: def minimizeMax(self, nums: list[int], p: int) -> int: nums.sort() def numPairs(maxDiff: int) -> int: """ Returns the number of pairs that can be obtained if the difference between each pair <= `maxDiff`. """ pairs = 0 i = 1 while i < len(nums): #...
Solution
python
openai__openai-python
src/openai/types/responses/response_input_item.py
{ "start": 8602, "end": 8825 }
class ____(BaseModel): path: str """Path of the file to delete relative to the workspace root.""" type: Literal["delete_file"] """The operation type. Always `delete_file`."""
ApplyPatchCallOperationDeleteFile
python
getsentry__sentry
tests/sentry/objectstore/endpoints/test_organization.py
{ "start": 177, "end": 833 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-objectstore" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def test_feature_flag_disabled(self): """Without feature flag, returns 404""" response = self.get_response(self.organization.sl...
OrganizationObjectstoreEndpointTest
python
getsentry__sentry
tests/snuba/rules/conditions/test_event_frequency.py
{ "start": 52639, "end": 52879 }
class ____( ErrorEventMixin, EventFrequencyPercentConditionTestCase ): pass @freeze_time( (timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0) )
ErrorIssueEventFrequencyPercentConditionTestCase
python
getsentry__sentry
src/sentry/workflow_engine/processors/data_condition_group.py
{ "start": 6825, "end": 15061 }
class ____: logic_result: TriggerResult condition_results: list[ProcessedDataCondition] DataConditionGroupResult = tuple[ProcessedDataConditionGroup, list[DataCondition]] # We use a defined function rather than a lambda below because otherwise # parameter type becomes Any. def _group_id_from_condition(condi...
ProcessedDataConditionGroup
python
fastai__fastai
fastai/vision/augment.py
{ "start": 28819, "end": 31157 }
class ____(Flip): "Flip the batch every other call" def __init__(self, size:int|tuple=None, # Output size, duplicated if one value is specified mode:str='bilinear', # PyTorch `F.grid_sample` interpolation pad_mode=PadMode.Reflection, # A `PadMode` align_corners=True, # PyTorch `...
DeterministicFlip
python
pandas-dev__pandas
pandas/tests/frame/methods/test_pop.py
{ "start": 117, "end": 2143 }
class ____: def test_pop(self, float_frame): float_frame.columns.name = "baz" float_frame.pop("A") assert "A" not in float_frame float_frame["foo"] = "bar" float_frame.pop("foo") assert "foo" not in float_frame assert float_frame.columns.name == "baz" ...
TestDataFramePop
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/pagination.py
{ "start": 2312, "end": 2752 }
class ____: storage_id: int def __str__(self) -> str: return self.to_string() def to_string(self) -> str: string_serialized = serialize_value(self) return base64.b64encode(bytes(string_serialized, encoding="utf-8")).decode( "utf-8" ) @classmethod def fr...
StorageIdCursor
python
run-llama__llama_index
llama-index-core/tests/agent/utils/test_agent_utils.py
{ "start": 634, "end": 6454 }
class ____(LLM): def __init__(self, responses: List[ChatMessage], structured_response: str): super().__init__() self._responses = responses self._structured_response = structured_response self._response_index = 0 @property def metadata(self) -> LLMMetadata: return LL...
TestLLM
python
streamlit__streamlit
lib/streamlit/runtime/app_session.py
{ "start": 2754, "end": 50410 }
class ____: """ Contains session data for a single "user" of an active app (that is, a connected browser tab). Each AppSession has its own ScriptData, root DeltaGenerator, ScriptRunner, and widget state. An AppSession is attached to each thread involved in running its script. """ def...
AppSession
python
takluyver__flit
flit/wheel.py
{ "start": 225, "end": 279 }
class ____(core_wheel.WheelBuilder): pass
WheelBuilder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_bool.py
{ "start": 575, "end": 645 }
class ____: def __bool__(self): x = True return x
Bool2
python
sympy__sympy
sympy/printing/llvmjitcode.py
{ "start": 1114, "end": 4293 }
class ____(Printer): '''Convert expressions to LLVM IR''' def __init__(self, module, builder, fn, *args, **kwargs): self.func_arg_map = kwargs.pop("func_arg_map", {}) if not llvmlite: raise ImportError("llvmlite is required for LLVMJITPrinter") super().__init__(*args, **kwarg...
LLVMJitPrinter
python
hynek__structlog
tests/test_config.py
{ "start": 4561, "end": 10963 }
class ____: def test_repr(self): """ repr reflects all attributes. """ p = BoundLoggerLazyProxy( None, processors=[1, 2, 3], context_class=dict, initial_values={"foo": 42}, logger_factory_args=(4, 5), ) asser...
TestBoundLoggerLazyProxy
python
streamlit__streamlit
lib/streamlit/runtime/scriptrunner_utils/script_requests.py
{ "start": 1038, "end": 1500 }
class ____(Enum): # The ScriptRunner should continue running its script. CONTINUE = "CONTINUE" # If the script is running, it should be stopped as soon # as the ScriptRunner reaches an interrupt point. # This is a terminal state. STOP = "STOP" # A script rerun has been requested. The Scrip...
ScriptRequestType
python
huggingface__transformers
src/transformers/models/hubert/modeling_hubert.py
{ "start": 14706, "end": 16068 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.attention = HubertAttention( embed_dim=config.hidden_size, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=False, ...
HubertEncoderLayer
python
pypa__pipenv
pipenv/patched/pip/_vendor/distlib/locators.py
{ "start": 20110, "end": 22432 }
class ____(object): """ This class represents a scraped HTML page. """ # The following slightly hairy-looking regex just looks for the contents of # an anchor link, which has an attribute "href" either immediately preceded # or immediately followed by a "rel" attribute. The attribute values can ...
Page
python
realpython__materials
python-class/shapes.py
{ "start": 14, "end": 398 }
class ____: def __set_name__(self, owner, name): self._name = name def __get__(self, instance, owner): return instance.__dict__[self._name] def __set__(self, instance, value): if (not isinstance(value, int | float)) or value <= 0: raise ValueError("positive number expec...
PositiveNumber
python
spyder-ide__spyder
spyder/utils/clipboard_helper.py
{ "start": 229, "end": 1687 }
class ____: # Clipboard metadata metadata_hash = None metadata_indent = None metadata_tab_stop_width_spaces = None def get_current_hash(self): clipboard = QApplication.clipboard() return hash(str(clipboard.text())) def get_line_indentation(self, text, tab_stop_width_spaces=None...
ClipboardHelper
python
realpython__materials
celery-async-tasks/source_code_final/feedback/views.py
{ "start": 380, "end": 457 }
class ____(TemplateView): template_name = "feedback/success.html"
SuccessView
python
lepture__mistune
tests/test_misc.py
{ "start": 47, "end": 5023 }
class ____(TestCase): def test_none(self): self.assertEqual(mistune.html(None), "") def test_before_parse_hooks(self): def _add_name(md, state): state.env["name"] = "test" md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = md.bloc...
TestMiscCases
python
getsentry__sentry
src/sentry/analytics/events/team_created.py
{ "start": 69, "end": 267 }
class ____(analytics.Event): user_id: int | None = None default_user_id: int | str | None = None organization_id: int team_id: int analytics.register(TeamCreatedEvent)
TeamCreatedEvent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_outline03.py
{ "start": 315, "end": 1952 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("outline03.xlsx") self.ignore_files = [ "xl/calcChain.xml", "[Content_Types].xml", "xl/_rels/workbook.xml.re...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/map_test.py
{ "start": 6141, "end": 58807 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def _map_dataset_factory(self, components, apply_map, count): def _map_fn(x, y, z): return math_ops.square(x), math_ops.square(y), math_ops.square(z) dataset = dataset_ops.Dataset.from_tensor_slices(components) dataset = apply_map(dat...
MapTest
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 45592, "end": 47501 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, host: str, port: int, database: str, username: str, replication_method: str, password: Optional[str] = None, jdbc_url_params: Optional[str] = None, ): ""...
ScaffoldJavaJdbcSource
python
walkccc__LeetCode
solutions/1842. Next Palindrome Using Same Digits/1842.py
{ "start": 0, "end": 1052 }
class ____: def nextPalindrome(self, num: str) -> str: def nextPermutation(nums: list[int]) -> bool: n = len(nums) # From the back to the front, find the first num < nums[i + 1]. i = n - 2 while i >= 0: if nums[i] < nums[i + 1]: break i -= 1 if i < 0: ...
Solution
python
redis__redis-py
tests/test_asyncio/test_lock.py
{ "start": 148, "end": 9923 }
class ____: @pytest_asyncio.fixture() async def r_decoded(self, create_redis): redis = await create_redis(decode_responses=True) yield redis await redis.flushall() def get_lock(self, redis, *args, **kwargs): kwargs["lock_class"] = Lock return redis.lock(*args, **kwar...
TestLock
python
protocolbuffers__protobuf
python/google/protobuf/internal/timestamp_test.py
{ "start": 591, "end": 4287 }
class ____(unittest.TestCase): def test_timestamp_integer_conversion(self): self.assertEqual(1, timestamp.to_nanoseconds(timestamp.from_nanoseconds(1))) self.assertEqual(-1, timestamp.to_seconds(timestamp.from_seconds(-1))) self.assertEqual( 123, timestamp.to_milliseconds(timestamp.from_milliseco...
TimestampTest
python
tensorflow__tensorflow
tensorflow/python/ops/variable_scope.py
{ "start": 56209, "end": 58988 }
class ____(threading.local): """A thread local store for the current variable scope and scope counts.""" def __init__(self): super(_VariableScopeStore, self).__init__() self.current_scope = VariableScope(False) self.variable_scopes_count = {} def open_variable_scope(self, scope_name): if scope_n...
_VariableScopeStore
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/checks.py
{ "start": 934, "end": 2088 }
class ____: errors: list[str] = field(default_factory=list) messages: list[str] = field(default_factory=list) def check_dagster_cloud_yaml(yaml_path: pathlib.Path) -> CheckResult: result = CheckResult() if not yaml_path.exists(): result.errors.append(f"No such file {yaml_path}") retur...
CheckResult
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/base.py
{ "start": 54626, "end": 54870 }
class ____(Enum): NONE = "none" UNKNOWN = "unknown" CLIENTSIDE = "clientside" SENTINEL_DEFAULT = "sentinel_default" SERVERSIDE = "serverside" IDENTITY = "identity" SEQUENCE = "sequence"
_SentinelDefaultCharacterization
python
gevent__gevent
src/greentest/3.13/test_socket.py
{ "start": 232240, "end": 235111 }
class ____(unittest.TestCase): def setUp(self): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) def tearDown(self): self.sock.close() def encoded(self, path): # Return the given path encoded in the file system encoding, # or skip the test if this is not possi...
TestUnixDomain
python
qdrant__qdrant-client
tests/congruence_tests/test_group_search.py
{ "start": 589, "end": 13838 }
class ____: __test__ = False def __init__(self): self.query_text = np.random.random(text_vector_size).tolist() self.query_image = np.random.random(image_vector_size).tolist() self.query_code = np.random.random(code_vector_size).tolist() self.group_by = "rand_digit" self....
TestGroupSearcher
python
bokeh__bokeh
src/bokeh/core/property/vectorization.py
{ "start": 1908, "end": 3097 }
class ____(Generic[T], Serializable): value: T transform: NotRequired[Transform] = Unspecified units: NotRequired[str] = Unspecified def to_serializable(self, serializer: Serializer) -> AnyRep: return serializer.encode_struct(type="value", value=self.value, transform=self.transform, units=self....
Value
python
PrefectHQ__prefect
src/prefect/logging/highlighters.py
{ "start": 413, "end": 730 }
class ____(RegexHighlighter): """Apply style to urls.""" base_style = "url." highlights: list[str] = [ r"(?P<web_url>(https|http|ws|wss):\/\/[0-9a-zA-Z\$\-\_\+\!`\(\)\,\.\?\/\;\:\&\=\%\#]*)", r"(?P<local_url>(file):\/\/[0-9a-zA-Z\$\-\_\+\!`\(\)\,\.\?\/\;\:\&\=\%\#]*)", ]
UrlHighlighter
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/logging/publish_connector_lifecycle.py
{ "start": 231, "end": 720 }
class ____(str, Enum): IN_PROGRESS = "in_progress" SUCCESS = "success" FAILED = "failed" def __str__(self) -> str: # convert to upper case return self.value.replace("_", " ").upper() def to_emoji(self) -> str: if self == StageStatus.IN_PROGRESS: return "🟡" ...
StageStatus
python
PyCQA__pylint
pylint/extensions/mccabe.py
{ "start": 1490, "end": 5821 }
class ____(Mccabe_PathGraphingAstVisitor): # type: ignore[misc] def __init__(self) -> None: super().__init__() self._bottom_counter = 0 self.graph: PathGraph | None = None def default(self, node: nodes.NodeNG, *args: Any) -> None: for child in node.get_children(): s...
PathGraphingAstVisitor
python
huggingface__transformers
src/transformers/models/align/configuration_align.py
{ "start": 11855, "end": 15448 }
class ____(PreTrainedConfig): r""" [`AlignConfig`] is the configuration class to store the configuration of a [`AlignModel`]. It is used to instantiate a ALIGN model according to the specified arguments, defining the text model and vision model configs. Instantiating a configuration with the defaults wi...
AlignConfig
python
pallets__jinja
tests/test_utils.py
{ "start": 419, "end": 2964 }
class ____: def test_simple(self): d = LRUCache(3) d["a"] = 1 d["b"] = 2 d["c"] = 3 d["a"] d["d"] = 4 assert d.keys() == ["d", "a", "c"] def test_values(self): cache = LRUCache(3) cache["b"] = 1 cache["a"] = 2 assert cache....
TestLRUCache
python
pytorch__pytorch
torch/_inductor/codegen/memory_planning.py
{ "start": 3670, "end": 5706 }
class ____(AllocationTreeNode): """ Represents memory allocated to a given node in the allocation pool. """ node: BufferLike live_range: LiveRange size_hint: int symbolic_size: sympy.Expr allocated: bool = False pool: Optional[AllocationPool] = None offset: Optional[sympy.Expr] ...
Allocation
python
coleifer__peewee
tests/sqlite.py
{ "start": 31575, "end": 33006 }
class ____(BaseTestCase): def test_virtual_model(self): class Test(VirtualModel): class Meta: database = database extension_module = 'ext1337' legacy_table_names = False options = {'huey': 'cat', 'mickey': 'dog'} pri...
TestSqliteExtensions
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/syntax.py
{ "start": 2550, "end": 8618 }
class ____(QSyntaxHighlighter): """Syntax highlighter for the Python language. """ # Python keywords keywords = [ 'and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',...
PythonHighlighter
python
GoogleCloudPlatform__python-docs-samples
appengine/standard_python3/bundled-services/deferred/wsgi/main.py
{ "start": 1779, "end": 2131 }
class ____(deferred.Handler): """Deferred task handler that adds additional logic.""" def post(self, environ): print("Executing deferred task.") return super().post(environ) routes = { "counter/increment": IncrementCounter, "counter/get": ViewCounter, "custom/path": CustomDeferred...
CustomDeferredHandler
python
allegroai__clearml
clearml/backend_api/services/v2_23/queues.py
{ "start": 22706, "end": 23845 }
class ____(Response): """ Response of queues.add_task endpoint. :param added: Number of tasks added (0 or 1) :type added: int """ _service = "queues" _action = "add_task" _version = "2.23" _schema = { "definitions": {}, "properties": { "added": { ...
AddTaskResponse
python
huggingface__transformers
src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py
{ "start": 5454, "end": 8981 }
class ____: """ Padding cache for KyutaiSpeechToTextConv1d causal convolutions in order to support streaming via cache padding. See: https://huggingface.co/papers/2005.06720 & https://huggingface.co/papers/2204.07064 A padding cache is a list of cached partial hidden states for each convolution layer. ...
KyutaiSpeechToTextConv1dPaddingCache
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 209894, "end": 210701 }
class ____(sgqlc.types.Input): """Autogenerated input type of DeclineTopicSuggestion""" __schema__ = github_schema __field_names__ = ("repository_id", "name", "reason", "client_mutation_id") repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId") """The Node ID of t...
DeclineTopicSuggestionInput
python
sqlalchemy__sqlalchemy
test/typing/plain_files/ext/hybrid/hybrid_four.py
{ "start": 380, "end": 603 }
class ____(Comparator[str]): def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501 return func.lower(self.__clause_element__()) == func.lower(other)
CaseInsensitiveComparator
python
numpy__numpy
numpy/f2py/tests/test_modules.py
{ "start": 1480, "end": 1853 }
class ____(util.F2PyTest): module_name = "example" sources = [ util.getpath("tests", "src", "modules", "gh25337", "data.f90"), util.getpath("tests", "src", "modules", "gh25337", "use_data.f90"), ] def test_gh25337(self): self.module.data.set_shift(3) assert "data" in dir...
TestModuleAndSubroutine
python
pydantic__pydantic
pydantic/types.py
{ "start": 16665, "end": 17708 }
class ____(BaseModel): finite: FiniteFloat m = Model(finite=1.0) print(m) #> finite=1.0 ``` """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def conbytes( *, min_length: int | None = None, max_length: int | None = None, strict: bool | None = None, ) -> type[by...
Model
python
openai__openai-python
src/openai/types/beta/realtime/realtime_response_status.py
{ "start": 385, "end": 1326 }
class ____(BaseModel): error: Optional[Error] = None """ A description of the error that caused the response to fail, populated when the `status` is `failed`. """ reason: Optional[Literal["turn_detected", "client_cancelled", "max_output_tokens", "content_filter"]] = None """The reason the R...
RealtimeResponseStatus
python
PyCQA__pylint
tests/functional/n/not_context_manager.py
{ "start": 1941, "end": 2562 }
class ____(ManagerMixin): def __enter__(self): return self def __exit__(self, *args): pass # Test a false positive with returning a generator # from a context manager. def generator(): yield 42 @contextmanager def context_manager_returning_generator(): return generator() with context_...
FullContextManager
python
huggingface__transformers
src/transformers/models/smolvlm/modeling_smolvlm.py
{ "start": 2569, "end": 6721 }
class ____(nn.Module): """ This is a modified version of `siglip.modelign_siglip.SiglipVisionEmbeddings` to enable images of variable resolution. The modifications are adapted from [Patch n' Pack: NaViT, a Vision Transformer for any Aspect Ratio and Resolution](https://huggingface.co/papers/2307.06304)...
SmolVLMVisionEmbeddings
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_collections.py
{ "start": 1468, "end": 3246 }
class ____(__TestCase): def _superset_test(self, a, b): self.assertGreaterEqual( set(dir(a)), set(dir(b)), '{a} should have all the methods of {b}'.format( a=a.__name__, b=b.__name__, ), ) def _copy_test(self, obj):...
TestUserObjects
python
django__django
tests/migrations/test_migrations_squashed_double/0004_auto.py
{ "start": 43, "end": 304 }
class ____(migrations.Migration): dependencies = [("migrations", "0002_auto")] operations = [ migrations.AlterField( model_name="a", name="foo", field=models.BooleanField(default=False), ), ]
Migration