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
pola-rs__polars
py-polars/src/polars/datatype_expr/list.py
{ "start": 68, "end": 496 }
class ____: """Namespace for list datatype expressions.""" _accessor = "list" def __init__(self, expr: pl.DataTypeExpr) -> None: self._pydatatype_expr = expr._pydatatype_expr def inner_dtype(self) -> pl.DataTypeExpr: """Get the inner DataType of list.""" return pl.DataTypeExpr...
DataTypeExprListNameSpace
python
huggingface__transformers
src/transformers/models/ernie4_5/modeling_ernie4_5.py
{ "start": 5006, "end": 9361 }
class ____(nn.Module): def __init__(self, config: Ernie4_5Config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config...
Ernie4_5MLP
python
tensorflow__tensorflow
tensorflow/python/ops/distributions/student_t.py
{ "start": 13274, "end": 14185 }
class ____(StudentT): """StudentT with `df = floor(abs(df))` and `scale = softplus(scale)`.""" @deprecation.deprecated( "2019-01-01", "Use `tfd.StudentT(tf.floor(tf.abs(df)), loc, " "tf.nn.softplus(scale)) instead.", warn_once=True) def __init__(self, df, loc...
StudentTWithAbsDfSoftplusScale
python
run-llama__llama_index
llama-index-packs/llama-index-packs-llama-dataset-metadata/llama_index/packs/llama_dataset_metadata/base.py
{ "start": 6239, "end": 8241 }
class ____(BaseLlamaPack): """ A llamapack for creating and saving the necessary metadata files for submitting a llamadataset: card.json and README.md. """ def run( self, index: BaseIndex, benchmark_df: pd.DataFrame, rag_dataset: "LabelledRagDataset", name: s...
LlamaDatasetMetadataPack
python
tiangolo__fastapi
docs_src/cookie_param_models/tutorial001_an_py310.py
{ "start": 116, "end": 343 }
class ____(BaseModel): session_id: str fatebook_tracker: str | None = None googall_tracker: str | None = None @app.get("/items/") async def read_items(cookies: Annotated[Cookies, Cookie()]): return cookies
Cookies
python
django__django
django/views/generic/__init__.py
{ "start": 802, "end": 886 }
class ____(Exception): """A problem in a generic view.""" pass
GenericViewError
python
kamyu104__LeetCode-Solutions
Python/k-inverse-pairs-array.py
{ "start": 797, "end": 1460 }
class ____(object): def kInversePairs(self, n, k): """ :type n: int :type k: int :rtype: int """ MOD = 10**9+7 dp = [0]*(k+1) dp[0] = 1 for i in xrange(n): new_dp = [0]*len(dp) for j in xrange(len(dp)): n...
Solution2
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/conv1d_transpose_test.py
{ "start": 1139, "end": 9188 }
class ____(test.TestCase): def testConv1DTransposeSingleStride(self): with self.cached_session(): strides = [1, 1, 1] # Input, output: [batch, width, depth] x_shape = [2, 6, 3] y_shape = [2, 6, 2] # Filter: [kernel_width, output_depth, input_depth] f_shape = [3, 2, 3] ...
Conv1DTransposeTest
python
getsentry__sentry
src/sentry/utils/retries.py
{ "start": 743, "end": 3436 }
class ____(ABC): @abstractmethod def __call__(self, function: Callable[[], T]) -> T: raise NotImplementedError @classmethod def wrap(cls, *args, **kwargs): """ A decorator that may be used to wrap a function to be retried using this policy. """ retrier = ...
RetryPolicy
python
readthedocs__readthedocs.org
readthedocs/organizations/views/base.py
{ "start": 4269, "end": 5364 }
class ____(SuccessMessageMixin, CheckOrganizationsEnabled): """Mixin for an organization view that doesn't have nested components.""" model = Organization form_class = OrganizationForm admin_only = True # Only relevant when mixed into lookup_field = "slug" lookup_url_field = "slug" de...
OrganizationView
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_eks.py
{ "start": 29991, "end": 37751 }
class ____: @mock.patch("airflow.providers.cncf.kubernetes.operators.pod.KubernetesPodOperator.execute") @mock.patch("airflow.providers.amazon.aws.hooks.eks.EksHook.generate_config_file") @mock.patch("airflow.providers.amazon.aws.hooks.eks.EksHook._secure_credential_context") @mock.patch("airflow.provid...
TestEksPodOperator
python
ethereum__web3.py
web3/providers/persistent/request_processor.py
{ "start": 678, "end": 1081 }
class ____(asyncio.Queue[T]): """ A queue that relies on a task to be running to process items in the queue. """ async def get(self) -> T: item = await super().get() if isinstance(item, Exception): # if the item is an exception, raise it so the task can handle this case ...
TaskReliantQueue
python
getsentry__sentry
tests/sentry/event_manager/test_event_manager.py
{ "start": 163816, "end": 168012 }
class ____(TransactionTestCase): def test_simple(self) -> None: perf_data = load_data("transaction-n-plus-one", timestamp=before_now(minutes=10)) perf_data["event_id"] = str(uuid.uuid4()) event = _get_event_instance(perf_data, project_id=self.project.id) group_hash = "some_group" ...
TestSaveGroupHashAndGroup
python
doocs__leetcode
solution/0100-0199/0111.Minimum Depth of Binary Tree/Solution.py
{ "start": 192, "end": 545 }
class ____: def minDepth(self, root: Optional[TreeNode]) -> int: if root is None: return 0 if root.left is None: return 1 + self.minDepth(root.right) if root.right is None: return 1 + self.minDepth(root.left) return 1 + min(self.minDepth(root.left)...
Solution
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 195863, "end": 196536 }
class ____(ParseElementEnhance): """Matches if expression matches at the beginning of the parse string:: AtStringStart(Word(nums)).parse_string("123") # prints ["123"] AtStringStart(Word(nums)).parse_string(" 123") # raises ParseException """ def __init__(self, expr...
AtStringStart
python
astropy__astropy
astropy/io/fits/tests/test_hdulist.py
{ "start": 601, "end": 46659 }
class ____(FitsTestCase): def test_update_name(self): with fits.open(self.data("o4sp040b0_raw.fits")) as hdul: hdul[4].name = "Jim" hdul[4].ver = 9 assert hdul[("JIM", 9)].header["extname"] == "JIM" def test_hdu_file_bytes(self): with fits.open(self.data("che...
TestHDUListFunctions
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 69200, "end": 71822 }
class ____(BaseType): "A C const or volatile type" subtypes = ['cv_base_type'] is_cv_qualified = 1 def __init__(self, base_type, is_const=0, is_volatile=0): self.cv_base_type = base_type self.is_const = is_const self.is_volatile = is_volatile if base_type.has_attribute...
CConstOrVolatileType
python
PrefectHQ__prefect
tests/server/orchestration/api/test_variables.py
{ "start": 11054, "end": 13246 }
class ____: async def test_no_results( self, client: AsyncClient, ): res = await client.post( "/variables/count", ) assert res.status_code == 200 assert res.json() == 0 async def test_no_filter( self, client: AsyncClient, v...
TestCountVariables
python
walkccc__LeetCode
solutions/2069. Walking Robot Simulation II/2069.py
{ "start": 0, "end": 683 }
class ____: def __init__(self, width: int, height: int): self.isOrigin = True self.i = 0 self.pos = ([((0, 0), 'South')] + [((i, 0), 'East') for i in range(1, width)] + [((width - 1, j), 'North') for j in range(1, height)] + [((i, height - 1), 'West') for i ...
Robot
python
pyparsing__pyparsing
tests/test_simple_unit.py
{ "start": 11298, "end": 13175 }
class ____(PyparsingExpressionTestCase): EQ = pp.Suppress("=") tests = [ PyparsingTest( desc="Define multiple results names in groups", expr=pp.Group( pp.Word(pp.alphas)("key") + EQ + pp.pyparsing_common.number("value") )[...], text="range=...
TestGroups
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/components/shell-script-component/pythonic/2-shell-command-empty-no-model-init.py
{ "start": 23, "end": 428 }
class ____(dg.Component, dg.Resolvable): """COMPONENT SUMMARY HERE. COMPONENT DESCRIPTION HERE. """ def __init__( self, # added arguments here will define yaml schema via Resolvable ): pass def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: ...
ShellCommand
python
huggingface__transformers
tests/models/dac/test_modeling_dac.py
{ "start": 36992, "end": 44211 }
class ____(unittest.TestCase): @parameterized.expand([(model_name,) for model_name in EXPECTED_PREPROC_SHAPE.keys()]) @require_deterministic_for_xpu def test_integration(self, model_name): # load model and processor model_id = f"descript/{model_name}" model = DacModel.from_pretrained...
DacIntegrationTest
python
walkccc__LeetCode
solutions/2533. Number of Good Binary Strings/2533.py
{ "start": 0, "end": 750 }
class ____: def goodBinaryStrings( self, minLength: int, maxLength: int, oneGroup: int, zeroGroup: int, ) -> int: MOD = 1_000_000_007 # dp[i] := the number of good binary strings with length i dp = [1] + [0] * maxLength for i in range(maxLength + 1): # There are ...
Solution
python
zarr-developers__zarr-python
src/zarr/codecs/numcodecs/_codecs.py
{ "start": 9356, "end": 9793 }
class ____(_NumcodecsArrayArrayCodec, codec_name="quantize"): def __init__(self, **codec_config: JSON) -> None: super().__init__(**codec_config) def evolve_from_array_spec(self, array_spec: ArraySpec) -> Quantize: if self.codec_config.get("dtype") is None: dtype = array_spec.dtype.t...
Quantize
python
django__django
django/db/transaction.py
{ "start": 3959, "end": 12506 }
class ____(ContextDecorator): """ Guarantee the atomic execution of a given block. An instance can be used either as a decorator or as a context manager. When it's used as a decorator, __call__ wraps the execution of the decorated function in the instance itself, used as a context manager. Wh...
Atomic
python
matplotlib__matplotlib
lib/matplotlib/bezier.py
{ "start": 418, "end": 5251 }
class ____(ValueError): pass # some functions def get_intersection(cx1, cy1, cos_t1, sin_t1, cx2, cy2, cos_t2, sin_t2): """ Return the intersection between the line through (*cx1*, *cy1*) at angle *t1* and the line through (*cx2*, *cy2*) at angle *t2*. """ # line1 => si...
NonIntersectingPathException
python
streamlit__streamlit
lib/tests/streamlit/elements/doc_string_test.py
{ "start": 1296, "end": 1730 }
class ____: def __init__(self, available, ExceptionType=AttributeError): self.available = available self.ExceptionType = ExceptionType def __getattribute__(self, name): if name == "say_hello" and not self.available: raise self.ExceptionType(f"{name} is not accessible when x ...
ConditionalHello
python
kamyu104__LeetCode-Solutions
Python/valid-palindrome-iii.py
{ "start": 31, "end": 637 }
class ____(object): def isValidPalindrome(self, s, k): """ :type s: str :type k: int :rtype: bool """ if s == s[::-1]: # optional, to optimize special case return True dp = [[1] * len(s) for _ in xrange(2)] for i in reversed(xrange(len(s)...
Solution
python
PrefectHQ__prefect
tests/server/models/test_flows.py
{ "start": 84, "end": 894 }
class ____: async def test_create_flow_succeeds(self, session): flow = await models.flows.create_flow( session=session, flow=schemas.core.Flow(name="my-flow") ) assert flow.name == "my-flow" assert flow.id async def test_create_flow_does_not_upsert(self, session): ...
TestCreateFlow
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 54930, "end": 55052 }
class ____(atlas_info): _lib_names = ['satlas'] _lib_atlas = _lib_names _lib_lapack = _lib_names
atlas_3_10_info
python
huggingface__transformers
src/transformers/models/phi3/modular_phi3.py
{ "start": 10807, "end": 11049 }
class ____(MistralForTokenClassification): pass __all__ = [ "Phi3PreTrainedModel", "Phi3Model", # noqa: F822 "Phi3ForCausalLM", "Phi3ForSequenceClassification", "Phi3ForTokenClassification", ]
Phi3ForTokenClassification
python
huggingface__transformers
src/transformers/models/xmod/modeling_xmod.py
{ "start": 44111, "end": 44980 }
class ____(nn.Module): """Roberta Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn....
XmodLMHead
python
numba__llvmlite
llvmlite/binding/executionengine.py
{ "start": 7717, "end": 9690 }
class ____(ffi.ObjectRef): """ Internal: an ObjectCache instance for use within an ExecutionEngine. """ def __init__(self, obj): ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook, _getbuffer_c_hook, ...
_ObjectCacheRef
python
davidhalter__jedi
jedi/inference/filters.py
{ "start": 4428, "end": 6019 }
class ____(_AbstractUsedNamesFilter): def __init__(self, parent_context, node_context=None, until_position=None, origin_scope=None): """ node_context is an option to specify a second value for use cases like the class mro where the parent class of a new name would be the ...
ParserTreeFilter
python
python-poetry__poetry
src/poetry/utils/cache.py
{ "start": 1246, "end": 1635 }
class ____(Generic[T]): """ Stores data and metadata for cache items. """ data: T expires: int | None = None @property def expired(self) -> bool: """ Return true if the cache item has exceeded its expiration period. """ return self.expires is not None and ti...
CacheItem
python
huggingface__transformers
src/transformers/models/sam/processing_sam.py
{ "start": 1070, "end": 1381 }
class ____(ImagesKwargs, total=False): segmentation_maps: Optional[ImageInput] input_points: Optional[NestedList] input_labels: Optional[NestedList] input_boxes: Optional[NestedList] point_pad_value: Optional[int] mask_size: dict[str, int] mask_pad_size: dict[str, int]
SamImagesKwargs
python
astropy__astropy
astropy/convolution/kernels.py
{ "start": 10019, "end": 11936 }
class ____(Kernel2D): """ 2D Tophat filter kernel. The Tophat filter is an isotropic smoothing filter. It can produce artifacts when applied repeatedly on the same data. The generated kernel is normalized so that it integrates to 1. Parameters ---------- radius : int Radius of...
Tophat2DKernel
python
streamlit__streamlit
lib/streamlit/runtime/forward_msg_queue.py
{ "start": 808, "end": 10620 }
class ____: """Accumulates a session's outgoing ForwardMsgs. Each AppSession adds messages to its queue, and the Server periodically flushes all session queues and delivers their messages to the appropriate clients. ForwardMsgQueue is not thread-safe - a queue should only be used from a single...
ForwardMsgQueue
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-jira-issue/tests/test_tools_jira_issue.py
{ "start": 378, "end": 11674 }
class ____: """Test suite for JiraIssueToolSpec.""" @pytest.fixture def mock_jira(self): """Create a mock JIRA client.""" with patch("llama_index.tools.jira_issue.base.JIRA") as mock: yield mock @pytest.fixture def jira_tool_spec(self, mock_jira): """Create a Ji...
TestJiraIssueToolSpec
python
facebookresearch__faiss
tests/test_standalone_codec.py
{ "start": 3497, "end": 5631 }
class ____(unittest.TestCase): """ comparative accuracy of a few types of indexes """ def compare_accuracy(self, lowac, highac, max_errs=(1e10, 1e10)): d = 96 nb = 1000 nq = 0 nt = 2000 xt, x, _ = get_dataset_2(d, nt, nb, nq) errs = [] for factory_stri...
TestAccuracy
python
allegroai__clearml
clearml/utilities/proxy_object.py
{ "start": 179, "end": 2048 }
class ____(dict): """Dictionary wrapper that updates an arguments instance on any item set in the dictionary""" def __init__( self, update_obj: Any, update_func: Callable, *args: Any, **kwargs: Any, ) -> None: super(ProxyDictPostWrite, self).__init__(*args, *...
ProxyDictPostWrite
python
realpython__materials
python-tuple/data_class.py
{ "start": 71, "end": 391 }
class ____: name: str age: int position: str = "Python Developer" with open("employees.csv", mode="r") as csv_file: reader = csv.reader(csv_file) next(reader) # Skip headers employees = [] for name, age, position in reader: employees.append(Employee(name, int(age), position))
Employee
python
redis__redis-py
redis/auth/err.py
{ "start": 522, "end": 694 }
class ____(Exception): """ Represents an exception during token renewal process. """ def __init__(self, *args): super().__init__(*args)
TokenRenewalErr
python
doocs__leetcode
solution/0200-0299/0207.Course Schedule/Solution.py
{ "start": 0, "end": 520 }
class ____: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: g = [[] for _ in range(numCourses)] indeg = [0] * numCourses for a, b in prerequisites: g[b].append(a) indeg[a] += 1 q = [i for i, x in enumerate(indeg) if x == 0] ...
Solution
python
pola-rs__polars
py-polars/src/polars/datatypes/classes.py
{ "start": 38765, "end": 42026 }
class ____(DataType): """ Base class for extension data types. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. See Also -------- Extension polars.register_extension_type """ d...
BaseExtension
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_d9m_test.py
{ "start": 1487, "end": 3004 }
class ____(test.TestCase): """Test d9m-unimplemented exceptions from SparseSoftmaxXentWithLogitsOp. Test that tf.errors.UnimplementedError is thrown, as appropriate, by the GPU code-paths through SparseSoftmaxXentWithLogitsOp when deterministic ops are enabled. This test assumes that sparse_xent_op_test.py ...
SparseXentOpDeterminismExceptionsTest
python
pytorch__pytorch
test/inductor/test_foreach.py
{ "start": 5799, "end": 34387 }
class ____(TestCase): check_model_gpu = check_model_gpu check_model_cpu = check_model check_kernel_count = True def setUp(self): super().setUp() torch._inductor.metrics.reset() def tearDown(self): super().tearDown() torch._inductor.metrics.reset() def _test_sin...
ForeachTests
python
pytorch__pytorch
test/package/test_save_load.py
{ "start": 544, "end": 10078 }
class ____(PackageTestCase): """Core save_* and loading API tests.""" def test_saving_source(self): buffer = BytesIO() with PackageExporter(buffer) as he: he.save_source_file("foo", str(packaging_directory / "module_a.py")) he.save_source_file("foodir", str(packaging_dir...
TestSaveLoad
python
faif__python-patterns
patterns/behavioral/publish_subscribe.py
{ "start": 969, "end": 2382 }
class ____: def __init__(self, name: str, msg_center: Provider) -> None: self.name = name self.provider = msg_center def subscribe(self, msg: str) -> None: self.provider.subscribe(msg, self) def unsubscribe(self, msg: str) -> None: self.provider.unsubscribe(msg, self) ...
Subscriber
python
getsentry__sentry
tests/sentry/integrations/gitlab/tasks/test_pr_comment.py
{ "start": 1021, "end": 5046 }
class ____(GitLabTestCase): def setUp(self) -> None: super().setUp() self.installation = get_installation_of_type( GitlabIntegration, integration=self.integration, org_id=self.organization.id ) self.pr_comment_workflow = self.installation.get_pr_comment_workflow() ...
GitlabCommentTestCase
python
pandas-dev__pandas
pandas/tests/io/formats/test_to_latex.py
{ "start": 20775, "end": 24863 }
class ____: @pytest.fixture def df_with_symbols(self): """Dataframe with special characters for testing chars escaping.""" a = "a" b = "b" return DataFrame({"co$e^x$": {a: "a", b: "b"}, "co^l1": {a: "a", b: "b"}}) def test_to_latex_escape_false(self, df_with_symbols): ...
TestToLatexEscape
python
doocs__leetcode
solution/3700-3799/3748.Count Stable Subarrays/Solution.py
{ "start": 0, "end": 805 }
class ____: def countStableSubarrays( self, nums: List[int], queries: List[List[int]] ) -> List[int]: s = [0] l, n = 0, len(nums) seg = [] for r, x in enumerate(nums): if r == n - 1 or x > nums[r + 1]: seg.append(l) k = r - l + ...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 151103, "end": 158795 }
class ____( HasCompileState, GenerativeSelect, TypedReturnsRows[Unpack[_Ts]] ): """Forms the basis of ``UNION``, ``UNION ALL``, and other SELECT-based set operations. .. seealso:: :func:`_expression.union` :func:`_expression.union_all` :func:`_expression.intersect` ...
CompoundSelect
python
spack__spack
lib/spack/spack/solver/requirements.py
{ "start": 796, "end": 1020 }
class ____(enum.Enum): """Origin of a requirement""" REQUIRE_YAML = enum.auto() PREFER_YAML = enum.auto() CONFLICT_YAML = enum.auto() DIRECTIVE = enum.auto() INPUT_SPECS = enum.auto()
RequirementOrigin
python
networkx__networkx
networkx/readwrite/tests/test_p2g.py
{ "start": 129, "end": 1319 }
class ____: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) def test_read_p2g(self): s = b"""\...
TestP2G
python
huggingface__transformers
tests/models/blip_2/test_modeling_blip_2.py
{ "start": 49172, "end": 52347 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (Blip2VisionModelWithProjection,) if is_torch_available() else () test_resize_embeddings = False def setUp(self): self.model_tester = Blip2VisionModelWithProjectionTester(self) def test_model(self): config_and_inputs...
Blip2VisionModelWithProjectionTest
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/migration/ndb/overview/main.py
{ "start": 808, "end": 2510 }
class ____(ndb.Model): """Models an individual Guestbook entry with content and date.""" content = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) with client.context(): @classmethod def query_book(cls, ancestor_key): return cls.query(ancestor=ancestor_...
Greeting
python
milvus-io__pymilvus
tests/test_grpc_handler.py
{ "start": 422, "end": 5327 }
class ____: @pytest.mark.parametrize("has", [True, False]) def test_has_collection_no_error(self, channel, client_thread, has): handler = GrpcHandler(channel=channel) has_collection_future = client_thread.submit(handler.has_collection, "fake") (invocation_metadata, request, rpc) = chan...
TestGrpcHandler
python
astropy__astropy
astropy/coordinates/polarization.py
{ "start": 2055, "end": 4550 }
class ____(MixinInfo): # The attributes containing actual information. _represent_as_dict_attrs = {"value"} # Since there is only one attribute, use a column with the name to represent it # (rather than as name.value) _represent_as_dict_primary_data = "value" # Attributes that should be presente...
StokesCoordInfo
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 15574, "end": 18274 }
class ____(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ def __init__( self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False, scale...
Sam2VideoPositionEmbeddingSine
python
jazzband__django-simple-history
simple_history/tests/tests/test_models.py
{ "start": 66636, "end": 67974 }
class ____(TestCase): def setUp(self): pre_create_historical_record.connect( add_static_history_ip_address, sender=HistoricalPollWithHistoricalIPAddress, dispatch_uid="add_static_history_ip_address", ) def tearDown(self): pre_create_historical_record....
ExtraFieldsStaticIPAddressTestCase
python
ray-project__ray
python/ray/tune/experiment/trial.py
{ "start": 6992, "end": 38610 }
class ____: """A trial object holds the state for one model training run. Trials are themselves managed by the TrialRunner class, which implements the event loop for submitting trial runs to a Ray cluster. Trials start in the PENDING state, and transition to RUNNING once started. On error, it tran...
Trial
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constructors.py
{ "start": 1282, "end": 1471 }
class ____(ParentWithInit): def __new__(cls, input): _test_sink(input) return object.__new__(cls) def test_new_thing(): c = ChildWithNew(_test_source())
ChildWithNew
python
google__python-fire
examples/widget/collector.py
{ "start": 708, "end": 1127 }
class ____(object): """A Collector has one Widget, but wants more.""" def __init__(self): self.widget = widget.Widget() self.desired_widget_count = 10 def collect_widgets(self): """Returns all the widgets the Collector wants.""" return [widget.Widget() for _ in range(self.desired_widget_count)] ...
Collector
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 40216, "end": 44481 }
class ____(AltCLIPPreTrainedModel): config: AltCLIPTextConfig # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->AltRoberta def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): ...
AltRobertaModel
python
getsentry__sentry
src/sentry/auth/providers/github/views.py
{ "start": 4539, "end": 4857 }
class ____(forms.Form): org = forms.ChoiceField(label="Organization") def __init__(self, org_list: list[dict[str, Any]], *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) set_field_choices(self.fields["org"], [(o["id"], o["login"]) for o in org_list])
SelectOrganizationForm
python
lazyprogrammer__machine_learning_examples
supervised_class2/rf_vs_bag2.py
{ "start": 1102, "end": 2854 }
class ____: def __init__(self, n_estimators): self.B = n_estimators def fit(self, X, Y, M=None): N, D = X.shape if M is None: M = int(np.sqrt(D)) self.models = [] self.features = [] for b in range(self.B): tree = DecisionTreeClassifier() # sample features features ...
NotAsRandomForest
python
fastapi__sqlmodel
docs_src/tutorial/connect/select/tutorial001.py
{ "start": 254, "end": 2194 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") sqlite_file_name = "database.db" sqli...
Hero
python
getsentry__sentry
src/sentry/management/commands/generate_reset_password_link.py
{ "start": 231, "end": 1190 }
class ____(BaseCommand): help = "Generate a link for a user to reset their password" def add_arguments(self, parser): parser.add_argument( "--noinput", dest="noinput", action="store_true", default=False, help="Dont ask for confirmation before ...
Command
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 67283, "end": 69322 }
class ____(Field): """A field that takes the value returned by a `Schema <marshmallow.Schema>` method. :param serialize: The name of the Schema method from which to retrieve the value. The method must take an argument ``obj`` (in addition to self) that is the object to be serialized. :param...
Method
python
Pylons__pyramid
src/pyramid/csrf.py
{ "start": 1557, "end": 2862 }
class ____: """A CSRF storage policy that persists the CSRF token in the session. Note that using this CSRF implementation requires that a :term:`session factory` is configured. ``key`` The session key where the CSRF token will be stored. Default: `_csrft_`. .. versionadded:: 1.9...
SessionCSRFStoragePolicy
python
econchick__interrogate
tests/functional/sample/full.py
{ "start": 1706, "end": 1879 }
class ____: """Bar class""" def method_bar(self): """a method that does bar""" class InnerBar: """an inner class""" pass
Bar
python
pytorch__pytorch
benchmarks/instruction_counts/core/api.py
{ "start": 900, "end": 1055 }
class ____(enum.Enum): FORWARD = "Forward" FORWARD_BACKWARD = "Forward + Backward" EXPLICIT = "" @dataclasses.dataclass(frozen=True)
AutogradMode
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 137686, "end": 139996 }
class ____(TypedDict, total=False): type: Required[Literal['url']] max_length: int allowed_schemes: list[str] host_required: bool # default False default_host: str default_port: int default_path: str strict: bool ref: str metadata: dict[str, Any] serialization: SerSchema d...
UrlSchema
python
Unity-Technologies__ml-agents
utils/validate_inits.py
{ "start": 106, "end": 1701 }
class ____(PEP420PackageFinder): """ The PEP420PackageFinder (used by find_namespace_packages) thinks everything looks like a package, even if there are no python files in it. This is a little stricter and only considers directories with python files in it. """ @staticmethod def _looks_like...
NonTrivialPEP420PackageFinder
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/dml.py
{ "start": 64211, "end": 64520 }
class ____(Update, TypedReturnsRows[Unpack[_Ts]]): """Typing-only class that establishes a generic type form of :class:`.Update` which tracks returned column types. This datatype is delivered when calling the :meth:`.Update.returning` method. .. versionadded:: 2.0 """
ReturningUpdate
python
tensorflow__tensorflow
tensorflow/python/data/util/nest_test.py
{ "start": 1711, "end": 23793 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testFlattenAndPack(self): structure = ((3, 4), 5, (6, 7, (9, 10), 8)) flat = ["a", "b", "c", "d", "e", "f", "g", "h"] self.assertEqual(nest.flatten(structure), [3, 4, 5, 6, 7...
NestTest
python
scikit-learn__scikit-learn
sklearn/tree/_classes.py
{ "start": 2398, "end": 25113 }
class ____(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta): """Base class for decision trees. Warning: This class should not be used directly. Use derived classes instead. """ # "check_input" is used for optimisation and isn't something to be passed # around in a pipeline. __metadata_r...
BaseDecisionTree
python
Textualize__textual
src/textual/_event_broker.py
{ "start": 73, "end": 158 }
class ____(Exception): """Raised when handler isn't found in the meta."""
NoHandler
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 123514, "end": 123606 }
class ____(Qwen3OmniMoeThinkerTextRotaryEmbedding): pass
Qwen3OmniMoeTalkerRotaryEmbedding
python
kamyu104__LeetCode-Solutions
Python/shortest-word-distance-iii.py
{ "start": 29, "end": 739 }
class ____(object): # @param {string[]} words # @param {string} word1 # @param {string} word2 # @return {integer} def shortestWordDistance(self, words, word1, word2): dist = float("inf") is_same = (word1 == word2) i, index1, index2 = 0, None, None while i < len(words)...
Solution
python
pytorch__pytorch
torch/fx/graph_module.py
{ "start": 1155, "end": 5385 }
class ____: def __init__(self): self.eval_cache = {} self.next_id = 0 def cache(self, src: str, globals: dict[str, Any], co_fields=None): """Store the source in a private cache, and add a lazy entry in linecache that allows the source to be retrieved by 'filename'. Args...
_EvalCacheLoader
python
ansible__ansible
lib/ansible/module_utils/facts/system/distribution.py
{ "start": 33010, "end": 33610 }
class ____(BaseFactCollector): name = 'distribution' _fact_ids = set(['distribution_version', 'distribution_release', 'distribution_major_version', 'os_family']) # type: t.Set[str] def collect(self, module=None, collected_facts=None): ...
DistributionFactCollector
python
kubernetes-client__python
kubernetes/client/models/v1_resource_slice_spec.py
{ "start": 383, "end": 12578 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ResourceSliceSpec
python
aimacode__aima-python
deep_learning4e.py
{ "start": 1870, "end": 2111 }
class ____(Activation): def __init__(self, alpha=0.01): self.alpha = alpha def function(self, x): return max(x, self.alpha * x) def derivative(self, value): return 1 if value > 0 else self.alpha
LeakyReLU
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 173965, "end": 176446 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 3, 3]"): l_x_ = L_x_ _saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors...
GraphModule
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dlp.py
{ "start": 13179, "end": 14062 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook") def test_get_deidentify_template(self, mock_hook): mock_hook.return_value.get_deidentify_template.return_value = DeidentifyTemplate() operator = CloudDLPGetDeidentifyTemplateOperator( template_id=TEM...
TestCloudDLPGetDeidentifyTemplateOperator
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 13339, "end": 13727 }
class ____(GenericModel, Generic[TestConfigT]): bypass_reason: Optional[str] tests: Optional[List[TestConfigT]] @validator("tests", always=True) def no_bypass_reason_when_tests_is_set(cls, tests, values): if tests and values.get("bypass_reason"): raise ValueError("You can't set a by...
GenericTestConfig
python
PrefectHQ__prefect
tests/test_flows.py
{ "start": 114052, "end": 121736 }
class ____: def test_noniterable_hook_raises(self): def crashed_hook(): pass with pytest.raises( TypeError, match=re.escape( "Expected iterable for 'on_crashed'; got function instead. Please" " provide a list of hooks to 'on_crashe...
TestFlowHooksOnCrashed
python
huggingface__transformers
src/transformers/models/rag/retrieval_rag.py
{ "start": 8275, "end": 10498 }
class ____(Index): def __init__(self, vector_size, dataset, index_initialized=False): requires_backends(self, ["faiss"]) self.vector_size = vector_size self.dataset = dataset self._index_initialized = index_initialized self._check_dataset_format(with_index=index_initialized) ...
HFIndexBase
python
sympy__sympy
sympy/vector/operators.py
{ "start": 719, "end": 1194 }
class ____(Expr): """ Represents unevaluated Gradient. Examples ======== >>> from sympy.vector import CoordSys3D, Gradient >>> R = CoordSys3D('R') >>> s = R.x*R.y*R.z >>> Gradient(s) Gradient(R.x*R.y*R.z) """ def __new__(cls, expr): expr = sympify(expr) ob...
Gradient
python
openai__openai-python
src/openai/types/fine_tuning/dpo_hyperparameters.py
{ "start": 220, "end": 1064 }
class ____(BaseModel): batch_size: Union[Literal["auto"], int, None] = None """Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. """ beta: Union[Literal["auto"], float, None] = None """The beta value for ...
DpoHyperparameters
python
astropy__astropy
astropy/coordinates/angles/errors.py
{ "start": 1153, "end": 1712 }
class ____(AstropyWarning): """ Raised when an hour value is 24. Parameters ---------- hour : int, float """ def __init__(self, hour, alternativeactionstr=None): self.hour = hour self.alternativeactionstr = alternativeactionstr def __str__(self): message = ( ...
IllegalHourWarning
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 112712, "end": 113705 }
class ____(torch.nn.Module): def forward( self, primals_1: "f32[24]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=0), attr='a') primals_2: "f32[24]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=0), attr='b') ): clone: "f32[24]" = torch.ops.aten.clone.default(primals_1...
GraphModule
python
conda__conda
conda/exceptions.py
{ "start": 19406, "end": 19550 }
class ____(ParseError): def __init__(self, reason: str): self.reason = reason super().__init__(self.args[0])
CouldntParseError
python
mwaskom__seaborn
tests/test_rcmod.py
{ "start": 1087, "end": 2310 }
class ____: @pytest.fixture(autouse=True) def reset_params(self): yield rcmod.reset_orig() def flatten_list(self, orig_list): iter_list = map(np.atleast_1d, orig_list) flat_list = [item for sublist in iter_list for item in sublist] return flat_list def assert_...
RCParamFixtures
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 58097, "end": 58387 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('total', c_ulonglong), ('reserved', c_ulonglong), ('free', c_ulonglong), ('used', c_ulonglong), ] _fmt_ = {'<default>': "%d B"} nvmlMemory_v2 = 0x02000028
c_nvmlMemory_v2_t
python
google__jax
jax/_src/test_loader.py
{ "start": 5960, "end": 7048 }
class ____(unittest.TestSuite): """Runs tests in parallel using threads if TEST_NUM_THREADS is > 1. Caution: this test suite does not run setUpClass or setUpModule methods if thread parallelism is enabled. """ def __init__(self, suite: unittest.TestSuite): super().__init__(list(suite)) def run(self, ...
JaxTestSuite
python
python-attrs__attrs
typing-examples/baseline.py
{ "start": 400, "end": 556 }
class ____: x: int ngf = NGFrozen(1) attrs.fields(NGFrozen).x.evolve(eq=False) a = attrs.fields(NGFrozen).x a.evolve(repr=False) @attrs.define
NGFrozen
python
pallets__itsdangerous
src/itsdangerous/timed.py
{ "start": 5955, "end": 8087 }
class ____(Serializer[_TSerialized]): """Uses :class:`TimestampSigner` instead of the default :class:`.Signer`. """ default_signer: type[TimestampSigner] = TimestampSigner # pyright: ignore def iter_unsigners( self, salt: str | bytes | None = None ) -> cabc.Iterator[TimestampSigner]: ...
TimedSerializer