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
huggingface__transformers
src/transformers/models/llava/modeling_llava.py
{ "start": 4752, "end": 5315 }
class ____(PreTrainedModel): config: LlavaConfig base_model_prefix = "model" input_modalities = ("image", "text") supports_gradient_checkpointing = True _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_sdpa = True _can_compile_fullgraph = True _...
LlavaPreTrainedModel
python
walkccc__LeetCode
solutions/2826. Sorting Three Groups/2826.py
{ "start": 0, "end": 345 }
class ____: def minimumOperations(self, nums: list[int]) -> int: # dp[i] := the longest non-decreasing subsequence so far with numbers in [1..i] dp = [0] * 4 for num in nums: dp[num] += 1 # Append num to the sequence so far. dp[2] = max(dp[2], dp[1]) dp[3] = max(dp[3], dp[2]) retu...
Solution
python
django__django
tests/generic_views/views.py
{ "start": 1963, "end": 2016 }
class ____(generic.ListView): model = Book
BookList
python
davidhalter__jedi
test/refactor/extract_function.py
{ "start": 2380, "end": 2528 }
class ____: def f(self, b, c): #? 18 text {'new_name': 'b'} return b | self.a # ++++++++++++++++++++++++++++++++++++++++++++++++++
X
python
sphinx-doc__sphinx
sphinx/domains/cpp/__init__.py
{ "start": 31093, "end": 32595 }
class ____(SphinxRole): def __init__(self, asCode: bool) -> None: super().__init__() if asCode: # render the expression as inline code self.class_type = 'cpp-expr' else: # render the expression as inline text self.class_type = 'cpp-texpr' ...
CPPExprRole
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 32971, "end": 33423 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the user has sent too many requests in a given amount of time ("rate limiting"). RFC 6585.4 code: 429, title: Too Many Requests """ code = 429 title = 'Too Many Requests' explanation = ...
HTTPTooManyRequests
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_variables.py
{ "start": 2002, "end": 3996 }
class ____: @pytest.mark.parametrize( ("key", "value"), [ ("var1", "value"), ("var2/with_slash", "slash_value"), ], ) def test_variable_get_from_db(self, client, session, key, value): Variable.set(key=key, value=value, session=session) session....
TestGetVariable
python
jazzband__django-oauth-toolkit
tests/test_ui_locales.py
{ "start": 443, "end": 2027 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.application = Application.objects.create( name="Test Application", client_id="test", redirect_uris="https://www.example.com/", client_type=Application.CLIENT_PUBLIC, authorization_g...
TestUILocalesParam
python
mlflow__mlflow
mlflow/pyfunc/scoring_server/client.py
{ "start": 3190, "end": 5432 }
class ____(BaseScoringServerClient): def __init__(self, process): super().__init__() self.process = process try: # Use /dev/shm (memory-based filesystem) if possible to make read/write efficient. tmpdir = tempfile.mkdtemp(dir="/dev/shm") except Exception: ...
StdinScoringServerClient
python
pydantic__pydantic
tests/mypy/outputs/pyproject-plugin-strict-equality_toml/strict_equality.py
{ "start": 33, "end": 448 }
class ____(BaseModel): username: str user = User(username='test') print(user == 'test') # MYPY: error: Non-overlapping equality check (left operand type: "User", right operand type: "Literal['test']") [comparison-overlap] print(user.username == int('1')) # MYPY: error: Non-overlapping equality check (left operan...
User
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/dbt_manifest_asset_selection.py
{ "start": 832, "end": 5072 }
class ____(AssetSelection): """Defines a selection of assets from a dbt manifest wrapper and a dbt selection string. Args: manifest (Mapping[str, Any]): The dbt manifest blob. select (str): A dbt selection string to specify a set of dbt resources. exclude (Optional[str]): A dbt selectio...
DbtManifestAssetSelection
python
huggingface__transformers
src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
{ "start": 35281, "end": 38622 }
class ____(Wav2Vec2ForSequenceClassification): def __init__(self, config): super().__init__(config) def freeze_feature_encoder(self): raise AttributeError("Not needed for Wav2Vec2Bert") def freeze_base_model(self): """ Calling this function will disable the gradient computa...
Wav2Vec2BertForSequenceClassification
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-dashscope/llama_index/readers/dashscope/domain/lease_domains.py
{ "start": 7074, "end": 7952 }
class ____(DictToObject): def __init__(self, url, method, headers) -> None: self.url = url self.method = method self.headers = headers @classmethod def from_dict(cls, data: dict): """ Creates an instance of `QueryFileResult` from a dictionary. Args: ...
HttpDownloadParameter
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 37716, "end": 37903 }
class ____(BoringModel): def on_before_optimizer_step(self, optimizer): if self.current_epoch == 1: raise RuntimeError("Trouble!")
TroubledModelOnBeforeOptimizerStep
python
anthropics__anthropic-sdk-python
src/anthropic/lib/vertex/_beta_messages.py
{ "start": 496, "end": 1472 }
class ____(SyncAPIResource): create = FirstPartyMessagesAPI.create stream = FirstPartyMessagesAPI.stream count_tokens = FirstPartyMessagesAPI.count_tokens @cached_property def with_raw_response(self) -> MessagesWithRawResponse: """ This property can be used as a prefix for any HTTP ...
Messages
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 4570, "end": 5572 }
class ____(Benchmark): param_names = ['sparse_type'] params = [ ['spmatrix', 'sparray'] ] def setup(self, sparse_type): coo = sparse.coo_array if sparse_type == "sparray" else sparse.coo_matrix H1, W1 = 1, 100000 H2, W2 = W1, 1000 C1 = 10 C2 = 1000000 ...
Matmul
python
matplotlib__matplotlib
lib/matplotlib/tests/test_category.py
{ "start": 4723, "end": 6061 }
class ____: test_cases = [("ascii", ["hello", "world", "hi"]), ("unicode", ["Здравствуйте", "привет"])] ids, cases = zip(*test_cases) @pytest.mark.parametrize("ydata", cases, ids=ids) def test_StrCategoryFormatter(self, ydata): unit = cat.UnitData(ydata) labels = cat....
TestStrCategoryFormatter
python
django__django
tests/forms_tests/field_tests/test_urlfield.py
{ "start": 166, "end": 6059 }
class ____(FormFieldAssertionsMixin, SimpleTestCase): def test_urlfield_widget(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" required>') def test_urlfield_widget_max_min_length(self): f = URLField(min_length=15, max_length=20) self.ass...
URLFieldTest
python
walkccc__LeetCode
solutions/1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/1414-2.py
{ "start": 0, "end": 416 }
class ____: def findMinFibonacciNumbers(self, k: int) -> int: ans = 0 a = 1 # F_1 b = 1 # F_2 while b <= k: # a, b = F_{i + 1}, F_{i + 2} # -> a, b = F_{i + 2}, F_{i + 3} a, b = b, a + b while a > 0: if a <= k: k -= a ans += 1 # a, b = F_{i +...
Solution
python
mlflow__mlflow
mlflow/server/job_api.py
{ "start": 2357, "end": 3182 }
class ____(BaseModel): """ Pydantic model for job searching response. """ jobs: list[Job] @job_api_router.post("/search", response_model=SearchJobsResponse) def search_jobs(payload: SearchJobPayload) -> SearchJobsResponse: from mlflow.server.handlers import _get_job_store try: store ...
SearchJobsResponse
python
matplotlib__matplotlib
lib/mpl_toolkits/mplot3d/art3d.py
{ "start": 13850, "end": 17214 }
class ____(LineCollection): """ A collection of 3D lines. """ def __init__(self, lines, axlim_clip=False, **kwargs): super().__init__(lines, **kwargs) self._axlim_clip = axlim_clip """ Parameters ---------- lines : list of (N, 3) array-like A s...
Line3DCollection
python
openai__openai-python
tests/test_response.py
{ "start": 3650, "end": 8394 }
class ____(BaseModel): foo: str bar: int def test_response_parse_custom_model(client: OpenAI) -> None: response = APIResponse( raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), client=client, stream=False, stream_cls=None, cast_to=str, ...
CustomModel
python
python__mypy
mypy/test/meta/_pytest.py
{ "start": 226, "end": 2276 }
class ____: input: str input_updated: str # any updates made by --update-data stdout: str stderr: str def dedent_docstring(s: str) -> str: return textwrap.dedent(s).lstrip() def run_pytest_data_suite( data_suite: str, *, data_file_prefix: str = "check", pytest_node_prefix: str =...
PytestResult
python
numpy__numpy
numpy/polynomial/tests/test_chebyshev.py
{ "start": 17356, "end": 17937 }
class ____: def test_100(self): x, w = cheb.chebgauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = cheb.chebvander(x, 99) vv ...
TestGauss
python
langchain-ai__langchain
libs/langchain/langchain_classic/memory/entity.py
{ "start": 10429, "end": 15155 }
class ____(BaseEntityStore): """SQLite-backed Entity store with safe query construction.""" session_id: str = "default" table_name: str = "memory_store" conn: Any = None model_config = ConfigDict( arbitrary_types_allowed=True, ) def __init__( self, session_id: str ...
SQLiteEntityStore
python
readthedocs__readthedocs.org
readthedocs/api/v3/views.py
{ "start": 21364, "end": 21641 }
class ____(APIv3Settings, RemoteQuerySetMixin, ListModelMixin, GenericViewSet): model = RemoteOrganization serializer_class = RemoteOrganizationSerializer filterset_class = RemoteOrganizationFilter permission_classes = (IsAuthenticated,)
RemoteOrganizationViewSet
python
pandas-dev__pandas
pandas/tests/indexes/interval/test_setops.py
{ "start": 424, "end": 8346 }
class ____: def test_union(self, closed, sort): index = monotonic_index(0, 11, closed=closed) other = monotonic_index(5, 13, closed=closed) expected = monotonic_index(0, 13, closed=closed) result = index[::-1].union(other, sort=sort) if sort in (None, True): tm.a...
TestIntervalIndex
python
wandb__wandb
wandb/sdk/mailbox/mailbox_handle.py
{ "start": 437, "end": 3231 }
class ____(abc.ABC, Generic[_T]): """A handle for waiting on a response to a request.""" def __init__(self, asyncer: asyncio_manager.AsyncioManager) -> None: self._asyncer = asyncer @property def asyncer(self) -> asyncio_manager.AsyncioManager: """The asyncio thread to which the handle...
MailboxHandle
python
aimacode__aima-python
gui/grid_mdp.py
{ "start": 12187, "end": 16421 }
class ____(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, 'Grid MDP') self.shared_data = { 'height': tk.IntVar(), 'width': tk.IntVar()} self.shared_data['height'].set(1) self.shared_data['width...
MDPapp
python
getsentry__sentry
src/sentry/snuba/dataset.py
{ "start": 40, "end": 1652 }
class ____(Enum): Events = "events" "The events dataset contains all ingested errors." Transactions = "transactions" "The transactions dataset contains all ingested transactions." Discover = "discover" "The discover dataset is a combination of both the events and transactions datasets." O...
Dataset
python
scikit-image__scikit-image
tests/skimage/exposure/test_histogram_matching.py
{ "start": 678, "end": 5157 }
class ____: image_rgb = data.chelsea() template_rgb = data.astronaut() @pytest.mark.parametrize( 'image, reference, channel_axis', [ (image_rgb, template_rgb, -1), (image_rgb[:, :, 0], template_rgb[:, :, 0], None), ], ) def test_match_histograms(self,...
TestMatchHistogram
python
huggingface__transformers
tests/tokenization/test_tokenization_fast.py
{ "start": 13447, "end": 14287 }
class ____(unittest.TestCase): def test_async_share_tokenizer(self): # See https://github.com/huggingface/transformers/pull/12550 # and https://github.com/huggingface/tokenizers/issues/537 tokenizer = PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel") tex...
ReduceMutableBorrowTests
python
jina-ai__jina
tests/integration/dynamic_batching/test_dynamic_batching.py
{ "start": 2214, "end": 3414 }
class ____(Executor): @requests(on=['/foo']) @dynamic_batching(preferred_batch_size=1) def foo_fun(self, docs, **kwargs): for doc in docs: doc.text += FOO_SUCCESS_MSG @requests(on=['/bar', '/baz']) @dynamic_batching(preferred_batch_size=1, timeout=1) def bar_fun(self, docs, ...
PlaceholderExecutorWrongDecorator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 849317, "end": 850181 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "md5", "name", "package_version", "sha1", "sha256", "size", "updated_at", "url", ) md5 = sgqlc.types.Fie...
PackageFile
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 15942, "end": 16363 }
class ____: """Test nl_NL currency provider""" num_samples = 100 @classmethod def setup_class(cls): from faker.providers.currency.nl_NL import Provider as NlCurrencyProvider cls.provider = NlCurrencyProvider def test_pricetag(self, faker, num_samples): for _ in range(num_...
TestNlNl
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/version.py
{ "start": 879, "end": 1011 }
class ____(BaseModel): """Version information serializer for responses.""" version: str git_version: str | None
VersionInfo
python
tiangolo__fastapi
docs_src/security/tutorial003.py
{ "start": 928, "end": 2477 }
class ____(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def fake_decode_token(token): # This doesn't provide any security at all # Check the next version user = get_user(fake_users_db, token)...
UserInDB
python
mahmoud__boltons
boltons/queueutils.py
{ "start": 6774, "end": 7205 }
class ____(BasePriorityQueue): """A priority queue inherited from :class:`BasePriorityQueue`, backed by a list and based on the :func:`heapq.heappop` and :func:`heapq.heappush` functions in the built-in :mod:`heapq` module. """ @staticmethod def _pop_entry(backend): return heappop(ba...
HeapPriorityQueue
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 60720, "end": 67705 }
class ____: # Carried over from ListApiResponse # We currently use list API for listing the resources total: int # Carried over from ListApiResponse # Number of resources returned by data sources after truncation num_after_truncation: int # Number of resources after filtering num_filtere...
SummaryApiResponse
python
xlwings__xlwings
tests/test_conversion.py
{ "start": 7648, "end": 23195 }
class ____(TestBase): def test_dataframe_1(self): df_expected = pd.DataFrame( [[1, "test1"], [2, "test2"], [np.nan, None], [3.3, "test3"]], columns=["a", "b"], ) self.wb1.sheets[0].range("A1").value = df_expected df_result = self.wb1.sheets[0].range("A1:C5").o...
TestPandas
python
astropy__astropy
astropy/modeling/_fitting_parallel.py
{ "start": 1528, "end": 3536 }
class ____: """ This class is intended to contain the object array of all fit_info values and provide a convenience method to access specific items from fit_info as arrays. """ def __init__(self, fit_info_array): self._fit_info_array = fit_info_array @property def shape(self): ...
FitInfoArrayContainer
python
sympy__sympy
sympy/printing/tests/test_latex.py
{ "start": 6007, "end": 140094 }
class ____(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printe...
lowergamma
python
pypa__pipenv
pipenv/patched/pip/_vendor/distlib/version.py
{ "start": 20249, "end": 21929 }
class ____(Matcher): version_class = LegacyVersion _operators = dict(Matcher._operators) _operators['~='] = '_match_compatible' numeric_re = re.compile(r'^(\d+(\.\d+)*)') def _match_compatible(self, version, constraint, prefix): if version < constraint: return False m ...
LegacyMatcher
python
PrefectHQ__prefect
tests/server/models/test_flow_run_input.py
{ "start": 232, "end": 2074 }
class ____: async def test_creates_flow_run_input(self, session: AsyncSession, flow_run): flow_run_input = await models.flow_run_input.create_flow_run_input( session=session, flow_run_input=schemas.core.FlowRunInput( flow_run_id=flow_run.id, key="my-ke...
TestCreateFlowRunInput
python
huggingface__transformers
tests/models/codegen/test_tokenization_codegen.py
{ "start": 248, "end": 2499 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = ["Salesforce/codegen-350M-mono"] tokenizer_class = CodeGenTokenizer integration_expected_tokens = ['This', 'Ġis', 'Ġa', 'Ġtest', 'ĠðŁĺ', 'Ĭ', 'Ċ', 'I', 'Ġwas', 'Ġborn', 'Ġin', 'Ġ92', '000', ',', 'Ġand', 'Ġthis', 'Ġis', 'Ġfals', 'é',...
CodeGenTokenizationTest
python
keras-team__keras
examples/demo_custom_jax_workflow.py
{ "start": 858, "end": 3226 }
class ____(Model): def __init__(self, hidden_dim, output_dim): super().__init__() self.dense1 = MyDense(hidden_dim) self.dense2 = MyDense(hidden_dim) self.dense3 = MyDense(output_dim) def call(self, x): x = jax.nn.relu(self.dense1(x)) x = jax.nn.relu(self.dense2(...
MyModel
python
redis__redis-py
redis/maint_notifications.py
{ "start": 213, "end": 322 }
class ____(enum.Enum): NONE = "none" MOVING = "moving" MAINTENANCE = "maintenance"
MaintenanceState
python
modin-project__modin
modin/core/storage_formats/pandas/parsers.py
{ "start": 12914, "end": 13873 }
class ____(PandasParser): @staticmethod @doc(_doc_parse_func, parameters=_doc_parse_parameters_common2) def parse(fname, common_read_kwargs, **kwargs): return PandasParser.generic_parse( fname, callback=PandasCSVParser.read_callback, **common_read_kwargs, ...
PandasCSVParser
python
imageio__imageio
imageio/plugins/grab.py
{ "start": 142, "end": 1236 }
class ____(Format): """Base format for grab formats.""" _pillow_imported = False _ImageGrab = None def __init__(self, *args, **kwargs): super(BaseGrabFormat, self).__init__(*args, **kwargs) self._lock = threading.RLock() def _can_write(self, request): return False def...
BaseGrabFormat
python
hynek__structlog
tests/processors/test_renderers.py
{ "start": 701, "end": 3354 }
class ____: def test_sort_keys(self, event_dict): """ Keys are sorted if sort_keys is set. """ rv = KeyValueRenderer(sort_keys=True)(None, None, event_dict) assert r"a=<A(\o/)> b=[3, 4] x=7 y='test' z=(1, 2)" == rv def test_order_complete(self, event_dict): """ ...
TestKeyValueRenderer
python
apache__airflow
providers/openlineage/tests/unit/openlineage/plugins/test_listener.py
{ "start": 2978, "end": 3495 }
class ____: def __init__(self, *args, **kwargs): self.submitted = False self.succeeded = False self.result = None def submit(self, fn, /, *args, **kwargs): self.submitted = True try: fn(*args, **kwargs) self.succeeded = True except Excepti...
MockExecutor
python
mlflow__mlflow
mlflow/genai/scorers/base.py
{ "start": 3673, "end": 43462 }
class ____(BaseModel): name: str aggregations: list[_AggregationType] | None = None description: str | None = None _cached_dump: dict[str, Any] | None = PrivateAttr(default=None) _sampling_config: ScorerSamplingConfig | None = PrivateAttr(default=None) _registered_backend: str | None = PrivateA...
Scorer
python
scipy__scipy
scipy/optimize/tests/test_minimize_constrained.py
{ "start": 7490, "end": 8014 }
class ____(Rosenbrock): """Rosenbrock subject to inequality constraints. The following optimization problem: minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2) subject to: -2 <= x[0] <= 0 0 <= x[1] <= 2 Taken from matlab ``fmincon`` documentation. """ ...
BoundedRosenbrock
python
sympy__sympy
sympy/utilities/codegen.py
{ "start": 10390, "end": 12835 }
class ____: """Represents a typed variable.""" def __init__(self, name, datatype=None, dimensions=None, precision=None): """Return a new variable. Parameters ========== name : Symbol or MatrixSymbol datatype : optional When not given, the data type will be...
Variable
python
django__django
tests/auth_tests/models/custom_user.py
{ "start": 2527, "end": 3559 }
class ____: """ A context manager to temporarily remove the groups and user_permissions M2M fields from the AbstractUser class, so they don't clash with the related_name sets. """ def __enter__(self): self._old_au_local_m2m = AbstractUser._meta.local_many_to_many self._old_pm_lo...
RemoveGroupsAndPermissions
python
huggingface__transformers
src/transformers/generation/utils.py
{ "start": 7131, "end": 10796 }
class ____(ModelOutput): """ Outputs of encoder-decoder generation models, when using non-beam methods. Args: sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`): The generated sequences. The second dimension (sequence_length) is either equal to ...
GenerateEncoderDecoderOutput
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/ext.py
{ "start": 13608, "end": 14436 }
class ____(_regconfig_fn): """The PostgreSQL ``phraseto_tsquery`` SQL function. This function applies automatic casting of the REGCONFIG argument to use the :class:`_postgresql.REGCONFIG` datatype automatically, and applies a return type of :class:`_postgresql.TSQUERY`. Assuming the PostgreSQL dia...
phraseto_tsquery
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 91600, "end": 92704 }
class ____(APITestCase): def setUp(self): user = self.create_user(is_staff=False, is_superuser=False) self.org = self.create_organization() self.org.save() team = self.create_team(organization=self.org) self.project = self.create_project(name="foo", organization=self.org, te...
ReleaseCommitPatchTest
python
pypa__hatch
backend/src/hatchling/builders/hooks/version.py
{ "start": 182, "end": 2416 }
class ____(BuildHookInterface): PLUGIN_NAME = "version" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.__config_path: str | None = None self.__config_template: str | None = None self.__config_pattern: str | bool | None = None ...
VersionBuildHook
python
numba__llvmlite
llvmlite/binding/newpassmanagers.py
{ "start": 19573, "end": 19785 }
class ____(ffi.ObjectRef): def __init__(self): super().__init__(ffi.lib.LLVMPY_CreateTimePassesHandler()) def _dispose(self): ffi.lib.LLVMPY_DisposeTimePassesHandler(self)
TimePassesHandler
python
getsentry__sentry
tests/sentry/integrations/slack/notifications/test_escalating.py
{ "start": 506, "end": 5558 }
class ____(SlackActivityNotificationTest, PerformanceIssueTestCase): def create_notification(self, group): return EscalatingActivityNotification( Activity( project=self.project, group=group, user_id=self.user.id, type=ActivityType.S...
SlackRegressionNotificationTest
python
huggingface__transformers
src/transformers/models/internvl/modeling_internvl.py
{ "start": 19523, "end": 20484 }
class ____(nn.Module): def __init__(self, config: InternVLConfig): super().__init__() self.layer_norm = nn.LayerNorm(config.vision_config.hidden_size * int(1 / config.downsample_ratio) ** 2) self.linear_1 = nn.Linear( config.vision_config.hidden_size * int(1 / config.downsample_r...
InternVLMultiModalProjector
python
getsentry__sentry
src/sentry/management/commands/createsuperuser.py
{ "start": 95, "end": 359 }
class ____(DjangoCommand): help = "Performs any pending database migrations and upgrades" def handle(self, **options): from sentry.runner import call_command call_command("sentry.runner.commands.createuser.createuser", superuser=True)
Command
python
jazzband__django-model-utils
model_utils/managers.py
{ "start": 13098, "end": 13192 }
class ____(SoftDeletableQuerySetMixin[ModelT], QuerySet[ModelT]): pass
SoftDeletableQuerySet
python
mitmproxy__pdoc
test/testdata/flavors_numpy.py
{ "start": 5314, "end": 6494 }
class ____(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document ...
ExampleError
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 115860, "end": 119903 }
class ____(Qwen3OmniMoePreTrainedModel): config_class = Qwen3OmniMoeTalkerCodePredictorConfig base_model_prefix = "talker.code_predictor.model" _can_record_outputs = { "attentions": Qwen3OmniMoeTalkerCodePredictorAttention, "hidden_states": Qwen3OmniMoeTalkerCodePredictorDecoderLayer, } ...
Qwen3OmniMoeTalkerCodePredictorModel
python
kamyu104__LeetCode-Solutions
Python/number-of-distinct-averages.py
{ "start": 66, "end": 426 }
class ____(object): def distinctAverages(self, nums): """ :type nums: List[int] :rtype: int """ lookup = set() nums.sort() left, right = 0, len(nums)-1 while left < right: lookup.add(nums[left]+nums[right]) left, right = left+1,...
Solution
python
facebook__pyre-check
client/commands/infer.py
{ "start": 1363, "end": 1987 }
class ____: """ Data structure for configuration options the backend infer command can recognize. Need to keep in sync with `source/command/inferCommand.ml` """ base_arguments: backend_arguments.BaseArguments paths_to_modify: Optional[Set[Path]] = None def serialize(self) -> Dict[str, Any]...
Arguments
python
python-markdown__markdown
markdown/inlinepatterns.py
{ "start": 36776, "end": 37253 }
class ____(InlineProcessor): """ Return a link Element given an auto-link (`<http://example/com>`). """ def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: """ Return an `a` [`Element`][xml.etree.ElementTree.Element] of `group(1)`. """ el = etree.Element("a") ...
AutolinkInlineProcessor
python
modin-project__modin
modin/core/dataframe/algebra/tree_reduce.py
{ "start": 1129, "end": 3212 }
class ____(Operator): """Builder class for TreeReduce operator.""" @classmethod def register( cls, map_function: Optional[Callable[..., pandas.DataFrame]], reduce_function: Optional[Callable[..., pandas.Series]] = None, axis: Optional[int] = None, compute_dtypes: Opt...
TreeReduce
python
python-attrs__attrs
tests/test_functional.py
{ "start": 1160, "end": 1239 }
class ____(Frozen): y = attr.ib() @attr.s(frozen=True, slots=False)
SubFrozen
python
facebook__pyre-check
client/libcst_vendored_visitors/_apply_type_annotations.py
{ "start": 18331, "end": 43333 }
class ____(ContextAwareTransformer): """ Apply type annotations to a source module using the given stub mdules. You can also pass in explicit annotations for functions and attributes and pass in new class definitions that need to be added to the source module. This is one of the transforms that is ...
ApplyTypeAnnotationsVisitor
python
huggingface__transformers
src/transformers/models/llava_onevision/processing_llava_onevision.py
{ "start": 1510, "end": 16607 }
class ____(ProcessorMixin): r""" Constructs a LLaVa-Onevision processor which wraps a LLaVa-Onevision video processor, LLaVa-NeXT image processor and a LLaMa tokenizer into a single processor. [`LlavaNextProcessor`] offers all the functionalities of [`LlavaOnevisionVideoProcessor`], [`LlavaOnevisionImagePr...
LlavaOnevisionProcessor
python
pydata__xarray
xarray/computation/rolling.py
{ "start": 44143, "end": 47202 }
class ____(Coarsen["DataArray"]): __slots__ = () _reduce_extra_args_docstring = """""" @classmethod def _reduce_method( cls, func: Callable, include_skipna: bool = False, numeric_only: bool = False ) -> Callable[..., DataArray]: """ Return a wrapped function for injecting r...
DataArrayCoarsen
python
PrefectHQ__prefect
tests/server/models/test_work_queues.py
{ "start": 8951, "end": 15055 }
class ____: running_flow_states = [ schemas.states.StateType.PENDING, schemas.states.StateType.CANCELLING, schemas.states.StateType.RUNNING, ] @pytest.fixture async def work_queue_2(self, session): work_queue = await models.work_queues.create_work_queue( sess...
TestGetRunsInWorkQueue
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/binary_operators.py
{ "start": 228, "end": 408 }
class ____: def __add__(self, other): _test_sink(other) def test1(): add = Add() add + _test_source() def test2(): add = Add() add += _test_source()
Add
python
dask__distributed
distributed/diagnostics/plugin.py
{ "start": 13065, "end": 13578 }
class ____(SchedulerPlugin): name = "upload_file" def __init__(self, filepath: str, load: bool = True): """ Initialize the plugin by reading in the data from the given file. """ self.filename = os.path.basename(filepath) self.load = load with open(filepath, "rb")...
SchedulerUploadFile
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/norm_op_test.py
{ "start": 1211, "end": 4810 }
class ____(test_lib.TestCase): @test_util.run_v1_only("b/120545219") def testBadOrder(self): matrix = [[0., 1.], [2., 3.]] for ord_ in "fro", -7, -1.1, 0: with self.assertRaisesRegex(ValueError, "'ord' must be a supported vector norm"): linalg_ops.norm(matrix...
NormOpTest
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/galaxy.py
{ "start": 2801, "end": 5094 }
class ____(CloudProvider): """ Galaxy plugin. Sets up pulp (ansible-galaxy) servers for tests. The pulp source itself resides at: https://github.com/pulp/pulp-oci-images """ def __init__(self, args: IntegrationConfig) -> None: super().__init__(args) self.image = os.environ.get( ...
GalaxyProvider
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/schemas/test_user_schema.py
{ "start": 3447, "end": 5094 }
class ____(TestUserBase): def test_serialize(self): user_model = User( first_name="Foo", last_name="Bar", username="test", password="test", email=TEST_EMAIL, created_on=timezone.parse(DEFAULT_TIME), changed_on=timezone.parse...
TestUserSchema
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 32410, "end": 52742 }
class ____(SimpleTestCase): def test_ambiguous_object(self): """ Names deployed via dynamic URL objects that require namespaces can't be resolved. """ test_urls = [ ("urlobject-view", [], {}), ("urlobject-view", [37, 42], {}), ("urlobject-v...
NamespaceTests
python
pytorch__pytorch
test/distributed/checkpoint/test_checkpoint.py
{ "start": 5448, "end": 6589 }
class ____(TestStorageBase, StorageWriter): def __init__(self, fail_conf): super().__init__(fail_conf) def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None: return def set_up_storage_writer( self, is_coordinator: bool, *args: Any, **kwargs: Any ) -> None...
FaultyStorageWriter
python
walkccc__LeetCode
solutions/430. Flatten a Multilevel Doubly Linked List/430.py
{ "start": 0, "end": 344 }
class ____: def flatten(self, head: 'Node') -> 'Node': def flatten(head: 'Node', rest: 'Node') -> 'Node': if not head: return rest head.next = flatten(head.child, flatten(head.next, rest)) if head.next: head.next.prev = head head.child = None return head return ...
Solution
python
RaRe-Technologies__gensim
gensim/models/translation_matrix.py
{ "start": 5514, "end": 14286 }
class ____(utils.SaveLoad): """Objects of this class realize the translation matrix which maps the source language to the target language. The main methods are: We map it to the other language space by computing z = Wx, then return the word whose representation is close to z. For details on use, s...
TranslationMatrix
python
huggingface__transformers
src/transformers/models/moonshine/modular_moonshine.py
{ "start": 26675, "end": 31588 }
class ____(LlamaModel): main_input_name = "input_ids" _can_record_outputs = { "attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="self_attn"), "hidden_states": MoonshineDecoderLayer, "cross_attentions": OutputRecorder(MoonshineAttention, index=1, layer_name="encoder_att...
MoonshineDecoder
python
getsentry__sentry
src/sentry/core/endpoints/organization_user_details.py
{ "start": 463, "end": 1113 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = (MemberPermission,) def get(self, request: Request, organization, user_id) -> Response: try: int(user_id) except ValueError: raise ValidationError...
OrganizationUserDetailsEndpoint
python
optuna__optuna
optuna/storages/journal/_base.py
{ "start": 158, "end": 1469 }
class ____(abc.ABC): """Base class for Journal storages. Storage classes implementing this base class must guarantee process safety. This means, multiple processes might concurrently call ``read_logs`` and ``append_logs``. If the backend storage does not internally support mutual exclusion mechanisms, ...
BaseJournalBackend
python
jmcnamara__XlsxWriter
xlsxwriter/exceptions.py
{ "start": 622, "end": 713 }
class ____(XlsxInputError): """Worksheet table name already exists."""
DuplicateTableName
python
sqlalchemy__sqlalchemy
examples/asyncio/gather_orm_statements.py
{ "start": 1107, "end": 3380 }
class ____(Base): __tablename__ = "a" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] def __repr__(self): id_, data = self.id, self.data return f"A({id_=}, {data=})" async def run_out_of_band(async_sessionmaker, statement, merge_results=True): """run an ORM st...
A
python
pypa__warehouse
tests/unit/admin/views/test_projects.py
{ "start": 29337, "end": 31448 }
class ____: def test_no_confirm(self): project = pretend.stub(name="foo", normalized_name="foo") request = pretend.stub( POST={}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), route_path=lambda *a, **kw: "/foo/bar/", ) ...
TestDeleteProject
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 267907, "end": 268265 }
class ____(StatNode): # Global variable declaration. # # names [string] child_attrs = [] def analyse_declarations(self, env): for name in self.names: env.declare_global(name, self.pos) def analyse_expressions(self, env): return self def generate_execution_c...
GlobalNode
python
pyenv__pyenv
plugins/python-build/scripts/add_miniconda.py
{ "start": 2660, "end": 2746 }
class ____(StrEnum): TWO = "2" THREE = "3" NONE = "" PyVersion = None
Suffix
python
Netflix__metaflow
metaflow/datastore/exceptions.py
{ "start": 44, "end": 120 }
class ____(MetaflowException): headline = "Data store error"
DataException
python
walkccc__LeetCode
solutions/3116. Kth Smallest Amount With Single Denomination Combination/3116.py
{ "start": 0, "end": 830 }
class ____: def findKthSmallest(self, coins: list[int], k: int) -> int: sizeToLcms = self._getSizeToLcms(coins) def count(m: int) -> int: """Returns the number of denominations <= m.""" res = 0 for sz, lcms in enumerate(sizeToLcms): for lcm in lcms: # Principle of Inclusio...
Solution
python
django__django
tests/model_inheritance/models.py
{ "start": 1041, "end": 1113 }
class ____(models.Model): title = models.CharField(max_length=50)
Post
python
huggingface__transformers
src/transformers/models/ibert/quant_modules.py
{ "start": 957, "end": 3713 }
class ____(nn.Module): """ Quantized version of `torch.nn.Embedding`. Adds quantization-specific arguments on top of `torch.nn.Embedding`. Args: weight_bit (`int`, *optional*, defaults to `8`): Bitwidth for the quantized weight. momentum (`float`, *optional*, defaults to `0.95`)...
QuantEmbedding
python
coleifer__peewee
tests/regressions.py
{ "start": 40739, "end": 40851 }
class ____(TestModel): user = ForeignKeyField(BCUser, field=BCUser.username) content = TextField()
BCTweet
python
pytorch__pytorch
torch/cuda/jiterator.py
{ "start": 1457, "end": 6861 }
class ____: def __init__( self, code_string: str, return_by_ref: bool, num_outputs: int, **kwargs ): self.code_string = code_string assert return_by_ref or num_outputs == 1, ( "Return by value only works for single output. " ) self.return_by_ref = return_by_r...
_JittedFunction
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 8333, "end": 11676 }
class ____(GoogleCloudBaseOperator): """ Delete the task resource. :param project_id: Required. The ID of the Google Cloud project that the task belongs to. :param region: Required. The ID of the Google Cloud region that the task belongs to. :param lake_id: Required. The ID of the Google Cloud lake...
DataplexDeleteTaskOperator
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_sparkline12.py
{ "start": 345, "end": 3978 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with no cell data.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) ...
TestAssembleWorksheet