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
pytorch__pytorch
test/distributed/checkpoint/test_compatibility.py
{ "start": 464, "end": 3461 }
class ____(TestCase): def test_metadata(self) -> None: # Ensure that all the new fields of all the metadata have the default # values so that we can always deserialize from a legacy metadata. try: tensor = torch.zeros(4, 4) chunk_meta = ChunkStorageMetadata( ...
TestDCPCompatbility
python
django__django
tests/admin_inlines/tests.py
{ "start": 36724, "end": 55235 }
class ____(TestCase): """ Make sure the admin respects permissions for objects that are edited inline. Refs #8060. """ @classmethod def setUpTestData(cls): cls.user = User(username="admin", is_staff=True, is_active=True) cls.user.set_password("secret") cls.user.save() ...
TestInlinePermissions
python
apache__airflow
shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py
{ "start": 16946, "end": 17223 }
class ____(logging.Formatter): """Don't include full path in exc_info messages""" def formatException(self, exc_info): formatted = super().formatException(exc_info) return formatted.replace(__file__, ".../" + os.path.basename(__file__))
ShortExcFormatter
python
keras-team__keras
keras/src/optimizers/rmsprop.py
{ "start": 161, "end": 5775 }
class ____(optimizer.Optimizer): """Optimizer that implements the RMSprop algorithm. The gist of RMSprop is to: - Maintain a moving (discounted) average of the square of gradients - Divide the gradient by the root of this average This implementation of RMSprop uses plain momentum, not Nesterov mo...
RMSprop
python
jazzband__django-formtools
tests/tests.py
{ "start": 6838, "end": 8646 }
class ____(unittest.TestCase): def test_textfield_hash(self): """ Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ f1 = HashTestForm({...
FormHmacTests
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 160274, "end": 164049 }
class ____(DialectKWArgs, HasConditionalDDL, SchemaItem): """A table-level SQL constraint. :class:`_schema.Constraint` serves as the base class for the series of constraint objects that can be associated with :class:`_schema.Table` objects, including :class:`_schema.PrimaryKeyConstraint`, :class:`_...
Constraint
python
simonw__sqlite-utils
sqlite_utils/db.py
{ "start": 6343, "end": 6415 }
class ____(Exception): "Specified columns do not exist"
InvalidColumns
python
numba__numba
numba/tests/test_record_dtype.py
{ "start": 26299, "end": 26693 }
class ____(TestRecordDtype): ''' Same as TestRecordDtype, but stressing the Dispatcher's type dispatch mechanism (issue #384). Note that this does not stress caching of ndarray typecodes as the path that uses the cache is not taken with recarrays. ''' def get_cfunc(self, pyfunc, argspec): ...
TestRecordDtypeWithDispatcher
python
kamyu104__LeetCode-Solutions
Python/maximum-area-rectangle-with-point-constraints-i.py
{ "start": 66, "end": 1588 }
class ____(object): def maxRectangleArea(self, points): """ :type points: List[List[int]] :rtype: int """ class BIT(object): # 0-indexed. def __init__(self, n): self.__bit = [0]*(n+1) # Extra one for dummy node. def add(self, i, val)...
Solution
python
joke2k__faker
faker/providers/lorem/az_AZ/__init__.py
{ "start": 68, "end": 1860 }
class ____(LoremProvider): """Implement lorem provider for ``az_AZ`` locale. Word list is based on the source(s) below with some filtering. Sources: - https://1000mostcommonwords.com/1000-most-common-azerbaijani-words/ """ word_list = ( "kimi", "mən", "olmaq", ...
Provider
python
huggingface__transformers
tests/quantization/torchao_integration/test_torchao.py
{ "start": 34769, "end": 35509 }
class ____(TorchAoSerializationTest): device = f"{torch_device}:0" # called only once for all test in this class @classmethod def setUpClass(cls): super().setUpClass() # fmt: off cls.quant_scheme = Int4WeightOnlyConfig(**{"group_size": 32, "version": 1}) cls.quant_scheme...
TorchAoSerializationAcceleratorTest
python
huggingface__transformers
src/transformers/models/chinese_clip/modeling_chinese_clip.py
{ "start": 23975, "end": 27127 }
class ____(PreTrainedModel): config: ChineseCLIPConfig base_model_prefix = "chinese_clip" input_modalities = ("image", "text") supports_gradient_checkpointing = True @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" factor = self.config.initializer_f...
ChineseCLIPPreTrainedModel
python
apache__airflow
providers/databricks/tests/unit/databricks/triggers/test_databricks.py
{ "start": 9733, "end": 13628 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): self.end_time = time.time() + 60 create_connection_without_db( Connection( conn_id=DEFAULT_CONN_ID, conn_type="databricks", host=HOST, ...
TestDatabricksSQLStatementExecutionTrigger
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-neptune/llama_index/graph_stores/neptune/database_property_graph.py
{ "start": 456, "end": 6184 }
class ____(NeptuneBasePropertyGraph): supports_vector_queries: bool = False def __init__( self, host: str, port: int = 8182, client: Any = None, credentials_profile_name: Optional[str] = None, region_name: Optional[str] = None, sign: bool = True, ...
NeptuneDatabasePropertyGraphStore
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 13372, "end": 14030 }
class ____(_GenerativeProvider): generative: Union[GenerativeSearches, _EnumLikeStr] = Field( default=GenerativeSearches.COHERE, frozen=True, exclude=True ) baseURL: Optional[AnyHttpUrl] kProperty: Optional[int] model: Optional[str] maxTokensProperty: Optional[int] returnLikelihoodsP...
_GenerativeCohereConfig
python
run-llama__llama_index
llama-index-integrations/postprocessor/llama-index-postprocessor-sbert-rerank/llama_index/postprocessor/sbert_rerank/base.py
{ "start": 656, "end": 5725 }
class ____(BaseNodePostprocessor): """ HuggingFace class for cross encoding two sentences/texts. Args: model (str): A model name from Hugging Face Hub that can be loaded with AutoModel, or a path to a local model. device (str, optional): Device (like “cuda”, “cpu”, “mps”, “npu”) that should...
SentenceTransformerRerank
python
realpython__materials
python-practice-problems/caesar.py
{ "start": 831, "end": 2079 }
class ____(unittest.TestCase): def test_a(self): start = "aaa" result = caesar(start, 1) self.assertEqual(result, "bbb") result = caesar(start, 5) self.assertEqual(result, "fff") def test_punctuation(self): start = "aaa.bbb" result = caesar(start, 1) ...
CaesarTestCase
python
nedbat__coveragepy
coverage/parser.py
{ "start": 24078, "end": 46313 }
class ____: """Analyze source text with an AST to find executable code paths. The .analyze() method does the work, and populates these attributes: `arcs`: a set of (from, to) pairs of the the arcs possible in the code. `missing_arc_fragments`: a dict mapping (from, to) arcs to lists of message fr...
AstArcAnalyzer
python
numba__numba
numba/cuda/tests/cudapy/test_userexc.py
{ "start": 109, "end": 246 }
class ____(Exception): pass regex_pattern = ( r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+' )
MyError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 5586, "end": 5725 }
class ____(ParentI): def f(self): super: "str" builtins.super(ChildI4, self).f() # no __class__ in the local scope
ChildI4
python
Lightning-AI__lightning
tests/tests_pytorch/test_cli.py
{ "start": 3714, "end": 8649 }
class ____(LightningModule): def __init__(self, model_param: int): super().__init__() self.model_param = model_param def _model_builder(model_param: int) -> Model: return Model(model_param) def _trainer_builder( limit_train_batches: int, fast_dev_run: bool = False, callbacks: Optional[Un...
Model
python
ApeWorX__ape
src/ape_test/accounts.py
{ "start": 411, "end": 3133 }
class ____(TestAccountContainerAPI): generated_accounts: list["TestAccount"] = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __len__(self) -> int: return self.number_of_accounts + len(self.generated_accounts) @property def mnemonic(self) -> str: ...
TestAccountContainer
python
PrefectHQ__prefect
src/integrations/prefect-dbt/tests/cloud/test_jobs.py
{ "start": 24020, "end": 24244 }
class ____: def test_run(self): assert get_run_id.fn({"id": 42}) == 42 def test_fail(self): with pytest.raises(RuntimeError, match="Unable to determine run"): get_run_id.fn({})
TestGetRunId
python
ray-project__ray
rllib/utils/filter.py
{ "start": 504, "end": 1391 }
class ____: """Processes input, possibly statefully.""" def apply_changes(self, other: "Filter", *args, **kwargs) -> None: """Updates self with "new state" from other filter.""" raise NotImplementedError def copy(self) -> "Filter": """Creates a new object with same state as self. ...
Filter
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/atomic_function_test.py
{ "start": 1364, "end": 5935 }
class ____(test.TestCase): def test_call_eager(self): definition, func_type = get_function_def_and_type( lambda x, y: x + y, (constant_op.constant(1), constant_op.constant(2)) ) atomic = atomic_function.from_function_def(definition, func_type) self.assertRegex( str(atomic), ...
AtomicFunctionTest
python
getsentry__sentry
src/sentry/integrations/utils/codecov.py
{ "start": 4872, "end": 6671 }
class ____(TypedDict): lineCoverage: NotRequired[LineCoverage] coverageUrl: NotRequired[str] status: NotRequired[int] attemptedUrl: NotRequired[str] def fetch_codecov_data(config: CodecovConfig) -> CodecovData: data: CodecovData = {} try: # Check if there's an error in the outcome or i...
CodecovData
python
yaml__pyyaml
lib/yaml/tokens.py
{ "start": 1557, "end": 1594 }
class ____(Token): id = '?'
KeyToken
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_fiscal.py
{ "start": 5001, "end": 11792 }
class ____: def test_get_year_end(self): assert makeFY5253NearestEndMonth( startingMonth=8, weekday=WeekDay.SAT ).get_year_end(datetime(2013, 1, 1)) == datetime(2013, 8, 31) assert makeFY5253NearestEndMonth( startingMonth=8, weekday=WeekDay.SUN ).get_year_end(...
TestFY5253NearestEndMonth
python
apache__airflow
providers/elasticsearch/src/airflow/providers/elasticsearch/log/es_response.py
{ "start": 1695, "end": 2339 }
class ____: """Helper class to provide attribute like access to Dictionary objects.""" def __init__(self, d): super().__setattr__("_d_", d) def __getattr__(self, attr_name): """Retrieve an item as an attribute from the dictionary.""" try: return self.__getitem__(attr_na...
AttributeDict
python
kamyu104__LeetCode-Solutions
Python/check-if-any-element-has-prime-frequency.py
{ "start": 514, "end": 802 }
class ____(object): def checkPrimeFrequency(self, nums): """ :type nums: List[int] :rtype: bool """ cnt = collections.defaultdict(int) for x in nums: cnt[x] += 1 return any(SPF[v] == v for v in cnt.itervalues())
Solution
python
pytorch__pytorch
torch/utils/_sympy/functions.py
{ "start": 6729, "end": 11682 }
class ____(sympy.Function): """ We maintain this so that: 1. We can use divisibility guards to simplify FloorDiv(a, b) to a / b. 2. Printing out the expression is nicer (compared to say, representing a//b as (a - a % b) / b) NB: This is Python-style floor division, round to -Inf """ nargs:...
FloorDiv
python
tiangolo__fastapi
docs_src/body_multiple_params/tutorial004.py
{ "start": 242, "end": 653 }
class ____(BaseModel): username: str full_name: Union[str, None] = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Item, user: User, importance: int = Body(gt=0), q: Union[str, None] = None, ): results = {"item_id": item_id, "item": item, "user": use...
User
python
falconry__falcon
tests/test_media_multipart.py
{ "start": 10672, "end": 11865 }
class ____: def on_post(self, req, resp): values = [] for part in req.media: values.append( { 'content_type': part.content_type, 'data': part.data.decode(), 'filename': part.filename, 'name': ...
MultipartAnalyzer
python
numpy__numpy
numpy/polynomial/tests/test_hermite_e.py
{ "start": 3464, "end": 6188 }
class ____: # coefficients of 1 + 2*x + 3*x**2 c1d = np.array([4., 2., 3.]) c2d = np.einsum('i,j->ij', c1d, c1d) c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d) # some random values in [-1, 1) x = np.random.random((3, 5)) * 2 - 1 y = polyval(x, [1., 2., 3.]) def test_hermeval(self): ...
TestEvaluation
python
tensorflow__tensorflow
tensorflow/compiler/tests/dynamic_slice_ops_test.py
{ "start": 985, "end": 3369 }
class ____(xla_test.XLATestCase): def _assertOpOutputMatchesExpected(self, op, args, expected): with self.session() as session: with self.test_scope(): placeholders = [ array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) for arg in args ] feeds = {pl...
DynamicUpdateSliceOpsTest
python
django__django
tests/admin_inlines/admin.py
{ "start": 1179, "end": 1290 }
class ____(admin.TabularInline): model = NonAutoPKBook classes = ("collapse",)
NonAutoPKBookTabularInline
python
has2k1__plotnine
plotnine/scales/scale_size.py
{ "start": 2729, "end": 3273 }
class ____(scale_datetime): """ Datetime area-size scale """ _aesthetics = ["size"] range: InitVar[tuple[float, float]] = (1, 6) """ Range ([Minimum, Maximum]) of the size. """ _: KW_ONLY guide: Literal["legend"] | None = "legend" def __post_init__( self, range, da...
scale_size_datetime
python
realpython__materials
django-vue-graphql/source_code_final/back_end/blog/models.py
{ "start": 363, "end": 495 }
class ____(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name
Tag
python
kamyu104__LeetCode-Solutions
Python/sort-array-by-parity.py
{ "start": 29, "end": 324 }
class ____(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ i = 0 for j in xrange(len(A)): if A[j] % 2 == 0: A[i], A[j] = A[j], A[i] i += 1 return A
Solution
python
numpy__numpy
tools/swig/test/testFortran.py
{ "start": 3270, "end": 3537 }
class ____(FortranTestCase): def __init__(self, methodName="runTest"): FortranTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" ######################################################################
ulongTestCase
python
mlflow__mlflow
dev/clint/src/clint/rules/forbidden_set_active_model_usage.py
{ "start": 84, "end": 667 }
class ____(Rule): def _message(self) -> str: return ( "Usage of `set_active_model` is not allowed in mlflow, use `_set_active_model` instead." ) @staticmethod def check(node: ast.Call, resolver: Resolver) -> bool: """Check if this is a call to set_active_model function."...
ForbiddenSetActiveModelUsage
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/events.py
{ "start": 2280, "end": 6065 }
class ____(event.Events[InstrumentationFactory]): """Events related to class instrumentation events. The listeners here support being established against any new style class, that is any object that is a subclass of 'type'. Events will then be fired off for events against that class. If the "prop...
InstrumentationEvents
python
readthedocs__readthedocs.org
readthedocs/core/history.py
{ "start": 3883, "end": 4391 }
class ____(forms.ModelForm): """Set the change_reason on the model changed through this form.""" change_reason = None def get_change_reason(self): if self.change_reason: return self.change_reason klass = self.__class__.__name__ return f"origin=form class={klass}" d...
SimpleHistoryModelForm
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_wx.py
{ "start": 50650, "end": 51191 }
class ____(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): if not self.canvas._isDrawn: self.canvas.draw() if not self.canvas.bitmap.IsOk() or not wx.TheClipboard.Open(): return try: wx.TheClipboard.SetData(wx.BitmapDataObject(s...
ToolCopyToClipboardWx
python
numpy__numpy
numpy/distutils/command/config.py
{ "start": 20334, "end": 20670 }
class ____: def __init__(self): self.sys_stdout = sys.stdout self.data = '' sys.stdout = self def write (self, data): self.sys_stdout.write(data) self.data += data def flush (self): self.sys_stdout.flush() def restore(self): sys.stdout = self.s...
GrabStdout
python
airbytehq__airbyte
airbyte-integrations/connectors/source-azure-table/source_azure_table/azure_table.py
{ "start": 235, "end": 4662 }
class ____: """ This reader reads data from given table Attributes ---------- logger : AirbyteLogger Airbyte's Logger instance account_name : str The name of your storage account. access_key : str The access key to your storage account. Read more about access keys he...
AzureTableReader
python
scikit-learn__scikit-learn
sklearn/compose/tests/test_column_transformer.py
{ "start": 59861, "end": 77372 }
class ____(Trans): def __init__(self, feature_names_out=None): self.feature_names_out = feature_names_out def get_feature_names_out(self, input_features=None): if self.feature_names_out is not None: return np.asarray(self.feature_names_out, dtype=object) return input_feature...
TransWithNames
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 11372, "end": 11489 }
class ____(ApeException): """ Raised when a problem occurs when using blockchain networks. """
NetworkError
python
euske__pdfminer
pdfminer/pdffont.py
{ "start": 4888, "end": 13966 }
class ____: STANDARD_STRINGS = ( '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', ...
CFFFont
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 62676, "end": 64594 }
class ____(Fittable1DModel): """ One dimensional Constant model. Parameters ---------- amplitude : float Value of the constant function See Also -------- Const2D Notes ----- Model formula: .. math:: f(x) = A Examples -------- .. plot:: ...
Const1D
python
allegroai__clearml
clearml/utilities/resource_monitor.py
{ "start": 477, "end": 26475 }
class ____(BackgroundMonitor): _title_machine = ":monitor:machine" _title_gpu = ":monitor:gpu" _first_report_sec_default = 30.0 _wait_for_first_iteration_to_start_sec_default = 180.0 _max_wait_for_first_iteration_to_start_sec_default = 1800.0 _resource_monitor_instances = [] _multi_node_sing...
ResourceMonitor
python
PrefectHQ__prefect
src/prefect/server/events/clients.py
{ "start": 6378, "end": 7327 }
class ____(EventsClient): _publisher: messaging.EventPublisher async def __aenter__(self) -> Self: publisher = messaging.create_event_publisher() self._publisher = await publisher.__aenter__() return self async def __aexit__( self, exc_type: Optional[Type[Exception]...
PrefectServerEventsClient
python
getsentry__sentry
tests/sentry/seer/explorer/test_index_data.py
{ "start": 6433, "end": 31814 }
class ____(APITransactionTestCase, SnubaTestCase, SpanTestCase): def setUp(self) -> None: super().setUp() self.ten_mins_ago = before_now(minutes=10) def test_get_profiles_for_trace(self) -> None: """Test the full end-to-end happy path for get_profiles_for_trace.""" trace_id = "a...
TestGetProfilesForTrace
python
dask__distributed
distributed/utils_test.py
{ "start": 67520, "end": 69179 }
class ____(Worker): """A Worker that sets event `in_execute` the first time it enters the execute method and then does not proceed, thus leaving the task in executing state indefinitely, until the test sets `block_execute`. Finally, the worker sets `in_execute_exit` when execute() terminates, but befor...
BlockedExecute
python
eth-brownie__brownie
brownie/exceptions.py
{ "start": 6678, "end": 6753 }
class ____(BrownieEnvironmentWarning): pass @final
InvalidArgumentWarning
python
pyca__cryptography
tests/hazmat/primitives/test_block.py
{ "start": 5819, "end": 6699 }
class ____: def test_cbc(self): with pytest.raises(TypeError): modes.CBC([1] * 16) # type:ignore[arg-type] def test_cfb(self): with pytest.raises(TypeError): CFB([1] * 16) # type:ignore[arg-type] def test_cfb8(self): with pytest.raises(TypeError): ...
TestModesRequireBytes
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 156097, "end": 169144 }
class ____(rv_continuous): r"""A Generalized Inverse Gaussian continuous random variable. %(before_notes)s Notes ----- The probability density function for `geninvgauss` is: .. math:: f(x, p, b) = x^{p-1} \exp(-b (x + 1/x) / 2) / (2 K_p(b)) where ``x > 0``, `p` is a real number ...
geninvgauss_gen
python
great-expectations__great_expectations
great_expectations/expectations/validation_handlers.py
{ "start": 91, "end": 227 }
class ____: def column_map_expectation(self) -> None: logger.debug("MetaPandasDataset.column_map_expectation")
MetaPandasDataset
python
streamlit__streamlit
lib/tests/streamlit/elements/color_picker_test.py
{ "start": 1041, "end": 9393 }
class ____(DeltaGeneratorTestCase): def test_just_label(self): """Test that it can be called with no value.""" st.color_picker("the label") c = self.get_delta_from_queue().new_element.color_picker assert c.label == "the label" assert ( c.label_visibility.value ...
ColorPickerTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 30628, "end": 32131 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook") def test_assert_valid_hook_call(self, mock_hook) -> None: with pytest.warns(AirflowProviderDeprecationWarning): task = CloudDataCatalogRenameTagTemplateFieldOperator( task_id=...
TestCloudDataCatalogRenameTagTemplateFieldOperator
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 17002, "end": 17280 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) destination: Optional[str] = Field( None, description="DBFS destination. Example: `dbfs:/my/path`" )
DbfsStorageInfo
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/pipes/message_readers.py
{ "start": 1609, "end": 3014 }
class ____(PipesChunkedLogReader): def __init__( self, *, bucket: str, key: str, client: Optional["S3Client"] = None, interval: float = 10, target_stream: Optional[IO[str]] = None, # TODO: maybe move this parameter to a different scope decode_f...
PipesS3LogReader
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 49247, "end": 53811 }
class ____(AggregateFnV2): def _require_datasketches(self): try: from datasketches import kll_floats_sketch # type: ignore[import] except ImportError as exc: raise ImportError( "ApproximateQuantile requires the `datasketches` package. " "Insta...
ApproximateQuantile
python
run-llama__llama_index
llama-index-core/llama_index/core/agent/workflow/codeact_agent.py
{ "start": 2771, "end": 15021 }
class ____(BaseWorkflowAgent): """ A workflow agent that can execute code. """ scratchpad_key: str = "scratchpad" code_execute_fn: Union[Callable, Awaitable] = Field( description=( "The function to execute code. Required in order to execute code generated by the agent.\n" ...
CodeActAgent
python
dagster-io__dagster
docs/sphinx/_ext/dagster-sphinx/dagster_sphinx/docstring_flags.py
{ "start": 4565, "end": 4970 }
class ____(SphinxDirective): # Takes two arguments-- the first word is the flag type and the remaining words are the message. required_arguments = 1 final_argument_whitespace = True has_content = True def run(self): flag_node = flag() flag_node["flag_type"] = self.arguments[0] ...
FlagDirective
python
kamyu104__LeetCode-Solutions
Python/insert-greatest-common-divisors-in-linked-list.py
{ "start": 43, "end": 484 }
class ____(object): def insertGreatestCommonDivisors(self, head): """ :type head: Optional[ListNode] :rtype: Optional[ListNode] """ def gcd(a, b): while b: a, b = b, a%b return a curr = head while curr.next: ...
Solution
python
astropy__astropy
astropy/visualization/tests/test_interval.py
{ "start": 3698, "end": 3919 }
class ____(TestInterval): # Make sure intervals work with MaskedArray data = np.concatenate((np.linspace(-20.0, 60.0, 100), np.full(100, 1e6))) data = np.ma.MaskedArray(data, data > 1000)
TestIntervalMaskedArray
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/polymorphic_function_test.py
{ "start": 151812, "end": 167643 }
class ____(test.TestCase, parameterized.TestCase): def testNestedCallWatchedVariables(self): v = variables.Variable(4.) @polymorphic_function.function def f(): return v**2. with backprop.GradientTape() as tape: f() self.assertEqual((v,), tape.watched_variables()) @polymorphic...
MultiDeviceTest
python
tensorflow__tensorflow
tensorflow/python/saved_model/save_context.py
{ "start": 766, "end": 1865 }
class ____(threading.local): """A context for building a graph of SavedModel.""" def __init__(self): super(SaveContext, self).__init__() self._in_save_context = False self._options = None def options(self): if not self.in_save_context(): raise ValueError("Not in a SaveContext.") return...
SaveContext
python
pytorch__pytorch
torch/_inductor/codegen/rocm/rocm_template.py
{ "start": 765, "end": 6637 }
class ____(KernelTemplate): index_counter = itertools.count() gfx9_threads_per_warp = 64 def __init__( self, name: str, input_nodes: list[Buffer], layout: Layout, input_reorder: Optional[list[int]] = None, ) -> None: """ Baseclass for ROCm C++ Te...
ROCmTemplate
python
pandas-dev__pandas
pandas/plotting/_core.py
{ "start": 25422, "end": 78431 }
class ____(PandasObject): """ Make plots of Series or DataFrame. Uses the backend specified by the option ``plotting.backend``. By default, matplotlib is used. Parameters ---------- data : Series or DataFrame The object for which the method is called. Attributes ----------...
PlotAccessor
python
google__jax
jax/experimental/slab/slab.py
{ "start": 1042, "end": 1145 }
class ____(NamedTuple): data: jax.Array cursor: Address @jax.tree_util.register_pytree_node_class
Slab
python
huggingface__transformers
src/transformers/models/deberta_v2/modeling_deberta_v2.py
{ "start": 51705, "end": 55646 }
class ____(DebertaV2PreTrainedModel): def __init__(self, config): super().__init__(config) num_labels = getattr(config, "num_labels", 2) self.num_labels = num_labels self.deberta = DebertaV2Model(config) self.pooler = ContextPooler(config) output_dim = self.pooler.o...
DebertaV2ForMultipleChoice
python
nryoung__algorithms
tests/test_data_structures.py
{ "start": 286, "end": 12543 }
class ____(unittest.TestCase): """ Test Binary Search Tree Implementation """ key_val = [ ("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6), ("g", 7), ("h", 8), ("i", 9) ] def shuffle_list(self, ls): shuffle(ls) return ls def test_size(self)...
TestBinarySearchTree
python
celery__celery
celery/app/defaults.py
{ "start": 1016, "end": 16093 }
class ____: """Describes a Celery configuration option.""" alt = None deprecate_by = None remove_by = None old = set() typemap = {'string': str, 'int': int, 'float': float, 'any': lambda v: v, 'bool': strtobool, 'dict': dict, 'tuple': tuple} def __init__(self, default=None, ...
Option
python
eventlet__eventlet
eventlet/green/http/cookies.py
{ "start": 11129, "end": 18623 }
class ____(dict): """A class to hold ONE (key, value) pair. In a cookie, each such pair may have several attributes, so this class is used to keep the attributes associated with the appropriate key,value pair. This class also includes a coded_value attribute, which is used to hold the network repre...
Morsel
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 59170, "end": 59732 }
class ____(PrefectFilterBaseModel): """Filter by `BlockSchema.capabilities`""" any_: Optional[list[str]] = Field( default=None, examples=[["2.0.0", "2.1.0"]], description="A list of block schema versions.", ) def _get_filter_list( self, db: "PrefectDBInterface" ) ->...
BlockSchemaFilterVersion
python
getsentry__sentry
src/sentry/models/options/organization_option.py
{ "start": 3845, "end": 4620 }
class ____(Model): """ Organization options apply only to an instance of a organization. Options which are specific to a plugin should namespace their key. e.g. key='myplugin:optname' key: onboarding:complete value: { updated: datetime } """ __relocation_scope__ = RelocationScope.Orga...
OrganizationOption
python
run-llama__llama_index
llama-index-core/tests/program/test_function_program.py
{ "start": 610, "end": 1522 }
class ____(BaseModel): title: str artist: str songs: List[MockSong] MOCK_ALBUM = MockAlbum( title="hello", artist="world", songs=[MockSong(title="song1"), MockSong(title="song2")], ) MOCK_ALBUM_2 = MockAlbum( title="hello2", artist="world2", songs=[MockSong(title="song3"), MockSon...
MockAlbum
python
pytest-dev__pytest
src/_pytest/legacypath.py
{ "start": 9355, "end": 10366 }
class ____: """Backward compatibility wrapper that implements ``py.path.local`` for :class:`TempPathFactory`. .. note:: These days, it is preferred to use ``tmp_path_factory``. :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`. """ _tmppath_factory: T...
TempdirFactory
python
PrefectHQ__prefect
src/prefect/server/schemas/responses.py
{ "start": 20845, "end": 21502 }
class ____(ORMBaseModel): """ A response object for global concurrency limits. """ active: bool = Field( default=True, description="Whether the global concurrency limit is active." ) name: str = Field( default=..., description="The name of the global concurrency limit." ) ...
GlobalConcurrencyLimitResponse
python
ethereum__web3.py
tests/conftest.py
{ "start": 812, "end": 1569 }
class ____: LogAnonymous = 0 LogNoArguments = 1 LogSingleArg = 2 LogDoubleArg = 3 LogTripleArg = 4 LogQuadrupleArg = 5 LogSingleAnonymous = 6 LogSingleWithIndex = 7 LogDoubleAnonymous = 8 LogDoubleWithIndex = 9 LogTripleWithIndex = 10 LogQuadrupleWithIndex = 11 LogByt...
LogFunctions
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 13735, "end": 14369 }
class ____(graphene.ObjectType, AssetEventMixin): class Meta: interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneDisplayableEvent) name = "HealthChangedEvent" def __init__(self, event: EventLogEntry): dagster_event = check.not_none(event.dagster_event) self.asset_hea...
GrapheneHealthChangedEvent
python
mlflow__mlflow
mlflow/entities/span_status.py
{ "start": 1882, "end": 5306 }
class ____: """ Status of the span or the trace. Args: status_code: The status code of the span or the trace. This must be one of the values of the :py:class:`mlflow.entities.SpanStatusCode` enum or a string representation of it like "OK", "ERROR". description: Descr...
SpanStatus
python
conda__conda
conda/common/configuration.py
{ "start": 3302, "end": 3699 }
class ____(ValidationError): def __init__(self, source, keys, preferred_key): self.source = source self.keys = keys msg = ( f"Multiple aliased keys in file {source}:\n" f"{pretty_list(keys)}\n" f"Must declare only one. Prefer '{preferred_key}'" ) ...
MultipleKeysError
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/schedules/__init__.py
{ "start": 1338, "end": 1470 }
class ____(graphene.ObjectType): scheduler_class = graphene.String() class Meta: name = "Scheduler"
GrapheneScheduler
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-google-genai/llama_index/llms/google_genai/utils.py
{ "start": 15992, "end": 21346 }
class ____(typing.TypedDict): model: str history: list[types.Content] config: types.GenerateContentConfig async def prepare_chat_params( model: str, messages: Sequence[ChatMessage], use_file_api: bool = False, client: Optional[Client] = None, **kwargs: Any, ) -> tuple[Union[types.Conte...
ChatParams
python
python-markdown__markdown
tests/test_syntax/extensions/test_smarty.py
{ "start": 805, "end": 5717 }
class ____(TestCase): default_kwargs = {'extensions': ['smarty']} def test_basic(self): self.assertMarkdownRenders( "It's fun. What's fun?", '<p>It&rsquo;s fun. What&rsquo;s fun?</p>' ) self.assertMarkdownRenders( '"Isn\'t this fun"? --- she said...'...
TestSmarty
python
facebook__pyre-check
client/commands/expression_level_coverage.py
{ "start": 952, "end": 1061 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): line: int column: int @dataclass(frozen=True)
Pair
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 19348, "end": 19654 }
class ____(Literal): """Any list literal such as ``[1, 2, 3]``""" fields = ("items",) items: list[Expr] def as_const(self, eval_ctx: EvalContext | None = None) -> list[t.Any]: eval_ctx = get_eval_context(self, eval_ctx) return [x.as_const(eval_ctx) for x in self.items]
List
python
ray-project__ray
python/ray/tune/tests/test_tune_restore_warm_start.py
{ "start": 7513, "end": 8246 }
class ____(AbstractWarmStartTest, unittest.TestCase): def set_basic_conf(self): dim_dict = { "height": (ValueType.CONTINUOUS, [-100, 100], 1e-2), "width": (ValueType.DISCRETE, [0, 20], False), } def cost(param): tune.report( dict(loss=(par...
ZOOptWarmStartTest
python
imageio__imageio
imageio/config/extensions.py
{ "start": 188, "end": 47023 }
class ____: """File Extension Metadata This class holds information about a image file format associated with a given extension. This information is used to track plugins that are known to be able to handle a particular format. It also contains additional information about a format, which is used w...
FileExtension
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 34470, "end": 35192 }
class ____(PipesStdioLogWriterChannel): """A log writer channel that writes stdout or stderr via the message writer channel.""" def __init__( self, message_channel: PipesMessageWriterChannel, stream: Literal["stdout", "stderr"], name: str, interval: float, ): ...
PipesDefaultLogWriterChannel
python
coleifer__peewee
peewee.py
{ "start": 55786, "end": 56129 }
class ____(ColumnBase): def __init__(self, namespace, attribute): self._namespace = namespace self._attribute = attribute def __sql__(self, ctx): return (ctx .literal(self._namespace._name + '.') .sql(Entity(self._attribute))) EXCLUDED = _Namespace('EXCL...
NamespaceAttribute
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/dml.py
{ "start": 2023, "end": 6727 }
class ____(StandardInsert): """SQLite-specific implementation of INSERT. Adds methods for SQLite-specific syntaxes such as ON CONFLICT. The :class:`_sqlite.Insert` object is created using the :func:`sqlalchemy.dialects.sqlite.insert` function. .. versionadded:: 1.4 .. seealso:: :ref...
Insert
python
dask__distributed
distributed/tests/test_nanny.py
{ "start": 28752, "end": 29783 }
class ____(Nanny): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.in_instantiate = asyncio.Event() self.wait_instantiate = asyncio.Event() async def instantiate(self): self.in_instantiate.set() await self.wait_instantiate.wait() raise...
SlowBrokenNanny
python
langchain-ai__langchain
libs/core/tests/unit_tests/test_tools.py
{ "start": 46822, "end": 47090 }
class ____(BaseTool): name: str = "foo" description: str = "foo." @override def _run(self, x: int, y: Annotated[str, InjectedToolArg]) -> Any: """Foo. Args: x: abc y: 123 """ return y
InjectedTool
python
pennersr__django-allauth
allauth/mfa/base/views.py
{ "start": 4930, "end": 5818 }
class ____(TemplateView): template_name = "mfa/index." + account_settings.TEMPLATE_EXTENSION def get_context_data(self, **kwargs): ret = super().get_context_data(**kwargs) authenticators = {} for auth in Authenticator.objects.filter(user=self.request.user): if auth.type == A...
IndexView
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/constant_op_test.py
{ "start": 1605, "end": 11586 }
class ____(test.TestCase): def _testCpu(self, x): np_ans = np.array(x) with self.cached_session(use_gpu=False): tf_ans = ops.convert_to_tensor(x).eval() dtype = dtypes_lib.as_dtype(np_ans.dtype) if dtype.is_floating or dtype.is_complex: self.assertAllClose(np_ans, tf_ans) else: ...
ConstantTest
python
pandas-dev__pandas
asv_bench/benchmarks/inference.py
{ "start": 1816, "end": 2280 }
class ____: # maybe_convert_numeric depends _exclusively_ on _libs, could # go in benchmarks/libs.py def setup_cache(self): N = 10**6 arr = np.repeat([2**63], N) + np.arange(N).astype("uint64") data = arr.astype(object) data[1::2] = arr[1::2].astype(str) data[-1] = ...
MaybeConvertNumeric