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
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_settings_options_details.py
{ "start": 363, "end": 515 }
class ____(APITestCase): endpoint = "sentry-api-0-user-notification-options-details" @control_silo_test
UserNotificationSettingsOptionsDetailsBaseTest
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 16162, "end": 17257 }
class ____(nn.Module): """ The `PatchTSMixer` layer that does all three kinds of mixing. Args: config (`PatchTSMixerConfig`): Configuration. """ def __init__(self, config: PatchTSMixerConfig): super().__init__() self.patch_mixer = PatchMixerBlock(config=config...
PatchTSMixerLayer
python
astropy__astropy
astropy/table/tests/conftest.py
{ "start": 1285, "end": 1343 }
class ____(pprint.TableFormatter): pass
MyTableFormatter
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/make_csv_dataset_test.py
{ "start": 1301, "end": 27096 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def _make_csv_dataset(self, filenames, batch_size, num_epochs=1, **kwargs): return readers.make_csv_dataset( filenames, batch_size=batch_size, num_epochs=num_epochs, **kwargs) def _setup_files(self, inputs, ...
MakeCsvDatasetTest
python
pypa__warehouse
warehouse/admin/views/organizations.py
{ "start": 42120, "end": 47500 }
class ____(wtforms.Form): issuer_type = wtforms.SelectField( choices=[(issuer.value, issuer.name) for issuer in OIDCIssuerType], coerce=OIDCIssuerType, validators=[ wtforms.validators.InputRequired(message="Select an issuer type"), ], ) issuer_url = wtforms.URLFie...
OrganizationOIDCIssuerForm
python
huggingface__transformers
src/transformers/models/llava_next/configuration_llava_next.py
{ "start": 831, "end": 6776 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`LlavaNextForConditionalGeneration`]. It is used to instantiate an Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults w...
LlavaNextConfig
python
PyCQA__pylint
pylint/checkers/non_ascii_names.py
{ "start": 1077, "end": 7243 }
class ____(base_checker.BaseChecker): """A strict name checker only allowing ASCII. Note: This check only checks Names, so it ignores the content of docstrings and comments! """ msgs = { "C2401": ( '%s name "%s" contains a non-ASCII character, consider renaming it.', ...
NonAsciiNameChecker
python
tensorflow__tensorflow
tensorflow/python/ops/unconnected_gradients.py
{ "start": 838, "end": 1677 }
class ____(enum.Enum): """Controls how gradient computation behaves when y does not depend on x. The gradient of y with respect to x can be zero in two different ways: there could be no differentiable path in the graph connecting x to y (and so we can statically prove that the gradient is zero) or it could be ...
UnconnectedGradients
python
dagster-io__dagster
python_modules/libraries/dagster-postgres/dagster_postgres/schedule_storage/schedule_storage.py
{ "start": 1377, "end": 8826 }
class ____(SqlScheduleStorage, ConfigurableClass): """Postgres-backed run storage. Users should not directly instantiate this class; it is instantiated by internal machinery when ``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in ``$DAGSTER_HOME``. C...
PostgresScheduleStorage
python
django__django
tests/expressions/tests.py
{ "start": 54911, "end": 58263 }
class ____(TestCase): def test_F_reuse(self): f = F("id") n = Number.objects.create(integer=-1) c = Company.objects.create( name="Example Inc.", num_employees=2300, num_chairs=5, ceo=Employee.objects.create(firstname="Joe", lastname="Smith"), ...
ExpressionsTests
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/bigquery.py
{ "start": 61920, "end": 62828 }
class ____: """ BigQuery connection. BigQuery does not have a notion of a persistent connection. Thus, these objects are small stateless factories for cursors, which do all the real work. """ def __init__(self, *args, **kwargs) -> None: self._args = args self._kwargs = kwar...
BigQueryConnection
python
tensorflow__tensorflow
tensorflow/python/debug/cli/debugger_cli_common_test.py
{ "start": 10488, "end": 22465 }
class ____(test_util.TensorFlowTestCase): def setUp(self): self._intentional_error_msg = "Intentionally raised exception" def _noop_handler(self, argv, screen_info=None): # A handler that does nothing other than returning "Done." return debugger_cli_common.RichTextLines(["Done."]) def _handler_rais...
CommandHandlerRegistryTest
python
miyuchina__mistletoe
mistletoe/block_token.py
{ "start": 12241, "end": 13917 }
class ____(BlockToken): """ Indented code block token. This is a leaf block token with a single child of type span_token.RawText. Attributes: language (str): always the empty string. """ repr_attributes = BlockToken.repr_attributes + ("language",) def __init__(self, lines): ...
BlockCode
python
pytorch__pytorch
torch/nn/modules/container.py
{ "start": 1397, "end": 11326 }
class ____(Module): r"""A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ``OrderedDict`` of modules can be passed in. The ``forward()`` method of ``Sequential`` accepts any input and forwards it to the first module it contains. I...
Sequential
python
streamlit__streamlit
lib/tests/streamlit/elements/markdown_test.py
{ "start": 8217, "end": 8707 }
class ____(DeltaGeneratorTestCase): """Test st.latex APIs.""" def test_st_latex_with_help(self): """Test st.latex with help.""" st.latex( r""" a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} = \sum_{k=0}^{n-1} ar^k = a \left(\frac{1-r^{n}}{1-r}\right)...
StLatexAPITest
python
lazyprogrammer__machine_learning_examples
rl2/a3c/nets.py
{ "start": 2786, "end": 4367 }
class ____: def __init__(self): # Placeholders for our input # After resizing we have 4 consecutive frames of size 84 x 84 self.states = tf.placeholder(shape=[None, 84, 84, 4], dtype=tf.uint8, name="X") # The TD target value self.targets = tf.placeholder(shape=[None], dtype=tf.float32, name="y") ...
ValueNetwork
python
eventlet__eventlet
tests/db_pool_test.py
{ "start": 1417, "end": 9984 }
class ____(DBTester): __test__ = False # so that nose doesn't try to execute this directly def setUp(self): super().setUp() self.pool = self.create_pool() self.connection = self.pool.get() def tearDown(self): if self.connection: self.pool.put(self.connection) ...
DBConnectionPool
python
aimacode__aima-python
search.py
{ "start": 25944, "end": 27226 }
class ____(Problem): """Problem of finding the highest peak in a limited grid""" def __init__(self, initial, grid, defined_actions=directions4): """The grid is a 2 dimensional array/list whose state is specified by tuple of indices""" super().__init__(initial) self.grid = grid s...
PeakFindingProblem
python
google__python-fire
fire/console/console_attr.py
{ "start": 15921, "end": 23495 }
class ____(object): """Resource string colorizer. Attributes: _con: ConsoleAttr object. _color: Color name. _string: The string to colorize. _justify: The justification function, no justification if None. For example, justify=lambda s: s.center(10) """ def __init__(self, string, color, j...
Colorizer
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py
{ "start": 2488, "end": 3962 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.activation_fn = ACT2FN[config.hidden_act] self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) ...
Phi4MultimodalVisionMLP
python
ApeWorX__ape
src/ape/cli/choices.py
{ "start": 14175, "end": 14627 }
class ____(Choice): """ A simple lazy-choice where choices are evaluated lazily. """ def __init__(self, get_choices: Callable[[], Sequence[str]], case_sensitive: bool = False): self._get_choices = get_choices self.case_sensitive = case_sensitive # Note: Purposely avoid super ini...
LazyChoice
python
spack__spack
lib/spack/spack/repo.py
{ "start": 21756, "end": 35730 }
class ____: """A RepoPath is a list of Repo instances that function as one. It functions exactly like a Repo, but it operates on the combined results of the Repos in its list instead of on a single package repository. """ def __init__(self, *repos: "Repo") -> None: self.repos: List[Rep...
RepoPath
python
huggingface__transformers
src/transformers/models/openai/modeling_openai.py
{ "start": 10348, "end": 10613 }
class ____(PreTrainedModel): config: OpenAIGPTConfig base_model_prefix = "transformer" @dataclass @auto_docstring( custom_intro=""" Base class for outputs of models predicting if two sentences are consecutive or not. """ )
OpenAIGPTPreTrainedModel
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 27161, "end": 30564 }
class ____(unittest.TestCase): """ Test Dates of Birth """ def setUp(self): self.fake = Faker() Faker.seed(0) def test_date_of_birth(self): dob = self.fake.date_of_birth() assert isinstance(dob, date) @freezegun.freeze_time("2020-02-29") def test_date_of_bi...
DatesOfBirth
python
tensorflow__tensorflow
tensorflow/python/ops/weak_tensor_special_math_ops_test.py
{ "start": 7501, "end": 9574 }
class ____(test.TestCase, parameterized.TestCase): @test_util.run_in_graph_and_eager_modes def test_fresnel_sin_boundary(self): self.assertAllClose(0., special_math_ops.fresnel_sin(0.)) self.assertTrue( np.isnan(self.evaluate(special_math_ops.fresnel_sin(np.nan)))) @parameterized.parameters(np.f...
FresnelSinTest
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py
{ "start": 12023, "end": 16573 }
class ____: """Test scenarios that simulate real-world usage.""" @pytest.fixture def mock_tool_spec(self): """Create a mocked tool spec for real-world testing.""" with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class: mock_client = Mock() mock_...
TestRealWorldScenarios
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 61021, "end": 61319 }
class ____(FieldValues): """ Values for `DurationField` with a no output format. """ valid_inputs = {} invalid_inputs = {} outputs = { datetime.timedelta(1): datetime.timedelta(1) } field = serializers.DurationField(format=None)
TestNoOutputFormatDurationField
python
zarr-developers__zarr-python
src/zarr/core/chunk_key_encodings.py
{ "start": 717, "end": 864 }
class ____(TypedDict): name: Literal["v2", "default"] separator: NotRequired[SeparatorLiteral] @dataclass(frozen=True)
ChunkKeyEncodingParams
python
hynek__structlog
tests/test_native.py
{ "start": 620, "end": 11043 }
class ____: def test_is_enabled_for(self, bl): """ is_enabled_for returns True if the log level is enabled. """ assert bl.is_enabled_for(20) assert bl.is_enabled_for(logging.INFO) assert not bl.is_enabled_for(19) assert not bl.is_enabled_for(logging.DEBUG) ...
TestNativeFilteringLogger
python
sympy__sympy
sympy/tensor/array/expressions/array_expressions.py
{ "start": 60626, "end": 62284 }
class ____(_CodegenArrayAbstract): """ Reshape the dimensions of an array expression. Examples ======== >>> from sympy.tensor.array.expressions import ArraySymbol, Reshape >>> A = ArraySymbol("A", (6,)) >>> A.shape (6,) >>> Reshape(A, (3, 2)).shape (3, 2) Check the compone...
Reshape
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataprep.py
{ "start": 1374, "end": 2527 }
class ____(GoogleCloudBaseOperator): """ Get information about the batch jobs within a Cloud Dataprep job. API documentation: https://clouddataprep.com/documentation/api#section/Overview. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`how...
DataprepGetJobsForJobGroupOperator
python
allegroai__clearml
clearml/backend_api/services/v2_13/workers.py
{ "start": 74658, "end": 83491 }
class ____(Request): """ Called periodically by the worker daemon to report machine status :param worker: Worker id. :type worker: str :param task: ID of a task currently being run by the worker. If no task is sent, the worker's task field will be cleared. :type task: str :param que...
StatusReportRequest
python
lazyprogrammer__machine_learning_examples
rl2/cartpole/pg_theano.py
{ "start": 767, "end": 1234 }
class ____: def __init__(self, M1, M2, f=T.tanh, use_bias=True): self.W = theano.shared(np.random.randn(M1, M2) * np.sqrt(2 / M1)) self.params = [self.W] self.use_bias = use_bias if use_bias: self.b = theano.shared(np.zeros(M2)) self.params += [self.b] self.f = f def forward(self, X...
HiddenLayer
python
pallets__jinja
tests/test_lexnparse.py
{ "start": 10407, "end": 19362 }
class ____: def test_call(self, env): env = Environment() env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}") assert tmpl.render() == "abdfh" def test_slicing(self, env): tmpl = env.fro...
TestSyntax
python
jmcnamara__XlsxWriter
xlsxwriter/test/sharedstrings/test_write_sst.py
{ "start": 328, "end": 1431 }
class ____(unittest.TestCase): """ Test the SharedStrings _write_sst() method. """ def setUp(self): self.fh = StringIO() self.sharedstrings = SharedStrings() self.sharedstrings._set_filehandle(self.fh) def test_write_sst(self): """Test the _write_sst() method""" ...
TestWriteSst
python
django__django
django/template/loader_tags.py
{ "start": 2619, "end": 5780 }
class ____(Node): must_be_first = True context_key = "extends_context" def __init__(self, nodelist, parent_name, template_dirs=None): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs self.blocks = {n.name: n for n in nodelist.get_nod...
ExtendsNode
python
kamyu104__LeetCode-Solutions
Python/average-of-levels-in-binary-tree.py
{ "start": 30, "end": 600 }
class ____(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ result = [] q = [root] while q: total, count = 0, 0 next_q = [] for n in q: total += n.val ...
Solution
python
pytorch__pytorch
test/onnx/model_defs/rnn_model_with_packed_sequence.py
{ "start": 67, "end": 611 }
class ____(nn.Module): def __init__(self, model, batch_first): super().__init__() self.model = model self.batch_first = batch_first def forward(self, input, *args): args, seq_lengths = args[:-1], args[-1] input = rnn_utils.pack_padded_sequence(input, seq_lengths, self.ba...
RnnModelWithPackedSequence
python
tensorflow__tensorflow
tensorflow/python/lib/io/tf_record_test.py
{ "start": 10409, "end": 12875 }
class ____(TFCompressionTestCase): """TFRecordWriter Zlib test""" def testZLibFlushRecord(self): """test ZLib Flush Record""" original = [b"small record"] fn = self._WriteRecordsToFile(original, "small_record") with open(fn, "rb") as h: buff = h.read() # creating more blocks and trailing...
TFRecordWriterZlibTest
python
realpython__materials
emacs-the-best-python-editor/PyEval/pyeval_operator.py
{ "start": 564, "end": 1431 }
class ____: """ Common operator class used by the evaluator. """ def __init__(self, operator_string): """Create a new operator object.""" # String to hold the operator self._op_string = operator_string # Integer to hold the precedence self._op_prec = PRECEDENCE...
Operator
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/redshift_cluster.py
{ "start": 23231, "end": 28439 }
class ____(AwsBaseOperator[RedshiftHook]): """ Resume a paused AWS Redshift Cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:RedshiftResumeClusterOperator` :param cluster_identifier: Unique identifier of the AWS Red...
RedshiftResumeClusterOperator
python
pytorch__pytorch
test/mobile/model_test/nn_ops.py
{ "start": 6534, "end": 7374 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.rnn = nn.ModuleList( [ nn.RNN(4, 8, 2), nn.RNNCell(4, 8), ] ) self.gru = nn.ModuleList([nn.GRU(4, 8, 2), nn.GRUCell(4, 8)]) self.lstm = nn....
NNRecurrentModule
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 3282, "end": 4314 }
class ____(Benchmark): r""" Cigar objective function. This class defines the Cigar [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Cigar}}(x) = x_1^2 + 10^6\sum_{i=2}^{n} x_i^2 Here, :math:`n` represents the number o...
Cigar
python
python-poetry__poetry
src/poetry/utils/env/mock_env.py
{ "start": 305, "end": 2633 }
class ____(NullEnv): def __init__( self, version_info: tuple[int, int, int] | PythonVersion = (3, 7, 0), *, python_implementation: str = "CPython", platform: str = "darwin", platform_machine: str = "amd64", os_name: str = "posix", is_venv: bool = False...
MockEnv
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 64676, "end": 65470 }
class ____(TypedDict, total=False): """ :class:`altair.BindCheckbox` ``TypedDict`` wrapper. Parameters ---------- input debounce If defined, delays event handling until the specified milliseconds have elapsed since the last event was fired. element An optional CSS s...
BindCheckboxKwds
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 221048, "end": 222261 }
class ____(TestCase): def test_concurrent_calls(self): unique = 10 # Number of distinct counters repetitions = 5 # Number of times each counter is used limit = 100 # Calls per counter per repetition @mi.synchronized def atomic_counter(): # This is a generator ...
TestSynchronized
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/cond_v2_test.py
{ "start": 48258, "end": 50241 }
class ____(test.TestCase): def testCollectionIntValueAccessInCond(self): """Read values from graph collections inside of cond_v2.""" with ops.Graph().as_default() as g: with self.session(graph=g): x = 2 y = 5 ops.add_to_collection("x", x) ops.add_to_collection("y", y) ...
CondV2CollectionTest
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/forward_multi_value/package.py
{ "start": 217, "end": 860 }
class ____(Package): """A package that forwards the value of a multi-valued variant to a dependency""" homepage = "http://www.spack.llnl.gov" url = "http://www.spack.llnl.gov/mpileaks-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") variant("cuda", default=False, description="Bu...
ForwardMultiValue
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py
{ "start": 8868, "end": 9423 }
class ____(BaseModel): class Config: extra = Extra.forbid suite: Literal["unitTests", "integrationTests", "acceptanceTests", "liveTests"] = ( Field(..., description="Name of the configured test suite") ) testSecrets: Optional[List[Secret]] = Field( None, description="List of sec...
ConnectorTestSuiteOptions
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/dictionary.py
{ "start": 9228, "end": 12767 }
class ____(Dict[Any, Any]): foo: int = 0 def __setitem__(self, key: Any, value: Any) -> None: self.foo = value def setitem_models(d3: Dict[str, Any], x): # Use the custom model of __setitem__ for MyDict d1 = MyDict() d1["a"] = x # Use the built-in model of __setitem__ for dict d2...
MyDict
python
getsentry__sentry
src/sentry/api/bases/project.py
{ "start": 1242, "end": 2168 }
class ____(OrganizationPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin"], "POST": ["project:write", "project:admin"], "PUT": ["project:write", "project:admin"], "DELETE": ["project:admin"], } def has_object_permission(self, request: Request...
ProjectPermission
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/server.py
{ "start": 53923, "end": 58658 }
class ____: def __init__( self, server_termination_event: threading.Event, dagster_api_servicer: DagsterApiServicer, logger: logging.Logger, threadpool_executor: FuturesAwareThreadPoolExecutor, host="localhost", port: Optional[int] = None, socket: Opti...
DagsterGrpcServer
python
kamyu104__LeetCode-Solutions
Python/max-chunks-to-make-sorted.py
{ "start": 396, "end": 855 }
class ____(object): def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ result, increasing_stk = 0, [] for num in arr: max_num = num if not increasing_stk else max(increasing_stk[-1], num) while increasing_stk and increas...
Solution2
python
tornadoweb__tornado
tornado/test/httputil_test.py
{ "start": 3097, "end": 3394 }
class ____(unittest.TestCase): def test_parsing(self): qsstring = "a=1&b=2&a=3" qs = urllib.parse.parse_qs(qsstring) qsl = list(qs_to_qsl(qs)) self.assertIn(("a", "1"), qsl) self.assertIn(("a", "3"), qsl) self.assertIn(("b", "2"), qsl)
QsParseTest
python
astropy__astropy
astropy/cosmology/_src/tests/io/test_cosmology.py
{ "start": 2092, "end": 2308 }
class ____(IODirectTestBase, ToFromCosmologyTestMixin): """Directly test ``to/from_cosmology``.""" def setup_class(self): self.functions = {"to": to_cosmology, "from": from_cosmology}
TestToFromCosmology
python
run-llama__llama_index
llama-index-core/tests/indices/vector_store/mock_services.py
{ "start": 91, "end": 1980 }
class ____(BaseEmbedding): @classmethod def class_name(cls) -> str: return "MockEmbedding" async def _aget_query_embedding(self, query: str) -> List[float]: del query return [0, 0, 1, 0, 0] async def _aget_text_embedding(self, text: str) -> List[float]: # assume dimensi...
MockEmbedding
python
pytorch__pytorch
test/inductor/test_inductor_annotations.py
{ "start": 280, "end": 1305 }
class ____(TestCase): def get_code(self): def f(a, b): return a + b, a * b a = torch.randn(5, device="cuda") b = torch.randn(5, device="cuda") f_comp = torch.compile(f) _, code = run_and_get_code(f_comp, a, b) return code[0] @requires_cuda_and_trito...
InductorAnnotationTestCase
python
django__django
tests/model_forms/tests.py
{ "start": 28749, "end": 29508 }
class ____(forms.ModelForm): class Meta: model = Category fields = ["name", "url", "slug"] widgets = { "name": forms.Textarea, "url": forms.TextInput(attrs={"class": "url"}), } labels = { "name": "Title", } help_texts = { ...
FieldOverridesByFormMetaForm
python
falconry__falcon
examples/recipes/output_csv_text_wsgi.py
{ "start": 38, "end": 438 }
class ____: def on_get(self, req, resp): output = io.StringIO() writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC) writer.writerow(('fruit', 'quantity')) writer.writerow(('apples', 13)) writer.writerow(('oranges', 37)) resp.content_type = falcon.MEDIA_CSV ...
Report
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_delayed_workflow.py
{ "start": 38615, "end": 44798 }
class ____: def test_event_key_from_redis_key(self) -> None: key = "123:456:789:1,2,3:10,9,8" event_key = EventKey.from_redis_key(key) assert event_key.workflow_id == 123 assert event_key.group_id == 456 assert event_key.when_dcg_id == 789 assert event_key.if_dcg_ids ...
TestEventKeyAndInstance
python
getsentry__sentry
tests/sentry/integrations/msteams/test_message_builder.py
{ "start": 17555, "end": 19569 }
class ____(TestCase): def setUp(self) -> None: owner = self.create_user() self.org = self.create_organization(owner=owner) self.notification = DummyNotificationWithMoreFields(self.org) self.project1 = self.create_project(organization=self.org) self.group1 = self.create_group...
MSTeamsNotificationMessageBuilderTest
python
coleifer__peewee
tests/migrations.py
{ "start": 34081, "end": 34276 }
class ____(TestModel): key = TextField() value = IntegerField() class Meta: constraints = [ SQL("CHECK (key != '')"), SQL('CHECK (value > 0)')]
HasChecks
python
huggingface__transformers
src/transformers/models/fsmt/modeling_fsmt.py
{ "start": 43929, "end": 47040 }
class ____(nn.Embedding): """ This module produces sinusoidal positional embeddings of any length. We don't want to save the weight of this embedding since it's not trained (deterministic) and it can be huge. Padding symbols are ignored. These embeddings get automatically extended in forward if m...
SinusoidalPositionalEmbedding
python
huggingface__transformers
tests/models/smolvlm/test_modeling_smolvlm.py
{ "start": 5231, "end": 13530 }
class ____(ModelTesterMixin, unittest.TestCase): """ Model tester for `SmolVLM`. """ all_model_classes = (SmolVLMModel,) if is_torch_available() else () test_resize_embeddings = True def setUp(self): self.model_tester = SmolVLMVisionText2TextModelTester(self) self.config_teste...
SmolVLMModelTest
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/operators/databricks.py
{ "start": 54005, "end": 68542 }
class ____(BaseOperator, ABC): """ Base class for operators that are run as Databricks job tasks or tasks within a Databricks workflow. :param caller: The name of the caller operator to be used in the logs. :param databricks_conn_id: The name of the Airflow connection to use. :param databricks_task...
DatabricksTaskBaseOperator
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 48187, "end": 48857 }
class ____(BaseDataset): """ Feature: Dataset dtype is available as .dtype property """ def test_dtype(self): """ Retrieve dtype from dataset """ dset = self.f.create_dataset(make_name(), (5,), '|S10') self.assertEqual(dset.dtype, np.dtype('|S10')) def test_dtype_compl...
TestDtype
python
huggingface__transformers
tests/models/dbrx/test_modeling_dbrx.py
{ "start": 955, "end": 2645 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = DbrxModel def __init__( self, parent, clip_qkv=8, rope_theta=500000, attn_config_model_type="", moe_jitter_eps=0, moe_loss_weight=0.05, moe_num_experts=8, ...
DbrxModelTester
python
python-markdown__markdown
markdown/blockprocessors.py
{ "start": 24365, "end": 25505 }
class ____(BlockProcessor): """ Process link references. """ RE = re.compile( r'^[ ]{0,3}\[([^\[\]]*)\]:[ ]*\n?[ ]*([^\s]+)[ ]*(?:\n[ ]*)?((["\'])(.*)\4[ ]*|\((.*)\)[ ]*)?$', re.MULTILINE ) def test(self, parent: etree.Element, block: str) -> bool: return True def run(self, parent:...
ReferenceProcessor
python
ray-project__ray
rllib/policy/policy.py
{ "start": 5860, "end": 69980 }
class ____(metaclass=ABCMeta): """RLlib's base class for all Policy implementations. Policy is the abstract superclass for all DL-framework specific sub-classes (e.g. TFPolicy or TorchPolicy). It exposes APIs to 1. Compute actions from observation (and possibly other) inputs. 2. Manage the Policy...
Policy
python
encode__django-rest-framework
tests/test_permissions.py
{ "start": 18723, "end": 18941 }
class ____(permissions.BasePermission): message = 'Custom: You cannot access this resource' code = 'permission_denied_custom' def has_permission(self, request, view): return False
BasicPermWithDetail
python
getsentry__sentry
src/sentry/workflow_engine/migration_helpers/issue_alert_migration.py
{ "start": 1568, "end": 12686 }
class ____: def __init__( self, rule: Rule, user_id: int | None = None, is_dry_run: bool | None = False, should_create_actions: bool | None = True, ): self.rule = rule self.user_id = user_id self.is_dry_run = is_dry_run self.should_create_a...
IssueAlertMigrator
python
h5py__h5py
h5py/tests/test_h5t.py
{ "start": 357, "end": 1703 }
class ____(ut.TestCase): """ Feature: Compound types can be created from Python dtypes """ def test_ref(self): """ Reference types are correctly stored in compound types (issue 144) """ dt = np.dtype([('a', h5py.ref_dtype), ('b', '<f4')]) tid = h5t.py_create(dt, log...
TestCompound
python
PyCQA__pylint
tests/functional/d/deprecated/deprecated_decorators.py
{ "start": 169, "end": 277 }
class ____: @abc.abstractclassmethod # [deprecated-decorator] def my_method(cls): pass
MyClass
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/v1_compat_tests/array_ops_test.py
{ "start": 2876, "end": 3291 }
class ____(test_util.TensorFlowTestCase): @test_util.run_v1_only("Variables need initialization only in V1") def testUninitialized(self): with self.assertRaisesRegex( errors.FailedPreconditionError, "Attempting to use uninitialized value Variable"): v = variable_v1.VariableV1([1, 2]) ...
SliceAssignTest
python
pypa__pip
src/pip/_internal/metadata/pkg_resources.py
{ "start": 8415, "end": 10544 }
class ____(BaseEnvironment): def __init__(self, ws: pkg_resources.WorkingSet) -> None: self._ws = ws @classmethod def default(cls) -> BaseEnvironment: return cls(pkg_resources.working_set) @classmethod def from_paths(cls, paths: list[str] | None) -> BaseEnvironment: return ...
Environment
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/batch.py
{ "start": 1376, "end": 4853 }
class ____(AwsBaseSensor[BatchClientHook]): """ Poll the state of the Batch Job until it reaches a terminal state; fails if the job fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:BatchSensor` :param job_id: Batch job_id ...
BatchSensor
python
huggingface__transformers
src/transformers/models/roformer/modeling_roformer.py
{ "start": 3327, "end": 4578 }
class ____(nn.Module): """Construct the embeddings from word and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id) self.token_type_embeddings = nn.Embedd...
RoFormerEmbeddings
python
huggingface__transformers
tests/models/hiera/test_modeling_hiera.py
{ "start": 8158, "end": 22106 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as Hiera does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = ( ( HieraModel, Hiera...
HieraModelTest
python
pandas-dev__pandas
pandas/core/groupby/ops.py
{ "start": 40491, "end": 40846 }
class ____(DataSplitter): def _chop(self, sdata: Series, slice_obj: slice) -> Series: # fastpath equivalent to `sdata.iloc[slice_obj]` mgr = sdata._mgr.get_slice(slice_obj) ser = sdata._constructor_from_mgr(mgr, axes=mgr.axes) ser._name = sdata.name return ser.__finalize__(sd...
SeriesSplitter
python
getsentry__sentry
tests/sentry/utils/test_samples.py
{ "start": 1508, "end": 4296 }
class ____: @pytest.mark.parametrize("platform", list(CONSOLES)) def test_console_platforms_trigger_screenshot_attachment( self, default_project: Project, platform: str ): with mock.patch( "sentry.utils.samples.create_console_screenshot_attachment" ) as mock_attachment: ...
TestConsoleSamples
python
networkx__networkx
networkx/algorithms/isomorphism/tests/test_isomorphvf2.py
{ "start": 192, "end": 2143 }
class ____: # Source: https://en.wikipedia.org/wiki/Graph_isomorphism # Nodes 'a', 'b', 'c' and 'd' form a column. # Nodes 'g', 'h', 'i' and 'j' form a column. g1edges = [ ["a", "g"], ["a", "h"], ["a", "i"], ["b", "g"], ["b", "h"], ["b", "j"], ["c...
TestWikipediaExample
python
getsentry__sentry
src/sentry/integrations/discord/handlers/discord_handler.py
{ "start": 790, "end": 2331 }
class ____(IntegrationActionHandler): group = ActionHandler.Group.NOTIFICATION provider_slug = IntegrationProviderSlug.DISCORD # Main difference between the discord and slack action config schemas is that the target_display is possibly null config_schema = { "$schema": "https://json-schema.org/...
DiscordActionHandler
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_fx.py
{ "start": 1321, "end": 4720 }
class ____(TestCase): def test_symbolic_tracing_outputs(self): """ Tests running ``tracer.trace()`` inside ``patch_tracer()`` by checking the saved data structures. """ model = Model() tracer = torch.fx.Tracer() orig_call_module = tracer.call_module or...
TestSymbolicTracing
python
sqlalchemy__sqlalchemy
test/orm/test_unitofworkv2.py
{ "start": 1970, "end": 2617 }
class ____: def _get_test_uow(self, session): uow = unitofwork.UOWTransaction(session) deleted = set(session._deleted) new = set(session._new) dirty = set(session._dirty_states).difference(deleted) for s in new.union(dirty): uow.register_object(s) for d in...
AssertsUOW
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/dagster/dagster_pipes/dagster_pipes_details_and_customization/custom_bootstrap_loader.py
{ "start": 216, "end": 582 }
class ____(PipesParamsLoader): def is_dagster_pipes_process(self) -> bool: return DAGSTER_PIPES_CONTEXT_ENV_VAR in METADATA def load_context_params(self) -> PipesParams: return METADATA[DAGSTER_PIPES_CONTEXT_ENV_VAR] def load_messages_params(self) -> PipesParams: return METADATA[DA...
MyCustomParamsLoader
python
streamlit__streamlit
lib/streamlit/runtime/caching/storage/cache_storage_protocol.py
{ "start": 5695, "end": 8610 }
class ____(Protocol): """Cache storage manager protocol, that should be implemented by the concrete cache storage managers. It is responsible for: - Creating cache storage instances for the specific decorated functions, - Validating the context for the cache storages. - Opti...
CacheStorageManager
python
django__django
tests/i18n/tests.py
{ "start": 19753, "end": 20815 }
class ____(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *ar...
TranslationThreadSafetyTests
python
getsentry__sentry
tests/sentry/middleware/test_access_log_middleware.py
{ "start": 3533, "end": 5711 }
class ____(ControlSiloOrganizationEndpoint): def get(self, request, organization_context, organization): return Response({"ok": True}) urlpatterns = [ re_path(r"^/dummy$", DummyEndpoint.as_view(), name="dummy-endpoint"), re_path(r"^api/0/internal/test$", DummyEndpoint.as_view(), name="internal-dum...
MyControlOrganizationEndpoint
python
etianen__django-reversion
tests/test_app/tests/base.py
{ "start": 2566, "end": 2618 }
class ____(TestBaseMixin, TestCase): pass
TestBase
python
pydantic__pydantic
tests/mypy/modules/pydantic_settings.py
{ "start": 288, "end": 461 }
class ____(BaseSettings): bar: str model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8') scd = SettingsWithConfigDict()
SettingsWithConfigDict
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol53.py
{ "start": 4412, "end": 4603 }
class ____(Proto_ContraGeneric): # This should not generate a reportIncompatibleMethodOverride error # but does currently. def m(self, x: Self) -> None: ...
Impl_ContraSelfExplicit3
python
getsentry__sentry
src/sentry/discover/endpoints/discover_saved_query_detail.py
{ "start": 2050, "end": 6094 }
class ____(DiscoverSavedQueryBase): publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } def has_feature(self, organization, request): return features.has( "organizations:discover", organization, ...
DiscoverSavedQueryDetailEndpoint
python
boto__boto3
tests/unit/resources/test_params.py
{ "start": 6655, "end": 8520 }
class ____(BaseTestCase): def test_simple_value(self): params = {} build_param_structure(params, 'foo', 'bar') assert params['foo'] == 'bar' def test_nested_dict(self): params = {} build_param_structure(params, 'foo.bar.baz', 123) assert params['foo']['bar']['baz...
TestStructBuilder
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 9334, "end": 10192 }
class ____(StrictBaseModel): """Schema for DagRun model with minimal required fields needed for Runtime.""" # TODO: `dag_id` and `run_id` are duplicated from TaskInstance # See if we can avoid sending these fields from API server and instead # use the TaskInstance data to get the DAG run informatio...
DagRun
python
tensorflow__tensorflow
tensorflow/python/ops/clustering_ops.py
{ "start": 25455, "end": 36028 }
class ____: """Internal class to create the op to initialize the clusters. The op performs this algorithm (see constructor args): num_remaining = num_clusters - length(cluster_centers) if num_remaining == 0: assert that cluster_centers_initialized is true else: assert that num_remaining ...
_InitializeClustersOpFactory
python
nedbat__coveragepy
tests/test_plugins.py
{ "start": 11682, "end": 11775 }
class ____(CoverageTest): """Tests of plugins that implement file_tracer."""
FileTracerTest
python
ray-project__ray
python/ray/actor.py
{ "start": 3716, "end": 4199 }
class ____(Generic[_Ret, _T0, _T1, _T2, _T3, _T4]): def remote( self, __arg0: "Union[_T0, ObjectRef[_T0]]", __arg1: "Union[_T1, ObjectRef[_T1]]", __arg2: "Union[_T2, ObjectRef[_T2]]", __arg3: "Union[_T3, ObjectRef[_T3]]", __arg4: "Union[_T4, ObjectRef[_T4]]", ) ->...
_RemoteMethod4
python
TheAlgorithms__Python
data_structures/heap/randomized_heap.py
{ "start": 175, "end": 1812 }
class ____[T: bool]: """ One node of the randomized heap. Contains the value and references to two children. """ def __init__(self, value: T) -> None: self._value: T = value self.left: RandomizedHeapNode[T] | None = None self.right: RandomizedHeapNode[T] | None = None @...
RandomizedHeapNode
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 168680, "end": 169591 }
class ____(sgqlc.types.Input): """Autogenerated input type of CopyProjectV2""" __schema__ = github_schema __field_names__ = ("project_id", "owner_id", "title", "include_draft_issues", "client_mutation_id") project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId") """The ID ...
CopyProjectV2Input
python
pypa__hatch
backend/src/hatchling/version/source/env.py
{ "start": 126, "end": 911 }
class ____(VersionSourceInterface): PLUGIN_NAME = "env" def get_version_data(self) -> dict: variable = self.config.get("variable", "") if not variable: message = "option `variable` must be specified" raise ValueError(message) if not isinstance(variable, str): ...
EnvSource