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
streamlit__streamlit
lib/streamlit/type_util.py
{ "start": 1569, "end": 1634 }
class ____(Protocol): def __str__(self) -> str: ...
SupportsStr
python
run-llama__llama_index
llama-index-packs/llama-index-packs-multidoc-autoretrieval/llama_index/packs/multidoc_autoretrieval/base.py
{ "start": 810, "end": 1697 }
class ____(BaseRetriever): """ Index auto-retriever. Simple wrapper around VectorIndexAutoRetriever to convert text nodes to index nodes. """ def __init__(self, retriever: VectorIndexAutoRetriever): """Init params.""" self.retriever = retriever def _retrieve(self, query_b...
IndexAutoRetriever
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT002.py
{ "start": 455, "end": 519 }
class ____(namedtuple("foo", ["str", "int"]), Enum): pass
Good
python
great-expectations__great_expectations
great_expectations/core/batch_spec.py
{ "start": 5134, "end": 5179 }
class ____(PathBatchSpec): pass
S3BatchSpec
python
doocs__leetcode
solution/2400-2499/2428.Maximum Sum of an Hourglass/Solution.py
{ "start": 0, "end": 434 }
class ____: def maxSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): s = -grid[i][j - 1] - grid[i][j + 1] s += sum( grid[x][y] for x in range(i - ...
Solution
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 14742, "end": 14960 }
class ____(ValidationActionRegistryError): def __init__(self, action_type: str) -> None: super().__init__(message=f"Action of type {action_type} is already registered.")
ValidationActionAlreadyRegisteredError
python
dagster-io__dagster
python_modules/dagster/dagster/_config/traversal_context.py
{ "start": 550, "end": 2911 }
class ____(ContextData): def for_field_snap(self, field_snap: ConfigFieldSnap) -> "ValidationContext": check.inst_param(field_snap, "field_snap", ConfigFieldSnap) field_snap_name = check.not_none(field_snap.name) return ValidationContext( config_schema_snapshot=self.config_schema...
ValidationContext
python
huggingface__transformers
src/transformers/models/deepseek_v2/modeling_deepseek_v2.py
{ "start": 13466, "end": 18649 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.attention_dropout = config.attention_...
DeepseekV2Attention
python
getsentry__sentry
src/sentry/db/router.py
{ "start": 500, "end": 8827 }
class ____: """ Django database router for multi-region deployments. We support two configurations: - Monolith - all tables reside in the same database. - Siloed - tables for control and region are separated. Within Siloed there are two flavours: - simulated - If the application is confi...
SiloRouter
python
django__django
tests/view_tests/tests/test_debug.py
{ "start": 79094, "end": 80047 }
class ____(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() self.addCleanup(get_default_exception_reporter_filter.cache_clear) def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), ...
CustomExceptionReporterFilterTests
python
python-openxml__python-docx
tests/oxml/unitdata/styles.py
{ "start": 94, "end": 250 }
class ____(BaseBuilder): __tag__ = "w:style" __nspfxs__ = ("w",) __attrs__ = ("w:type", "w:styleId", "w:default", "w:customStyle")
CT_StyleBuilder
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 10930, "end": 11125 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): return np.log(metafeatures.get_value("DatasetRatio")) @metafeatures.define("InverseDatasetRatio")
LogDatasetRatio
python
openai__openai-python
tests/api_resources/evals/runs/test_output_items.py
{ "start": 485, "end": 5452 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: output_item = client.evals.runs.output_items.retrieve( output_item_id="output_item_id", eva...
TestOutputItems
python
facebookresearch__faiss
tests/test_index_binary.py
{ "start": 11115, "end": 13191 }
class ____(unittest.TestCase): @unittest.skipIf(os.name == "posix" and os.uname().sysname == "Darwin", "There is a bug in the OpenMP implementation on OSX.") def test_replicas(self): d = 32 nq = 100 nb = 200 (_, xb, xq) = make_binary_dataset(d, 0, nb, nq) ...
TestReplicasAndShards
python
palantir__python-language-server
pyls/_version.py
{ "start": 1117, "end": 1595 }
class ____: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep44...
VersioneerConfig
python
gevent__gevent
src/greentest/3.9/test_ssl.py
{ "start": 110311, "end": 119770 }
class ____(threading.Thread): # this one's based on asyncore.dispatcher class EchoServer (asyncore.dispatcher): class ConnectionHandler(asyncore.dispatcher_with_send): def __init__(self, conn, certfile): self.socket = test_wrap_socket(conn, server_side=True, ...
AsyncoreEchoServer
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 3464, "end": 3573 }
class ____(Protocol): __name__: str def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
SearchFn
python
kamyu104__LeetCode-Solutions
Python/search-suggestions-system.py
{ "start": 213, "end": 711 }
class ____(object): def __init__(self): self.__TOP_COUNT = 3 self.leaves = collections.defaultdict(TrieNode) self.infos = [] def insert(self, words, i): curr = self for c in words[i]: curr = curr.leaves[c] curr.add_info(words, i) def add_inf...
TrieNode
python
huggingface__transformers
src/transformers/models/edgetam/modeling_edgetam.py
{ "start": 15276, "end": 17488 }
class ____(nn.Module): def __init__(self, config: EdgeTamVisionConfig): super().__init__() self.config = config self.position_encoding = EdgeTamSinePositionEmbedding( num_pos_feats=config.fpn_hidden_size // 2, normalize=True ) self.convs = nn.ModuleList() ...
EdgeTamVisionNeck
python
yangshun__tech-interview-handbook
apps/website/experimental/utilities/python/linked_list.py
{ "start": 151, "end": 3243 }
class ____: def __init__(self, value): self.value = value self.next = None def linked_list_append(linked_list, value): '''Appends a value to the end of the linked list''' node = linked_list insert_node = LinkedListNode(value) if not node: return insert_node while node.ne...
LinkedListNode
python
conda__conda
tests/plugins/test_env_specs.py
{ "start": 1296, "end": 1510 }
class ____: @plugins.hookimpl def conda_environment_specifiers(self): yield CondaEnvironmentSpecifier( name="rand-spec", environment_spec=RandomSpec, )
RandomSpecPlugin
python
qiwsir__algorithm
binary_tree2.py
{ "start": 366, "end": 3589 }
class ____: def __init__(self): # initializes the root member self.root = None def addNode(self, data): # creates a new node and returns it return CNode(data) def insert(self, root, data): # inserts a new data if root == None: ...
CBOrdTree
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 8785, "end": 17424 }
class ____(BaseModel, allow_population_by_field_name=True): """ Specifies options for one deployment within a Serve application. For each deployment this can optionally be included in `ServeApplicationSchema` to override deployment options specified in code. """ name: str = Field( ..., ...
DeploymentSchema
python
coleifer__peewee
examples/hexastore.py
{ "start": 2981, "end": 3104 }
class ____(object): def __getattr__(self, name): return Variable(name) __call__ = __getattr__
_VariableFactory
python
OmkarPathak__pygorithm
tests/test_math.py
{ "start": 557, "end": 687 }
class ____(unittest.TestCase): def test_factorial(self): self.assertEqual(factorial.factorial(10), 3628800)
TestFactorial
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 79632, "end": 81731 }
class ____(fixtures.DeclarativeMappedTest): run_create_tables = None @classmethod def setup_classes(cls): class Point(cls.Basic): def __init__(self, x, y): self.x = x self.y = y def __composite_values__(self): return [self.x, ...
CompositeAccessTest
python
gabrielfalcao__HTTPretty
httpretty/http.py
{ "start": 3526, "end": 4736 }
class ____(BaseClass): GET = 'GET' PUT = 'PUT' POST = 'POST' DELETE = 'DELETE' HEAD = 'HEAD' PATCH = 'PATCH' OPTIONS = 'OPTIONS' CONNECT = 'CONNECT' METHODS = (GET, PUT, POST, DELETE, HEAD, PATCH, OPTIONS, CONNECT) def parse_requestline(s): """ http://www.w3.org/Protocols/r...
HttpBaseClass
python
getsentry__sentry
src/sentry/utils/prompts.py
{ "start": 172, "end": 2252 }
class ____(TypedDict): required_fields: list[str] DEFAULT_PROMPTS: dict[str, _PromptConfig] = { "alert_stream": {"required_fields": ["organization_id"]}, "chonk_ui_dot_indicator": {"required_fields": ["organization_id"]}, "chonk_ui_banner": {"required_fields": ["organization_id"]}, "code_owners": ...
_PromptConfig
python
scikit-learn__scikit-learn
sklearn/utils/_metadata_requests.py
{ "start": 28366, "end": 44882 }
class ____: """Coordinates metadata routing for a :term:`router` object. This class is used by :term:`meta-estimators` or functions that can route metadata, to handle their metadata routing. Routing information is stored in a dictionary-like structure of the form ``{"object_name": RouterMappingPair...
MetadataRouter
python
bokeh__bokeh
src/bokeh/application/handlers/code_runner.py
{ "start": 1771, "end": 7886 }
class ____: ''' Compile and run Python source code. ''' _code: CodeType | None _doc: str | None _permanent_error: str | None _permanent_error_detail: str | None _path: PathLike _source: str _argv: list[str] _package: ModuleType | None ran: bool _failed: bool _error...
CodeRunner
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_new_mexico_zip.py
{ "start": 757, "end": 1766 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_new_mexico_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pa...
ColumnValuesToBeValidNewMexicoZip
python
jazzband__prettytable
tests/test_sorting.py
{ "start": 141, "end": 4594 }
class ____: def test_sort_by_different_per_columns(self, city_data: PrettyTable) -> None: city_data.sortby = city_data.field_names[0] old = city_data.get_string() for field in city_data.field_names[1:]: city_data.sortby = field new = city_data.get_string() ...
TestSorting
python
pennersr__django-allauth
allauth/idp/oidc/internal/oauthlib/server.py
{ "start": 994, "end": 1736 }
class ____(DeviceApplicationServer): def __init__(self): verification_uri = context.request.build_absolute_uri( reverse("idp:oidc:device_authorization") ) super().__init__( request_validator=OAuthLibRequestValidator(), verification_uri=verification_uri, ...
DeviceOAuthLibServer
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 27286, "end": 28738 }
class ____(JitBackendTestCase): """ Tests for adding attributes to a model after lowering. """ def setUp(self): super().setUp() # Create Python, JIT and backend versions of BasicModule. self.module = BasicModule() self.scripted_module = torch.jit.script(BasicModule()) ...
AddedAttributesTest
python
tornadoweb__tornado
tornado/test/simple_httpclient_test.py
{ "start": 3161, "end": 3270 }
class ____(RequestHandler): def get(self): self.write(self.request.headers["Host"])
HostEchoHandler
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2.py
{ "start": 28209, "end": 29793 }
class ____(VarianceScaling): """The Glorot uniform initializer, also called Xavier uniform initializer. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Draws samples from a uniform dis...
GlorotUniform
python
pandas-dev__pandas
pandas/tests/indexes/period/test_indexing.py
{ "start": 18115, "end": 20691 }
class ____: def test_where(self, listlike_box): i = period_range("20130101", periods=5, freq="D") cond = [True] * len(i) expected = i result = i.where(listlike_box(cond)) tm.assert_index_equal(result, expected) cond = [False] + [True] * (len(i) - 1) expected ...
TestWhere
python
doocs__leetcode
solution/3600-3699/3616.Number of Student Replacements/Solution.py
{ "start": 0, "end": 221 }
class ____: def totalReplacements(self, ranks: List[int]) -> int: ans, cur = 0, ranks[0] for x in ranks: if x < cur: cur = x ans += 1 return ans
Solution
python
kamyu104__LeetCode-Solutions
Python/number-of-zigzag-arrays-i.py
{ "start": 60, "end": 530 }
class ____(object): def zigZagArrays(self, n, l, r): """ :type n: int :type l: int :type r: int :rtype: int """ MOD = 10**9+7 r -= l dp = [1]*(r+1) for _ in xrange(n-1): prefix = 0 for i in xrange(len(dp)): ...
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_bedrock.py
{ "start": 3047, "end": 4527 }
class ____(TestBaseBedrockTrigger): EXPECTED_WAITER_NAME = "provisioned_model_throughput_complete" PROVISIONED_MODEL_ID = "provisioned_model_id" def test_serialization(self): """Assert that arguments and classpath are correctly serialized.""" trigger = BedrockProvisionModelThroughputComplet...
TestBedrockProvisionModelThroughputCompletedTrigger
python
google__python-fire
fire/test_components.py
{ "start": 1630, "end": 1857 }
class ____: """Test class for testing when class has a help= arg.""" def __init__(self, help=True): # pylint: disable=redefined-builtin self.has_help = help self.dictionary = {'__help': 'help in a dict'}
WithHelpArg
python
streamlit__streamlit
lib/tests/streamlit/runtime/state/test_presentation.py
{ "start": 1059, "end": 1163 }
class ____: def __init__(self) -> None: self.widget_metadata: dict[str, Any] = {}
_FakeWStates
python
openai__openai-python
src/openai/types/beta/file_search_tool.py
{ "start": 261, "end": 626 }
class ____(BaseModel): score_threshold: float """The score threshold for the file search. All values must be a floating point number between 0 and 1. """ ranker: Optional[Literal["auto", "default_2024_08_21"]] = None """The ranker to use for the file search. If not specified will use the ...
FileSearchRankingOptions
python
walkccc__LeetCode
solutions/3091. Apply Operations to Make Sum of Array Greater Than or Equal to k/3091.py
{ "start": 0, "end": 574 }
class ____: def minOperations(self, k: int) -> int: # The required operations are # 1. Increase `1` to `x` # 2. Duplicate `x`, `y` times, to `sum` s.t. x * (1 + y) >= k. # The number of operations used would be (x - 1) + y. Equivalently, the # problem can be rephrased as finding min(x - 1 + y)...
Solution
python
celery__celery
celery/worker/control.py
{ "start": 963, "end": 19921 }
class ____(UserDict): """Global registry of remote control commands.""" data = {} # global dict. meta = {} # -"- @classmethod def register(cls, *args, **kwargs): if args: return cls._register(**kwargs)(*args) return cls._register(**kwargs) @classmethod ...
Panel
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/tests/test_core.py
{ "start": 78555, "end": 88771 }
class ____(BaseTest): MANDATORY_FOR_TEST_STRICTNESS_LEVELS = [] # Used so that this is not part of the mandatory high strictness test suite yet PREREQUISITES = "Prerequisites" HEADING = "heading" CREDENTIALS_KEYWORDS = ["account", "auth", "credentials", "access"] CONNECTOR_SPECIFIC_HEADINGS = "<Co...
TestConnectorDocumentation
python
euske__pdfminer
pdfminer/layout.py
{ "start": 4340, "end": 5107 }
class ____(LTComponent): def __init__(self, name, stream, bbox): LTComponent.__init__(self, bbox) self.name = name self.stream = stream self.srcsize = (stream.get_any(('W', 'Width')), stream.get_any(('H', 'Height'))) self.imagemask = stream.get_any(('...
LTImage
python
spack__spack
lib/spack/spack/vendor/jinja2/ext.py
{ "start": 1450, "end": 8361 }
class ____: """Extensions can be used to add extra functionality to the Jinja template system at the parser level. Custom extensions are bound to an environment but may not store environment specific data on `self`. The reason for this is that an extension can be bound to another environment (for ...
Extension
python
Pylons__pyramid
tests/test_authorization.py
{ "start": 55, "end": 9555 }
class ____(unittest.TestCase): def setUp(self): cleanUp() def tearDown(self): cleanUp() def _getTargetClass(self): from pyramid.authorization import ACLAuthorizationPolicy return ACLAuthorizationPolicy def _makeOne(self): return self._getTargetClass()() d...
TestACLAuthorizationPolicy
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/rich/prompt.py
{ "start": 9501, "end": 11304 }
class ____(PromptBase[bool]): """A yes / no confirmation prompt. Example: >>> if Confirm.ask("Continue"): run_job() """ response_type = bool validate_error_message = "[prompt.invalid]Please enter Y or N" choices: List[str] = ["y", "n"] def render_default(self, def...
Confirm
python
huggingface__transformers
src/transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py
{ "start": 11389, "end": 11564 }
class ____(MoshiModel): def __init__(self, config): super().__init__(config) self.embed_tokens = KyutaiSpeechToTextEmbeddings(config)
KyutaiSpeechToTextModel
python
kamyu104__LeetCode-Solutions
Python/cracking-the-safe.py
{ "start": 3121, "end": 3853 }
class ____(object): def crackSafe(self, n, k): """ :type n: int :type k: int :rtype: str """ def dfs(k, node, lookup, result): for i in xrange(k): # preorder like traversal relative to initial result to avoid getting stuck, i.e. don't use k-1 until there ...
Solution5
python
mlflow__mlflow
tests/h2o/test_h2o_model_export.py
{ "start": 1031, "end": 14537 }
class ____(NamedTuple): model: Any inference_data: Any @pytest.fixture def h2o_iris_model(): h2o.init() iris = datasets.load_iris() data = h2o.H2OFrame( { "feature1": list(iris.data[:, 0]), "feature2": list(iris.data[:, 1]), "target": ([f"Flower {i}" for...
ModelWithData
python
realpython__materials
python-with-statement/exc_handling.py
{ "start": 0, "end": 611 }
class ____: def __enter__(self): print("Entering the context...") return "Hello, World!" def __exit__(self, exc_type, exc_value, exc_tb): print("Leaving the context...") if isinstance(exc_value, IndexError): # Handle IndexError here... print(f"An exceptio...
HelloContextManager
python
FactoryBoy__factory_boy
tests/test_fuzzy.py
{ "start": 10236, "end": 14643 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): # Setup useful constants cls.jan1 = datetime.datetime(2013, 1, 1) cls.jan3 = datetime.datetime(2013, 1, 3) cls.jan31 = datetime.datetime(2013, 1, 31) def test_accurate_definition(self): """Tests explici...
FuzzyNaiveDateTimeTestCase
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/test_tests/test_python_connectors.py
{ "start": 5491, "end": 8345 }
class ____: @pytest.fixture def compatible_connector(self): return Connector("source-faker") @pytest.fixture def incompatible_connector(self): return Connector("source-postgres") @pytest.fixture def context_for_valid_connector(self, compatible_connector, dagger_client, current_...
TestPyAirbyteValidationTests
python
plotly__plotly.py
plotly/graph_objs/layout/legend/_title.py
{ "start": 235, "end": 4642 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.legend" _path_str = "layout.legend.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this legend's title font. Defaults to `legend.font` with its size increased about 20%. ...
Title
python
pypa__pipenv
pipenv/patched/pip/_internal/req/req_set.py
{ "start": 272, "end": 2888 }
class ____: def __init__(self, check_supported_wheels: bool = True) -> None: """Create a RequirementSet.""" self.requirements: Dict[str, InstallRequirement] = OrderedDict() self.check_supported_wheels = check_supported_wheels self.unnamed_requirements: List[InstallRequirement] = []...
RequirementSet
python
pytorch__pytorch
test/jit/test_fuser_common.py
{ "start": 173, "end": 788 }
class ____(JitTestCase): def test_autodiff_fallback(self): for rq in [True, False]: @torch.jit.script def fn(x): return torch.max(x**2.0, x**3.0) x = torch.randn(5, requires_grad=not rq) # cause optimization to be created for _ in...
TestFuserCommon
python
walkccc__LeetCode
solutions/1657. Determine if Two Strings Are Close/1657.py
{ "start": 0, "end": 328 }
class ____: def closeStrings(self, word1: str, word2: str) -> bool: if len(word1) != len(word2): return False count1 = collections.Counter(word1) count2 = collections.Counter(word2) if count1.keys() != count2.keys(): return False return sorted(count1.values()) == sorted(count2.values...
Solution
python
doocs__leetcode
solution/3100-3199/3115.Maximum Prime Difference/Solution.py
{ "start": 0, "end": 436 }
class ____: def maximumPrimeDifference(self, nums: List[int]) -> int: def is_prime(x: int) -> bool: if x < 2: return False return all(x % i for i in range(2, int(sqrt(x)) + 1)) for i, x in enumerate(nums): if is_prime(x): for j in ...
Solution
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 7737, "end": 8593 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.layers = torch.nn.ModuleList( [ torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 10), torch.nn.ReLU(), ] ) ...
ModuleList
python
ray-project__ray
python/ray/air/_internal/json.py
{ "start": 49, "end": 908 }
class ____(json.JSONEncoder): def __init__(self, nan_str="null", **kwargs): super(SafeFallbackEncoder, self).__init__(**kwargs) self.nan_str = nan_str def default(self, value): try: if type(value).__module__ == np.__name__ and isinstance(value, np.ndarray): r...
SafeFallbackEncoder
python
tensorflow__tensorflow
tensorflow/python/ops/linalg/linear_operator_block_diag.py
{ "start": 1569, "end": 32814 }
class ____(linear_operator.LinearOperator): """Combines one or more `LinearOperators` in to a Block Diagonal matrix. This operator combines one or more linear operators `[op1,...,opJ]`, building a new `LinearOperator`, whose underlying matrix representation has each operator `opi` on the main diagonal, and zer...
LinearOperatorBlockDiag
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 77026, "end": 77893 }
class ____(HasExpressionLookup, TypeEngine[dt.timedelta]): operator_classes = OperatorClass.DATETIME @util.memoized_property def _expression_adaptations(self): # Based on # https://www.postgresql.org/docs/current/static/functions-datetime.html. return { operators.add: {...
_AbstractInterval
python
bottlepy__bottle
bottle.py
{ "start": 17214, "end": 22417 }
class ____: """ This class wraps a route callback along with route specific metadata and configuration and applies Plugins on demand. It is also responsible for turning an URL path rule into a regular expression usable by the Router. """ def __init__(self, app, rule, method, callback, ...
Route
python
huggingface__transformers
src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py
{ "start": 2886, "end": 3847 }
class ____(DPRState): def load_dpr_model(self): model = DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("google-bert/bert-base-uncased")[0])) print(f"Loading DPR biencoder from {self.src_file}") saved_state = load_states_from_checkpoint(self.src_file) encoder, prefix = mode...
DPRQuestionEncoderState
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1303758, "end": 1308379 }
class ____(sgqlc.types.Type, Node, Closable, Updatable): """Projects manage issues, pull requests and notes within a project owner. """ __schema__ = github_schema __field_names__ = ( "body", "body_html", "columns", "created_at", "creator", "database_i...
Project
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 24907, "end": 25069 }
class ____(RunInput): """Represents a task run result input to another task run.""" input_type: Literal["task_run"] = "task_run" id: UUID
TaskRunResult
python
fastai__fastai
fastai/callback/training.py
{ "start": 2254, "end": 2450 }
class ____(Callback): run_after=TrainEvalCallback "Freeze moving average statistics in all non-trainable batchnorm layers." def before_train(self): set_bn_eval(self.model)
BnFreeze
python
Textualize__textual
src/textual/canvas.py
{ "start": 921, "end": 1176 }
class ____: """Base class for a canvas primitive.""" def render(self, canvas: Canvas) -> None: """Render to the canvas. Args: canvas: Canvas instance. """ raise NotImplementedError() @dataclass
Primitive
python
getsentry__sentry
src/sentry/api/serializers/models/rule.py
{ "start": 2173, "end": 2557 }
class ____(RuleSerializerResponseOptional): """ This represents a Sentry Rule. """ id: str | None conditions: list[dict] filters: list[dict] actions: list[dict] actionMatch: str filterMatch: str frequency: int name: str dateCreated: datetime projects: list[str] s...
RuleSerializerResponse
python
tensorflow__tensorflow
tensorflow/python/training/session_run_hook.py
{ "start": 9485, "end": 10450 }
class ____( collections.namedtuple("SessionRunValues", ["results", "options", "run_metadata"])): """Contains the results of `Session.run()`. In the future we may use this object to add more information about result of run without changing the Hook API. Args: results: The ret...
SessionRunValues
python
scipy__scipy
scipy/_build_utils/tempita/_tempita.py
{ "start": 13666, "end": 14449 }
class ____(dict): def __init__(self, **kw): for name, value in kw.items(): setattr(self, name, value) def __setattr__(self, name, value): self[name] = value def __getattr__(self, name): try: return self[name] except KeyError: raise Attri...
bunch
python
crytic__slither
slither/solc_parsing/declarations/event_top_level.py
{ "start": 546, "end": 2628 }
class ____(CallerContextExpression): """ EventTopLevel class """ def __init__( self, event: EventTopLevel, event_data: Dict, slither_parser: "SlitherCompilationUnitSolc" ) -> None: self._event = event self._slither_parser = slither_parser if self.is_compact_ast: ...
EventTopLevelSolc
python
python__mypy
mypy/plugin.py
{ "start": 20285, "end": 20536 }
class ____(NamedTuple): call: CallExpr # The r.h.s. of dynamic class definition name: str # The name this class is being assigned to api: SemanticAnalyzerPluginInterface @mypyc_attr(allow_interpreted_subclasses=True)
DynamicClassDefContext
python
run-llama__llama_index
llama-index-core/llama_index/core/query_engine/sql_join_query_engine.py
{ "start": 6471, "end": 14295 }
class ____(BaseQueryEngine): """ SQL Join Query Engine. This query engine can "Join" a SQL database results with another query engine. It can decide it needs to query the SQL database or the other query engine. If it decides to query the SQL database, it will first query the SQL database, w...
SQLJoinQueryEngine
python
dagster-io__dagster
python_modules/dagster/dagster/_core/executor/child_process_executor.py
{ "start": 763, "end": 883 }
class ____( NamedTuple("ChildProcessStartEvent", [("pid", int)]), ChildProcessEvent ): pass
ChildProcessStartEvent
python
justquick__django-activity-stream
actstream/tests/test_feeds.py
{ "start": 121, "end": 3523 }
class ____(base.DataTestCase): urls = 'actstream.urls' @property def rss_base(self): return ['<?xml version="1.0" encoding="utf-8"?>\n', '<rss ', 'xmlns:atom="http://www.w3.org/2005/Atom"', 'version="2.0"', '<language>%s' % settings.LANGUAGE_CODE] @property ...
FeedsTestCase
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 39496, "end": 39564 }
class ____: def test_besselpoly(self): pass
TestBesselpoly
python
huggingface__transformers
src/transformers/models/sam3_tracker/modeling_sam3_tracker.py
{ "start": 13693, "end": 16119 }
class ____(nn.Module): """ SAM3_TRACKER's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values. """ def __init__(self, config, downsample_rate=None): super().__init__() downsample_rate = config.attention_downsample_rate ...
Sam3TrackerAttention
python
pyinstaller__pyinstaller
PyInstaller/utils/win32/versioninfo.py
{ "start": 11050, "end": 12660 }
class ____: """ WORD wLength; // length of the version resource WORD wValueLength; // length of the Value member in the current // VS_VERSION_INFO structure WORD wType; // 1 means text, 0 means binary WCHAR szKey[]; // Contain...
StringFileInfo
python
walkccc__LeetCode
solutions/2392. Build a Matrix With Conditions/2392.py
{ "start": 0, "end": 1177 }
class ____: def buildMatrix(self, k: int, rowConditions: list[list[int]], colConditions: list[list[int]]) -> list[list[int]]: rowOrder = self._topologicalSort(rowConditions, k) if not rowOrder: return [] colOrder = self._topologicalSort(colConditions, k) if not colOrder: ...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py
{ "start": 1680, "end": 1933 }
class ____(models.Model): new_field = models.CharField(max_length=10) class Meta: abstract = True @property def my_brand_new_property(self): return 1 def my_beautiful_method(self): return 2
AbstractTestModel1
python
tensorflow__tensorflow
tensorflow/python/debug/cli/analyzer_cli.py
{ "start": 4509, "end": 58529 }
class ____(object): """Analyzer for debug data from dump directories.""" _TIMESTAMP_COLUMN_HEAD = "t (ms)" _DUMP_SIZE_COLUMN_HEAD = "Size (B)" _OP_TYPE_COLUMN_HEAD = "Op type" _TENSOR_NAME_COLUMN_HEAD = "Tensor name" # Op types to be omitted when generating descriptions of graph structure. _GRAPH_STRUCT...
DebugAnalyzer
python
kamyu104__LeetCode-Solutions
Python/replace-the-substring-for-balanced-string.py
{ "start": 50, "end": 563 }
class ____(object): def balancedString(self, s): """ :type s: str :rtype: int """ count = collections.Counter(s) result = len(s) left = 0 for right in xrange(len(s)): count[s[right]] -= 1 while left < len(s) and \ ...
Solution
python
openai__openai-python
src/openai/types/fine_tuning/dpo_hyperparameters_param.py
{ "start": 238, "end": 1048 }
class ____(TypedDict, total=False): batch_size: Union[Literal["auto"], int] """Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. """ beta: Union[Literal["auto"], float] """The beta value for the DPO metho...
DpoHyperparametersParam
python
pandas-dev__pandas
pandas/core/window/ewm.py
{ "start": 3788, "end": 29117 }
class ____(BaseWindow): r""" Provide exponentially weighted (EW) calculations. Exactly one of ``com``, ``span``, ``halflife``, or ``alpha`` must be provided if ``times`` is not provided. If ``times`` is provided and ``adjust=True``, ``halflife`` and one of ``com``, ``span`` or ``alpha`` may be prov...
ExponentialMovingWindow
python
django__django
tests/auth_tests/test_models.py
{ "start": 2027, "end": 2324 }
class ____(TestCase): fixtures = ["natural.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get())
LoadDataWithNaturalKeysTestCase
python
doocs__leetcode
solution/2100-2199/2109.Adding Spaces to a String/Solution.py
{ "start": 0, "end": 300 }
class ____: def addSpaces(self, s: str, spaces: List[int]) -> str: ans = [] j = 0 for i, c in enumerate(s): if j < len(spaces) and i == spaces[j]: ans.append(' ') j += 1 ans.append(c) return ''.join(ans)
Solution
python
eventlet__eventlet
eventlet/db_pool.py
{ "start": 380, "end": 9557 }
class ____(Pool): def __init__(self, db_module, min_size=0, max_size=4, max_idle=10, max_age=30, connect_timeout=5, cleanup=cleanup_rollback, *args, **kwargs): """ Constructs a pool with at least *min_size* connecti...
BaseConnectionPool
python
apache__airflow
providers/standard/src/airflow/providers/standard/operators/trigger_dagrun.py
{ "start": 2320, "end": 2612 }
class ____(AirflowException): """Raise when a dag is paused and something tries to run it.""" def __init__(self, dag_id: str) -> None: super().__init__(dag_id) self.dag_id = dag_id def __str__(self) -> str: return f"Dag {self.dag_id} is paused"
DagIsPaused
python
sphinx-doc__sphinx
sphinx/domains/c/__init__.py
{ "start": 24818, "end": 26304 }
class ____(SphinxRole): def __init__(self, asCode: bool) -> None: super().__init__() if asCode: # render the expression as inline code self.class_type = 'c-expr' else: # render the expression as inline text self.class_type = 'c-texpr' def ...
CExprRole
python
jazzband__django-model-utils
tests/models.py
{ "start": 7880, "end": 8100 }
class ____(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = FieldTracker(fields=['name']) number_tracker = FieldTracker(fields=['number'])
TrackedMultiple
python
astropy__astropy
astropy/modeling/tests/test_fitters.py
{ "start": 27914, "end": 31748 }
class ____: def setup_class(self): self.y, self.x = np.mgrid[-3:3:128j, -3:3:128j] self.model_params = (3.0, 1.0, 0.0, 0.8, 0.8) def Gaussian_2D(p, pos): return p[0] * np.exp( -0.5 * (pos[0] - p[2]) ** 2 / p[4] ** 2 - 0.5 * (pos[1] - p[1]) ** 2 / ...
Test2DFittingWithOutlierRemoval
python
getsentry__sentry
src/sentry/users/api/endpoints/user_identity_details.py
{ "start": 370, "end": 776 }
class ____(UserEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, } def delete(self, request: Request, user: User, identity_id: int) -> Response: try: ai = AuthIdentity.objects.get(user=user, id=identity_id) ai.delete() except AuthIdentity.Does...
UserIdentityDetailsEndpoint
python
tensorflow__tensorflow
tensorflow/python/keras/utils/tf_utils.py
{ "start": 6341, "end": 17278 }
class ____(object): """A wrapper for lists to be treated as elements for `nest`.""" def __init__(self, list_to_wrap): self._list = list_to_wrap def as_list(self): return self._list def convert_inner_node_data(nested, wrap=False): """Either wraps or unwraps innermost node data lists in `ListWrapper` ...
ListWrapper
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/unit_tests/integration/test_media_insights.py
{ "start": 4230, "end": 14436 }
class ____(TestCase): @staticmethod def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput: return read_output( config_builder=config_, stream_name=_STREAM_NAME, sync_mode=SyncMode.full_refresh, expecting_exception=expecti...
TestFullRefresh
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/validators/actions/test_email_validator.py
{ "start": 176, "end": 2334 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.team = self.create_team(organization=self.organization) self.valid_data = { "type": Action.Type.EMAIL, "config": {"targetType": "user", "targetIdentifier": str(self.user.id)}, "data": {}, ...
TestEmailActionValidator
python
google__jax
tests/mosaic/gpu_torch_test_distributed.py
{ "start": 1447, "end": 5084 }
class ____(parameterized.TestCase): def setUpClass(): torch.cuda.set_device("cuda:0") torch.set_default_device("cuda") if torch is None: raise unittest.SkipTest("Test requires torch") if not torch.cuda.is_available(): raise unittest.SkipTest("Test requires torch with CUDA support") if...
TorchTest