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
scrapy__scrapy
tests/test_downloadermiddleware_httpauth.py
{ "start": 193, "end": 267 }
class ____(Spider): http_user = "foo" http_pass = "bar"
LegacySpider
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 9406, "end": 9504 }
class ____(PipError): """Raised when there is an error in command-line arguments"""
CommandError
python
langchain-ai__langchain
libs/langchain/langchain_classic/memory/summary.py
{ "start": 906, "end": 2746 }
class ____(BaseModel): """Mixin for summarizer.""" human_prefix: str = "Human" ai_prefix: str = "AI" llm: BaseLanguageModel prompt: BasePromptTemplate = SUMMARY_PROMPT summary_message_cls: type[BaseMessage] = SystemMessage def predict_new_summary( self, messages: list[BaseM...
SummarizerMixin
python
scipy__scipy
scipy/_lib/_pep440.py
{ "start": 7551, "end": 14005 }
class ____(_BaseVersion): _regex = re.compile( r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE, ) def __init__(self, version): # Validate the version and parse it into pieces match = self._regex.search(version) if not match: raise Invalid...
Version
python
realpython__materials
web-scraping-with-scrapy-and-mongodb/books/books/pipelines.py
{ "start": 108, "end": 1206 }
class ____: COLLECTION_NAME = "books" def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get("MONGO_URI"), mongo_db=crawler.sett...
MongoPipeline
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-dappier/llama_index/tools/dappier/ai_recommendations/base.py
{ "start": 163, "end": 11611 }
class ____(BaseToolSpec): """ Dappier AI Recommendations tool spec. Provides AI-powered recommendations across various domains such as Sports News, Lifestyle News, iHeartDogs, iHeartCats, GreenMonster, WISH-TV and 9 and 10 News. """ spec_functions = [ "get_sports_news_recommendations",...
DappierAIRecommendationsToolSpec
python
lazyprogrammer__machine_learning_examples
pytorch/rl_trader.py
{ "start": 544, "end": 2063 }
class ____: def __init__(self, obs_dim, act_dim, size): self.obs1_buf = np.zeros([size, obs_dim], dtype=np.float32) self.obs2_buf = np.zeros([size, obs_dim], dtype=np.float32) self.acts_buf = np.zeros(size, dtype=np.uint8) self.rews_buf = np.zeros(size, dtype=np.float32) self.done_buf = np.zeros(s...
ReplayBuffer
python
django__django
tests/template_tests/filter_tests/test_lower.py
{ "start": 163, "end": 901 }
class ____(SimpleTestCase): @setup( { "lower01": ( "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}" ) } ) def test_lower01(self): output = self.engine.render_to_string( "lower01", {"a": "Apple & banana", "b": mar...
LowerTests
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 39259, "end": 43036 }
class ____(VyperNode): """ A contract variable declaration. Excludes `simple` attribute from Python `AnnAssign` node. Attributes ---------- target : VyperNode Left-hand side of the assignment. value : VyperNode Right-hand side of the assignment. annotation : VyperNode ...
VariableDecl
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/quality-testing/unit-testing-assets-and-ops/asset-combo.py
{ "start": 36, "end": 529 }
class ____(dg.Config): separator: str @dg.asset def processed_file( primary_file: str, secondary_file: str, config: SeparatorConfig ) -> str: return f"{primary_file}{config.separator}{secondary_file}" # end_file # start_test def test_processed_file() -> None: assert ( processed_file( ...
SeparatorConfig
python
kamyu104__LeetCode-Solutions
Python/count-numbers-with-non-decreasing-digits.py
{ "start": 81, "end": 1582 }
class ____(object): def countNumbers(self, l, r, b): """ :type l: str :type r: str :type b: int :rtype: int """ MOD = 10**9+7 fact, inv, inv_fact = [[1]*2 for _ in xrange(3)] def nCr(n, k): while len(inv) <= n: # lazy initializatio...
Solution
python
scrapy__scrapy
extras/qpsclient.py
{ "start": 293, "end": 1623 }
class ____(Spider): name = "qps" benchurl = "http://localhost:8880/" # Max concurrency is limited by global CONCURRENT_REQUESTS setting max_concurrent_requests = 8 # Requests per second goal qps = None # same as: 1 / download_delay download_delay = None # time in seconds to delay serve...
QPSSpider
python
bokeh__bokeh
src/bokeh/models/selections.py
{ "start": 1488, "end": 3422 }
class ____(Model): ''' A Selection represents a portion of the data in a ``DataSource``, which can be visually manipulated in a plot. Selections are typically created by selecting points in a plot with a ``SelectTool``, but can also be programmatically specified. For most glyphs, the ``indices...
Selection
python
jmcnamara__XlsxWriter
xlsxwriter/chart_stock.py
{ "start": 285, "end": 3540 }
class ____(chart.Chart): """ A class for writing the Excel XLSX Stock charts. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self) -> None: ...
ChartStock
python
scipy__scipy
scipy/fft/tests/mock_backend.py
{ "start": 54, "end": 2685 }
class ____: def __init__(self, return_value = None): self.number_calls = threading.local() self.return_value = return_value self.last_args = threading.local() def __call__(self, *args, **kwargs): if not hasattr(self.number_calls, 'c'): self.number_calls.c = 0 ...
_MockFunction
python
catalyst-team__catalyst
catalyst/contrib/optimizers/ralamb.py
{ "start": 127, "end": 5724 }
class ____(Optimizer): """RAdam optimizer with LARS/LAMB tricks. Adapted from: https://github.com/mgrankin/over9000/blob/master/ralamb.py (Apache-2.0 License) """ def __init__( self, params: Iterable, lr: float = 1e-3, betas: Tuple[float, float] = (0.9, 0.999), ...
Ralamb
python
getsentry__sentry
src/sentry/utils/security/orgauthtoken_token.py
{ "start": 219, "end": 1621 }
class ____(Exception): # system.url-prefix is not set. You need to set this to generate a token. pass def generate_token(org_slug: str, region_url: str) -> str: sentry_url = options.get("system.url-prefix") if sentry_url is None: raise SystemUrlPrefixMissingException payload = { ...
SystemUrlPrefixMissingException
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/layout_test.py
{ "start": 16710, "end": 23041 }
class ____(test_util.DTensorBaseTest): def setUp(self): super().setUp() global_ids = test_util.create_device_ids_array((2, 2)) local_ids = np.ravel(global_ids).tolist() mesh_dict = { # pylint: disable=g-complex-comprehension device: layout.Mesh( [_MESH_DIM_X, _MESH_DIM_Y], ...
RelayoutTest
python
scipy__scipy
scipy/special/tests/test_spherical_bessel.py
{ "start": 10843, "end": 11042 }
class ____(SphericalDerivativesTestCase): def f(self, n, z): return spherical_kn(n, z) def df(self, n, z): return spherical_kn(n, z, derivative=True)
TestSphericalKnDerivatives
python
spyder-ide__spyder
external-deps/python-lsp-server/pylsp/lsp.py
{ "start": 898, "end": 958 }
class ____: PlainText = 1 Snippet = 2
InsertTextFormat
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/TreeWidget.py
{ "start": 81, "end": 8940 }
class ____(QtWidgets.QTreeWidget): """Extends QTreeWidget to allow internal drag/drop with widgets in the tree. Also maintains the expanded state of subtrees as they are moved. This class demonstrates the absurd lengths one must go to to make drag/drop work.""" sigItemMoved = QtCore.Signal(object, ...
TreeWidget
python
GoogleCloudPlatform__python-docs-samples
generative_ai/chat_completions/chat_completions_credentials_refresher.py
{ "start": 837, "end": 2265 }
class ____: def __init__(self, **kwargs: Any) -> None: # Set a placeholder key here self.client = openai.OpenAI(**kwargs, api_key="PLACEHOLDER") self.creds, self.project = google.auth.default( scopes=["https://www.googleapis.com/auth/cloud-platform"] ) def __getattr_...
OpenAICredentialsRefresher
python
pytorch__pytorch
torch/_export/db/examples/scalar_output.py
{ "start": 117, "end": 543 }
class ____(torch.nn.Module): """ Returning scalar values from the graph is supported, in addition to Tensor outputs. Symbolic shapes are captured and rank is specialized. """ def __init__(self) -> None: super().__init__() def forward(self, x): return x.shape[1] + 1 example_args...
ScalarOutput
python
pytorch__pytorch
torchgen/gen_schema_utils.py
{ "start": 2202, "end": 2481 }
class ____: @staticmethod def from_example( name: str, obj: Any, default: str | None, annotation: Annotation | None ) -> Argument: return Argument( name, TypeGen.from_example(obj), default=default, annotation=annotation )
ArgumentGen
python
doocs__leetcode
solution/0200-0299/0214.Shortest Palindrome/Solution2.py
{ "start": 0, "end": 469 }
class ____: def shortestPalindrome(self, s: str) -> str: t = s + "#" + s[::-1] + "$" n = len(t) next = [0] * n next[0] = -1 i, j = 2, 0 while i < n: if t[i - 1] == t[j]: j += 1 next[i] = j i += 1 ...
Solution
python
kamyu104__LeetCode-Solutions
Python/the-k-weakest-rows-in-a-matrix.py
{ "start": 33, "end": 794 }
class ____(object): def kWeakestRows(self, mat, k): """ :type mat: List[List[int]] :type k: int :rtype: List[int] """ result, lookup = [], set() for j in xrange(len(mat[0])): for i in xrange(len(mat)): if mat[i][j] or i in lookup: ...
Solution
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 17898, "end": 19284 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden stat...
AltRobertaPooler
python
django__django
tests/test_runner_apps/sample/tests_sample.py
{ "start": 259, "end": 361 }
class ____(DjangoTestCase): def test_sample(self): self.assertEqual(1, 1)
TestDjangoTestCase
python
kamyu104__LeetCode-Solutions
Python/get-maximum-in-generated-array.py
{ "start": 55, "end": 507 }
class ____(object): def getMaximumGenerated(self, n): """ :type n: int :rtype: int """ if n+1 > len(dp): for i in xrange(len(nums), n+1): if i%2 == 0: nums.append(nums[i//2]) else: nums.append...
Solution
python
xlwings__xlwings
xlwings/com_server.py
{ "start": 1765, "end": 2949 }
class ____: _public_methods_ = ["Next", "Skip", "Reset", "Clone"] def __init__(self, gen): self.iter = gen.__iter__() def _query_interface_(self, iid): if iid == pythoncom.IID_IEnumVARIANT: return 1 def Next(self, count): r = [] try: r.append(To...
XLPythonEnumerator
python
arrow-py__arrow
tests/test_locales.py
{ "start": 149767, "end": 153911 }
class ____: def test_singles_mk(self): assert self.locale._format_timeframe("second", 1) == "бір секунд" assert self.locale._format_timeframe("minute", 1) == "бір минут" assert self.locale._format_timeframe("hour", 1) == "бір сағат" assert self.locale._format_timeframe("day", 1) == "...
TestKazakhLocale
python
faif__python-patterns
patterns/behavioral/command.py
{ "start": 983, "end": 1442 }
class ____: """ A command to hide a file given its name """ def __init__(self) -> None: # an array of files hidden, to undo them as needed self._hidden_files: List[str] = [] def execute(self, filename: str) -> None: print(f"hiding {filename}") self._hidden_files.app...
HideFileCommand
python
conda__conda
conda/exceptions.py
{ "start": 7579, "end": 8626 }
class ____(ClobberError): def __init__( self, target_path: PathType, colliding_dist_being_linked: PackageRecord | str, context: Context, ): message = dals( """ The package '%(colliding_dist_being_linked)s' cannot be installed due to a path coll...
UnknownPackageClobberError
python
doocs__leetcode
solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py
{ "start": 0, "end": 483 }
class ____: def validPath( self, n: int, edges: List[List[int]], source: int, destination: int ) -> bool: def dfs(i: int) -> bool: if i == destination: return True if i in vis: return False return any(dfs(j) for j in g[i]) ...
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0152_create_gh_app_integration.py
{ "start": 862, "end": 1089 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0151_addons_linkpreviews_selector"), ] operations = [ migrations.RunPython(forwards_func), ]
Migration
python
tensorflow__tensorflow
tensorflow/python/module/module_test.py
{ "start": 14552, "end": 15374 }
class ____(module.Module): def __init__(self): super().__init__() self._setter_scope_name = None @property @module.Module.with_name_scope def some_property(self): getter_scope_name = get_name_scope() return getter_scope_name, self._setter_scope_name @some_property.setter @module.Module.wi...
PropertyModule
python
getsentry__sentry
tests/sentry/integrations/msteams/test_webhook.py
{ "start": 1162, "end": 23167 }
class ____(APITestCase): @pytest.fixture(autouse=True) def _setup_metric_patch(self) -> Generator[None]: with mock.patch("sentry.shared_integrations.client.base.metrics") as self.metrics: yield def setUp(self) -> None: super().setUp() responses.add( response...
MsTeamsWebhookTest
python
huggingface__transformers
src/transformers/models/dinov3_vit/modeling_dinov3_vit.py
{ "start": 1921, "end": 6053 }
class ____(nn.Module): """ Construct the CLS token, mask token, position and patch embeddings. """ def __init__(self, config: DINOv3ViTConfig): super().__init__() self.config = config self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.mask_token = ...
DINOv3ViTEmbeddings
python
sqlalchemy__sqlalchemy
test/sql/test_compare.py
{ "start": 48348, "end": 55583 }
class ____(fixtures.CacheKeyFixture, CoreFixtures, fixtures.TestBase): @testing.combinations( table_a.insert().values( # multivalues doesn't cache [ {"name": "some name"}, {"name": "some other name"}, {"name": "yet another name"}, ] ...
CacheKeyTest
python
spack__spack
lib/spack/spack/report.py
{ "start": 5015, "end": 5835 }
class ____(SpecRecord): """Record class with specialization for test logs.""" def __init__(self, spec, directory): super().__init__(spec) self.directory = directory def fetch_log(self): """Get output from test log""" log_file = os.path.join(self.directory, self._package.tes...
TestRecord
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/connections.py
{ "start": 3535, "end": 4041 }
class ____(BaseModel): """ Response model for Hook information == Connection type meta data. It is used to transfer providers information loaded by providers_manager such that the API server/Web UI can use this data to render connection form UI. """ connection_type: str | None hook_class_n...
ConnectionHookMetaData
python
doocs__leetcode
solution/2600-2699/2681.Power of Heroes/Solution.py
{ "start": 0, "end": 314 }
class ____: def sumOfPower(self, nums: List[int]) -> int: mod = 10**9 + 7 nums.sort() ans = 0 p = 0 for x in nums[::-1]: ans = (ans + (x * x % mod) * x) % mod ans = (ans + x * p) % mod p = (p * 2 + x * x) % mod return ans
Solution
python
scipy__scipy
scipy/spatial/transform/_rotation.py
{ "start": 99840, "end": 106817 }
class ____: """Spherical Linear Interpolation of Rotations. The interpolation between consecutive rotations is performed as a rotation around a fixed axis with a constant angular velocity [1]_. This ensures that the interpolated rotations follow the shortest path between initial and final orientati...
Slerp
python
pytorch__pytorch
test/distributed/elastic/agent/server/test/local_elastic_agent_test.py
{ "start": 7188, "end": 53296 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): # start a standalone, single process etcd server to use for all tests cls._etcd_server = EtcdServer() cls._etcd_server.start() @classmethod def tearDownClass(cls): # stop the standalone etcd server ...
LocalElasticAgentTest
python
huggingface__transformers
src/transformers/models/afmoe/modeling_afmoe.py
{ "start": 10472, "end": 15219 }
class ____(nn.Module): """ Mixture of Experts (MoE) module for AFMoE. This module implements a sparse MoE layer with both shared experts (always active) and routed experts (activated based on token-choice routing). """ def __init__(self, config): super().__init__() self.config ...
AfmoeMoE
python
huggingface__transformers
src/transformers/models/levit/modeling_levit.py
{ "start": 17704, "end": 18150 }
class ____(nn.Module): """ LeViT Classification Layer """ def __init__(self, input_dim, output_dim): super().__init__() self.batch_norm = nn.BatchNorm1d(input_dim) self.linear = nn.Linear(input_dim, output_dim) def forward(self, hidden_state): hidden_state = self.ba...
LevitClassificationLayer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType3.py
{ "start": 360, "end": 599 }
class ____(Root[T]): pass root_int: Root[int] = Root[int](lambda x: x << 2) # This should generate an error. root_float: Root[float] = root_int # This should generate an error. root_float: Root[float] = Root[int](lambda x: x << 2)
Leaf
python
bokeh__bokeh
src/bokeh/models/expressions.py
{ "start": 9114, "end": 9890 }
class ____(XYComponent): """ Y-component of a coordinate system transform to cartesian coordinates. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) #--------------------------------------------------------...
YComponent
python
numba__numba
numba/core/datamodel/models.py
{ "start": 39763, "end": 41265 }
class ____(StructModel): def __init__(self, dmm, fe_type): array_types = fe_type.arrays ndim = fe_type.ndim shape_len = ndim if fe_type.need_shaped_indexing else 1 members = [('exhausted', types.EphemeralPointer(types.boolean)), ('arrays', types.Tuple(array_types))...
NdIter
python
great-expectations__great_expectations
great_expectations/execution_engine/pandas_batch_data.py
{ "start": 167, "end": 443 }
class ____(BatchData): def __init__(self, execution_engine, dataframe: pd.DataFrame) -> None: super().__init__(execution_engine=execution_engine) self._dataframe = dataframe @property def dataframe(self): return self._dataframe
PandasBatchData
python
pandas-dev__pandas
pandas/core/_numba/extensions.py
{ "start": 5784, "end": 16982 }
class ____(models.StructModel): def __init__(self, dmm, fe_type) -> None: members = [ ("index", fe_type.index), ("values", fe_type.as_array), ("name", fe_type.namety), ] models.StructModel.__init__(self, dmm, fe_type, members) make_attribute_wrapper(Inde...
SeriesModel
python
squidfunk__mkdocs-material
material/plugins/social/layout.py
{ "start": 3664, "end": 5020 }
class ____(Config): definitions = ListOfItems(Type(str), default = []) tags = DictOfItems(Type(str), default = {}) size = SubConfig(Size) layers = ListOfItems(SubConfig(Layer), default = []) # ----------------------------------------------------------------------------- # Functions # ------------------...
Layout
python
coleifer__peewee
tests/sqlite.py
{ "start": 91692, "end": 94972 }
class ____(ModelTestCase): database = database requires = [Person, User, KVR] def test_sqlite_returning(self): iq = (User .insert_many([{'username': 'u%s' % i} for i in range(3)]) .returning(User.id)) self.assertEqual([r.id for r in iq.execute()], [1, 2, 3]) ...
TestSqliteReturning
python
django__django
tests/deprecation/tests.py
{ "start": 208, "end": 836 }
class ____(SimpleTestCase): def setUp(self): django_file_prefixes.cache_clear() self.addCleanup(django_file_prefixes.cache_clear) def test_no_file(self): orig_file = django.__file__ try: del django.__file__ self.assertEqual(django_file_prefixes(), ()) ...
DjangoFilePrefixesTests
python
davidhalter__jedi
test/test_api/test_full_name.py
{ "start": 1061, "end": 1388 }
class ____(MixinTestFullName, TestCase): operation = 'infer' def test_tuple_mapping(self): self.check(""" import re any_re = re.compile('.*') any_re""", 'typing.Pattern') def test_from_import(self): self.check('from os import path', 'os.path')
TestFullNameWithGotoDefinitions
python
openai__openai-python
src/openai/_response.py
{ "start": 9577, "end": 12938 }
class ____(BaseAPIResponse[R]): @property def request_id(self) -> str | None: return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] @overload def parse(self, *, to: type[_T]) -> _T: ... @overload def parse(self) -> R: ... def parse(self, *, to: type[...
APIResponse
python
django__django
django/contrib/auth/migrations/0006_require_contenttypes_0002.py
{ "start": 35, "end": 369 }
class ____(migrations.Migration): dependencies = [ ("auth", "0005_alter_user_last_login_null"), ("contenttypes", "0002_remove_content_type_name"), ] operations = [ # Ensure the contenttypes migration is applied before sending # post_migrate signals (which create ContentTypes...
Migration
python
celery__celery
t/unit/worker/test_request.py
{ "start": 3199, "end": 5695 }
class ____(RequestCase): def test_process_cleanup_fails(self, patching): _logger = patching('celery.app.trace.logger') self.mytask.backend = Mock() self.mytask.backend.process_cleanup = Mock(side_effect=KeyError()) tid = uuid() ret = jail(self.app, tid, self.mytask.name, {},...
test_trace_task
python
django__django
tests/or_lookups/tests.py
{ "start": 158, "end": 7620 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Article.objects.create( headline="Hello", pub_date=datetime(2005, 11, 27) ).pk cls.a2 = Article.objects.create( headline="Goodbye", pub_date=datetime(2005, 11, 28) ).pk cls.a3 = Ar...
OrLookupsTests
python
tensorflow__tensorflow
tensorflow/python/client/session.py
{ "start": 16770, "end": 17507 }
class ____(_FetchMapper): """Fetch mapper for attrs decorated classes.""" def __init__(self, fetches): """Creates a _AttrsFetchMapper. Args: fetches: An instance of an attrs decorated class. """ values = _get_attrs_values(fetches) self._fetch_type = type(fetches) self._mappers = [_Fe...
_AttrsFetchMapper
python
tensorflow__tensorflow
tensorflow/tools/proto_splitter/split_graph_def.py
{ "start": 1167, "end": 5369 }
class ____(split.ComposableSplitter): """Implements proto splitter for GraphDef. This Splitter will modify the passed in proto in place. """ def build_chunks(self): """Splits a GraphDef proto into smaller chunks.""" proto = self._proto if not isinstance(proto, graph_pb2.GraphDef): raise Type...
GraphDefSplitter
python
spyder-ide__spyder
spyder/app/tests/script_outline_4.py
{ "start": 255, "end": 350 }
class ____: def __init__(self): pass def some_method(self): pass
SomeClass
python
doocs__leetcode
solution/1600-1699/1642.Furthest Building You Can Reach/Solution.py
{ "start": 0, "end": 446 }
class ____: def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: h = [] for i, a in enumerate(heights[:-1]): b = heights[i + 1] d = b - a if d > 0: heappush(h, d) if len(h) > ladders: ...
Solution
python
joke2k__faker
faker/documentor.py
{ "start": 318, "end": 4246 }
class ____: def __init__(self, generator: Union[Generator, Faker]) -> None: """ :param generator: a localized Generator with providers filled, for which to write the documentation :type generator: faker.Generator() """ self.generator = generator ...
Documentor
python
doocs__leetcode
solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/Solution.py
{ "start": 0, "end": 680 }
class ____: def equalDigitFrequency(self, s: str) -> int: def check(i, j): v = set() for k in range(10): cnt = presum[j + 1][k] - presum[i][k] if cnt > 0: v.add(cnt) if len(v) > 1: return False ...
Solution
python
numpy__numpy
numpy/lib/tests/test_index_tricks.py
{ "start": 14581, "end": 14976 }
class ____: def test_regression_1(self): # ticket #1196 a = np.arange(2) assert_equal(a[:-1], a[s_[:-1]]) assert_equal(a[:-1], a[index_exp[:-1]]) def test_simple_1(self): a = np.random.rand(4, 5, 6) assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]]) ...
TestIndexExpression
python
scipy__scipy
scipy/integrate/_ivp/base.py
{ "start": 832, "end": 8770 }
class ____: """Base class for ODE solvers. In order to implement a new solver you need to follow the guidelines: 1. A constructor must accept parameters presented in the base class (listed below) along with any other parameters specific to a solver. 2. A constructor must accept arbi...
OdeSolver
python
pytorch__pytorch
torch/_subclasses/functional_tensor.py
{ "start": 36109, "end": 37906 }
class ____(BaseFunctionalizeAPI): def __init__(self, interpreter): self.interpreter = interpreter def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]: from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional return _wrap_all_tensors_to_functional(args, level=sel...
FunctorchFunctionalizeAPI
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_to_series.py
{ "start": 105, "end": 495 }
class ____: def test_to_series(self): naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") idx = naive.tz_localize("US/Pacific") expected = Series(np.array(idx.tolist(), dtype="object"), name="B") result = idx.to_series(index=range(2)) assert expected.dtype ...
TestToSeries
python
kamyu104__LeetCode-Solutions
Python/longest-common-prefix-of-k-strings-after-removal.py
{ "start": 72, "end": 1388 }
class ____(object): def longestCommonPrefix(self, words, k): """ :type words: List[str] :type k: int :rtype: List[int] """ idxs = range(len(words)) idxs.sort(key=lambda x: words[x]) def longest_common_prefix(k): lcp = [0]*len(words) ...
Solution
python
huggingface__transformers
tests/models/mask2former/test_modeling_mask2former.py
{ "start": 15739, "end": 23830 }
class ____(unittest.TestCase): @cached_property def model_checkpoints(self): return "facebook/mask2former-swin-small-coco-instance" @cached_property def default_image_processor(self): return Mask2FormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else ...
Mask2FormerModelIntegrationTest
python
ray-project__ray
doc/source/serve/doc_code/grpc_proxy/user_defined_protos_pb2_grpc.py
{ "start": 1478, "end": 3748 }
class ____(object): """Missing associated documentation comment in .proto file.""" def __call__(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") ...
UserDefinedServiceServicer
python
readthedocs__readthedocs.org
readthedocs/gold/migrations/0002_rename_last_4_digits.py
{ "start": 120, "end": 436 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("gold", "0001_initial"), ] operations = [ migrations.RenameField( model_name="golduser", old_name="last_4_digits", new_name="last_4_card_digits", ), ]
Migration
python
openai__openai-python
src/openai/types/beta/threads/run.py
{ "start": 975, "end": 1228 }
class ____(BaseModel): code: Literal["server_error", "rate_limit_exceeded", "invalid_prompt"] """One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.""" message: str """A human-readable description of the error."""
LastError
python
huggingface__transformers
src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
{ "start": 26484, "end": 29602 }
class ____(nn.Module): """ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information. """ def __init__(self, config): super().__init__() self.num_groups = config.num_codevector_g...
UniSpeechSatGumbelVectorQuantizer
python
huggingface__transformers
src/transformers/models/janus/modeling_janus.py
{ "start": 21140, "end": 22212 }
class ____(GradientCheckpointingLayer): def __init__(self, config: JanusConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = JanusAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = JanusMLP(confi...
JanusEncoderLayer
python
airbytehq__airbyte
airbyte-ci/connectors/erd/tests/test_dbml_assembler.py
{ "start": 327, "end": 2526 }
class ____(TestCase): def setUp(self) -> None: self._source = Mock(spec=Source) self._source.is_dynamic.return_value = False self._assembler = DbmlAssembler() def test_given_no_streams_then_database_is_empty(self) -> None: dbml = self._assembler.assemble( self._sourc...
RelationshipsMergerTest
python
PrefectHQ__prefect
tests/server/models/test_block_schemas.py
{ "start": 36458, "end": 37054 }
class ____: async def test_list_available_block_capabilities( self, session, block_schemas_with_capabilities ): assert sorted( await models.block_schemas.read_available_block_capabilities( session=session ) ) == sorted(["run", "fly", "swim"]) ...
TestListAvailableBlockCapabilities
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/self11.py
{ "start": 158, "end": 179 }
class ____(Base): ...
A
python
ApeWorX__ape
src/ape/types/private_mempool.py
{ "start": 2296, "end": 2641 }
class ____(BaseModel): """ Data used by block builders to check if the bundle should be considered for inclusion. """ block: HexInt """ The first block the bundle is valid for. """ max_block: Union[HexInt, None] = Field(None, alias="maxBlock") """ The last block the bundle is v...
Inclusion
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_build_signature.py
{ "start": 1307, "end": 2077 }
class ____(Model): def __init__(self, **kwargs): assert set(kwargs) == {"a", "b", "x", "y"} self.b = kwargs["b"] assert self.b is None or isinstance(self.b, list) @given(st.from_type(ModelForFromType)) def test_from_type_uses_signature_attribute(val): assert isinstance(val, ModelForFro...
ModelForFromType
python
sphinx-doc__sphinx
sphinx/errors.py
{ "start": 3288, "end": 3413 }
class ____(Exception): """Raised by get_filetype() if a filename matches no source suffix.""" pass
FiletypeNotFoundError
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 56012, "end": 58752 }
class ____: def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None: """Regression for (#11239) Walrus operator rewriting would leak to separate test cases if they used the same variables. """ pytester.makepyfile( """ def test_1(): ...
TestIssue11239
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 18414, "end": 19364 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, start_date: str, store_hash: str, access_token: str): """Airbyte Source for Bigcommerce. Documentation can be found at https://docs.airbyte.com/integrations/sources/bigcommerce Args: name (str): The n...
BigcommerceSource
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 23774, "end": 27879 }
class ____(PreTrainedModel): config: MMGroundingDinoConfig base_model_prefix = "model" main_input_name = "pixel_values" input_modalities = ("image", "text") @torch.no_grad() def _init_weights(self, module): std = self.config.init_std if isinstance(module, MMGroundingDinoLearned...
MMGroundingDinoPreTrainedModel
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B021.py
{ "start": 664, "end": 829 }
class ____: f"hello {VARIABLE}!" def baz(): f"""I'm probably a docstring: {VARIABLE}!""" print(f"""I'm a normal string""") f"""Don't detect me!"""
bar2
python
pytorch__pytorch
test/torch_np/numpy_tests/fft/test_helper.py
{ "start": 5872, "end": 6248 }
class ____(TestCase): def test_definition(self): x = [0, 1, 2, 3, 4] assert_array_almost_equal(9 * fft.rfftfreq(9), x) assert_array_almost_equal(9 * pi * fft.rfftfreq(9, pi), x) x = [0, 1, 2, 3, 4, 5] assert_array_almost_equal(10 * fft.rfftfreq(10), x) assert_array_al...
TestRFFTFreq
python
pypa__pip
src/pip/_vendor/rich/console.py
{ "start": 2099, "end": 2758 }
class ____: pass NO_CHANGE = NoChange() try: _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr] except Exception: _STDIN_FILENO = 0 try: _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr] except Exception: _STDOUT_FILENO = 1 try: _STDERR_FILENO = sys.__stderr...
NoChange
python
django-extensions__django-extensions
django_extensions/logging/filters.py
{ "start": 108, "end": 1102 }
class ____(logging.Filter): def filter(self, record): from django.conf import settings from django.core.cache import cache # Rate is specified as 1 messages logged per N seconds. (aka cache timeout) rate = getattr(settings, "RATE_LIMITER_FILTER_RATE", 10) prefix = getattr(se...
RateLimiterFilter
python
apache__thrift
test/crossrunner/report.py
{ "start": 3566, "end": 7203 }
class ____(TestReporter): def __init__(self, testdir, test, prog): super(ExecReporter, self).__init__() self._test = test self._prog = prog self.logpath = self.test_logfile(test.name, prog.kind, testdir) self.out = None def begin(self): self._start() self...
ExecReporter
python
sympy__sympy
sympy/polys/matrices/exceptions.py
{ "start": 306, "end": 398 }
class ____(Exception): """Base class for errors raised by DomainMatrix""" pass
DMError
python
doocs__leetcode
solution/0900-0999/0949.Largest Time for Given Digits/Solution.py
{ "start": 0, "end": 467 }
class ____: def largestTimeFromDigits(self, arr: List[int]) -> str: cnt = [0] * 10 for v in arr: cnt[v] += 1 for h in range(23, -1, -1): for m in range(59, -1, -1): t = [0] * 10 t[h // 10] += 1 t[h % 10] += 1 ...
Solution
python
huggingface__transformers
tests/models/qwen3_omni_moe/test_processing_qwen3_omni_moe.py
{ "start": 1268, "end": 13970 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Qwen3OmniMoeProcessor model_id = "Qwen/Qwen2.5-Omni-7B" @classmethod def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class.fr...
Qwen3OmniMoeProcessorTest
python
ray-project__ray
python/ray/util/client/server/proxier.py
{ "start": 32810, "end": 36320 }
class ____(ray_client_pb2_grpc.RayletLogStreamerServicer): def __init__(self, proxy_manager: ProxyManager): super().__init__() self.proxy_manager = proxy_manager def Logstream(self, request_iterator, context): request_iterator = RequestIteratorProxy(request_iterator) client_id =...
LogstreamServicerProxy
python
TheAlgorithms__Python
data_compression/huffman.py
{ "start": 297, "end": 2727 }
class ____: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all le...
TreeNode
python
huggingface__transformers
src/transformers/models/levit/configuration_levit.py
{ "start": 807, "end": 5147 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`LevitModel`]. It is used to instantiate a LeViT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configura...
LevitConfig
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 66243, "end": 66856 }
class ____(roles.InElementRole, KeyedColumnElement[_T]): """Refer to another column's VALUES or SET expression in an INSERT or UPDATE statement. See the public-facing :func:`_sql.from_dml_column` constructor for background. .. versionadded:: 2.1 """ def __init__(self, column: _DMLOnlyCo...
DMLTargetCopy
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_translate_speech.py
{ "start": 1284, "end": 7144 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudSpeechToTextHook") @mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudTranslateHook") def test_minimal_green_path(self, mock_translate_hook, mock_speech_hook): mock_speech_hook.return_val...
TestCloudTranslateSpeech
python
nedbat__coveragepy
tests/test_oddball.py
{ "start": 22186, "end": 24101 }
class ____(CoverageTest): """Tests of exec.""" def test_correct_filename(self) -> None: # https://github.com/coveragepy/coveragepy/issues/380 # Bug was that exec'd files would have their lines attributed to the # calling file. Make two files, both with ~30 lines, but no lines in ...
ExecTest
python
pypa__setuptools
setuptools/_distutils/fancy_getopt.py
{ "start": 1172, "end": 17196 }
class ____: """Wrapper around the standard 'getopt()' module that provides some handy extra functionality: * short and long options are tied together * options have help strings, and help text can be assembled from them * options set attributes of a passed-in object * boolean opt...
FancyGetopt