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
numpy__numpy
tools/swig/test/testFortran.py
{ "start": 1407, "end": 1674 }
class ____(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "schar" self.typeCode = "b" ######################################################################
scharTestCase
python
mlflow__mlflow
mlflow/genai/scorers/base.py
{ "start": 1843, "end": 3673 }
class ____: """ Dataclass defining the serialization schema for Scorer objects. """ # Core scorer fields name: str aggregations: list[str] | None = None description: str | None = None # Version metadata mlflow_version: str = mlflow.__version__ serialization_version: int = _SERI...
SerializedScorer
python
tensorflow__tensorflow
tensorflow/python/distribute/experimental/rpc/rpc_ops.py
{ "start": 2293, "end": 4513 }
class ____(object): """A Server base class for accepting RPCs for registered tf.functions. Functions can be registered on the server and are exposed via RPCs. """ @staticmethod def create(rpc_layer, address): """Create TF RPC server at given address. Args: rpc_layer: Communication layer bet...
Server
python
scikit-image__scikit-image
tests/skimage/feature/test_texture.py
{ "start": 9188, "end": 12925 }
class ____: def setup_method(self): self.image = np.array( [ [255, 6, 255, 0, 141, 0], [48, 250, 204, 166, 223, 63], [8, 0, 159, 50, 255, 30], [167, 255, 63, 40, 128, 255], [0, 255, 30, 34, 255, 24], ...
TestLBP
python
readthedocs__readthedocs.org
readthedocs/builds/filters.py
{ "start": 533, "end": 2939 }
class ____(ModelFilterSet): """Project build list dashboard filter.""" STATE_ACTIVE = "active" STATE_SUCCESS = "succeeded" STATE_FAILED = "failed" STATE_CHOICES = ( (STATE_ACTIVE, _("Active")), (STATE_SUCCESS, _("Build successful")), (STATE_FAILED, _("Build failed")), )...
BuildListFilter
python
gevent__gevent
src/greentest/3.9/test_threading.py
{ "start": 2385, "end": 30789 }
class ____(BaseTestCase): # Create a bunch of threads, let each do some work, wait until all are # done. def test_various_ops(self): # This takes about n/3 seconds to run (about n/3 clumps of tasks, # times about 1 second per clump). NUMTASKS = 10 # no more than 3 of the 10...
ThreadTests
python
celery__celery
t/unit/backends/test_base.py
{ "start": 7330, "end": 10442 }
class ____: def setup_method(self): self.b = BaseBackend(self.app) @self.app.task(shared=False) def callback(result): pass self.callback = callback def test__forget(self): with pytest.raises(NotImplementedError): self.b._forget('SOMExx-N0Nex1st...
test_BaseBackend_interface
python
PrefectHQ__prefect
tests/runner/test_runner.py
{ "start": 2992, "end": 3099 }
class ____: @flow @classmethod def dummy_flow_classmethod(cls): pass
ClassNameClassmethod
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 992, "end": 1036 }
class ____(object): ... import builtins
B
python
pydantic__pydantic
pydantic/deprecated/config.py
{ "start": 2508, "end": 2663 }
class ____(metaclass=_ExtraMeta): allow: Literal['allow'] = 'allow' ignore: Literal['ignore'] = 'ignore' forbid: Literal['forbid'] = 'forbid'
Extra
python
huggingface__transformers
src/transformers/models/marian/modeling_marian.py
{ "start": 19069, "end": 19953 }
class ____(PreTrainedModel): config: MarianConfig base_model_prefix = "model" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = True @torch.no_grad() def _init_weights(self, module): ...
MarianPreTrainedModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1030641, "end": 1031164 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateIpAllowListEntry""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "ip_allow_list_entry") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client pe...
UpdateIpAllowListEntryPayload
python
getsentry__sentry
src/sentry/projects/services/project_key/model.py
{ "start": 380, "end": 781 }
class ____(Enum): store = "store" api = "api" def as_orm_role(self) -> Any: from sentry.models.projectkey import ProjectKey if self == ProjectKeyRole.store: return ProjectKey.roles.store elif self == ProjectKeyRole.api: return ProjectKey.roles.api el...
ProjectKeyRole
python
coleifer__peewee
peewee.py
{ "start": 269444, "end": 269806 }
class ____(ModelTupleCursorWrapper): def initialize(self): self._initialize_columns() attributes = [] for i in range(self.ncols): attributes.append(self.columns[i]) self.tuple_class = collections.namedtuple('Row', attributes) self.constructor = lambda row: self.tu...
ModelNamedTupleCursorWrapper
python
numba__numba
numba/tests/test_dictobject.py
{ "start": 36339, "end": 42573 }
class ____(MemoryLeakMixin, TestCase): def test_str_key(self): @njit def foo(): d = Dict.empty( key_type=types.unicode_type, value_type=types.int32, ) d["123"] = 123 d["321"] = 321 return d d = foo(...
TestDictRefctTypes
python
apache__airflow
helm-tests/tests/helm_tests/webserver/test_ingress_flower.py
{ "start": 932, "end": 9864 }
class ____: """Tests ingress flower.""" def test_should_pass_validation_with_just_ingress_enabled_v1(self): render_chart( values={"flower": {"enabled": True}, "ingress": {"flower": {"enabled": True}}}, show_only=["templates/flower/flower-ingress.yaml"], ) # checks that ...
TestIngressFlower
python
facebook__pyre-check
tools/upgrade/commands/codemods.py
{ "start": 652, "end": 2929 }
class ____(Command): def __init__(self, *, repository: Repository, only_fix_error_code: int) -> None: super().__init__(repository) self._only_fix_error_code: int = only_fix_error_code @staticmethod def from_arguments( arguments: argparse.Namespace, repository: Repository ) -> "M...
MissingOverrideReturnAnnotations
python
conda__conda
conda/common/_os/windows.py
{ "start": 2263, "end": 2506 }
class ____(IntEnum): HIDE = 0 MAXIMIZE = 3 MINIMIZE = 6 RESTORE = 9 SHOW = 5 SHOWDEFAULT = 10 SHOWMAXIMIZED = 3 SHOWMINIMIZED = 2 SHOWMINNOACTIVE = 7 SHOWNA = 8 SHOWNOACTIVATE = 4 SHOWNORMAL = 1
SW
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 46521, "end": 50428 }
class ____(ErniePreTrainedModel): def __init__(self, config): super().__init__(config) self.ernie = ErnieModel(config) self.cls = ErnieOnlyNSPHead(config) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def for...
ErnieForNextSentencePrediction
python
xlwings__xlwings
xlwings/constants.py
{ "start": 48287, "end": 48525 }
class ____: xlBeginsWith = 2 # from enum XlContainsOperator xlContains = 0 # from enum XlContainsOperator xlDoesNotContain = 1 # from enum XlContainsOperator xlEndsWith = 3 # from enum XlContainsOperator
ContainsOperator
python
huggingface__transformers
src/transformers/models/zamba2/modular_zamba2.py
{ "start": 3463, "end": 3509 }
class ____(ZambaRMSNorm): pass
Zamba2RMSNorm
python
scrapy__scrapy
tests/spiders.py
{ "start": 6538, "end": 6777 }
class ____(SimpleSpider): name = "asyncdef_asyncio_gen" async def parse(self, response): await asyncio.sleep(0.2) yield {"foo": 42} self.logger.info(f"Got response {response.status}")
AsyncDefAsyncioGenSpider
python
buildout__buildout
src/zc/buildout/easy_install.py
{ "start": 67641, "end": 82809 }
class ____(zc.buildout.UserError): """A specified version is incompatible with a given requirement. """ IncompatibleVersionError = IncompatibleConstraintError # Backward compatibility def call_pip_install(spec, dest, editable=False): """ Call `pip install` from a subprocess to install a distribut...
IncompatibleConstraintError
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 13036, "end": 13071 }
class ____(FromWKB): pass
FromWKT
python
pandas-dev__pandas
pandas/tests/series/test_subclass.py
{ "start": 213, "end": 2131 }
class ____: @pytest.mark.parametrize( "idx_method, indexer, exp_data, exp_idx", [ ["loc", ["a", "b"], [1, 2], "ab"], ["iloc", [2, 3], [3, 4], "cd"], ], ) def test_indexing_sliced(self, idx_method, indexer, exp_data, exp_idx): s = tm.SubclassedSeries([1...
TestSeriesSubclassing
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_api_server.py
{ "start": 24338, "end": 28855 }
class ____: """Tests api-server service.""" def test_default_service(self): docs = render_chart( show_only=["templates/api-server/api-server-service.yaml"], ) assert jmespath.search("metadata.name", docs[0]) == "release-name-api-server" assert jmespath.search("metad...
TestAPIServerService
python
encode__starlette
starlette/routing.py
{ "start": 22382, "end": 22721 }
class ____: def __init__(self, router: Router): self._router = router async def __aenter__(self) -> None: await self._router.startup() async def __aexit__(self, *exc_info: object) -> None: await self._router.shutdown() def __call__(self: _T, app: object) -> _T: return ...
_DefaultLifespan
python
huggingface__transformers
tests/models/granitemoehybrid/test_modeling_granitemoehybrid.py
{ "start": 1594, "end": 2642 }
class ____(BambaModelTester): config_class = GraniteMoeHybridConfig if is_torch_available(): model_class = GraniteMoeHybridModel for_causal_lm_class = GraniteMoeHybridForCausalLM def __init__( self, parent, use_cache=False, shared_intermediate_size=174, ...
GraniteMoeHybridModelTester
python
geekcomputers__Python
Flappy Bird - created with tkinter/Flappy Bird.py
{ "start": 836, "end": 2109 }
class ____: def __init__(self): self.image = pipe_image self.x = screen_width self.y = random.randint(150, screen_height - 150) self.vel = 5 def update(self): self.x -= self.vel def draw(self, screen): screen.blit(self.image, (self.x, self.y)) screen...
Pipe
python
getsentry__sentry
tests/sentry/integrations/slack/test_link_team.py
{ "start": 4283, "end": 8124 }
class ____(SlackIntegrationLinkTeamTestBase): def setUp(self) -> None: super().setUp() self.url = build_team_linking_url( integration=self.integration, slack_id=self.external_id, channel_id=self.channel_id, channel_name=self.channel_name, r...
SlackIntegrationLinkTeamTest
python
Textualize__textual
src/textual/notifications.py
{ "start": 1903, "end": 3714 }
class ____: """Class for managing a collection of notifications.""" def __init__(self) -> None: """Initialise the notification collection.""" self._notifications: dict[str, Notification] = {} def _reap(self) -> Self: """Remove any expired notifications from the notification collect...
Notifications
python
huggingface__transformers
src/transformers/models/emu3/image_processing_emu3.py
{ "start": 1440, "end": 2734 }
class ____(ImagesKwargs, total=False): ratio: str image_area: int def smart_resize( height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280 ): """Rescales the image so that the following conditions are met: 1. Both dimensions (height and width) a...
Emu3ImageProcessorKwargs
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 35580, "end": 38695 }
class ____(OrderedDictTests, CPythonOrderedDictSideEffects, __TestCase): module = c_coll OrderedDict = c_coll.OrderedDict check_sizeof = support.check_sizeof @support.cpython_only def test_sizeof_exact(self): OrderedDict = self.Or...
CPythonOrderedDictTests
python
kamyu104__LeetCode-Solutions
Python/number-of-ships-in-a-rectangle.py
{ "start": 471, "end": 1393 }
class ____(object): def countShips(self, sea, topRight, bottomLeft): """ :type sea: Sea :type topRight: Point :type bottomLeft: Point :rtype: integer """ result = 0 if topRight.x >= bottomLeft.x and \ topRight.y >= bottomLeft.y and \ ...
Solution
python
django__django
tests/admin_utils/models.py
{ "start": 119, "end": 244 }
class ____(models.Model): domain = models.CharField(max_length=100) def __str__(self): return self.domain
Site
python
keras-team__keras
keras/src/ops/operation_test.py
{ "start": 1910, "end": 2239 }
class ____(operation.Operation): def __init__(self, alpha, *args, name=None): super().__init__(name=name) self.alpha = alpha def call(self, x): return self.alpha * x + self.beta def compute_output_spec(self, x): return keras_tensor.KerasTensor(x.shape, x.dtype)
OpWithArgsInConstructor
python
pyinstaller__pyinstaller
tests/unit/test_hookutils.py
{ "start": 996, "end": 1819 }
class ____(object): # Verify that removing a prefix from an empty string is OK. def test_empty_string(self): assert '' == hookutils.remove_prefix('', 'prefix') # An empty prefix should pass the string through unmodified. def test_emptystr_unmodif(self): assert 'test' == hookutils.remove...
TestRemovePrefix
python
python-rapidjson__python-rapidjson
tests/test_dict_subclass.py
{ "start": 884, "end": 1671 }
class ____(ObjectsAsKeyValuePairsDecoder): def end_object(self, ordered_pairs): # Adapted from https://stackoverflow.com/a/38307621 d = {} for k, v in ordered_pairs: if k in d: if type(d[k]) == list: d[k].append(v) else: ...
JoinDuplicatedKeysDecoder
python
sphinx-doc__sphinx
tests/test_builders/test_build_epub.py
{ "start": 825, "end": 23737 }
class ____: """Test helper for content.opf and toc.ncx""" namespaces = { 'idpf': 'http://www.idpf.org/2007/opf', 'dc': 'http://purl.org/dc/elements/1.1/', 'ibooks': 'http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/', 'ncx': 'http://www.daisy.org/z3986/200...
EPUBElementTree
python
sqlalchemy__sqlalchemy
test/sql/test_selectable.py
{ "start": 84535, "end": 94730 }
class ____(fixtures.TestBase, AssertsExecutionResults): def test_reduce(self): meta = MetaData() t1 = Table( "t1", meta, Column("t1id", Integer, primary_key=True), Column("t1data", String(30)), ) t2 = Table( "t2", ...
ReduceTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 83631, "end": 87479 }
class ____(GoogleCloudBaseOperator): """ Lists InspectTemplates. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPListInspectTemplatesOperator` :param organization_id: (Optional) The organization ID. Required to set t...
CloudDLPListInspectTemplatesOperator
python
sphinx-doc__sphinx
tests/test_builders/test_build_linkcheck.py
{ "start": 1264, "end": 2372 }
class ____(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_HEAD(self) -> None: if self.path[1:].rstrip() in {'', 'anchor.html'}: self.send_response(200, 'OK') self.send_header('Content-Length', '0') self.end_headers() else: self.send...
DefaultsHandler
python
google__jax
jax/_src/interpreters/partial_eval.py
{ "start": 110455, "end": 116718 }
class ____: ... dne_sentinel = DoesNotExist() def infer_lambda_input_type( axes_specs: Sequence[AbstractedAxesSpec] | None, args: Sequence[Any] ) -> InputType: ndims = [getattr(get_aval(x), 'ndim', 0) for x in args] partial_specs = _canonicalize_specs(ndims, axes_specs) specs = _complete_specs(args, p...
DoesNotExist
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 14941, "end": 16486 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to create a task run""" id: Optional[UUID] = Field(None, description="The ID to assign to the task run") # TaskRunCreate states must be provided as StateCreate objects state: Optional[StateCreate] = Field( default=None, descripti...
TaskRunCreate
python
getsentry__sentry
tests/sentry/integrations/github/test_webhooks.py
{ "start": 6203, "end": 13750 }
class ____(APITestCase): base_url = "https://api.github.com" def setUp(self) -> None: self.url = "/extensions/github/webhook/" self.secret = "b3002c3e321d4b7880360d397db2ccfd" options.set("github-app.webhook-secret", self.secret) @patch("sentry.integrations.github.client.get_jwt", ...
InstallationDeleteEventWebhookTest
python
lepture__authlib
authlib/integrations/flask_oauth2/requests.py
{ "start": 675, "end": 1093 }
class ____(OAuth2Request): def __init__(self, request: Request): super().__init__( method=request.method, uri=request.url, headers=request.headers ) self._request = request self.payload = FlaskOAuth2Payload(request) @property def args(self): return self._...
FlaskOAuth2Request
python
PyCQA__pylint
doc/data/messages/a/abstract-method/good/function_raising_not_implemented_error.py
{ "start": 73, "end": 139 }
class ____(Pet): def make_sound(self): print("Meeeow")
Cat
python
pytest-dev__pytest
testing/code/test_source.py
{ "start": 2417, "end": 12966 }
class ____: def setup_class(self) -> None: self.source = Source( """\ def f(x): assert (x == 3 + 4) """ ).strip() def test_getstatement(self) -> None: # print str(self.source) ass = s...
TestSourceParsing
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_ops_test.py
{ "start": 56510, "end": 69388 }
class ____(test.Benchmark): def benchmark_sparse_matrix_mat_mul_gpu(self): if not test_util.is_gpu_available(): return sparsify = lambda m: array_ops.where(m > 2, m, array_ops.zeros_like(m)) # XW, X dense and W sparse # X is shaped [{1, 8, 16}, 2000] # W is shaped [2000, 4000] for ba...
CSRSparseMatrixOpsBenchmark
python
pytorch__pytorch
test/distributed/test_store.py
{ "start": 8923, "end": 10331 }
class ____(TestCase, StoreTestBase): def setUp(self): super().setUp() self.file = tempfile.NamedTemporaryFile(delete=False) def _create_store(self): store = dist.FileStore(self.file.name, 1) store.set_timeout(timedelta(seconds=300)) return store def test_init_pg_and...
FileStoreTest
python
Textualize__textual
src/textual/await_remove.py
{ "start": 362, "end": 1345 }
class ____: """An awaitable that waits for nodes to be removed.""" def __init__( self, tasks: list[Task], post_remove: CallbackType | None = None ) -> None: self._tasks = tasks self._post_remove = post_remove self._caller = get_caller_file_and_line() def __rich_repr__(s...
AwaitRemove
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 3729, "end": 3842 }
class ____(MilvusException): """Raise when server version is incompatible"""
ServerVersionIncompatibleException
python
redis__redis-py
redis/asyncio/multidb/event.py
{ "start": 1042, "end": 1797 }
class ____(AsyncEventListenerInterface): """ Re-subscribe the currently active pub / sub to a new active database. """ async def listen(self, event: AsyncActiveDatabaseChanged): old_pubsub = event.command_executor.active_pubsub if old_pubsub is not None: # Re-assign old cha...
ResubscribeOnActiveDatabaseChanged
python
apache__airflow
airflow-core/tests/unit/models/test_xcom.py
{ "start": 4014, "end": 6907 }
class ____: @conf_vars({("core", "xcom_backend"): "unit.models.test_xcom.CustomXCom"}) def test_resolve_xcom_class(self): cls = resolve_xcom_backend() assert issubclass(cls, CustomXCom) @conf_vars({("core", "xcom_backend"): ""}) def test_resolve_xcom_class_fallback_to_basexcom(self): ...
TestXCom
python
Netflix__metaflow
metaflow/plugins/env_escape/override_decorators.py
{ "start": 2668, "end": 2992 }
class ____(object): def __init__(self, class_path, deserializer): self._class_path = class_path self._deserializer = deserializer @property def class_path(self): return self._class_path @property def deserializer(self): return self._deserializer
LocalExceptionDeserializer
python
django__django
tests/urlpatterns_reverse/middleware.py
{ "start": 176, "end": 315 }
class ____(MiddlewareMixin): def process_request(self, request): request.urlconf = urlconf_inner.__name__
ChangeURLconfMiddleware
python
walkccc__LeetCode
solutions/438. Find All Anagrams in a String/438.py
{ "start": 0, "end": 430 }
class ____: def findAnagrams(self, s: str, p: str) -> list[int]: ans = [] count = collections.Counter(p) required = len(p) for r, c in enumerate(s): count[c] -= 1 if count[c] >= 0: required -= 1 if r >= len(p): count[s[r - len(p)]] += 1 if count[s[r - len(p)]...
Solution
python
PrefectHQ__prefect
src/prefect/utilities/dockerutils.py
{ "start": 4240, "end": 6532 }
class ____(Exception): """Raised when a Docker build fails""" # Labels to apply to all images built with Prefect IMAGE_LABELS = { "io.prefect.version": prefect.__version__, } @silence_docker_warnings() def build_image( context: Path, dockerfile: str = "Dockerfile", tag: Optional[str] = None, ...
BuildError
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/sensors/spark_kubernetes.py
{ "start": 1223, "end": 5371 }
class ____(BaseSensorOperator): """ Checks sparkApplication object in kubernetes cluster. .. seealso:: For more detail about Spark Application Object have a look at the reference: https://github.com/GoogleCloudPlatform/spark-on-k8s-operator/blob/v1beta2-1.1.0-2.4.5/docs/api-docs.md#sparkapp...
SparkKubernetesSensor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/gcs_to_local.py
{ "start": 1278, "end": 5851 }
class ____(BaseOperator): """ Downloads a file from Google Cloud Storage. If a filename is supplied, it writes the file to the specified location, alternatively one can set the ``store_to_xcom_key`` parameter to True push the file content into xcom. When the file size exceeds the maximum size for x...
GCSToLocalFilesystemOperator
python
django__django
tests/db_functions/math/test_cot.py
{ "start": 268, "end": 2292 }
class ____(TestCase): def test_null(self): IntegerModel.objects.create() obj = IntegerModel.objects.annotate(null_cot=Cot("normal")).first() self.assertIsNone(obj.null_cot) def test_decimal(self): DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6")) obj = ...
CotTests
python
apache__airflow
providers/alibaba/src/airflow/providers/alibaba/cloud/operators/analyticdb_spark.py
{ "start": 5322, "end": 8139 }
class ____(AnalyticDBSparkBaseOperator): """ Submits a Spark batch application to the underlying cluster; wraps the AnalyticDB Spark REST API. :param file: path of the file containing the application to execute. :param class_name: name of the application Java/Spark main class. :param args: applicat...
AnalyticDBSparkBatchOperator
python
getsentry__sentry
tests/sentry/ratelimits/utils/test_enforce_rate_limit.py
{ "start": 1628, "end": 1962 }
class ____(APITestCase): endpoint = "unenforced-endpoint" def test_unenforced_rate_limit(self) -> None: """Endpoints with enforce_rate_limit disabled shouldn't reject requests""" with freeze_time("2000-01-01"): self.get_success_response() self.get_success_response()
UnEnforceRateLimitTest
python
apache__avro
lang/py/avro/ipc.py
{ "start": 15888, "end": 17015 }
class ____: """Wrapper around a file-like object to write framed data.""" def __init__(self, writer): self._writer = writer # read-only properties @property def writer(self): return self._writer def write_framed_message(self, message): message_length = len(message) ...
FramedWriter
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_pgf.py
{ "start": 29488, "end": 34774 }
class ____(FigureCanvasBase): filetypes = {"pgf": "LaTeX PGF picture", "pdf": "LaTeX compiled PGF picture", "png": "Portable Network Graphics", } def get_default_filetype(self): return 'pdf' def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None): hea...
FigureCanvasPgf
python
neetcode-gh__leetcode
python/0269-alien-dictionary.py
{ "start": 0, "end": 1044 }
class ____: def alienOrder(self, words: List[str]) -> str: adj = {char: set() for word in words for char in word} for i in range(len(words) - 1): w1, w2 = words[i], words[i + 1] minLen = min(len(w1), len(w2)) if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: ...
Solution
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_include.py
{ "start": 1407, "end": 4135 }
class ____: def test_include_with_prefix(self) -> None: class IncludesDelegateWithPrefix(HasProps): z = bcpi.Include(IsDelegate, prefix="z") o = IncludesDelegateWithPrefix() assert o.z_x == 12 assert o.z_y == "hello" assert not hasattr(o, 'z') assert not...
Test_Include
python
walkccc__LeetCode
solutions/3082. Find the Sum of the Power of All Subsequences/3082-3.py
{ "start": 0, "end": 384 }
class ____: def sumOfPower(self, nums: list[int], k: int) -> int: MOD = 1_000_000_007 # dp[i] := the number of subsequences in nums so far that sums to k dp = [1] + [0] * k for num in nums: for i in range(k, -1, -1): if i < num: dp[i] = (dp[i] * 2) % MOD else: ...
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 919084, "end": 919467 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "branch_protection_rule") actor = sgqlc.types.Field("PushAllowanceActor", graphql_name="actor") branch_protection_rule = sgqlc.types.Field( BranchProtec...
PushAllowance
python
python__mypy
mypy/plugin.py
{ "start": 17252, "end": 18438 }
class ____(NamedTuple): arg_types: list[list[Type]] # List of actual caller types for each formal argument arg_kinds: list[list[ArgKind]] # Ditto for argument kinds, see nodes.ARG_* constants # Names of formal parameters from the callee definition, # these will be sufficient in most cases. callee_...
FunctionContext
python
python-openxml__python-docx
src/docx/image/image.py
{ "start": 387, "end": 6381 }
class ____: """Graphical image stream such as JPEG, PNG, or GIF with properties and methods required by ImagePart.""" def __init__(self, blob: bytes, filename: str, image_header: BaseImageHeader): super(Image, self).__init__() self._blob = blob self._filename = filename self...
Image
python
encode__django-rest-framework
tests/test_throttling.py
{ "start": 1630, "end": 1777 }
class ____(APIView): throttle_classes = (NonTimeThrottle,) def get(self, request): return Response('foo')
MockView_NonTimeThrottling
python
plotly__plotly.py
plotly/graph_objs/_mesh3d.py
{ "start": 215, "end": 94824 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "mesh3d" _valid_props = { "alphahull", "autocolorscale", "cauto", "cmax", "cmid", "cmin", "color", "coloraxis", "colorbar", "colorscale", "contour", "...
Mesh3d
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 205, "end": 1776 }
class ____(GeneratedAirbyteDestination): @public def __init__( self, name: str, dynamodb_table_name_prefix: str, dynamodb_region: str, access_key_id: str, secret_access_key: str, dynamodb_endpoint: Optional[str] = None, ): """Airbyte Destinatio...
DynamodbDestination
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 202228, "end": 203576 }
class ____(ParseElementEnhance): """ Decorates a returned token with its starting and ending locations in the input string. This helper adds the following results names: - ``locn_start`` - location where matched expression begins - ``locn_end`` - location where matched expression ends - ``...
Located
python
tensorflow__tensorflow
tensorflow/python/distribute/random_generator_test.py
{ "start": 3179, "end": 13650 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): super(GeneratorTest, self).setUp() v2_compat.enable_v2_behavior() def assertAllDifferent(self, tensors): """Checks that there are no duplicate elements anywhere among the tensors. Args: tensors: a list of tensors. They can ...
GeneratorTest
python
sympy__sympy
sympy/functions/special/bessel.py
{ "start": 37967, "end": 41856 }
class ____(SphericalHankelBase): r""" Spherical Hankel function of the second kind. Explanation =========== This function is defined as .. math:: h_\nu^(2)(z) = j_\nu(z) - i y_\nu(z), where $j_\nu(z)$ and $y_\nu(z)$ are the spherical Bessel function of the first and second kinds. ...
hn2
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_import_errors.py
{ "start": 598, "end": 10244 }
class ____(AdminTestMixin, TestCase): def test_import_action_handles_UnicodeDecodeError_as_form_error(self): with mock.patch( "import_export.admin.TempFolderStorage.read" ) as mock_tmp_folder_storage: b_arr = b"\x00" mock_tmp_folder_storage.side_effect = UnicodeD...
ImportErrorHandlingTests
python
django__django
tests/test_client_regress/tests.py
{ "start": 32819, "end": 33206 }
class ____(SimpleTestCase): def test_urlconf_was_changed(self): "TestCase can enforce a custom URLconf on a per-test basis" url = reverse("arg_view", args=["somename"]) self.assertEqual(url, "/arg_view/somename/") # This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in ...
UrlconfSubstitutionTests
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 60978, "end": 65535 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "people", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("type", String(30)), ) T...
JoinedInhAdjacencyTest
python
huggingface__transformers
tests/utils/test_convert_slow_tokenizer.py
{ "start": 245, "end": 1740 }
class ____(unittest.TestCase): def test_spm_converter_bytefallback_warning(self): spm_model_file_without_bytefallback = get_tests_dir("fixtures/test_sentencepiece.model") spm_model_file_with_bytefallback = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model") original_tokeniz...
ConvertSlowTokenizerTest
python
realpython__materials
solid-principles-python/shapes_lsp.py
{ "start": 662, "end": 854 }
class ____(Shape): def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height
Rectangle
python
gevent__gevent
src/gevent/tests/known_failures.py
{ "start": 1209, "end": 1598 }
class ____(Condition): __slots__ = ( 'value', '__name__', ) def __init__(self, value, name=None): self.value = bool(value) self.__name__ = name or str(value) def __bool__(self): return self.value def __repr__(self): return self.__name__ ALWAYS = Co...
ConstantCondition
python
huggingface__transformers
src/transformers/models/lfm2_vl/processing_lfm2_vl.py
{ "start": 1524, "end": 11207 }
class ____(ProcessorMixin): r""" Constructs a Lfm2Vl processor which wraps a Lfm2Tokenizer tokenizer and Lfm2VlImageProcessor into a single processor. [`Lfm2VlProcessor`] offers all the functionalities of [`Lfm2ImageProcessor`] and [`Lfm2Tokenizer`]. Args: image_processor (`Lfm2VlImageProcesso...
Lfm2VlProcessor
python
conda__conda
conda/base/context.py
{ "start": 80739, "end": 89977 }
class ____: def __init__(self): self._stack = [ContextStackObject() for _ in range(3)] self._stack_idx = 0 self._last_search_path = None self._last_argparse_args = None def push(self, search_path: PathsType, argparse_args: Namespace | None) -> None: self._stack_idx += 1 ...
ContextStack
python
kamyu104__LeetCode-Solutions
Python/maximum-strong-pair-xor-i.py
{ "start": 120, "end": 1985 }
class ____(object): def maximumStrongPairXor(self, nums): """ :type nums: List[int] :rtype: int """ class Trie(object): def __init__(self, bit_length): self.__nodes = [] self.__cnts = [] self.__new_node() ...
Solution
python
google__jax
jax/experimental/jax2tf/tests/flax_models/transformer_nlp_seq.py
{ "start": 4609, "end": 5790 }
class ____(nn.Module): """Transformer encoder layer. Attributes: config: TransformerConfig dataclass containing hyperparameters. """ config: TransformerConfig @nn.compact def __call__(self, inputs, deterministic): """Applies Encoder1DBlock module. Args: inputs: input data. determi...
Encoder1DBlock
python
numba__numba
numba/tests/test_listobject.py
{ "start": 21503, "end": 24373 }
class ____(MemoryLeakMixin, TestCase): """Test list delitem. """ def test_list_singleton_delitem_index(self): @njit def foo(): l = listobject.new_list(int32) l.append(0) del l[0] return len(l) self.assertEqual(foo(), 0) def test_...
TestListObjectDelitem
python
getlogbook__logbook
src/logbook/ticketing.py
{ "start": 15881, "end": 16673 }
class ____(Handler, HashingHandlerMixin): """Baseclass for ticketing handlers. This can be used to interface ticketing systems that do not necessarily provide an interface that would be compatible with the :class:`BackendBase` interface. """ def __init__(self, hash_salt, level=NOTSET, filter=None,...
TicketingBaseHandler
python
walkccc__LeetCode
solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py
{ "start": 0, "end": 523 }
class ____: def numSteps(self, s: str) -> int: ans = 0 chars = list(s) # All the trailing 0s can be popped by 1 step. while chars[-1] == '0': chars.pop() ans += 1 if ''.join(chars) == '1': return ans # `s` is now odd, so add 1 to `s` and cost 1 step. # All the 1s will ...
Solution
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/py_test_callback/package.py
{ "start": 998, "end": 1353 }
class ____(BuilderWithDefaults): phases = ("install",) #: Callback names for install-time test install_time_test_callbacks = ["test_callback"] def install(self, pkg, spec, prefix): pkg.install(spec, prefix) run_after("install")(execute_install_time_tests) def test_callback(self): ...
MyBuilder
python
xlwings__xlwings
xlwings/_win32patch.py
{ "start": 1803, "end": 3353 }
class ____: def __init__(self, oobj=None): if oobj is None: oobj = pythoncom.new(self.CLSID) self.__dict__["_dispobj_"] = self.default_interface(oobj) def __repr__(self): return "<win32com.gen_py.%s.%s>" % (__doc__, self.__class__.__name__) def __getattr__(self, attr): ...
CoClassBaseClass
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 87060, "end": 89380 }
class ____(Elemwise): _parameters = ["left", "right"] @functools.cached_property def _broadcastable(self): deps = self.dependencies() return ( 1 in {dep.npartitions for dep in deps} and len({dep.ndim for dep in deps}) == 2 ) def __str__(self): re...
Binop
python
ansible__ansible
test/lib/ansible_test/_internal/cli/environments.py
{ "start": 1248, "end": 21511 }
class ____(enum.Enum): """Type of provisioning to use for the controller.""" NO_DELEGATION = enum.auto() ORIGIN = enum.auto() DELEGATED = enum.auto() def add_environments( parser: argparse.ArgumentParser, completer: CompositeActionCompletionFinder, controller_mode: ControllerMode, tar...
ControllerMode
python
google__pytype
pytype/matcher.py
{ "start": 2312, "end": 2651 }
class ____: """An expected type/actual value mismatch.""" view: _ViewType expected: error_types.BadType actual: cfg.Variable @property def actual_binding(self): return self.view[self.actual] @property def error_details(self): return self.expected.error_details @dataclasses.dataclass(eq=True...
BadMatch
python
sqlalchemy__sqlalchemy
test/orm/test_selectin_relations.py
{ "start": 91741, "end": 94303 }
class ____( fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL ): __dialect__ = "default" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Foo(ComparableEntity, Base): __tablename__ = "foo" id = Column(Integer, primary_key=True) ...
SelfRefInheritanceAliasedTest
python
fluentpython__example-code-2e
10-dp-1class-func/pytypes/classic_strategy.py
{ "start": 1133, "end": 1213 }
class ____(typing.NamedTuple): name: str fidelity: int @typelogged
Customer
python
getsentry__sentry
src/sentry/monitors/processing_errors/errors.py
{ "start": 1344, "end": 1521 }
class ____(TypedDict): """ The checkin was already completed and we attempted to modify it """ type: Literal[ProcessingErrorType.CHECKIN_FINISHED]
CheckinFinished
python
airbytehq__airbyte
airbyte-integrations/connectors/source-sftp-bulk/source_sftp_bulk/spec.py
{ "start": 643, "end": 1006 }
class ____(BaseModel): class Config(OneOfOptionConfig): title = "Authenticate via Private Key" discriminator = "auth_type" auth_type: Literal["private_key"] = Field("private_key", const=True) private_key: str = Field(title="Private key", description="The Private key", multiline=True, order=...
PrivateKeyCredentials
python
optuna__optuna
tests/storages_tests/journal_tests/test_journal.py
{ "start": 1342, "end": 10865 }
class ____: def __init__(self, storage_type: str, grace_period: int | None) -> None: self.storage_type = storage_type self.tempfile: IO[Any] | None = None self.grace_period = grace_period def __enter__(self) -> optuna.storages.journal.BaseJournalBackend: if self.storage_type.sta...
JournalLogStorageSupplier