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
conda__conda
conda/exceptions.py
{ "start": 14888, "end": 15440 }
class ____(CondaError): def __init__(self, message: str | None = None): if message is None: message = dals( """ Conda cannot proceed due to an error in your proxy configuration. Check for typos and other configuration errors in any '.netrc' file in...
ProxyError
python
run-llama__llama_index
llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py
{ "start": 2176, "end": 2578 }
class ____(BaseVoiceAgentEvent): audio: Union[bytes, str] @model_validator(mode="after") def validate_audio_input(self) -> Self: try: base64.b64decode(self.audio, validate=True) except binascii.Error: if isinstance(self.audio, bytes): self.audio = bas...
ConversationInputEvent
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 18637, "end": 18877 }
class ____: def test_endpoints(self): # Regression test for gh-13697. The following calculation # should not generate a warning. p = stats.arcsine.pdf([0, 1]) assert_equal(p, [np.inf, np.inf])
TestArcsine
python
readthedocs__readthedocs.org
readthedocs/projects/tests/test_views.py
{ "start": 6332, "end": 11433 }
class ____(TestCase): def setUp(self): self.user = get(User) get(EmailAddress, email=self.user.email, user=self.user, verified=True) self.project = get(Project, users=[self.user]) self.another_user = get(User) get( EmailAddress, email=self.another_user...
TestProjectUsersViews
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/xcom.py
{ "start": 1267, "end": 1407 }
class ____(RootModel): """XCom schema with minimal structure for slice-based access.""" root: list[JsonValue]
XComSequenceSliceResponse
python
sympy__sympy
sympy/polys/domains/mpelements.py
{ "start": 1183, "end": 5042 }
class ____(PythonMPContext): def __init__(ctx, prec=53, dps=None, tol=None, real=False): ctx._prec_rounding = [prec, round_nearest] if dps is None: ctx._set_prec(prec) else: ctx._set_dps(dps) ctx.mpf = RealElement ctx.mpc = ComplexElement ct...
MPContext
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 94655, "end": 95612 }
class ____(MeanMetricWrapper): """Computes the mean squared logarithmic error between `y_true` and `y_pred`. Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. Standalone usage: >>> m = tf.keras.metrics.MeanSquaredLogarithmicError() >>> m.up...
MeanSquaredLogarithmicError
python
sympy__sympy
sympy/assumptions/assume.py
{ "start": 6485, "end": 10738 }
class ____(Boolean, metaclass=PredicateMeta): """ Base class for mathematical predicates. It also serves as a constructor for undefined predicate objects. Explanation =========== Predicate is a function that returns a boolean value [1]. Predicate function is object, and it is instance of ...
Predicate
python
TheAlgorithms__Python
data_structures/heap/min_heap.py
{ "start": 338, "end": 4507 }
class ____: """ >>> r = Node("R", -1) >>> b = Node("B", 6) >>> a = Node("A", 3) >>> x = Node("X", 1) >>> e = Node("E", 4) >>> print(b) Node(B, 6) >>> myMinHeap = MinHeap([r, b, a, x, e]) >>> myMinHeap.decrease_key(b, -17) >>> print(b) Node(B, -17) >>> myMinHeap["B"] ...
MinHeap
python
realpython__materials
python-tic-tac-toe-game-tkinter/source_code_final/tic_tac_toe.py
{ "start": 3092, "end": 6773 }
class ____(tk.Tk): def __init__(self, game): super().__init__() self.title("Tic-Tac-Toe Game") self._cells = {} self._game = game self._create_menu() self._create_board_display() self._create_board_grid() def _create_menu(self): menu_bar = tk.Menu...
TicTacToeBoard
python
django__django
django/db/models/lookups.py
{ "start": 15760, "end": 15850 }
class ____(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lte"
LessThanOrEqual
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/data_structures.py
{ "start": 157, "end": 212 }
class ____(NamedTuple): rows: int columns: int
Size
python
pytorch__pytorch
test/jit/test_dataclasses.py
{ "start": 1192, "end": 1501 }
class ____: def __init__(self, alpha: float = 0.125, scheme: MixupScheme2 = MixupScheme2.A): self.alpha = alpha self.scheme = scheme # Make sure the Meta internal tooling doesn't raise an overflow error NonHugeFloats = st.floats(min_value=-1e4, max_value=1e4, allow_nan=False)
MixupParams3
python
encode__django-rest-framework
tests/test_bound_fields.py
{ "start": 8368, "end": 8807 }
class ____: def test_as_form_fields(self): class TestSerializer(serializers.Serializer): json_field = serializers.JSONField() data = QueryDict(mutable=True) data.update({'json_field': '{"some": ["json"}'}) serializer = TestSerializer(data=data) assert serializer....
TestJSONBoundField
python
scikit-learn__scikit-learn
sklearn/linear_model/_passive_aggressive.py
{ "start": 579, "end": 11969 }
class ____(BaseSGDClassifier): """Passive Aggressive Classifier. .. deprecated:: 1.8 The whole class `PassiveAggressiveClassifier` was deprecated in version 1.8 and will be removed in 1.10. Instead use: .. code-block:: python clf = SGDClassifier( loss="hing...
PassiveAggressiveClassifier
python
astropy__astropy
astropy/coordinates/tests/test_geodetic_representations.py
{ "start": 669, "end": 10163 }
class ____: @classmethod def setup_class(cls): # Preserve the original REPRESENTATION_CLASSES dict so that importing # the test file doesn't add a persistent test subclass (CustomGeodetic, etc.) cls.REPRESENTATION_CLASSES_ORIG = deepcopy(REPRESENTATION_CLASSES) cls.DUPLICATE_REPR...
TestCustomGeodeticRepresentations
python
facebookresearch__faiss
tests/test_residual_quantizer.py
{ "start": 40015, "end": 41841 }
class ____(unittest.TestCase): def test_accuracy1(self): """check that the error is in the same ballpark as RQ.""" recall1 = self.eval_index_accuracy("PRQ4x3x5_Nqint8") recall2 = self.eval_index_accuracy("RQ12x5_Nqint8") self.assertGreaterEqual(recall1 * 1.1, recall2) # 657 vs 665 ...
TestIndexProductResidualQuantizer
python
huggingface__transformers
tests/models/instructblipvideo/test_modeling_instructblipvideo.py
{ "start": 25930, "end": 26917 }
class ____(unittest.TestCase): def test_inference_vicuna_7b(self): processor = InstructBlipVideoProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b") model = InstructBlipVideoForConditionalGeneration.from_pretrained( "Salesforce/instructblip-vicuna-7b", quantization_...
InstructBlipVideoModelIntegrationTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/logging_ops_test.py
{ "start": 2464, "end": 13491 }
class ____(test.TestCase): def testPrintOneTensor(self): tensor = math_ops.range(10) with self.captureWritesToStream(sys.stderr) as printed: print_op = logging_ops.print_v2(tensor) self.evaluate(print_op) expected = "[0 1 2 ... 7 8 9]" self.assertIn((expected + "\n"), printed.contents())...
PrintV2Test
python
facebook__pyre-check
scripts/shape_type_coverage.py
{ "start": 639, "end": 727 }
class ____: name: str parameters: List[str] @dataclass(frozen=True)
ParametricType
python
getsentry__sentry
tests/sentry/web/frontend/test_oauth_authorize.py
{ "start": 46498, "end": 54835 }
class ____(TestCase): """Tests for OAuth flows using custom URI schemes with strict matching (version 1).""" @cached_property def path(self) -> str: return "/oauth/authorize/" def setUp(self) -> None: super().setUp() self.custom_uri = "sentry-mobile-agent://sentry.io/auth" ...
OAuthAuthorizeCustomSchemeStrictTest
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dtbuild2/package.py
{ "start": 217, "end": 483 }
class ____(Package): """Simple package which acts as a build dependency""" homepage = "http://www.example.com" url = "http://www.example.com/dtbuild2-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") provides("vdtbuild2")
Dtbuild2
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 799, "end": 870 }
class ____(Model2A): field2 = models.CharField(max_length=30)
Model2B
python
ray-project__ray
python/ray/serve/tests/test_config_files/multi_fastapi.py
{ "start": 173, "end": 278 }
class ____: def add(self, a: int): return a + 1 @serve.deployment @serve.ingress(app1)
SubModel
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 247766, "end": 249663 }
class ____(Annotated): def _copy_internals( self, _annotations_traversal: bool = False, ind_cols_on_fromclause: bool = False, **kw: Any, ) -> None: super()._copy_internals(**kw) # passed from annotations._shallow_annotate(), _deep_annotate(), etc. # the t...
AnnotatedFromClause
python
apache__airflow
providers/dingding/tests/unit/dingding/hooks/test_dingding.py
{ "start": 958, "end": 8788 }
class ____: conn_id = "dingding_conn_id_test" @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id=self.conn_id, conn_type="dingding", host="https://oapi...
TestDingdingHook
python
doocs__leetcode
solution/3100-3199/3120.Count the Number of Special Characters I/Solution.py
{ "start": 0, "end": 180 }
class ____: def numberOfSpecialChars(self, word: str) -> int: s = set(word) return sum(a in s and b in s for a, b in zip(ascii_lowercase, ascii_uppercase))
Solution
python
pypa__warehouse
warehouse/search/services.py
{ "start": 710, "end": 998 }
class ____: def __init__(self, **kwargs): pass @classmethod def create_service(cls, context, request): return cls() def reindex(self, config, projects_to_update): pass def unindex(self, config, projects_to_delete): pass
NullSearchService
python
ray-project__ray
python/ray/train/v2/_internal/exceptions.py
{ "start": 441, "end": 976 }
class ____(RayTrainError): """Exception raised when a worker health check hangs for long enough.""" def __init__(self, message): timeout = os.getenv( WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S ) message += ( f"\nSet the {WORKER_H...
WorkerHealthCheckTimeoutError
python
scikit-learn__scikit-learn
sklearn/tests/test_metadata_routing.py
{ "start": 1446, "end": 40566 }
class ____(BaseEstimator): """A very simple pipeline, assuming the last step is always a predictor. Parameters ---------- steps : iterable of objects An iterable of transformers with the last step being a predictor. """ def __init__(self, steps): self.steps = steps def fit...
SimplePipeline
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor16.py
{ "start": 178, "end": 292 }
class ____(A): def __new__(cls) -> A: return A() def __init__(self, a: int) -> None: pass
B
python
tensorflow__tensorflow
tensorflow/python/checkpoint/saveable_compat_test.py
{ "start": 2892, "end": 6532 }
class ____(test.TestCase): def test_checkpoint(self): saveable_compat.force_checkpoint_conversion() table_module = generate_checkpoint.TableModule() table_module.lookup_table.insert(3, 9) ckpt = checkpoint.Checkpoint(table_module) checkpoint_directory = self.get_temp_dir() checkpoint_path = ...
TestForceCheckpointConversionFlag
python
pandas-dev__pandas
pandas/core/arrays/sparse/accessor.py
{ "start": 577, "end": 954 }
class ____: _validation_msg = "Can only use the '.sparse' accessor with Sparse data." def __init__(self, data=None) -> None: self._parent = data self._validate(data) def _validate(self, data) -> None: raise NotImplementedError @delegate_names( SparseArray, ["npoints", "densit...
BaseAccessor
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 192012, "end": 193639 }
class ____: def test_string(self): g1 = np.array(["This", "is", "example"]) g2 = np.array(["This", "was", "example"]) assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) assert_array_equal(g1 <= g...
TestStringCompare
python
encode__django-rest-framework
tests/test_permissions.py
{ "start": 19458, "end": 19540 }
class ____(PermissionInstanceView): permission_classes = (BasicPerm,)
DeniedView
python
pexpect__pexpect
tests/test_winsize.py
{ "start": 1035, "end": 2377 }
class ____(PexpectTestCase.PexpectTestCase): def test_initial_winsize(self): """ Assert initial window dimension size (24, 80). """ p = pexpect.spawn('{self.PYTHONBIN} sigwinch_report.py' .format(self=self), timeout=3) # default size by PtyProcess class is 24 rows ...
TestCaseWinsize
python
davidhalter__jedi
test/completion/flow_analysis.py
{ "start": 3590, "end": 4266 }
class ____(): pass if X: a = 1 else: a = '' #? int() a # ----------------- # Recursion issues # ----------------- def possible_recursion_error(filename): if filename == 'a': return filename # It seems like without the brackets there wouldn't be a RecursionError. elif type(filename) ==...
X
python
google__pytype
pytype/compare_test.py
{ "start": 14586, "end": 14805 }
class ____(CompareTestBase): def test_compatible_with(self): cls = abstract.InterpreterClass("X", [], {}, None, None, (), self._ctx) self.assertTruthy(cls) if __name__ == "__main__": unittest.main()
ClassTest
python
eth-brownie__brownie
brownie/convert/datatypes.py
{ "start": 7060, "end": 8378 }
class ____(str): """String subclass that raises TypeError when compared to a non-address.""" def __new__(cls, value: Any) -> Self: converted_value: HexStr if isinstance(value, str): converted_value = value # type: ignore [assignment] elif isinstance(value, bytes): ...
EthAddress
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 16225, "end": 16511 }
class ____(SendMessageToScheduler): """Worker->Scheduler response to ``{op: steal-request}`` See also -------- StealRequestEvent """ op = "steal-response" __slots__ = ("key", "state") key: Key state: TaskStateState | None @dataclass
StealResponseMsg
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py
{ "start": 13602, "end": 68161 }
class ____(ExecutingGraphQLContextTestMatrix): def test_launch_full_pipeline_backfill(self, graphql_context): repository_selector = infer_repository_selector(graphql_context) result = execute_dagster_graphql( graphql_context, LAUNCH_PARTITION_BACKFILL_MUTATION, va...
TestDaemonPartitionBackfill
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 9367, "end": 9627 }
class ____(ShopifyStream): """ The location API does not support any form of filtering. https://shopify.dev/api/admin-rest/2021-07/resources/location Therefore, only FULL_REFRESH mode is supported. """ data_field = "locations"
Locations
python
h5py__h5py
h5py/tests/test_attrs.py
{ "start": 8770, "end": 9652 }
class ____(BaseAttrs): def test_datatype(self): name = make_name() self.f[name] = np.dtype('f') dt = self.f[name] self.assertEqual(list(dt.attrs.keys()), []) dt.attrs.create('a', 4.0) self.assertEqual(list(dt.attrs.keys()), ['a']) self.assertEqual(list(dt.att...
TestDatatype
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 10211, "end": 11484 }
class ____(util.MdCase): """Test no Pygments with custom line number class.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'use_pygments': False, 'linenums_class': 'line-numbers', 'linenums': True ...
TestNoPygmentsCustomLineClass
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_collections.py
{ "start": 1903, "end": 2128 }
class ____(collections.abc.Collection[int]): # [abstract-method,abstract-method,abstract-method] # __contains__, __iter__, __len__ pass # No implementation required for 'builtins' and 'collections' types
DerivedCollection
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-reach-city-with-discounts.py
{ "start": 223, "end": 1364 }
class ____(object): def minimumCost(self, n, highways, discounts): """ :type n: int :type highways: List[List[int]] :type discounts: int :rtype: int """ adj = [[] for _ in xrange(n)] for u, v, w in highways: adj[u].append((v, w)) ...
Solution
python
joerick__pyinstrument
pyinstrument/__main__.py
{ "start": 20693, "end": 20898 }
class ____: def __init__(self, value: str, remaining_args: list[str]): self.value = value self.remaining_args = remaining_args if __name__ == "__main__": main()
ValueWithRemainingArgs
python
scikit-learn__scikit-learn
sklearn/exceptions.py
{ "start": 466, "end": 1167 }
class ____(ValueError): """Exception class to raise if a metadata is passed which is not explicitly \ requested (metadata=True) or not requested (metadata=False). .. versionadded:: 1.3 Parameters ---------- message : str The message unrequested_params : dict A dictiona...
UnsetMetadataPassedError
python
astropy__astropy
astropy/modeling/tests/test_quantities_parameters.py
{ "start": 638, "end": 12123 }
class ____(Fittable1DModel): @staticmethod def evaluate(x, a): return x def test_parameter_quantity(): """ Basic tests for initializing general models (that do not require units) with parameters that have units attached. """ g = Gaussian1D(1 * u.J, 1 * u.m, 0.1 * u.m) assert g....
BaseTestModel
python
encode__django-rest-framework
tests/test_throttling.py
{ "start": 1345, "end": 1479 }
class ____(APIView): throttle_classes = (User3SecRateThrottle,) def get(self, request): return Response('foo')
MockView
python
kamyu104__LeetCode-Solutions
Python/palindrome-permutation.py
{ "start": 50, "end": 251 }
class ____(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ return sum(v % 2 for v in collections.Counter(s).values()) < 2
Solution
python
sympy__sympy
sympy/core/core.py
{ "start": 62, "end": 547 }
class ____: """ Base class for registry objects. Registries map a name to an object using attribute notation. Registry classes behave singletonically: all their instances share the same state, which is stored in the class object. All subclasses should set `__slots__ = ()`. """ __slots_...
Registry
python
FactoryBoy__factory_boy
tests/cyclic/bar.py
{ "start": 106, "end": 193 }
class ____: def __init__(self, foo, y): self.foo = foo self.y = y
Bar
python
pytransitions__transitions
transitions/experimental/utils.py
{ "start": 4954, "end": 6028 }
class ____: definitions = defaultdict(lambda: defaultdict(list)) def __init__(self, configs): self.configs = deque(configs) def __set_name__(self, owner, name): for config in self.configs: TriggerPlaceholder.definitions[owner][name].append(config) def __call__(self, *args,...
TriggerPlaceholder
python
kamyu104__LeetCode-Solutions
Python/prime-palindrome.py
{ "start": 58, "end": 552 }
class ____(object): def primePalindrome(self, N): """ :type N: int :rtype: int """ def is_prime(n): if n < 2 or n % 2 == 0: return n == 2 return all(n % d for d in xrange(3, int(n**.5) + 1, 2)) if 8 <= N <= 11: retu...
Solution
python
tensorflow__tensorflow
tensorflow/python/keras/layers/convolutional.py
{ "start": 70107, "end": 79456 }
class ____(Conv): """Abstract base layer for separable nD convolution. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It the...
SeparableConv
python
getsentry__sentry
src/sentry/search/events/datasets/metrics.py
{ "start": 733, "end": 88049 }
class ____(DatasetConfig): missing_function_error = IncompatibleMetricsQuery def __init__(self, builder: metrics.MetricsQueryBuilder): self.builder = builder self.total_transaction_duration: float | None = None self.total_score_weights: dict[str, int] = {} @property def search_...
MetricsDatasetConfig
python
numba__numba
numba/core/controlflow.py
{ "start": 23385, "end": 31439 }
class ____(object): """ Attributes ---------- - bytecode - blocks - blockseq - doms: dict of set Dominators - backbone: set of block offsets The set of block that is common to all possible code path. """ def __init__(self, bytecode): self.bytecode = b...
ControlFlowAnalysis
python
facebookresearch__faiss
benchs/distributed_ondisk/search_server.py
{ "start": 1820, "end": 3042 }
class ____: """ Combine query results from a sliced dataset (for k-nn search) """ def __init__(self, nq, k): " nq: number of query vectors, k: number of results per query " self.I = np.zeros((nq, k), dtype='int64') self.D = np.zeros((nq, k), dtype='float32') self.nq, self.k = nq...
ResultHeap
python
python-openxml__python-docx
src/docx/oxml/document.py
{ "start": 1158, "end": 3593 }
class ____(BaseOxmlElement): """`w:body`, the container element for the main document story in `document.xml`.""" add_p: Callable[[], CT_P] get_or_add_sectPr: Callable[[], CT_SectPr] p_lst: List[CT_P] tbl_lst: List[CT_Tbl] _insert_tbl: Callable[[CT_Tbl], CT_Tbl] p = ZeroOrMore("w:p", succ...
CT_Body
python
astropy__astropy
astropy/utils/data.py
{ "start": 41349, "end": 41680 }
class ____(urllib.request.ftpwrapper): def init(self): self.busy = 0 self.ftp = ftplib.FTP_TLS() self.ftp.connect(self.host, self.port, self.timeout) self.ftp.login(self.user, self.passwd) self.ftp.prot_p() _target = "/".join(self.dirs) self.ftp.cwd(_target) ...
_ftptlswrapper
python
django__django
django/utils/autoreload.py
{ "start": 9473, "end": 13343 }
class ____: def __init__(self): self.extra_files = set() self.directory_globs = defaultdict(set) self._stop_condition = threading.Event() def watch_dir(self, path, glob): path = Path(path) try: path = path.absolute() except FileNotFoundError: ...
BaseReloader
python
RaRe-Technologies__gensim
gensim/models/lda_worker.py
{ "start": 2006, "end": 7555 }
class ____: """Used as a Pyro4 class with exposed methods. Exposes every non-private method and property of the class automatically to be available for remote access. """ def __init__(self): """Partly initialize the model.""" self.model = None @Pyro4.expose def initialize(sel...
Worker
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/kubernetes_engine.py
{ "start": 14258, "end": 15883 }
class ____(GoogleBaseAsyncHook): """Asynchronous client of GKE.""" sync_hook_class = GKEHook def __init__( self, gcp_conn_id: str = "google_cloud_default", location: str | None = None, impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: ...
GKEAsyncHook
python
jina-ai__jina
tests/integration/floating_deployments/test_floating_deployments.py
{ "start": 172, "end": 10451 }
class ____(Executor): def __init__(self, file_name, *args, **kwargs): super().__init__(*args, **kwargs) self.file_name = file_name @requests def foo(self, docs, **kwargs): time.sleep(TIME_SLEEP_FLOATING) with open(self.file_name, 'a+', encoding='utf-8') as f: f.w...
FloatingTestExecutor
python
celery__celery
t/unit/backends/test_redis.py
{ "start": 11115, "end": 12661 }
class ____: def get_backend(self): from celery.backends.redis import RedisBackend class _RedisBackend(RedisBackend): redis = redis return _RedisBackend def get_E_LOST(self): from celery.backends.redis import E_LOST return E_LOST def create_task(self, i...
basetest_RedisBackend
python
getsentry__sentry
tests/sentry/mail/activity/test_note.py
{ "start": 628, "end": 3450 }
class ____(ActivityTestCase): def setUp(self) -> None: super().setUp() self.email = NoteActivityNotification( Activity( project=self.project, group=self.group, user_id=self.user.id, type=ActivityType.NOTE, da...
NoteTestCase
python
joblib__joblib
joblib/parallel.py
{ "start": 37786, "end": 86989 }
class ____(Logger): """Helper class for readable parallel mapping. Read more in the :ref:`User Guide <parallel>`. Parameters ---------- n_jobs: int, default=None The maximum number of concurrently running jobs, such as the number of Python worker processes when ``backend="loky"`` o...
Parallel
python
huggingface__transformers
src/transformers/models/opt/modeling_opt.py
{ "start": 11988, "end": 12336 }
class ____(PreTrainedModel): config: OPTConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["OPTDecoderLayer"] _supports_attention_backend = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullg...
OPTPreTrainedModel
python
apache__thrift
compiler/cpp/test/compiler/staleness_check.py
{ "start": 907, "end": 5627 }
class ____(unittest.TestCase): CURRENT_DIR_PATH = os.path.dirname(os.path.realpath(__file__)) THRIFT_EXECUTABLE_PATH = None SINGLE_THRIFT_FILE_PATH = os.path.join(CURRENT_DIR_PATH, "Single.thrift") INCLUDING_THRIFT_FILE_PATH = os.path.join(CURRENT_DIR_PATH, "Including.thrift") INCLUDED_THRIFT_FILE_...
TestStalenessCheck
python
pytorch__pytorch
torch/fx/_graph_pickler.py
{ "start": 1234, "end": 1451 }
class ____: # A filter for which ops will cause the pickler to raise a # BypassFxGraphCache exception. If None then all ops are allowed. ops_filter: Optional[Callable[[str], bool]] = _ops_filter_safe
Options
python
doocs__leetcode
solution/2000-2099/2047.Number of Valid Words in a Sentence/Solution.py
{ "start": 0, "end": 664 }
class ____: def countValidWords(self, sentence: str) -> int: def check(s: str) -> bool: st = False for i, c in enumerate(s): if c.isdigit() or (c in "!.," and i < len(s) - 1): return False if c == "-": if ( ...
Solution
python
django__django
tests/delete/models.py
{ "start": 1583, "end": 2095 }
class ____(models.Model): db_setdefault = models.ForeignKey( RelatedDbOptionParent, models.DB_SET_DEFAULT, db_default=models.Value(1), related_name="db_setdefault_set", ) db_setdefault_none = models.ForeignKey( RelatedDbOptionParent, models.DB_SET_DEFAULT, ...
SetDefaultDbModel
python
huggingface__transformers
src/transformers/models/glm4v_moe/modular_glm4v_moe.py
{ "start": 21693, "end": 21860 }
class ____(Glm4MoeDecoderLayer): def __init__(self, config: Glm4vMoeTextConfig, layer_idx: int): super().__init__(config, layer_idx)
Glm4vMoeTextDecoderLayer
python
facelessuser__pymdown-extensions
tests/test_extensions/test_tilde.py
{ "start": 40, "end": 5167 }
class ____(util.MdCase): """Test escaping cases for Tilde with smart enabled.""" extension = [ 'pymdownx.tilde' ] extension_configs = { "pymdownx.tilde": { "smart_delete": True } } def test_case_1(self): """Test case 1.""" self.check_markdow...
TestTildeSmart
python
spyder-ide__spyder
external-deps/python-lsp-server/pylsp/lsp.py
{ "start": 1423, "end": 1582 }
class ____: Markup = 1 Code = 2 # https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#errorCodes
NotebookCellKind
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 91898, "end": 91971 }
class ____(Binop): operation = operator.eq _operator_repr = "=="
EQ
python
PyCQA__pylint
tests/functional/i/implicit/implicit_flag_alias.py
{ "start": 209, "end": 369 }
class ____(IntFlag): """Class with flags that overlap using explicit union syntax""" X = 1 W = 2 R = 4 RO = 4 RW = R | W
ExplicitUnionFlags
python
django__django
tests/admin_views/admin.py
{ "start": 3101, "end": 3434 }
class ____(admin.TabularInline): model = Article fk_name = "section" prepopulated_fields = {"title": ("content",)} fieldsets = ( ("Some fields", {"classes": ("collapse",), "fields": ("title", "content")}), ("Some other fields", {"classes": ("wide",), "fields": ("date", "section")}), ...
ArticleInline
python
huggingface__transformers
src/transformers/models/blip_2/modeling_blip_2.py
{ "start": 19846, "end": 24122 }
class ____(nn.Module): def __init__(self, config, is_cross_attention=False): super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( "The hidden size (%d) is not a...
Blip2QFormerMultiHeadAttention
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 20719, "end": 25837 }
class ____(nn.Module): r""" Compute a single vector summary of a sequence hidden states. Args: config ([`ClvpConfig`]): The config used by the model. Relevant arguments in the config class of the model are (refer to the actual config class of your model for the default value...
ClvpSequenceSummary
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 4488, "end": 7365 }
class ____: @pytest.mark.parametrize( "initial_state_type", [states.StateType.SCHEDULED, states.StateType.PENDING] ) async def test_running_after_scheduled_start_time_is_not_delayed( self, session, run_type, initialize_orchestration, initial_state_type, ):...
TestWaitForScheduledTimeRule
python
kamyu104__LeetCode-Solutions
Python/reverse-string.py
{ "start": 29, "end": 332 }
class ____(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ i, j = 0, len(s) - 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1
Solution
python
wandb__wandb
wandb/sdk/lib/service/service_token.py
{ "start": 1324, "end": 2150 }
class ____(abc.ABC): """A way of connecting to a running service process.""" @abc.abstractmethod def connect( self, *, asyncer: asyncio_manager.AsyncioManager, ) -> ServiceClient: """Connect to the service process. Args: asyncer: A started AsyncioMan...
ServiceToken
python
pyca__cryptography
tests/hazmat/primitives/test_hmac_vectors.py
{ "start": 2366, "end": 3073 }
class ____: def test_blake2b(self, backend): h = hmac.HMAC(b"0" * 64, hashes.BLAKE2b(digest_size=64), backend) h.update(b"test") digest = h.finalize() assert digest == binascii.unhexlify( b"b5319122f8a24ba134a0c9851922448104e25be5d1b91265c0c68b22722f0f29" b"87...
TestHMACBLAKE2
python
openai__openai-python
src/openai/types/eval_create_response.py
{ "start": 1042, "end": 1939 }
class ____(BaseModel): schema_: Dict[str, object] = FieldInfo(alias="schema") """ The json schema for the run data source items. Learn how to build JSON schemas [here](https://json-schema.org/). """ type: Literal["logs"] """The type of data source. Always `logs`.""" metadata: Optional[...
DataSourceConfigLogs
python
airbytehq__airbyte
airbyte-integrations/connectors/source-twilio/components.py
{ "start": 3881, "end": 5922 }
class ____(StateMigration): """ Migrate legacy `usage_records` state to low-code shape. - Add empty `parent_slice` to each partition. - Drop legacy `partition.date_created`. - Run if any partition lacks `parent_slice`. Initial: { "states": [ { "cursor": { "start_dat...
TwilioUsageRecordsStateMigration
python
ray-project__ray
python/ray/_private/function_manager.py
{ "start": 1487, "end": 29610 }
class ____: """A class used to export/load remote functions and actors. Attributes: _worker: The associated worker that this manager related. _functions_to_export: The remote functions to export when the worker gets connected. _actors_to_export: The actors to export when the ...
FunctionActorManager
python
run-llama__llama_index
llama-index-core/llama_index/core/ingestion/transformations.py
{ "start": 2364, "end": 2873 }
class ____(BaseModel): """ A class containing metadata for a type of transformation that can be in a pipeline. """ name: str = Field( description="Unique and human-readable name for the type of transformation" ) transformation_category: TransformationCategories = Field( descript...
ConfigurableTransformation
python
wandb__wandb
wandb/vendor/pygments/lexers/parsers.py
{ "start": 8550, "end": 9013 }
class ____(DelegatingLexer): """ A lexer for `Ragel`_ in a Ruby host file. .. versionadded:: 1.1 """ name = 'Ragel in Ruby Host' aliases = ['ragel-ruby', 'ragel-rb'] filenames = ['*.rl'] def __init__(self, **options): super(RagelRubyLexer, self).__init__(RubyLexer, RagelEmbedd...
RagelRubyLexer
python
numpy__numpy
numpy/f2py/tests/test_array_from_pyobj.py
{ "start": 11086, "end": 11439 }
class ____: def test_in_out(self): assert str(intent.in_.out) == "intent(in,out)" assert intent.in_.c.is_intent("c") assert not intent.in_.c.is_intent_exact("c") assert intent.in_.c.is_intent_exact("c", "in") assert intent.in_.c.is_intent_exact("in", "c") assert not i...
TestIntent
python
sqlalchemy__sqlalchemy
test/sql/test_returning.py
{ "start": 34067, "end": 36430 }
class ____(fixtures.TablesTest): __requires__ = ("delete_returning",) run_define_tables = "each" __sparse_driver_backend__ = True define_tables = InsertReturnDefaultsTest.define_tables def test_delete(self, connection): t1 = self.tables.t1 connection.execute(t1.insert().values(updd...
DeleteReturnDefaultsTest
python
google__jax
jax/_src/pallas/pipelining/internal.py
{ "start": 2501, "end": 2713 }
class ____: stages: Sequence[PipelineStage] grid: Sequence[int] def make_token(obj: Hashable) -> str: """Returns a fake input ID used to thread data dependencies.""" return f"token_{hash(obj)}"
NDLoopStruct
python
redis__redis-py
redis/commands/core.py
{ "start": 187148, "end": 188225 }
class ____(CommandsProtocol): """ Redis commands of HyperLogLogs data type. see: https://redis.io/topics/data-types-intro#hyperloglogs """ def pfadd(self, name: KeyT, *values: FieldT) -> ResponseT: """ Adds the specified elements to the specified HyperLogLog. For more infor...
HyperlogCommands
python
django__django
django/contrib/gis/geos/libgeos.py
{ "start": 3457, "end": 3497 }
class ____(Structure): pass
GEOSGeom_t
python
pytorch__pytorch
torch/ao/pruning/_experimental/pruner/FPGM_pruner.py
{ "start": 173, "end": 3471 }
class ____(BaseStructuredSparsifier): r"""Filter Pruning via Geometric Median (FPGM) Structured Pruner This sparsifier prune filter (row) in a tensor according to distances among filters according to `Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration <https://arxiv.org/...
FPGMPruner
python
graphql-python__graphene
graphene/types/tests/test_base64.py
{ "start": 172, "end": 2798 }
class ____(ObjectType): base64 = Base64(_in=Base64(name="input"), _match=String(name="match")) bytes_as_base64 = Base64() string_as_base64 = Base64() number_as_base64 = Base64() def resolve_base64(self, info, _in=None, _match=None): if _match: assert _in == _match return...
Query
python
redis__redis-py
redis/commands/search/__init__.py
{ "start": 3872, "end": 5648 }
class ____(Search, AsyncSearchCommands): class BatchIndexer(Search.BatchIndexer): """ A batch indexer allows you to automatically batch document indexing in pipelines, flushing it every N documents. """ async def add_document( self, doc_id, ...
AsyncSearch
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 65787, "end": 68353 }
class ____(Locator): """ Place ticks at evenly spaced values. The first time this function is called, it will try to set the number of ticks to make a nice tick partitioning. Thereafter, the number of ticks will be fixed to avoid jumping during interactive navigation. """ def __init__(sel...
LinearLocator
python
huggingface__transformers
tests/models/pvt_v2/test_modeling_pvt_v2.py
{ "start": 9779, "end": 12365 }
class ____(unittest.TestCase): @slow def test_inference_image_classification(self): # only resize + normalize image_processor = AutoImageProcessor.from_pretrained("OpenGVLab/pvt_v2_b0") model = PvtV2ForImageClassification.from_pretrained("OpenGVLab/pvt_v2_b0").to(torch_device).eval() ...
PvtV2ModelIntegrationTest