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
mlflow__mlflow
tests/langchain/test_langchain_model_export.py
{ "start": 31898, "end": 82983 }
class ____(SimpleChatModel): def _call(self, messages, stop, run_manager, **kwargs): return "\n".join([f"{message.type}: {message.content}" for message in messages]) @property def _llm_type(self) -> str: return "chat model" @skip_if_v1 def test_predict_with_builtin_pyfunc_chat_conversion(...
ChatModel
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_custom_job.py
{ "start": 12075, "end": 20357 }
class ____: @pytest.mark.asyncio @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_pipeline_service_client")) async def test_get_training_pipeline( self, mock_pipeline_service_client, test_async_hook, test_training_pipeline_name ): mock_pipeline_service_client.return_value.tra...
TestCustomJobAsyncHook
python
readthedocs__readthedocs.org
readthedocs/builds/querysets.py
{ "start": 5131, "end": 9546 }
class ____(NoReprQuerySet, models.QuerySet): """ Build objects that are privacy aware. i.e. they take into account the privacy of the Version that they relate to. """ use_for_related_fields = True def _add_from_user_projects(self, queryset, user, admin=False, member=False): """Add rel...
BuildQuerySet
python
Textualize__textual
src/textual/app.py
{ "start": 6719, "end": 6812 }
class ____(ModeError): """Raised if there is an issue with a mode name."""
InvalidModeError
python
getsentry__sentry
src/sentry/snuba/metrics/query.py
{ "start": 3240, "end": 3958 }
class ____(MetricActionByField): alias: str = "" def __post_init__(self) -> None: if not self.alias: if isinstance(self.field, str): alias = self.field else: assert self.field.alias is not None alias = self.field.alias ...
MetricGroupByField
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/liveness.py
{ "start": 1327, "end": 3309 }
class ____(cfg.GraphVisitor): """CFG visitor that performs liveness analysis at statement level.""" def __init__(self, graph, include_annotations): super(Analyzer, self).__init__(graph) self.include_annotations = include_annotations def init_state(self, _): return set() def lamba_check(self, fn_a...
Analyzer
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_date_range.py
{ "start": 36145, "end": 39120 }
class ____: def test_constructor(self): bdate_range(START, END, freq=BDay()) bdate_range(START, periods=20, freq=BDay()) bdate_range(end=START, periods=20, freq=BDay()) msg = "periods must be an integer, got B" with pytest.raises(TypeError, match=msg): date_range...
TestBusinessDateRange
python
TheAlgorithms__Python
electronics/electric_power.py
{ "start": 117, "end": 1951 }
class ____(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0...
Result
python
getsentry__sentry
src/sentry/api/endpoints/project_plugins.py
{ "start": 468, "end": 907 }
class ____(ProjectEndpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, project) -> Response: context = serialize( [plugin for plugin in plugins.configurable_for_project(project, version=None)], ...
ProjectPluginsEndpoint
python
huggingface__transformers
tests/models/roc_bert/test_modeling_roc_bert.py
{ "start": 32386, "end": 33520 }
class ____(unittest.TestCase): @slow def test_inference_masked_lm(self): model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh") # input_text: ['[CLS]', 'b', 'a', '里', '系', '[MASK]', '国', '的', '首', '都', '[SEP]'] is the adversarial text # of ['[CLS]', '巴', '黎', '是', '[MA...
RoCBertModelIntegrationTest
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 45622, "end": 48125 }
class ____(Request): """ Get an attachment containing the task's log :param task: Task ID :type task: str :param line_type: Line format type :type line_type: str :param line_format: Line string format. Used if the line type is 'text' :type line_format: str """ _service = "event...
DownloadTaskLogRequest
python
pyca__cryptography
tests/hazmat/primitives/test_poly1305.py
{ "start": 924, "end": 4820 }
class ____: @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("poly1305", "rfc7539.txt"), load_nist_vectors ), ) def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) msg = binascii.unhexlify(vector["msg"])...
TestPoly1305
python
huggingface__transformers
src/transformers/models/zoedepth/modeling_zoedepth.py
{ "start": 30624, "end": 31590 }
class ____(nn.Module): def __init__(self, in_features, out_features, mlp_dim=128): """Projector MLP. Args: in_features (`int`): Number of input channels. out_features (`int`): Number of output channels. mlp_dim (`int`, *optional*, ...
ZoeDepthProjector
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 834844, "end": 835232 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("PinnableItem", graphql_na...
PinnableItemEdge
python
walkccc__LeetCode
solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py
{ "start": 0, "end": 725 }
class ____: def lowestCommonAncestor( self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode', ) -> 'TreeNode': def getLCA(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root or root == p or root == q: return root left = getLCA(root.left, p, q) ...
Solution
python
huggingface__transformers
src/transformers/models/idefics/modeling_idefics.py
{ "start": 12725, "end": 15282 }
class ____(nn.Linear): # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear """ Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), a...
IdeficsDecoupledLinear
python
bokeh__bokeh
tests/unit/bokeh/embed/test_elements.py
{ "start": 1800, "end": 2712 }
class ____: def test_issue_13629(self) -> None: bundle = Bundle(js_files=[ URL(url='http://localhost:5006/static/js/bokeh.js'), ]) render_item = RenderItem(docid=ID("doc123"), elementid=ID("foo123")) docs_json = { ID("doc123"): DocJson( version...
Test_html_page_for_render_items
python
mlflow__mlflow
tests/langgraph/sample_code/langgraph_chat_agent_custom_inputs.py
{ "start": 4024, "end": 6391 }
class ____(ChatAgent): def __init__(self, agent: CompiledStateGraph): self.agent = agent def predict( self, messages: list[ChatAgentMessage], context: ChatContext | None = None, custom_inputs: dict[str, Any] | None = None, ) -> ChatAgentResponse: request = { ...
LangGraphChatAgent
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 193296, "end": 213429 }
class ____(TestCase): # Calls to super() in dynamically created classes are a bit odd. # See https://github.com/pytorch/pytorch/pull/118586 for more info # Subclassing this class and then calling super(TestCaseBase) will run # TestCase's setUp, tearDown etc functions pass def download_file(url, bi...
TestCaseBase
python
keon__algorithms
tests/test_strings.py
{ "start": 7252, "end": 7827 }
class ____(unittest.TestCase): """[summary] Test for the file license_number.py Arguments: unittest {[type]} -- [description] """ def test_license_number(self): self.assertEqual("a-b-c-d-f-d-d-f", license_number("a-bc-dfd-df", 1)) self.assertEqual("ab-cd-fd-df", license_num...
TestLicenseNumber
python
doocs__leetcode
solution/0700-0799/0775.Global and Local Inversions/Solution2.py
{ "start": 343, "end": 722 }
class ____: def isIdealPermutation(self, nums: List[int]) -> bool: n = len(nums) tree = BinaryIndexedTree(n) cnt = 0 for i, v in enumerate(nums): cnt += i < n - 1 and v > nums[i + 1] cnt -= i - tree.query(v) if cnt < 0: return False...
Solution
python
gevent__gevent
src/greentest/3.12/test_interpreters.py
{ "start": 25267, "end": 25804 }
class ____(TestBase): def test_create(self): r, s = interpreters.create_channel() self.assertIsInstance(r, interpreters.RecvChannel) self.assertIsInstance(s, interpreters.SendChannel) def test_list_all(self): self.assertEqual(interpreters.list_all_channels(), []) create...
TestChannels
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 882, "end": 2094 }
class ____(util.MdCase): """Test that highlighting works with guessing for block.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'guess_lang': "block" } } def test_guess_block(self): """Test guessing f...
TestHighlightGuessBlock
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 54759, "end": 60716 }
class ____(SimpleElement): """ COOSYS_ element: defines a coordinate system. The keyword arguments correspond to setting members of the same name, documented below. """ _attr_list = ["ID", "equinox", "epoch", "system", "refposition"] _element_name = "COOSYS" _reference_frames = None ...
CooSys
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/processors.py
{ "start": 30030, "end": 31343 }
class ____(Processor): """ Processor that applies another processor, according to a certain condition. Example:: # Create a function that returns whether or not the processor should # currently be applied. def highlight_enabled(): return true_or_false # Wrapped ...
ConditionalProcessor
python
jina-ai__jina
jina/parsers/helper.py
{ "start": 11009, "end": 12230 }
class ____(argparse.Action): """argparse action to cast potential inputs to `peer-ports` argument""" def __call__(self, parser, args, values, option_string=None): """ call the CastPeerPorts .. # noqa: DAR401 :param parser: the parser :param args: args to initialize the...
CastPeerPorts
python
google__jax
jax/_src/interpreters/ad.py
{ "start": 36942, "end": 50460 }
class ____(Trace): def __init__(self, parent_trace, tangent_trace, tag=None): super().__init__() self.tag = core.TraceTag() if tag is None else tag self.parent_trace = parent_trace self.tangent_trace = tangent_trace self._name_stack_prefix_len = len(source_info_util.current_name_stack()) self...
LinearizeTrace
python
run-llama__llama_index
llama-index-core/llama_index/core/prompts/base.py
{ "start": 7163, "end": 11323 }
class ____(BasePromptTemplate): # type: ignore[no-redef] message_templates: List[ChatMessage] def __init__( self, message_templates: Sequence[ChatMessage], prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[st...
ChatPromptTemplate
python
spyder-ide__spyder
spyder/plugins/updatemanager/workers.py
{ "start": 2280, "end": 8229 }
class ____(TypedDict): """Schema for asset information.""" # Version version: Version # Filename with extension of the release asset to download. filename: str # Type of update update_type: UpdateType # Download URL for the asset. url: str # File sha256 checksum checksum...
AssetInfo
python
pytransitions__transitions
transitions/extensions/factory.py
{ "start": 2252, "end": 2508 }
class ____(LockedMachine, HierarchicalMachine): """ A threadsafe hierarchical machine. """ event_cls = NestedEvent def _get_qualified_state_name(self, state): return self.get_global_name(state.name)
LockedHierarchicalMachine
python
google__jax
jax/_src/pallas/core.py
{ "start": 9357, "end": 9896 }
class ____: index: jax_typing.Array size: int # Stores the kernel execution position and the size along grid axes. GridEnv = Sequence[GridAxis] @contextlib.contextmanager def grid_env(env: GridEnv) -> Iterator[None]: _pallas_tracing_env.grid_env_stack.append(env) try: yield finally: _pallas_tracing_e...
GridAxis
python
walkccc__LeetCode
solutions/1828. Queries on Number of Points Inside a Circle/1828.py
{ "start": 0, "end": 327 }
class ____: def countPoints( self, points: list[list[int]], queries: list[list[int]], ) -> list[int]: ans = [] for xj, yj, rj in queries: count = 0 for xi, yi in points: if (xi - xj)**2 + (yi - yj)**2 <= rj**2: count += 1 ans.append(count) return a...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 776379, "end": 777269 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "allow_list_value", "created_at", "is_active", "name", "owner", "updated_at", ) allow_list_value = sgqlc.types.Field( ...
IpAllowListEntry
python
getsentry__sentry
src/sentry/notifications/platform/target.py
{ "start": 2272, "end": 2940 }
class ____(GenericNotificationTarget): """ Adds necessary properties and methods to designate a target within an integration. Accepts the renderable object type that matches the connected provider. """ integration_id: int organization_id: int def to_dict(self) -> dict[str, Any]: ba...
IntegrationNotificationTarget
python
scrapy__scrapy
scrapy/core/engine.py
{ "start": 2935, "end": 23858 }
class ____: _SLOT_HEARTBEAT_INTERVAL: float = 5.0 def __init__( self, crawler: Crawler, spider_closed_callback: Callable[ [Spider], Coroutine[Any, Any, None] | Deferred[None] | None ], ) -> None: self.crawler: Crawler = crawler self.settings: Sett...
ExecutionEngine
python
aio-libs__aiohttp
aiohttp/client_exceptions.py
{ "start": 3308, "end": 3399 }
class ____(ClientError): """Base class for client socket errors."""
ClientConnectionError
python
huggingface__transformers
src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py
{ "start": 115485, "end": 120552 }
class ____(BigBirdPegasusPreTrainedModel): def __init__(self, config): super().__init__(config) config.num_labels = 2 self.num_labels = config.num_labels self.model = BigBirdPegasusModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # I...
BigBirdPegasusForQuestionAnswering
python
sympy__sympy
sympy/core/exprtools.py
{ "start": 26677, "end": 51352 }
class ____: """Efficient representation of ``coeff*(numer/denom)``. """ __slots__ = ('coeff', 'numer', 'denom') def __init__(self, term, numer=None, denom=None): # Term if numer is None and denom is None: if not term.is_commutative: raise NonCommutativeExpression( ...
Term
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 37590, "end": 38838 }
class ____(Base): """SQLAlchemy model of a work queue""" name: Mapped[str] filter: Mapped[Optional[schemas.core.QueueFilter]] = mapped_column( Pydantic(schemas.core.QueueFilter) ) description: Mapped[str] = mapped_column(default="", server_default="") is_paused: Mapped[bool] = mapped_c...
WorkQueue
python
doocs__leetcode
solution/2700-2799/2784.Check if Array is Good/Solution.py
{ "start": 0, "end": 181 }
class ____: def isGood(self, nums: List[int]) -> bool: cnt = Counter(nums) n = len(nums) - 1 return cnt[n] == 2 and all(cnt[i] for i in range(1, n))
Solution
python
wandb__wandb
wandb/vendor/pygments/formatters/img.py
{ "start": 19455, "end": 19780 }
class ____(ImageFormatter): """ Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code. .. versionadded:: 1.0 """ name = 'img_bmp' aliases = ['bmp', 'bitmap'] filenames = ['*.bmp'] default_image_format = 'bmp'
BmpImageFormatter
python
hynek__structlog
tests/test_threadlocal.py
{ "start": 1649, "end": 3128 }
class ____: def test_bind(self, log): """ tmp_bind does not modify the thread-local state. """ log = log.bind(y=23) with pytest.deprecated_call(), tmp_bind(log, x=42, y="foo") as tmp_log: assert ( {"y": "foo", "x": 42} == tmp_log._c...
TestTmpBind
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_all_reduce_strategy.py
{ "start": 9369, "end": 9807 }
class ____(type): @classmethod def __instancecheck__(cls, instance): # This is to make isinstance(tf.distribute.MultiWorkerMirroredStrategy(), # tf.distribute.experimental.MultiWorkerMirroredStrategy). Some libraries is # performing such check. return isinstance(instance, CollectiveAllReduceStrateg...
_CollectiveAllReduceStrategyExperimentalMeta
python
spack__spack
var/spack/test_repos/spack_repo/duplicates_test/packages/py_setuptools/package.py
{ "start": 216, "end": 552 }
class ____(Package): """Build tool for an extendable package""" homepage = "http://www.example.com" url = "http://www.example.com/tdep-1.0.tar.gz" tags = ["build-tools"] extends("python") version("60", md5="0123456789abcdef0123456789abcdef") version("59", md5="0123456789abcdef0123456789a...
PySetuptools
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 376079, "end": 376744 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateSubscription""" __schema__ = github_schema __field_names__ = ("subscribable_id", "state", "client_mutation_id") subscribable_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subscribableId") """The Node ID of the subs...
UpdateSubscriptionInput
python
apache__airflow
providers/google/tests/unit/google/common/hooks/test_base_google.py
{ "start": 5013, "end": 5391 }
class ____: def __init__(self, project_id): self.mock = mock.Mock() self.fixture_project_id = project_id @hook.GoogleBaseHook.fallback_to_default_project_id def method(self, project_id=None): self.mock(project_id=project_id) @property def project_id(self): return se...
FallbackToDefaultProjectIdFixtureClass
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 85138, "end": 88479 }
class ____: Py_single_input = 256 Py_file_input = 257 Py_eval_input = 258 def malloc(self, size): chunk = (gdb.parse_and_eval("(void *) malloc((size_t) %d)" % size)) pointer = pointervalue(chunk) if pointer == 0: raise gdb.GdbError("No memory could be allocated in ...
PythonCodeExecutor
python
encode__django-rest-framework
rest_framework/generics.py
{ "start": 6926, "end": 7158 }
class ____(mixins.ListModelMixin, GenericAPIView): """ Concrete view for listing a queryset. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs)
ListAPIView
python
getsentry__sentry
tests/sentry/new_migrations/monkey/test_executor.py
{ "start": 470, "end": 636 }
class ____(AppConfig): name = "getsentry" label = "getsentry" verbose_name = "Dummy Getsentry App" path = "/tmp/dummy_getsentry"
DummyGetsentryAppConfig
python
huggingface__transformers
src/transformers/models/squeezebert/modeling_squeezebert.py
{ "start": 5371, "end": 9365 }
class ____(nn.Module): def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1): """ config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers """ super().__init_...
SqueezeBertSelfAttention
python
PyCQA__pyflakes
pyflakes/checker.py
{ "start": 16897, "end": 16932 }
class ____(Scope): pass
TypeScope
python
optuna__optuna
optuna/storages/_rdb/models.py
{ "start": 3180, "end": 4239 }
class ____(BaseModel): __tablename__ = "study_user_attributes" __table_args__: Any = (UniqueConstraint("study_id", "key"),) study_user_attribute_id = _Column(Integer, primary_key=True) study_id = _Column(Integer, ForeignKey("studies.study_id")) key = _Column(String(MAX_INDEXED_STRING_LENGTH)) va...
StudyUserAttributeModel
python
jina-ai__jina
tests/integration/docarray_v2/test_streaming.py
{ "start": 3592, "end": 5519 }
class ____(Executor): @requests(on='/hello') async def task(self, doc: MyDocument, **kwargs) -> MyDocument: for i in range(5): yield MyDocument(text=f'{doc.text} {doc.number + i}') await asyncio.sleep(0.5) @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc...
WaitStreamExecutor
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 90476, "end": 92029 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) host_private_ip: Optional[str] = Field( None, description="The private IP address of the host instance." ) instance_id: Optional[str] = Field( N...
SparkNode
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 138032, "end": 138504 }
class ____(ColumnDefault): """default generator for a fixed scalar Python value .. versionadded:: 2.0 """ is_scalar = True has_arg = True def __init__(self, arg: Any, for_update: bool = False) -> None: self.for_update = for_update self.arg = arg def _copy(self) -> Scalar...
ScalarElementColumnDefault
python
django__django
tests/m2m_recursive/models.py
{ "start": 777, "end": 1118 }
class ____(models.Model): name = models.CharField(max_length=20) friends = models.ManyToManyField("self") colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague") idols = models.ManyToManyField("self", symmetrical=False, related_name="stalkers") def __str__(self): ...
Person
python
pytorch__pytorch
torch/_dynamo/device_interface.py
{ "start": 17818, "end": 19464 }
class ____(DeviceInterface): # pyrefly: ignore [bad-override] class Event(torch.Event): def __init__(self, enable_timing: bool = True) -> None: self.time = 0.0 def elapsed_time(self, end_event: Any) -> float: return (end_event.time - self.time) * 1000 def record...
CpuInterface
python
Netflix__metaflow
metaflow/parameters.py
{ "start": 2770, "end": 3214 }
class ____(click.ParamType): name = "JSON" def convert(self, value, param, ctx): if not isinstance(value, strtype): # Already a correct type return value try: return json.loads(value) except: self.fail("%s is not a valid JSON object" % val...
JSONTypeClass
python
Textualize__textual
src/textual/widgets/_button.py
{ "start": 1052, "end": 15330 }
class ____(Widget, can_focus=True): """A simple clickable button. Clicking the button will send a [Button.Pressed][textual.widgets.Button.Pressed] message, unless the `action` parameter is provided. """ ALLOW_SELECT = False DEFAULT_CSS = """ Button { width: auto; min-widt...
Button
python
PrefectHQ__prefect
tests/utilities/test_asyncutils.py
{ "start": 3695, "end": 10092 }
class ____: attr = 4 @staticmethod @sync_compatible async def static_method(x, y, z=3): assert SyncCompatibleClass.attr == 4, "Can access class attributes" return x + y + z @classmethod @sync_compatible async def class_method(cls, x, y, z=3): assert cls.attr == 4, "...
SyncCompatibleClass
python
bokeh__bokeh
tests/unit/bokeh/embed/test_notebook__embed.py
{ "start": 1464, "end": 3675 }
class ____(object): @patch('bokeh.embed.notebook.standalone_docs_json_and_render_items') def test_notebook_content(self, mock_sdjari: MagicMock, test_plot: MagicMock) -> None: (docs_json, render_items) = ("DOC_JSON", [RenderItem(docid="foo", elementid="bar")]) mock_sdjari.return_value = (docs_j...
Test_notebook_content
python
astropy__astropy
astropy/utils/masked/tests/test_table.py
{ "start": 820, "end": 1022 }
class ____(MaskedArrayTableSetup): @classmethod def setup_arrays(cls): cls.a = np.array([3.0, 5.0, 0.0]) << u.m cls.mask_a = np.array([True, False, False])
MaskedQuantityTableSetup
python
celery__celery
celery/bin/base.py
{ "start": 7855, "end": 8120 }
class ____(ParamType): """ISO 8601 Date Time argument.""" name = "iso-86091" def convert(self, value, param, ctx): try: return maybe_iso8601(value) except (TypeError, ValueError) as e: self.fail(e)
ISO8601DateTime
python
ApeWorX__ape
src/ape/types/private_mempool.py
{ "start": 3170, "end": 3326 }
class ____(BaseModel): """ A nested bundle request. """ bundle: "Bundle" """ A bundle request of type Bundle """
BundleNestedItem
python
doocs__leetcode
solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/Solution.py
{ "start": 0, "end": 202 }
class ____: def countTriplets(self, nums: List[int]) -> int: cnt = Counter(x & y for x in nums for y in nums) return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0)
Solution
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qconv_test.py
{ "start": 161, "end": 1277 }
class ____(op_bench.TorchBenchmarkBase): # def init(self, N, IC, OC, L, G, kernel, stride, pad): def init(self, IC, OC, kernel, stride, N, L, device): G = 1 pad = 0 self.scale = 1.0 / 255 self.zero_point = 0 X = torch.randn(N, IC, L, dtype=torch.float32) qX = torc...
QConv1dBenchmark
python
huggingface__transformers
src/transformers/models/dpt/modeling_dpt.py
{ "start": 19487, "end": 20320 }
class ____(nn.Module): def __init__(self, config: DPTConfig): super().__init__() self.config = config self.layer = nn.ModuleList([DPTViTLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, hidden_states: torch.Tensor, out...
DPTViTEncoder
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 22055, "end": 22139 }
class ____(AutomationCore, ActionBaseModel, extra="forbid"): pass
AutomationUpdate
python
openai__openai-python
src/openai/types/completion_choice.py
{ "start": 244, "end": 466 }
class ____(BaseModel): text_offset: Optional[List[int]] = None token_logprobs: Optional[List[float]] = None tokens: Optional[List[str]] = None top_logprobs: Optional[List[Dict[str, float]]] = None
Logprobs
python
gevent__gevent
src/greentest/3.10/test_httplib.py
{ "start": 57411, "end": 58919 }
class ____(TestCase): PORT = None def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TimeoutTest.PORT = socket_helper.bind_port(self.serv) self.serv.listen() def tearDown(self): self.serv.close() self.serv = None def testTimeoutAttri...
TimeoutTest
python
langchain-ai__langchain
libs/langchain/tests/unit_tests/chains/test_sequential.py
{ "start": 556, "end": 10153 }
class ____(Chain): """Fake Chain for testing purposes.""" input_variables: list[str] output_variables: list[str] @property def input_keys(self) -> list[str]: """Input keys this chain returns.""" return self.input_variables @property def output_keys(self) -> list[str]: ...
FakeChain
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/lexers/pygments.py
{ "start": 1910, "end": 4070 }
class ____(SyntaxSync): """ Synchronize by starting at a line that matches the given regex pattern. """ # Never go more than this amount of lines backwards for synchronization. # That would be too CPU intensive. MAX_BACKWARDS = 500 # Start lexing at the start, if we are in the first 'n' li...
RegexSync
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 38714, "end": 41663 }
class ____(_InverseTrigonometric1D): """ One dimensional ArcCosine returning values between 0 and pi only. Parameters ---------- amplitude : float Oscillation amplitude for corresponding Cosine frequency : float Oscillation frequency for corresponding Cosine phase : float ...
ArcCosine1D
python
allegroai__clearml
clearml/utilities/pyhocon/converter.py
{ "start": 340, "end": 13100 }
class ____(object): _number_re = r'[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE][+\-]?\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))' _number_re_matcher = re.compile(_number_re) @classmethod def to_json(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a JSON output :return: JSON st...
HOCONConverter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/slice_generators.py
{ "start": 444, "end": 810 }
class ____: """ Base class for slice generators. """ _start_date: DateTime = None _end_data: DateTime = None def __init__(self, start_date: DateTime, end_date: Optional[DateTime] = None): self._start_date = start_date self._end_date = end_date or pendulum.now("UTC") def __...
SliceGenerator
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py
{ "start": 8176, "end": 10125 }
class ____(BaseTrigger): """ RedshiftClusterTrigger is fired as deferred class with params to run the task in trigger worker. :param aws_conn_id: Reference to AWS connection id for redshift :param cluster_identifier: unique identifier of a cluster :param target_status: Reference to the status which...
RedshiftClusterTrigger
python
geekcomputers__Python
insta_monitering/insta_datafetcher.py
{ "start": 12622, "end": 15836 }
class ____: def __init__(self, user, tags, type, productId): try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) db = self.mon[productId + ":" + user + ":insta"] self._collection = db[tags] except Exception as err: print(f"exce...
DBDataFetcher
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 651, "end": 1420 }
class ____(object): """ Base class for all renderers """ def activate(self): pass def __repr__(self): try: init_sig = inspect.signature(self.__init__) init_args = list(init_sig.parameters.keys()) except AttributeError: # Python 2.7 ...
BaseRenderer
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 51965, "end": 52270 }
class ____(TestOnlySetsInBinaryOps, TestCase): def setUp(self): super().setUp() self.OrderedSet = OrderedSet((1, 2, 3)) self.other = (2, 4, 6) self.otherIsIterable = True # ------------------------------------------------------------------------------
TestOnlySetsTuple
python
ray-project__ray
python/ray/data/_internal/execution/operators/sub_progress.py
{ "start": 72, "end": 806 }
class ____(ABC): """Abstract class for operators that support sub-progress bars""" @abstractmethod def get_sub_progress_bar_names(self) -> Optional[List[str]]: """ Returns list of sub-progress bar names This is used to create the sub-progress bars in the progress manager. N...
SubProgressBarMixin
python
pennersr__django-allauth
allauth/mfa/totp/views.py
{ "start": 2720, "end": 4515 }
class ____(FormView): form_class = DeactivateTOTPForm template_name = "mfa/totp/deactivate_form." + account_settings.TEMPLATE_EXTENSION success_url = reverse_lazy("mfa_index") def dispatch(self, request, *args, **kwargs): self.authenticator = get_object_or_404( Authenticator, ...
DeactivateTOTPView
python
apache__airflow
providers/standard/src/airflow/providers/standard/operators/python.py
{ "start": 51481, "end": 53758 }
class ____(BaseBranchOperator, ExternalPythonOperator): """ A workflow can "branch" or follow a path after the execution of this task. Extends ExternalPythonOperator, so expects to get Python: virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path, so it can run o...
BranchExternalPythonOperator
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 25940, "end": 26553 }
class ____(MixinSequenceOfValues): """ Facet labels along the vertical axis Parameters ---------- theme_element : element_text """ _omit = ["margin", "ha", "va"] def apply_figure(self, figure: Figure, targets: ThemeTargets): super().apply_figure(figure, targets) if tex...
strip_text_y
python
openai__openai-python
src/openai/resources/uploads/uploads.py
{ "start": 24876, "end": 25443 }
class ____: def __init__(self, uploads: AsyncUploads) -> None: self._uploads = uploads self.create = async_to_streamed_response_wrapper( uploads.create, ) self.cancel = async_to_streamed_response_wrapper( uploads.cancel, ) self.complete = asyn...
AsyncUploadsWithStreamingResponse
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 33534, "end": 35481 }
class ____(rv_discrete): r"""A Boltzmann (Truncated Discrete Exponential) random variable. %(before_notes)s Notes ----- The probability mass function for `boltzmann` is: .. math:: f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N)) for :math:`k = 0,..., N-1`. ...
boltzmann_gen
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/win32.py
{ "start": 20476, "end": 24576 }
class ____: """ Similar to `ConsoleInputReader`, but for usage when `ENABLE_VIRTUAL_TERMINAL_INPUT` is enabled. This assumes that Windows sends us the right vt100 escape sequences and we parse those with our vt100 parser. (Using this instead of `ConsoleInputReader` results in the "data" attribu...
Vt100ConsoleInputReader
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 33323, "end": 35337 }
class ____(LossFunctionWrapper): """Computes the categorical hinge loss between `y_true` and `y_pred`. `loss = maximum(neg - pos + 1, 0)` where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)` Standalone usage: >>> y_true = [[0, 1], [0, 0]] >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] >>> # Using '...
CategoricalHinge
python
ethereum__web3.py
web3/types.py
{ "start": 13728, "end": 13885 }
class ____(TypedDict): blockOverrides: NotRequired[BlockData] stateOverrides: NotRequired[StateOverride] calls: Sequence[TxParams]
BlockStateCallV1
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py
{ "start": 2323, "end": 3574 }
class ____(Benchmark): r""" Ackley03 [1]_ objective function. The Ackley03 global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{Ackley03}}(x) = -200 e^{-0.02 \sqrt{x_1^2 + x_2^2}} + 5e^{\cos(3x_1) + \sin(3x_2)} with :ma...
Ackley03
python
getsentry__sentry
tests/sentry/notifications/notification_action/test_metric_alert_registry_handlers.py
{ "start": 10274, "end": 25466 }
class ____(MetricAlertHandlerBase): def setUp(self) -> None: super().setUp() self.action = self.create_action( type=Action.Type.DISCORD, integration_id="1234567890", config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC}, data...
TestBaseMetricAlertHandler
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_eks.py
{ "start": 4748, "end": 7398 }
class ____: @pytest.fixture(autouse=True) def _setup_test_cases(self): self.target_state = FargateProfileStates.ACTIVE self.sensor = EksFargateProfileStateSensor( task_id=TASK_ID, cluster_name=CLUSTER_NAME, fargate_profile_name=FARGATE_PROFILE_NAME, ...
TestEksFargateProfileStateSensor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/cloud_storage_transfer.py
{ "start": 1975, "end": 2220 }
class ____(BaseGoogleLink): """Helper class for constructing Cloud Storage Transfer Link.""" name = "Cloud Storage Transfer" key = "cloud_storage_transfer" format_str = CLOUD_STORAGE_TRANSFER_LIST_LINK
CloudStorageTransferListLink
python
getsentry__sentry
src/sentry/workflow_engine/models/data_source.py
{ "start": 909, "end": 4023 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Organization # DataSource.source_id dynamically references different models based on the 'type' field. # We declare all possible dependencies here to ensure proper import ordering. __relocation_dependencies__ = { "monitors.mo...
DataSource
python
huggingface__transformers
src/transformers/models/rag/retrieval_rag.py
{ "start": 1366, "end": 3007 }
class ____: """ A base class for the Indices encapsulated by the [`RagRetriever`]. """ def get_doc_dicts(self, doc_ids: np.ndarray) -> list[dict]: """ Returns a list of dictionaries, containing titles and text of the retrieved documents. Args: doc_ids (`np.ndarray` ...
Index
python
ray-project__ray
python/ray/tests/test_autoscaling_policy.py
{ "start": 1484, "end": 1514 }
class ____(Task): pass
Actor
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/properties/snippets.py
{ "start": 3406, "end": 3615 }
class ____(ndb.Model): name = ndb.StringProperty() color = msgprop.EnumProperty(Color, required=True) def print_part(): p1 = Part(name="foo", color=Color.RED) print(p1.color) # prints "RED"
Part
python
MongoEngine__mongoengine
tests/fields/test_reference_field.py
{ "start": 111, "end": 7032 }
class ____(MongoDBTestCase): def test_reference_field_fails_init_wrong_document_type(self): class User(Document): name = StringField() ERROR_MSG = "Argument to ReferenceField constructor must be a document class or a string" # fails if given an instance with pytest.raise...
TestReferenceField
python
scipy__scipy
benchmarks/benchmarks/tests/test_go_benchmark_functions.py
{ "start": 148, "end": 2683 }
class ____: def setup_method(self): bench_members = inspect.getmembers(gbf, inspect.isclass) self.benchmark_functions = {it[0]:it[1] for it in bench_members if issubclass(it[1], gbf.Benchmark)} def teardown_method(self): pass def test_optimum_so...
TestGoBenchmarkFunctions
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 48789, "end": 49785 }
class ____(AssetSelection): selected_key_wildcard: str def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: regex = re.compile("^" + re.escape(self.selected_key_wildcard).replace("\\*", ".*") + "$") return { key for key in...
KeyWildCardAssetSelection
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/steps.py
{ "start": 3008, "end": 3422 }
class ____(Result): """A dataclass to capture the result of a command.""" command: click.Command def __repr__(self) -> str: # noqa D105 return f"{self.command.name}: {self.status.value}" def __str__(self) -> str: # noqa D105 return f"{self.command.name}: {self.status.value}\n\nSTDOU...
CommandResult