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
bokeh__bokeh
src/bokeh/models/axes.py
{ "start": 9100, "end": 9552 }
class ____(ContinuousAxis): ''' An axis that picks nice numbers for tick locations on a log scale. Configured with a ``LogTickFormatter`` by default. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ticker = Override(default=InstanceDefault(LogTicker)) formatter = Override(default=InstanceDefault(LogTickFormatter))
LogAxis
python
sqlalchemy__sqlalchemy
test/sql/test_types.py
{ "start": 135462, "end": 144358 }
class ____( fixtures.TablesTest, AssertsExecutionResults, AssertsCompiledSQL ): """test edge cases for booleans. Note that the main boolean test suite is now in testing/suite/test_types.py the default value of create_constraint was changed to False in version 1.4 with #5367. """ __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "boolean_table", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("value", Boolean(create_constraint=True)), Column("unconstrained_value", Boolean()), ) @testing.requires.enforces_check_constraints @testing.requires.non_native_boolean_unconstrained def test_constraint(self, connection): assert_raises( ( exc.IntegrityError, exc.ProgrammingError, exc.OperationalError, exc.InternalError, # older pymysql's do this ), connection.exec_driver_sql, "insert into boolean_table (id, value) values(1, 5)", ) @testing.skip_if(lambda: testing.db.dialect.supports_native_boolean) def test_unconstrained(self, connection): connection.exec_driver_sql( "insert into boolean_table (id, unconstrained_value)" "values (1, 5)" ) def test_non_native_constraint_custom_type(self): class Foob: def __init__(self, value): self.value = value class MyBool(TypeDecorator): impl = Boolean(create_constraint=True) cache_ok = True # future method def process_literal_param(self, value, dialect): return value.value def process_bind_param(self, value, dialect): return value.value m = MetaData() t1 = Table("t", m, Column("x", MyBool())) const = [c for c in t1.constraints if isinstance(c, CheckConstraint)][ 0 ] self.assert_compile( AddConstraint(const), "ALTER TABLE t ADD CHECK (x IN (0, 1))", dialect="sqlite", ) @testing.skip_if(lambda: testing.db.dialect.supports_native_boolean) def test_nonnative_processor_coerces_to_onezero(self): boolean_table = self.tables.boolean_table with testing.db.connect() as conn: assert_raises_message( exc.StatementError, "Value 5 is not None, True, or False", conn.execute, boolean_table.insert(), {"id": 1, "unconstrained_value": 5}, ) @testing.requires.non_native_boolean_unconstrained def test_nonnative_processor_coerces_integer_to_boolean(self, connection): boolean_table = self.tables.boolean_table connection.exec_driver_sql( "insert into boolean_table (id, unconstrained_value) " "values (1, 5)" ) eq_( connection.exec_driver_sql( "select unconstrained_value from boolean_table" ).scalar(), 5, ) eq_( connection.scalar(select(boolean_table.c.unconstrained_value)), True, ) def test_bind_processor_coercion_native_true(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) is_(proc(True), True) def test_bind_processor_coercion_native_false(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) is_(proc(False), False) def test_bind_processor_coercion_native_none(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) is_(proc(None), None) def test_bind_processor_coercion_native_0(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) is_(proc(0), False) def test_bind_processor_coercion_native_1(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) is_(proc(1), True) def test_bind_processor_coercion_native_str(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) assert_raises_message( TypeError, "Not a boolean value: 'foo'", proc, "foo" ) def test_bind_processor_coercion_native_int_out_of_range(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=True) ) assert_raises_message( ValueError, "Value 15 is not None, True, or False", proc, 15 ) def test_bind_processor_coercion_nonnative_true(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) eq_(proc(True), 1) def test_bind_processor_coercion_nonnative_false(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) eq_(proc(False), 0) def test_bind_processor_coercion_nonnative_none(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) is_(proc(None), None) def test_bind_processor_coercion_nonnative_0(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) eq_(proc(0), 0) def test_bind_processor_coercion_nonnative_1(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) eq_(proc(1), 1) def test_bind_processor_coercion_nonnative_str(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) assert_raises_message( TypeError, "Not a boolean value: 'foo'", proc, "foo" ) def test_bind_processor_coercion_nonnative_int_out_of_range(self): proc = Boolean().bind_processor( mock.Mock(supports_native_boolean=False) ) assert_raises_message( ValueError, "Value 15 is not None, True, or False", proc, 15 ) def test_literal_processor_coercion_native_true(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) eq_(proc(True), "true") def test_literal_processor_coercion_native_false(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) eq_(proc(False), "false") def test_literal_processor_coercion_native_1(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) eq_(proc(1), "true") def test_literal_processor_coercion_native_0(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) eq_(proc(0), "false") def test_literal_processor_coercion_native_str(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) assert_raises_message( TypeError, "Not a boolean value: 'foo'", proc, "foo" ) def test_literal_processor_coercion_native_int_out_of_range(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=True) ) assert_raises_message( ValueError, "Value 15 is not None, True, or False", proc, 15 ) def test_literal_processor_coercion_nonnative_true(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=False) ) eq_(proc(True), "1") def test_literal_processor_coercion_nonnative_false(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=False) ) eq_(proc(False), "0") def test_literal_processor_coercion_nonnative_1(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=False) ) eq_(proc(1), "1") def test_literal_processor_coercion_nonnative_0(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=False) ) eq_(proc(0), "0") def test_literal_processor_coercion_nonnative_str(self): proc = Boolean().literal_processor( default.DefaultDialect(supports_native_boolean=False) ) assert_raises_message( TypeError, "Not a boolean value: 'foo'", proc, "foo" )
BooleanTest
python
tiangolo__fastapi
tests/test_dependency_after_yield_streaming.py
{ "start": 256, "end": 3314 }
class ____: def __init__(self) -> None: self.data = ["foo", "bar", "baz"] self.open = True def __iter__(self) -> Generator[str, None, None]: for item in self.data: if self.open: yield item else: raise ValueError("Session closed") @contextmanager def acquire_session() -> Generator[Session, None, None]: session = Session() try: yield session finally: session.open = False def dep_session() -> Any: with acquire_session() as s: yield s def broken_dep_session() -> Any: with acquire_session() as s: s.open = False yield s SessionDep = Annotated[Session, Depends(dep_session)] BrokenSessionDep = Annotated[Session, Depends(broken_dep_session)] app = FastAPI() @app.get("/data") def get_data(session: SessionDep) -> Any: data = list(session) return data @app.get("/stream-simple") def get_stream_simple(session: SessionDep) -> Any: def iter_data(): yield from ["x", "y", "z"] return StreamingResponse(iter_data()) @app.get("/stream-session") def get_stream_session(session: SessionDep) -> Any: def iter_data(): yield from session return StreamingResponse(iter_data()) @app.get("/broken-session-data") def get_broken_session_data(session: BrokenSessionDep) -> Any: return list(session) @app.get("/broken-session-stream") def get_broken_session_stream(session: BrokenSessionDep) -> Any: def iter_data(): yield from session return StreamingResponse(iter_data()) client = TestClient(app) def test_regular_no_stream(): response = client.get("/data") assert response.json() == ["foo", "bar", "baz"] def test_stream_simple(): response = client.get("/stream-simple") assert response.text == "xyz" def test_stream_session(): response = client.get("/stream-session") assert response.text == "foobarbaz" def test_broken_session_data(): with pytest.raises(ValueError, match="Session closed"): client.get("/broken-session-data") def test_broken_session_data_no_raise(): client = TestClient(app, raise_server_exceptions=False) response = client.get("/broken-session-data") assert response.status_code == 500 assert response.text == "Internal Server Error" def test_broken_session_stream_raise(): # Can raise ValueError on Pydantic v2 and ExceptionGroup on Pydantic v1 with pytest.raises((ValueError, Exception)): client.get("/broken-session-stream") def test_broken_session_stream_no_raise(): """ When a dependency with yield raises after the streaming response already started the 200 status code is already sent, but there's still an error in the server afterwards, an exception is raised and captured or shown in the server logs. """ with TestClient(app, raise_server_exceptions=False) as client: response = client.get("/broken-session-stream") assert response.status_code == 200 assert response.text == ""
Session
python
Lightning-AI__lightning
tests/tests_pytorch/loops/test_loops.py
{ "start": 25315, "end": 25680 }
class ____(torch.utils.data.Dataset): def __init__(self, size: int, length: int): self.len = length data = torch.arange(0, size) / size self.data = data.unsqueeze(0).repeat(length, 1) def __getitem__(self, index: int) -> torch.Tensor: return self.data[index] def __len__(self) -> int: return self.len
RangeDataset
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 34172, "end": 35054 }
class ____(TestCase): @unittest.skipIf(RESOLVER_DNSPYTHON, "dnspython raises an error when multiple results are returned") def test_NUMERICHOST(self): self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), 0) self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), socket.NI_NUMERICHOST) @unittest.skipIf(RESOLVER_DNSPYTHON, "dnspython raises an error when multiple results are returned") def test_NUMERICSERV(self): self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), socket.NI_NUMERICSERV) def test_domain1(self): self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), 0) def test_domain2(self): self._test('getnameinfo', ('www.gevent.org', 80), 0) def test_port_zero(self): self._test('getnameinfo', ('www.gevent.org', 0), 0)
Test_getnameinfo_geventorg
python
getsentry__sentry
tests/sentry/utils/test_services.py
{ "start": 655, "end": 5865 }
class ____(Operation): def apply(self, x: int, y: int) -> int: raise Exception("error") @pytest.fixture def delegator_fixture() -> tuple[Delegator, Mock, Mock]: executor = SynchronousExecutor() selector = Mock() callback = Mock() delegator = Delegator( Operation, {"add": (Add(), executor), "sub": (Sub(), executor), "error": (Error(), executor)}, selector, callback, ) return (delegator, selector, callback) def test_single_backend(delegator_fixture: tuple[Delegator, Mock, Mock]) -> None: (delegator, selector, callback) = delegator_fixture selector.return_value = ["add"] assert delegator.apply(1, 1) == 2 (_, method, kwargs), _ = selector.call_args assert method == "apply" assert kwargs.items() >= {"x": 1, "y": 1}.items() (_, method, kwargs, backends, futures), _ = callback.call_args assert method == "apply" assert kwargs.items() >= {"x": 1, "y": 1}.items() assert backends == ["add"] assert [f.result() for f in futures] == [2] def test_multiple_backends(delegator_fixture: tuple[Delegator, Mock, Mock]) -> None: (delegator, selector, callback) = delegator_fixture selector.return_value = ["add", "sub", "error"] assert delegator.apply(1, 1) == 2 (_, _, _, backends, futures), _ = callback.call_args results = dict(zip(backends, futures)) assert results["add"].result() == 2 assert results["sub"].result() == 0 with pytest.raises(Exception): results["error"].result() def test_invalid_primary_backend(delegator_fixture: tuple[Delegator, Mock, Mock]) -> None: (delegator, selector, callback) = delegator_fixture selector.return_value = ["invalid", "add"] with pytest.raises(Delegator.InvalidBackend): assert delegator.apply(1, 1) assert callback.called is False def test_invalid_secondary_backend(delegator_fixture: tuple[Delegator, Mock, Mock]) -> None: (delegator, selector, callback) = delegator_fixture selector.return_value = ["add", "invalid"] assert delegator.apply(1, 1) == 2 (_, _, _, backends, futures), _ = callback.call_args assert backends == ["add", "invalid"] primary_future, secondary_future = futures assert primary_future.result() == 2 assert secondary_future is None @pytest.fixture def register_option(): options.register("feature.rollout", default=0.0, flags=options.FLAG_AUTOMATOR_MODIFIABLE) yield options.unregister("feature.rollout") def test_make_writebehind_selector_str_key(register_option) -> None: context = Mock() selector = make_writebehind_selector( option_name="feature.rollout", move_to="new", move_from="old", key_fetch=lambda *args: "a-random-key", ) with override_options({"feature.rollout": 0.0}): result = selector(context, "do_thing", {}) assert result == ["old"] with override_options({"feature.rollout": -0.5}): result = selector(context, "do_thing", {}) assert result == ["old"] with override_options({"feature.rollout": -0.8}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": -1.0}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": 0.01}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": 0.1}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": 0.5}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": 0.8}): result = selector(context, "do_thing", {}) assert result == ["new", "old"] with override_options({"feature.rollout": 1.0}): result = selector(context, "do_thing", {}) assert result == ["new", "old"] def test_make_writebehind_selector_int_key(register_option) -> None: context = Mock() selector = make_writebehind_selector( option_name="feature.rollout", move_to="new", move_from="old", key_fetch=lambda *args: 42, ) with override_options({"feature.rollout": 0.0}): result = selector(context, "do_thing", {}) assert result == ["old"] with override_options({"feature.rollout": -0.5}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": -1.0}): result = selector(context, "do_thing", {}) assert result == ["old", "new"] with override_options({"feature.rollout": 0.01}): result = selector(context, "do_thing", {}) assert result == ["new", "old"] with override_options({"feature.rollout": 0.5}): result = selector(context, "do_thing", {}) assert result == ["new", "old"] with override_options({"feature.rollout": 1.0}): result = selector(context, "do_thing", {}) assert result == ["new", "old"]
Error
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 6547, "end": 7000 }
class ____(BaseSafeMigrationTest): app = "bad_flow_run_sql_nested_disabled_app" migrate_from = "0001_initial" migrate_to = "0001_initial" def test(self) -> None: with pytest.raises( UnsafeOperationException, match="Using `RunSQL` is unsafe because our migrations safety framework can't detect problems with the " "migration", ): self.run_migration()
RunSqlDisabledNestedTest
python
huggingface__transformers
src/transformers/models/idefics/perceiver.py
{ "start": 5122, "end": 8626 }
class ____(nn.Module): def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None: """Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`""" super().__init__() self.embed_dim, self.n_heads, self.head_dim = embed_dim, n_heads, head_dim self.qk_layer_norms = qk_layer_norms # Normalization & Scaling self.context_layer_norm = nn.LayerNorm(self.embed_dim) self.latents_layer_norm = nn.LayerNorm(self.embed_dim) if self.qk_layer_norms: self.q_layer_norm = nn.LayerNorm(self.head_dim) self.k_layer_norm = nn.LayerNorm(self.head_dim) self.qk_scale = self.head_dim**-0.5 # Q, K, V Projection (no bias -- detail from Perceiver/Flamingo Papers). self.q_proj = nn.Linear(self.embed_dim, self.n_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(self.embed_dim, self.n_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(self.embed_dim, self.n_heads * self.head_dim, bias=False) self.output_proj = nn.Linear(self.n_heads * self.head_dim, embed_dim, bias=False) def forward(self, context: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: """ Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension! Args: context (`torch.Tensor`): Tensor of shape `[bsz, seq, embed_dim]` representing long-form context to resample. latents (`torch.Tensor`): Tensor of shape `[bsz, n_latents, embed_dim]` representing fixed length latents to compress to. Returns: `torch.Tensor`: Tensor of shape `[bsz, n_latents, embed_dim]` representing attention over latents w/ cross from context. """ context = self.context_layer_norm(context) latents = self.latents_layer_norm(latents) batch_size, seq_length, embed_dim = context.shape[:3] # Query, Key, Value Projections --> Note that in Flamingo, latents are *concatenated* with context prior to attn! # Note: This results in queries w/ `seq = n_latents`, and keys, values with `seq = len(context) + n_latents` q = self.q_proj(latents) k = self.k_proj(torch.cat([context, latents], dim=-2)) v = self.v_proj(torch.cat([context, latents], dim=-2)) # Multiheaded Self-Attention w/ stable softmax (subtract per-row max -- `amax` -- before softmax call) # =>> `attn` should be a 2D matrix of shape [n_latents x (context + n_latents)] # einsum.rearrange(x, "bsz seq (heads embed) -> bsz heads seq embed", heads=self.n_heads) q, k, v = [x.reshape(batch_size, x.shape[1], self.n_heads, self.head_dim).transpose(1, 2) for x in (q, k, v)] if self.qk_layer_norms: q = self.q_layer_norm(q) k = self.k_layer_norm(k) scores = torch.einsum("... i d, ... j d -> ... i j", q * self.qk_scale, k) stabilized_scores = scores - (scores.amax(dim=-1, keepdim=True).detach()) attn = stabilized_scores.softmax(dim=-1) # Attend & project back to output... resampled = torch.einsum("... i j, ... j d -> ... i d", attn, v) # einsum.rearrange(resampled, "bsz heads seq embed -> bsz seq (heads embed)", heads=self.n_heads) return self.output_proj(resampled.transpose(1, 2).flatten(-2))
IdeficsPerceiverAttention
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 59116, "end": 59376 }
class ____(CreateMinimalProxyTo): def build_IR(self, expr, context): vyper_warn( "`create_forwarder_to` is a deprecated alias of `create_minimal_proxy_to`!", expr ) return super().build_IR(expr, context)
CreateForwarderTo
python
catalyst-team__catalyst
catalyst/contrib/data/transforms.py
{ "start": 2798, "end": 3491 }
class ____(object): """Convert a ``numpy.ndarray`` to tensor. Converts numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] if the numpy.ndarray has dtype = np.uint8 In the other cases, tensors are returned without scaling. """ def __call__(self, pic): """ Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: torch.Tensor: Converted image. """ return image_to_tensor(pic) def __repr__(self): """@TODO: Docs. Contribution is welcome.""" return self.__class__.__name__ + "()"
ImageToTensor
python
run-llama__llama_index
llama-index-packs/llama-index-packs-searchain/llama_index/packs/searchain/base.py
{ "start": 1361, "end": 11501 }
class ____(BaseLlamaPack): """Simple short form SearChain pack.""" def __init__( self, data_path: str, dprtokenizer_path: str = "facebook/dpr-reader-multiset-base", # download from https://huggingface.co/facebook/dpr-reader-multiset-base, dprmodel_path: str = "facebook/dpr-reader-multiset-base", # download from https://huggingface.co/facebook/dpr-reader-multiset-base, crossencoder_name_or_path: str = "microsoft/MiniLM-L12-H384-uncased", # down load from https://huggingface.co/microsoft/MiniLM-L12-H384-uncased, device: str = "cuda", **kwargs: Any, ) -> None: """Init params.""" self.device = device self.crossencoder = CrossEncoder(crossencoder_name_or_path, device=self.device) self.documents = SimpleDirectoryReader(data_path).load_data() self.index = VectorStoreIndex.from_documents(self.documents) self.query_engine = self.index.as_query_engine() self.llm = OpenAI() self.dprtokenizer = DPRReaderTokenizer.from_pretrained(dprtokenizer_path) self.dprmodel = DPRReader.from_pretrained(dprmodel_path) self.dprmodel.eval() self.dprmodel.to(self.device) def _get_answer(self, query, texts, title): print("texts:" + texts) encoded_inputs = self.dprtokenizer( questions=[query], titles=[title], texts=[texts], return_tensors="pt", max_length=510, ) outputs = self.dprmodel(**encoded_inputs.to(self.device)) start_logits = outputs.start_logits end_logits = outputs.end_logits relevance_logits = outputs.relevance_logits answer_start_index = outputs.start_logits.argmax() answer_end_index = outputs.end_logits.argmax() predict_answer_tokens = encoded_inputs.input_ids[ 0, answer_start_index : answer_end_index + 1 ] answer = self.dprtokenizer.decode(predict_answer_tokens) return answer, relevance_logits def _ir(self, query, query_seen_list): flag_contibue_label = False query_list = query.split("\n") message = "" for idx in range(len(query_list)): query_item = query_list[idx] if "Query" in query_item and "]:" in query_item: temp = query_item.split("]") if len(temp) < 2: continue query_type = temp[0] query_item = temp[1] if ":" in query_item: query_item = query_item[1:] if not _have_seen_or_not( self.crossencoder, query_item, query_seen_list, query_type ): now_reference = {} query_seen_list.append(query_item) response = str(self.query_engine.query(query_item)) answer, relevance_score = self._get_answer( query=query_item, texts="", title=response ) now_reference["query"] = query_item now_reference["answer"] = answer now_reference["reference"] = response now_reference["ref_score"] = relevance_score now_reference["idx"] = response if "Unsolved" in query_type: message = "[Unsolved Query]:{}<SEP>[Answer]:{}<SEP>[Reference]:{}<SEP>".format( query_item, answer, response ) flag_contibue_label = True break elif relevance_score > 1.5: answer_start_idx = idx + 1 predict_answer = "" while answer_start_idx < len(query_list): if "Answer" in query_list[answer_start_idx]: predict_answer = query_list[answer_start_idx] break answer_start_idx += 1 match_label = _match_or_not( prediction=predict_answer, ground_truth=answer ) if match_label: continue else: message = "[Query]:{}<SEP>[Answer]:{}<SEP>[Reference]:{}<SEP>".format( query_item, answer, response ) flag_contibue_label = True break return message, flag_contibue_label, query_seen_list def _extract(self, message_keys_list): text = message_keys_list idx = len(text) while idx > 0: idx = idx - 1 item = text[idx] if item.role == "assistant" and "Final Content" in item.content: list_item = item.content.split("\n") for sp in list_item: if "Final Content" in sp: return item.content return "Sorry, I still cannot solve this question!" def execute(self, data_path, start_idx): data = open(data_path) for k, example in enumerate(data): if k < start_idx: continue example = json.loads(example) q = example["question"] round_count = 0 message_keys_list = [ ChatMessage( role="user", content="""Construct a global reasoning chain for this complex [Question] : " {} " You should generate a query to the search engine based on what you already know at each step of the reasoning chain, starting with [Query]. If you know the answer for [Query], generate it starting with [Answer]. You can try to generate the final answer for the [Question] by referring to the [Query]-[Answer] pairs, starting with [Final Content]. If you don't know the answer, generate a query to search engine based on what you already know and do not know, starting with [Unsolved Query]. For example: [Question]: "Where do greyhound buses that are in the birthplace of Spirit If...'s performer leave from? " [Query 1]: Who is the performer of Spirit If... ? If you don't know the answer: [Unsolved Query]: Who is the performer of Spirit If... ? If you know the answer: [Answer 1]: The performer of Spirit If... is Kevin Drew. [Query 2]: Where was Kevin Drew born? If you don't know the answer: [Unsolved Query]: Where was Kevin Drew born? If you know the answer: [Answer 2]: Toronto. [Query 3]: Where do greyhound buses in Toronto leave from? If you don't know the answer: [Unsolved Query]: Where do greyhound buses in Toronto leave from? If you know the answer: [Answer 3]: Toronto Coach Terminal. [Final Content]: The performer of Spirit If... is Kevin Drew [1]. Kevin Drew was born in Toronto [2]. Greyhound buses in Toronto leave from Toronto Coach Terminal [3]. So the final answer is Toronto Coach Terminal. [Question]:"Which magazine was started first Arthur’s Magazine or First for Women?" [Query 1]: When was Arthur’s Magazine started? [Answer 1]: 1844. [Query 2]: When was First for Women started? [Answer 2]: 1989 [Final Content]: Arthur’s Magazine started in 1844 [1]. First for Women started in 1989 [2]. So Arthur’s Magazine was started first. So the answer is Arthur’s Magazi [Question]: {}""".format(q, q), ) ] feedback_answer = "continue" predict_answer = "" query_seen_list = [] while round_count < 5 and feedback_answer != "end": time.sleep(0.5) rsp = self.llm.chat(message_keys_list) round_count += 1 input_str = str(rsp.message.content) message_keys_list.append( ChatMessage(role="assistant", content=input_str) ) predict_answer += input_str message, flag_contibue_label, query_seen_list = self._ir( input_str, query_seen_list ) if flag_contibue_label: feedback = message else: feedback = "end" if feedback == "end": break # [Query]:xxxx<SEP>[Answer]:xxxx<SEP>[Reference]:xxxx<SEP> feedback_list = feedback.split("<SEP>") if "Unsolved Query" not in feedback: new_prompt = """Reference: {} According to this Reference, the answer for "{}" should be "{}", you can change your answer based on the Reference and continue constructing the reasoning chain to give the final answer for [Question]:{}""".format( feedback_list[0], feedback_list[1], q, feedback_list[2] ) else: new_prompt = """Reference: {} According to this Reference, the answer for "{}" should be "{}", you can give your answer based on the Reference and continue constructing the reasoning chain to give the final answer for [Question]:{} """.format( feedback_list[0], feedback_list[1], q, feedback_list[2] ) message_keys_list.append(ChatMessage(role="user", content=new_prompt)) result = self._extract(message_keys_list) print(result) return -1
SearChainPack
python
gevent__gevent
src/gevent/_ffi/watcher.py
{ "start": 14873, "end": 15862 }
class ____(object): EVENT_MASK = 0 def __init__(self, loop, fd, events, ref=True, priority=None, _args=None): # Win32 only works with sockets, and only when we use libuv, because # we don't use _open_osfhandle. See libuv/watchers.py:io for a description. self._validate_fd(fd) if events & ~self.EVENT_MASK: raise ValueError('illegal event mask: %r' % events) self._fd = fd super(IoMixin, self).__init__(loop, ref=ref, priority=priority, args=_args or (fd, events)) @classmethod def _validate_fd(cls, fd): if fd < 0: raise ValueError('fd must be non-negative: %r' % fd) def start(self, callback, *args, **kwargs): args = args or _NOARGS if kwargs.get('pass_events'): args = (GEVENT_CORE_EVENTS, ) + args super(IoMixin, self).start(callback, *args) def _format(self): return ' fd=%d' % self._fd
IoMixin
python
charliermarsh__ruff
crates/ruff_benchmark/resources/pydantic/types.py
{ "start": 2654, "end": 8367 }
class ____(_fields.PydanticMetadata): allow_inf_nan: bool = True def confloat( *, strict: bool | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, multiple_of: float | None = None, allow_inf_nan: bool | None = None, ) -> type[float]: return Annotated[ # type: ignore[return-value] float, Strict(strict) if strict is not None else None, annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None, AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None, ] PositiveFloat = Annotated[float, annotated_types.Gt(0)] NegativeFloat = Annotated[float, annotated_types.Lt(0)] NonPositiveFloat = Annotated[float, annotated_types.Le(0)] NonNegativeFloat = Annotated[float, annotated_types.Ge(0)] StrictFloat = Annotated[float, Strict(True)] FiniteFloat = Annotated[float, AllowInfNan(False)] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def conbytes( *, min_length: int | None = None, max_length: int | None = None, strict: bool | None = None, ) -> type[bytes]: return Annotated[ # type: ignore[return-value] bytes, Strict(strict) if strict is not None else None, annotated_types.Len(min_length or 0, max_length), ] StrictBytes = Annotated[bytes, Strict()] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def constr( *, strip_whitespace: bool | None = None, to_upper: bool | None = None, to_lower: bool | None = None, strict: bool | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, ) -> type[str]: return Annotated[ # type: ignore[return-value] str, Strict(strict) if strict is not None else None, annotated_types.Len(min_length or 0, max_length), _fields.PydanticGeneralMetadata( strip_whitespace=strip_whitespace, to_upper=to_upper, to_lower=to_lower, pattern=pattern, ), ] StrictStr = Annotated[str, Strict()] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~ COLLECTION TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HashableItemType = TypeVar('HashableItemType', bound=Hashable) def conset( item_type: Type[HashableItemType], *, min_length: int = None, max_length: int = None ) -> Type[Set[HashableItemType]]: return Annotated[ # type: ignore[return-value] Set[item_type], annotated_types.Len(min_length or 0, max_length) # type: ignore[valid-type] ] def confrozenset( item_type: Type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None ) -> Type[FrozenSet[HashableItemType]]: return Annotated[ # type: ignore[return-value] FrozenSet[item_type], # type: ignore[valid-type] annotated_types.Len(min_length or 0, max_length), ] AnyItemType = TypeVar('AnyItemType') def conlist( item_type: Type[AnyItemType], *, min_length: int | None = None, max_length: int | None = None ) -> Type[List[AnyItemType]]: return Annotated[ # type: ignore[return-value] List[item_type], # type: ignore[valid-type] annotated_types.Len(min_length or 0, max_length), ] def contuple( item_type: Type[AnyItemType], *, min_length: int | None = None, max_length: int | None = None ) -> Type[Tuple[AnyItemType]]: return Annotated[ # type: ignore[return-value] Tuple[item_type], annotated_types.Len(min_length or 0, max_length), ] # ~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORT STRING TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AnyType = TypeVar('AnyType') if TYPE_CHECKING: ImportString = Annotated[AnyType, ...] else: class ImportString: @classmethod def __class_getitem__(cls, item: AnyType) -> AnyType: return Annotated[item, cls()] @classmethod def __get_pydantic_core_schema__( cls, schema: core_schema.CoreSchema | None = None, **_kwargs: Any ) -> core_schema.CoreSchema: if schema is None or schema == {'type': 'any'}: # Treat bare usage of ImportString (`schema is None`) as the same as ImportString[Any] return core_schema.function_plain_schema(lambda v, _: _validators.import_string(v)) else: return core_schema.function_before_schema(lambda v, _: _validators.import_string(v), schema) def __repr__(self) -> str: return 'ImportString' # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def condecimal( *, strict: bool | None = None, gt: int | Decimal | None = None, ge: int | Decimal | None = None, lt: int | Decimal | None = None, le: int | Decimal | None = None, multiple_of: int | Decimal | None = None, max_digits: int | None = None, decimal_places: int | None = None, allow_inf_nan: bool | None = None, ) -> Type[Decimal]: return Annotated[ # type: ignore[return-value] Decimal, Strict(strict) if strict is not None else None, annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None, _fields.PydanticGeneralMetadata(max_digits=max_digits, decimal_places=decimal_places), AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None, ] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @_dataclasses.dataclass(frozen=True) # Add frozen=True to make it hashable
AllowInfNan
python
python-openxml__python-docx
tests/opc/test_packuri.py
{ "start": 105, "end": 3313 }
class ____: def cases(self, expected_values): """ Return list of tuples zipped from uri_str cases and `expected_values`. Raise if lengths don't match. """ uri_str_cases = [ "/", "/ppt/presentation.xml", "/ppt/slides/slide1.xml", ] if len(expected_values) != len(uri_str_cases): msg = "len(expected_values) differs from len(uri_str_cases)" raise AssertionError(msg) pack_uris = [PackURI(uri_str) for uri_str in uri_str_cases] return zip(pack_uris, expected_values) def it_can_construct_from_relative_ref(self): baseURI = "/ppt/slides" relative_ref = "../slideLayouts/slideLayout1.xml" pack_uri = PackURI.from_rel_ref(baseURI, relative_ref) assert pack_uri == "/ppt/slideLayouts/slideLayout1.xml" def it_should_raise_on_construct_with_bad_pack_uri_str(self): with pytest.raises(ValueError, match="PackURI must begin with slash"): PackURI("foobar") def it_can_calculate_baseURI(self): expected_values = ("/", "/ppt", "/ppt/slides") for pack_uri, expected_baseURI in self.cases(expected_values): assert pack_uri.baseURI == expected_baseURI def it_can_calculate_extension(self): expected_values = ("", "xml", "xml") for pack_uri, expected_ext in self.cases(expected_values): assert pack_uri.ext == expected_ext def it_can_calculate_filename(self): expected_values = ("", "presentation.xml", "slide1.xml") for pack_uri, expected_filename in self.cases(expected_values): assert pack_uri.filename == expected_filename def it_knows_the_filename_index(self): expected_values = (None, None, 1) for pack_uri, expected_idx in self.cases(expected_values): assert pack_uri.idx == expected_idx def it_can_calculate_membername(self): expected_values = ( "", "ppt/presentation.xml", "ppt/slides/slide1.xml", ) for pack_uri, expected_membername in self.cases(expected_values): assert pack_uri.membername == expected_membername def it_can_calculate_relative_ref_value(self): cases = ( ("/", "/ppt/presentation.xml", "ppt/presentation.xml"), ( "/ppt", "/ppt/slideMasters/slideMaster1.xml", "slideMasters/slideMaster1.xml", ), ( "/ppt/slides", "/ppt/slideLayouts/slideLayout1.xml", "../slideLayouts/slideLayout1.xml", ), ) for baseURI, uri_str, expected_relative_ref in cases: pack_uri = PackURI(uri_str) assert pack_uri.relative_ref(baseURI) == expected_relative_ref def it_can_calculate_rels_uri(self): expected_values = ( "/_rels/.rels", "/ppt/_rels/presentation.xml.rels", "/ppt/slides/_rels/slide1.xml.rels", ) for pack_uri, expected_rels_uri in self.cases(expected_values): assert pack_uri.rels_uri == expected_rels_uri
DescribePackURI
python
doocs__leetcode
solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.py
{ "start": 0, "end": 831 }
class ____: def countSubMultisets(self, nums: List[int], l: int, r: int) -> int: kMod = 1_000_000_007 # dp[i] := # of submultisets of nums with sum i dp = [1] + [0] * r count = collections.Counter(nums) zeros = count.pop(0, 0) for num, freq in count.items(): # stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... stride = dp.copy() for i in range(num, r + 1): stride[i] += stride[i - num] for i in range(r, 0, -1): if i >= num * (freq + 1): # dp[i] + dp[i - num] + dp[i - freq * num] dp[i] = stride[i] - stride[i - num * (freq + 1)] else: dp[i] = stride[i] return (zeros + 1) * sum(dp[l : r + 1]) % kMod
Solution
python
doocs__leetcode
solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/Solution.py
{ "start": 0, "end": 664 }
class ____: def maxIncreasingCells(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) g = defaultdict(list) for i in range(m): for j in range(n): g[mat[i][j]].append((i, j)) rowMax = [0] * m colMax = [0] * n ans = 0 for _, pos in sorted(g.items()): mx = [] for i, j in pos: mx.append(1 + max(rowMax[i], colMax[j])) ans = max(ans, mx[-1]) for k, (i, j) in enumerate(pos): rowMax[i] = max(rowMax[i], mx[k]) colMax[j] = max(colMax[j], mx[k]) return ans
Solution
python
PrefectHQ__prefect
src/prefect/client/schemas/schedules.py
{ "start": 6241, "end": 12602 }
class ____(PrefectBaseModel): """ RRule schedule, based on the iCalendar standard ([RFC 5545](https://datatracker.ietf.org/doc/html/rfc5545)) as implemented in `dateutils.rrule`. RRules are appropriate for any kind of calendar-date manipulation, including irregular intervals, repetition, exclusions, week day or day-of-month adjustments, and more. Note that as a calendar-oriented standard, `RRuleSchedules` are sensitive to to the initial timezone provided. A 9am daily schedule with a daylight saving time-aware start date will maintain a local 9am time through DST boundaries; a 9am daily schedule with a UTC start date will maintain a 9am UTC time. Args: rrule (str): a valid RRule string timezone (str, optional): a valid timezone string """ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid") rrule: str timezone: Optional[str] = Field( default="UTC", examples=["America/New_York"], validate_default=True ) @field_validator("rrule") @classmethod def validate_rrule_str(cls, v: str) -> str: return validate_rrule_string(v) @classmethod def from_rrule( cls, rrule: Union[dateutil.rrule.rrule, dateutil.rrule.rruleset] ) -> "RRuleSchedule": if isinstance(rrule, dateutil.rrule.rrule): dtstart = _rrule_dt(rrule) if dtstart and dtstart.tzinfo is not None: timezone = dtstart.tzinfo.tzname(dtstart) else: timezone = "UTC" return RRuleSchedule(rrule=str(rrule), timezone=timezone) rrules = _rrule(rrule) dtstarts = [dts for rr in rrules if (dts := _rrule_dt(rr)) is not None] unique_dstarts = set(d.astimezone(ZoneInfo("UTC")) for d in dtstarts) unique_timezones = set(d.tzinfo for d in dtstarts if d.tzinfo is not None) if len(unique_timezones) > 1: raise ValueError( f"rruleset has too many dtstart timezones: {unique_timezones}" ) if len(unique_dstarts) > 1: raise ValueError(f"rruleset has too many dtstarts: {unique_dstarts}") if unique_dstarts and unique_timezones: [unique_tz] = unique_timezones timezone = unique_tz.tzname(dtstarts[0]) else: timezone = "UTC" rruleset_string = "" if rrules: rruleset_string += "\n".join(str(r) for r in rrules) if exrule := _rrule(rrule, "_exrule"): rruleset_string += "\n" if rruleset_string else "" rruleset_string += "\n".join(str(r) for r in exrule).replace( "RRULE", "EXRULE" ) if rdates := _rdates(rrule): rruleset_string += "\n" if rruleset_string else "" rruleset_string += "RDATE:" + ",".join( rd.strftime("%Y%m%dT%H%M%SZ") for rd in rdates ) if exdates := _rdates(rrule, "_exdate"): rruleset_string += "\n" if rruleset_string else "" rruleset_string += "EXDATE:" + ",".join( exd.strftime("%Y%m%dT%H%M%SZ") for exd in exdates ) return RRuleSchedule(rrule=rruleset_string, timezone=timezone) def to_rrule(self) -> Union[dateutil.rrule.rrule, dateutil.rrule.rruleset]: """ Since rrule doesn't properly serialize/deserialize timezones, we localize dates here """ rrule = dateutil.rrule.rrulestr( self.rrule, dtstart=DEFAULT_ANCHOR_DATE, cache=True, ) timezone = dateutil.tz.gettz(self.timezone) if isinstance(rrule, dateutil.rrule.rrule): dtstart = _rrule_dt(rrule) assert dtstart is not None kwargs: dict[str, Any] = dict(dtstart=dtstart.replace(tzinfo=timezone)) if until := _rrule_dt(rrule, "_until"): kwargs.update( until=until.replace(tzinfo=timezone), ) return rrule.replace(**kwargs) # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] missing type hints # update rrules localized_rrules: list[dateutil.rrule.rrule] = [] for rr in _rrule(rrule): dtstart = _rrule_dt(rr) assert dtstart is not None kwargs: dict[str, Any] = dict(dtstart=dtstart.replace(tzinfo=timezone)) if until := _rrule_dt(rr, "_until"): kwargs.update(until=until.replace(tzinfo=timezone)) localized_rrules.append(rr.replace(**kwargs)) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType] missing type hints setattr(rrule, "_rrule", localized_rrules) # update exrules localized_exrules: list[dateutil.rrule.rruleset] = [] for exr in _rrule(rrule, "_exrule"): dtstart = _rrule_dt(exr) assert dtstart is not None kwargs = dict(dtstart=dtstart.replace(tzinfo=timezone)) if until := _rrule_dt(exr, "_until"): kwargs.update(until=until.replace(tzinfo=timezone)) localized_exrules.append(exr.replace(**kwargs)) # pyright: ignore[reportArgumentType, reportUnknownArgumentType, reportUnknownMemberType] missing type hints setattr(rrule, "_exrule", localized_exrules) # update rdates localized_rdates: list[datetime.datetime] = [] for rd in _rdates(rrule): localized_rdates.append(rd.replace(tzinfo=timezone)) setattr(rrule, "_rdate", localized_rdates) # update exdates localized_exdates: list[datetime.datetime] = [] for exd in _rdates(rrule, "_exdate"): localized_exdates.append(exd.replace(tzinfo=timezone)) setattr(rrule, "_exdate", localized_exdates) return rrule @field_validator("timezone") def valid_timezone(cls, v: Optional[str]) -> str: """ Validate that the provided timezone is a valid IANA timezone. Unfortunately this list is slightly different from the list of valid timezones we use for cron and interval timezone validation. """ if v is None: return "UTC" if is_valid_timezone(v): return v raise ValueError(f'Invalid timezone: "{v}"')
RRuleSchedule
python
h5py__h5py
h5py/tests/test_dataset_getitem.py
{ "start": 16309, "end": 17300 }
class ____(TestCase): def setUp(self): TestCase.setUp(self) self.data = np.ones((5,3), dtype='f') self.dset = self.f.create_dataset('x', data=self.data) def test_ndim(self): """ Verify number of dimensions """ self.assertEqual(self.dset.ndim, 2) def test_size(self): """ Verify size """ self.assertEqual(self.dset.size, 15) def test_nbytes(self): """ Verify nbytes """ self.assertEqual(self.dset.nbytes, 15*self.data.dtype.itemsize) # not sure if 'f' is always alias for 'f4' def test_shape(self): """ Verify shape """ self.assertEqual(self.dset.shape, (5, 3)) def test_indexlist(self): """ see issue #473 """ self.assertNumpyBehavior(self.dset, self.data, np.s_[:,[0,1,2]]) def test_index_emptylist(self): self.assertNumpyBehavior(self.dset, self.data, np.s_[:, []]) self.assertNumpyBehavior(self.dset, self.data, np.s_[[]])
Test2DFloat
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 538135, "end": 538784 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("PullRequestReviewEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("PullRequestReview"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null(PageInfo), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
PullRequestReviewConnection
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 12187, "end": 13108 }
class ____(BaseModel): g: GSpec | None = None p: PSpec | None """ ) Filter = module.Filter assert isinstance(Filter(p={'sort': 'some_field:asc', 'fields': []}), Filter) def test_forward_ref_with_create_model(create_module): @create_module def module(): import pydantic Sub = pydantic.create_model('Sub', foo=(str, 'bar'), __module__=__name__) assert Sub # get rid of "local variable 'Sub' is assigned to but never used" Main = pydantic.create_model('Main', sub=('Sub', ...), __module__=__name__) instance = Main(sub={}) assert instance.sub.model_dump() == {'foo': 'bar'} def test_resolve_forward_ref_dataclass(create_module): module = create_module( # language=Python """ from __future__ import annotations from dataclasses import dataclass from pydantic import BaseModel from typing import Literal @dataclass
Filter
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_view.py
{ "start": 1230, "end": 12045 }
class ____(object): """Gathers and serializes a checkpoint view. This is for loading specific portions of a module from a checkpoint, and be able to compare two modules by matching components. Example usage: >>> class SimpleModule(tf.Module): ... def __init__(self, name=None): ... super().__init__(name=name) ... self.a_var = tf.Variable(5.0) ... self.b_var = tf.Variable(4.0) ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] >>> root = SimpleModule(name="root") >>> root.leaf = SimpleModule(name="leaf") >>> ckpt = tf.train.Checkpoint(root) >>> save_path = ckpt.save('/tmp/tf_ckpts') >>> checkpoint_view = tf.train.CheckpointView(save_path) Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the dictionary of all children directly linked to the checkpoint root. >>> for name, node_id in checkpoint_view.children(0).items(): ... print(f"- name: '{name}', node_id: {node_id}") - name: 'a_var', node_id: 1 - name: 'b_var', node_id: 2 - name: 'vars', node_id: 3 - name: 'leaf', node_id: 4 - name: 'root', node_id: 0 - name: 'save_counter', node_id: 5 """ def __init__(self, save_path): """Configure the checkpoint view. Args: save_path: The path to the checkpoint. Raises: ValueError: If the save_path does not lead to a TF2 checkpoint. """ reader = py_checkpoint_reader.NewCheckpointReader(save_path) try: object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY) except errors_impl.NotFoundError as not_found_error: raise ValueError( f"The specified checkpoint \"{save_path}\" does not appear to be " "object-based (saved with TF2) since it is missing the key " f"\"{base.OBJECT_GRAPH_PROTO_KEY}\". Likely it was created with the " "TF1 name-based saver and does not contain an object dependency graph." ) from not_found_error object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph()) object_graph_proto.ParseFromString(object_graph_string) self._object_graph_proto = object_graph_proto def children(self, node_id): """Returns all child trackables attached to obj. Args: node_id: Id of the node to return its children. Returns: Dictionary of all children attached to the object with name to node_id. """ return { child.local_name: child.node_id for child in self._object_graph_proto.nodes[node_id].children } def descendants(self): """Returns a list of trackables by node_id attached to obj.""" return list(self._descendants_with_paths().keys()) def _descendants_with_paths(self): """Returns a dict of descendants by node_id and paths to node. The names returned by this private method are subject to change. """ all_nodes_with_paths = {} to_visit = collections.deque([0]) # node_id:0 will always be "root". all_nodes_with_paths[0] = "root" path = all_nodes_with_paths.get(0) while to_visit: node_id = to_visit.popleft() obj = self._object_graph_proto.nodes[node_id] for child in obj.children: if child.node_id == 0 or child.node_id in all_nodes_with_paths.keys(): continue path = all_nodes_with_paths.get(node_id) if child.node_id not in all_nodes_with_paths.keys(): to_visit.append(child.node_id) all_nodes_with_paths[child.node_id] = path + "." + child.local_name return all_nodes_with_paths def match(self, obj): """Returns all matching trackables between CheckpointView and Trackable. Matching trackables represents trackables with the same name and position in graph. Args: obj: `Trackable` root. Returns: Dictionary containing all overlapping trackables that maps `node_id` to `Trackable`. Example usage: >>> class SimpleModule(tf.Module): ... def __init__(self, name=None): ... super().__init__(name=name) ... self.a_var = tf.Variable(5.0) ... self.b_var = tf.Variable(4.0) ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] >>> root = SimpleModule(name="root") >>> leaf = root.leaf = SimpleModule(name="leaf") >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3") >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4") >>> ckpt = tf.train.Checkpoint(root) >>> save_path = ckpt.save('/tmp/tf_ckpts') >>> checkpoint_view = tf.train.CheckpointView(save_path) >>> root2 = SimpleModule(name="root") >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2") >>> leaf2.leaf3 = tf.Variable(6.0) >>> leaf2.leaf4 = tf.Variable(7.0) Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the dictionary of all children directly linked to the checkpoint root. >>> checkpoint_view_match = checkpoint_view.match(root2).items() >>> for item in checkpoint_view_match: ... print(item) (0, ...) (1, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>) (2, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>) (3, ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>])) (6, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>) (7, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>) """ if not isinstance(obj, base.Trackable): raise ValueError(f"Expected a Trackable, got {obj} of type {type(obj)}.") overlapping_nodes = {} # Root node is always matched. overlapping_nodes[0] = obj # Queue of tuples of node_id and trackable. to_visit = collections.deque([(0, obj)]) visited = set() view = trackable_view.TrackableView(obj) while to_visit: current_node_id, current_trackable = to_visit.popleft() trackable_children = view.children(current_trackable) for child_name, child_node_id in self.children(current_node_id).items(): if child_node_id in visited or child_node_id == 0: continue if child_name in trackable_children: current_assignment = overlapping_nodes.get(child_node_id) if current_assignment is None: overlapping_nodes[child_node_id] = trackable_children[child_name] to_visit.append((child_node_id, trackable_children[child_name])) else: # The object was already mapped for this checkpoint load, which # means we don't need to do anything besides check that the mapping # is consistent (if the dependency DAG is not a tree then there are # multiple paths to the same object). if current_assignment is not trackable_children[child_name]: logging.warning( "Inconsistent references when matching the checkpoint into " "this object graph. The referenced objects are: " f"({current_assignment} and " f"{trackable_children[child_name]}).") visited.add(current_node_id) return overlapping_nodes def diff(self, obj): """Returns diff between CheckpointView and Trackable. This method is intended to be used to compare the object stored in a checkpoint vs a live model in Python. For example, if checkpoint restoration fails the `assert_consumed()` or `assert_existing_objects_matched()` checks, you can use this to list out the objects/checkpoint nodes which were not restored. Example Usage: >>> class SimpleModule(tf.Module): ... def __init__(self, name=None): ... super().__init__(name=name) ... self.a_var = tf.Variable(5.0) ... self.b_var = tf.Variable(4.0) ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] >>> root = SimpleModule(name="root") >>> leaf = root.leaf = SimpleModule(name="leaf") >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3") >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4") >>> ckpt = tf.train.Checkpoint(root) >>> save_path = ckpt.save('/tmp/tf_ckpts') >>> checkpoint_view = tf.train.CheckpointView(save_path) >>> root2 = SimpleModule(name="root") >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2") >>> leaf2.leaf3 = tf.Variable(6.0) >>> leaf2.leaf4 = tf.Variable(7.0) Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the dictionary of all children directly linked to the checkpoint root. >>> checkpoint_view_diff = checkpoint_view.diff(root2) >>> checkpoint_view_match = checkpoint_view_diff[0].items() >>> for item in checkpoint_view_match: ... print(item) (0, ...) (1, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>) (2, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>) (3, ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>])) (6, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>) (7, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>) >>> only_in_checkpoint_view = checkpoint_view_diff[1] >>> print(only_in_checkpoint_view) [4, 5, 8, 9, 10, 11, 12, 13, 14] >>> only_in_trackable = checkpoint_view_diff[2] >>> print(only_in_trackable) [..., <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=5.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=4.0>, ListWrapper([<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>]), <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=6.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=7.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>] Args: obj: `Trackable` root. Returns: Tuple of ( - Overlaps: Dictionary containing all overlapping trackables that maps `node_id` to `Trackable`, same as CheckpointView.match(). - Only in CheckpointView: List of `node_id` that only exist in CheckpointView. - Only in Trackable: List of `Trackable` that only exist in Trackable. ) """ overlapping_nodes = self.match(obj) only_in_checkpoint_view = [] only_in_trackable = [] for node_id in self.descendants(): if node_id not in overlapping_nodes.keys(): only_in_checkpoint_view.append(node_id) for trackable in trackable_view.TrackableView(obj).descendants(): if trackable not in object_identity.ObjectIdentitySet( overlapping_nodes.values()): only_in_trackable.append(trackable) return overlapping_nodes, only_in_checkpoint_view, only_in_trackable
CheckpointView
python
pytorch__pytorch
test/inductor/test_aot_inductor_arrayref.py
{ "start": 10587, "end": 11581 }
class ____( TestCase ): device = "cpu" device_type = "cpu" check_model = check_model check_model_with_multiple_inputs = check_model_with_multiple_inputs code_check_count = code_check_count allow_stack_allocation = True use_minimal_arrayref_interface = True if IS_FBCODE: # The following tests look like they pass in both pytest and unittest (xml # and terminal output say pass), but the process will segfault. This only # happens in OSS CI and is fine internally. # See https://github.com/pytorch/pytorch/issues/123691 copy_tests( AOTInductorTestsTemplate, AOTInductorTestABICompatibleCpuWithStackAllocationAndMinimalArrayRefInterface, "cpu_with_stack_allocation_and_minimal_arrayref_interface", CPU_TEST_FAILURES, ) if __name__ == "__main__": from torch._inductor.test_case import run_tests run_tests(needs="filelock")
AOTInductorTestABICompatibleCpuWithStackAllocationAndMinimalArrayRefInterface
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_asset_decorators.py
{ "start": 7845, "end": 9934 }
class ____: @mock.patch("airflow.sdk.definitions.asset.decorators._AssetMainOperator.from_definition") @mock.patch("airflow.sdk.definitions.dag.DAG") def test__attrs_post_init__(self, DAG, from_definition, example_asset_func_with_valid_arg_as_inlet_asset): asset_definition = asset(schedule=None, uri="s3://bucket/object", group="MLModel", extra={"k": "v"})( example_asset_func_with_valid_arg_as_inlet_asset ) DAG.assert_called_once_with( dag_id="example_asset_func", dag_display_name="example_asset_func", description=None, schedule=None, catchup=False, is_paused_upon_creation=None, on_failure_callback=None, on_success_callback=None, params=None, access_control=None, owner_links={}, tags=set(), auto_register=True, ) from_definition.assert_called_once_with(asset_definition) @mock.patch("airflow.sdk.bases.decorator._TaskDecorator.__call__") @mock.patch("airflow.sdk.definitions.dag.DAG") def test_with_task_decorator(self, DAG, __call__, func_fixer): @task(retries=3) @func_fixer def _example_task_func(): return "This is example_task" asset_definition = asset(schedule=None, uri="s3://bucket/object", group="MLModel", extra={"k": "v"})( _example_task_func ) DAG.assert_called_once_with( dag_id="example_asset_func", dag_display_name="example_asset_func", description=None, schedule=None, catchup=False, is_paused_upon_creation=None, on_failure_callback=None, on_success_callback=None, params=None, access_control=None, owner_links={}, tags=set(), auto_register=True, ) __call__.assert_called_once_with() assert asset_definition._function.kwargs["outlets"] == [asset_definition]
TestAssetDefinition
python
skorch-dev__skorch
skorch/llm/classifier.py
{ "start": 6351, "end": 9362 }
class ____: """Helper class that caches model generations For label ids, if one token sequence is [1, 2, 3] and the next token sequence is [1, 2, 4], for the 2nd sequence, the generation will retrieve the cached logits for [1, 2] and only generate [4]. Set use_caching=False to disable it, e.g. for debugging. """ def __init__(self, model, tokenizer, use_caching=True): self.model = model self.tokenizer = tokenizer self.use_caching = use_caching self.cache = {} self._total_calls = 0 self._uncached_calls = 0 def clear(self): self.cache.clear() def _make_key(self, kwargs): input_ids = kwargs['input_ids'] input_id = input_ids[0].tolist() key = str(input_id) return key def get_cache(self, kwargs): if not self.use_caching: return key = self._make_key(kwargs) val = self.cache.get(key) return val def set_cache(self, kwargs, label_id, scores): if not self.use_caching: return key = self._make_key(kwargs) # store 1st element self.cache[key] = scores[0] # note that label_id i corresponds to score i+1 # this is because the first score is for the input w/o label_id (only # the prompt); for this reason, the two sequences are offset by +1 input_id = kwargs['input_ids'][0].tolist() for lid, score in zip(label_id, scores[1:]): input_id.append(lid) key = str(input_id) self.cache[key] = score def generate_logits(self, *, label_id, **kwargs): self._total_calls += 1 # mainly for debugging recorded_logits = [] logits_cached = self.get_cache(kwargs) while logits_cached is not None: if not label_id or label_id[0] == self.tokenizer.eos_token_id: # don't extend with eos_token -- it is already there at the end, # we don't need it twice break recorded_logits.append(logits_cached) kwargs = _extend_inputs(kwargs, label_id[:1]) label_id = label_id[1:] logits_cached = self.get_cache(kwargs) if not label_id: # the whole generation was cached return recorded_logits if label_id[0] == self.tokenizer.pad_token_id: # no need to generate on pad tokens return recorded_logits self._uncached_calls += 1 # mainly for debugging recorder = _LogitsRecorder( label_ids=label_id, tokenizer=self.tokenizer, ) self.model.generate( logits_processor=[recorder], # TODO: should this be the max len of all labels? max_new_tokens=len(label_id), **kwargs ) self.set_cache(kwargs, label_id, recorder.recorded_scores) return recorded_logits + recorder.recorded_scores[:]
_CacheModelWrapper
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/dataplex.py
{ "start": 2163, "end": 2351 }
class ____(BaseGoogleLink): """Helper class for constructing Dataplex Task link.""" name = "Dataplex Task" key = "task_conf" format_str = DATAPLEX_TASK_LINK
DataplexTaskLink
python
huggingface__transformers
src/transformers/models/distilbert/modeling_distilbert.py
{ "start": 5817, "end": 8130 }
class ____(nn.Module): def __init__(self, config: PreTrainedConfig): super().__init__() self.config = config self.n_heads = config.n_heads self.dim = config.dim self.attention_head_size = self.dim // self.n_heads self.scaling = self.attention_head_size**-0.5 # Have an even number of multi heads that divide the dimensions if self.dim % self.n_heads != 0: # Raise value errors for even multi-head attention nodes raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly") self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim) self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim) self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim) self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim) self.dropout = nn.Dropout(p=config.attention_dropout) self.is_causal = False def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.attention_head_size) # get all proj query_layer = self.q_lin(hidden_states).view(*hidden_shape).transpose(1, 2) key_layer = self.k_lin(hidden_states).view(*hidden_shape).transpose(1, 2) value_layer = self.v_lin(hidden_states).view(*hidden_shape).transpose(1, 2) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_layer, key_layer, value_layer, attention_mask, dropout=0.0 if not self.training else self.dropout.p, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.out_lin(attn_output) return attn_output, attn_weights
DistilBertSelfAttention
python
spack__spack
lib/spack/spack/solver/asp.py
{ "start": 52018, "end": 53444 }
class ____(SourceContext): """Tracks context in which a condition (i.e. ``SpackSolverSetup.condition``) is generated (e.g. for a ``depends_on``). This may modify the required/imposed specs generated as relevant for the context. """ def __init__(self): super().__init__() # transformation applied to facts from the required spec. Defaults # to leave facts as they are. self.transform_required = None # transformation applied to facts from the imposed spec. Defaults # to removing "node" and "virtual_node" facts. self.transform_imposed = None # Whether to wrap direct dependency facts as node requirements, # imposed by the parent. If None, the default is used, which is: # - wrap head of rules # - do not wrap body of rules self.wrap_node_requirement: Optional[bool] = None def requirement_context(self) -> ConditionIdContext: ctxt = ConditionIdContext() ctxt.source = self.source ctxt.transform = self.transform_required ctxt.wrap_node_requirement = self.wrap_node_requirement return ctxt def impose_context(self) -> ConditionIdContext: ctxt = ConditionIdContext() ctxt.source = self.source ctxt.transform = self.transform_imposed ctxt.wrap_node_requirement = self.wrap_node_requirement return ctxt
ConditionContext
python
pytorch__pytorch
test/distributed/checkpoint/test_hf_safetensor_e2e.py
{ "start": 1131, "end": 9584 }
class ____(TestCase): @with_temp_dir def test_save(self) -> None: try: from safetensors.torch import load_file except ImportError: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir state_dict_to_save = MyTestModule().state_dict() dist_cp.save( state_dict=state_dict_to_save, storage_writer=dist_cp.HuggingFaceStorageWriter(path=CHECKPOINT_DIR), ) state_dict_loaded = load_file( CHECKPOINT_DIR + "/model-00001-of-00001.safetensors" ) self.assertEqual( sorted(state_dict_to_save.keys()), sorted(state_dict_loaded.keys()) ) for key in state_dict_to_save: self.assertTrue( torch.equal(state_dict_to_save[key], state_dict_loaded[key]) ) @with_temp_dir def test_load(self) -> None: try: from safetensors.torch import save_file except ImportError: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir state_dict_to_save = MyTestModule().state_dict() state_dict_to_load = MyTestModule().state_dict() save_file( state_dict_to_save, CHECKPOINT_DIR + "/model-00001-of-00001.safetensors" ) dist_cp.load( state_dict=state_dict_to_load, storage_reader=dist_cp.HuggingFaceStorageReader(path=CHECKPOINT_DIR), ) self.assertEqual( sorted(state_dict_to_save.keys()), sorted(state_dict_to_load.keys()) ) for key in state_dict_to_save: self.assertTrue( torch.equal(state_dict_to_save[key], state_dict_to_load[key]) ) @with_temp_dir def test_load_into_empty_dict(self) -> None: try: from safetensors.torch import save_file except ImportError: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir state_dict_to_save = MyTestModule().state_dict() save_file( state_dict_to_save, CHECKPOINT_DIR + "/model-00001-of-00001.safetensors" ) state_dict_loaded = _load_state_dict_from_keys( storage_reader=dist_cp.HuggingFaceStorageReader(path=CHECKPOINT_DIR), ) self.assertEqual( sorted(state_dict_to_save.keys()), sorted(state_dict_loaded.keys()) ) for key in state_dict_to_save: self.assertTrue( torch.equal(state_dict_to_save[key], state_dict_loaded[key]) ) @with_temp_dir def test_load_with_multiple_threads(self) -> None: if importlib.util.find_spec("safetensors") is None: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir state_dict_to_save = MyTestModule().state_dict() state_dict_to_load = MyTestModule().state_dict() # Create a mapping to split tensors across multiple files # This will force multiple files to be created, enabling multi-threading fqn_to_index_mapping = {} for i, fqn in enumerate(state_dict_to_save.keys()): fqn_to_index_mapping[fqn] = (i % 2) + 1 # Split across 2 files # Save using HuggingFaceStorageWriter with multiple files dist_cp.save( state_dict=state_dict_to_save, storage_writer=dist_cp.HuggingFaceStorageWriter( path=CHECKPOINT_DIR, fqn_to_index_mapping=fqn_to_index_mapping ), ) dist_cp.load( state_dict=state_dict_to_load, storage_reader=dist_cp.HuggingFaceStorageReader( path=CHECKPOINT_DIR, thread_count=2 ), ) self.assertEqual( sorted(state_dict_to_save.keys()), sorted(state_dict_to_load.keys()) ) for key in state_dict_to_save: self.assertTrue( torch.equal(state_dict_to_save[key], state_dict_to_load[key]) ) @with_temp_dir def test_quantized_checkpoint_loading(self) -> None: """Test end-to-end saving a quantizaed checkpoint and loading it.""" try: from safetensors.torch import save_file except ImportError: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir # Create original (unquantized) tensors to validate against original_tensors = { "linear1.weight": torch.randn(256, 128, dtype=torch.float32) * 2.0, "linear2.weight": torch.randn(128, 64, dtype=torch.float32) * 1.5, "embedding.weight": torch.randn(512, 256, dtype=torch.float32) * 3.0, } # Create quantized tensors and scale tensors quantized_checkpoint = {} block_size = 128 for tensor_name, original_tensor in original_tensors.items(): # Simulate quantization: scale down the tensor for quantization # This is a simplified quantization - in real scenarios it would be more complex rows, cols = original_tensor.shape # Create scale tensor for block-wise dequantization block_rows = (rows + block_size - 1) // block_size block_cols = (cols + block_size - 1) // block_size # Create scale inverse tensor (used for dequantization) scale_inv = torch.ones(block_rows, block_cols, dtype=torch.float32) * 2.0 # Create quantized version (divide by scale for quantization) quantized_tensor = original_tensor / 2.0 # Simplified quantization # Store quantized tensor and its scale quantized_checkpoint[tensor_name] = quantized_tensor quantized_checkpoint[f"{tensor_name}_scale_inv"] = scale_inv # Save quantized checkpoint to safetensors file safetensors_file = os.path.join(CHECKPOINT_DIR, "model.safetensors") save_file(quantized_checkpoint, safetensors_file) # Create model.safetensors.index.json with weight mapping weight_map = {} for key in quantized_checkpoint: weight_map[key] = "model.safetensors" index_data = { "metadata": { "total_size": sum( t.numel() * t.element_size() for t in quantized_checkpoint.values() ) }, "weight_map": weight_map, } index_file = os.path.join(CHECKPOINT_DIR, "model.safetensors.index.json") with open(index_file, "w") as f: json.dump(index_data, f, indent=2) # Prepare state dict to load into state_dict_to_load = {} for tensor_name, original_tensor in original_tensors.items(): state_dict_to_load[tensor_name] = torch.zeros_like(original_tensor) # Load using QuantizedHuggingFaceStorageReader dist_cp.load( state_dict=state_dict_to_load, storage_reader=QuantizedHuggingFaceStorageReader( path=CHECKPOINT_DIR, target_dtype=torch.float32, block_size=block_size, thread_count=2, ), ) # Validate that loaded tensors match original tensors self.assertEqual( sorted(original_tensors.keys()), sorted(state_dict_to_load.keys()) ) for tensor_name in original_tensors: original = original_tensors[tensor_name] loaded = state_dict_to_load[tensor_name] # Verify shapes match self.assertEqual( original.shape, loaded.shape, f"Shape mismatch for {tensor_name}: {original.shape} vs {loaded.shape}", ) # Verify dtypes match self.assertEqual( original.dtype, loaded.dtype, f"Dtype mismatch for {tensor_name}: {original.dtype} vs {loaded.dtype}", ) # Verify dequantized values match original values # We expect exact match since we used simple 2x scaling torch.testing.assert_close( loaded, original, rtol=1e-5, atol=1e-5, msg=f"Value mismatch for tensor {tensor_name}", )
TestSingleRankSaveLoad
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 57246, "end": 58057 }
class ____(ASTBase): def __init__(self, name: ASTNestedName) -> None: self.name = name def __eq__(self, other: object) -> bool: if not isinstance(other, ASTStruct): return NotImplemented return self.name == other.name def __hash__(self) -> int: return hash(self.name) def get_id(self, version: int, objectType: str, symbol: Symbol) -> str: return symbol.get_full_nested_name().get_id(version) def _stringify(self, transform: StringifyTransform) -> str: return transform(self.name) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: verify_description_mode(mode) self.name.describe_signature(signode, mode, env, symbol=symbol)
ASTStruct
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py
{ "start": 1843, "end": 3260 }
class ____(Step): context: PublishConnectorContext title = "Check if the connector docker image does not exist on the registry." async def _run(self) -> StepResult: docker_repository, docker_tag = self.context.docker_image.split(":") crane_ls = ( docker.with_crane( self.context, ) .with_env_variable("CACHEBUSTER", str(uuid.uuid4())) .with_exec(["ls", docker_repository], use_entrypoint=True) ) try: crane_ls_stdout = await crane_ls.stdout() except ExecError as e: if "NAME_UNKNOWN" in e.stderr: return StepResult(step=self, status=StepStatus.SUCCESS, stdout=f"The docker repository {docker_repository} does not exist.") else: return StepResult(step=self, status=StepStatus.FAILURE, stderr=e.stderr, stdout=e.stdout) else: # The docker repo exists and ls was successful existing_tags = crane_ls_stdout.split("\n") docker_tag_already_exists = docker_tag in existing_tags if docker_tag_already_exists: return StepResult(step=self, status=StepStatus.SKIPPED, stderr=f"{self.context.docker_image} already exists.") return StepResult(step=self, status=StepStatus.SUCCESS, stdout=f"No manifest found for {self.context.docker_image}.")
CheckConnectorImageDoesNotExist
python
walkccc__LeetCode
solutions/543. Diameter of Binary Tree/543.py
{ "start": 0, "end": 348 }
class ____: def diameterOfBinaryTree(self, root: TreeNode | None) -> int: ans = 0 def maxDepth(root: TreeNode | None) -> int: nonlocal ans if not root: return 0 l = maxDepth(root.left) r = maxDepth(root.right) ans = max(ans, l + r) return 1 + max(l, r) maxDepth(root) return ans
Solution
python
huggingface__transformers
src/transformers/utils/quantization_config.py
{ "start": 1356, "end": 1827 }
class ____(str, Enum): BITS_AND_BYTES = "bitsandbytes" GPTQ = "gptq" AWQ = "awq" AQLM = "aqlm" VPTQ = "vptq" QUANTO = "quanto" EETQ = "eetq" HIGGS = "higgs" HQQ = "hqq" COMPRESSED_TENSORS = "compressed-tensors" FBGEMM_FP8 = "fbgemm_fp8" TORCHAO = "torchao" BITNET = "bitnet" SPQR = "spqr" FP8 = "fp8" QUARK = "quark" FPQUANT = "fp_quant" AUTOROUND = "auto-round" MXFP4 = "mxfp4"
QuantizationMethod
python
qdrant__qdrant-client
qdrant_client/local/payload_value_setter.py
{ "start": 5563, "end": 6219 }
class ____(_ListSetter): @classmethod def _set_compatible_types( cls, data: Any, current_key: JsonPathItem, k_list: list[JsonPathItem], value: dict[str, Any], ) -> None: assert current_key.index is not None if current_key.index < len(data): if len(k_list) == 0: if isinstance(data[current_key.index], dict): data[current_key.index].update(value) else: data[current_key.index] = value return cls.set(data[current_key.index], k_list.copy(), value, data, current_key)
IndexSetter
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 121262, "end": 127426 }
class ____(TestCase): # most of this is already tested by TestPercentile @skip(reason="do not chase 1ulp") def test_max_ulp(self): x = [0.0, 0.2, 0.4] a = np.quantile(x, 0.45) # The default linear method would result in 0 + 0.2 * (0.45/2) = 0.18. # 0.18 is not exactly representable and the formula leads to a 1 ULP # different result. Ensure it is this exact within 1 ULP, see gh-20331. np.testing.assert_array_max_ulp(a, 0.18, maxulp=1) def test_basic(self): x = np.arange(8) * 0.5 assert_equal(np.quantile(x, 0), 0.0) assert_equal(np.quantile(x, 1), 3.5) assert_equal(np.quantile(x, 0.5), 1.75) @xfail # (reason="quantile w/integers or bools") def test_correct_quantile_value(self): a = np.array([True]) tf_quant = np.quantile(True, False) assert_equal(tf_quant, a[0]) assert_equal(type(tf_quant), a.dtype) a = np.array([False, True, True]) quant_res = np.quantile(a, a) assert_array_equal(quant_res, a) assert_equal(quant_res.dtype, a.dtype) @skip(reason="support arrays of Fractions?") def test_fraction(self): # fractional input, integral quantile x = [Fraction(i, 2) for i in range(8)] q = np.quantile(x, 0) assert_equal(q, 0) assert_equal(type(q), Fraction) q = np.quantile(x, 1) assert_equal(q, Fraction(7, 2)) assert_equal(type(q), Fraction) q = np.quantile(x, Fraction(1, 2)) assert_equal(q, Fraction(7, 4)) assert_equal(type(q), Fraction) q = np.quantile(x, [Fraction(1, 2)]) assert_equal(q, np.array([Fraction(7, 4)])) assert_equal(type(q), np.ndarray) q = np.quantile(x, [[Fraction(1, 2)]]) assert_equal(q, np.array([[Fraction(7, 4)]])) assert_equal(type(q), np.ndarray) # repeat with integral input but fractional quantile x = np.arange(8) assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2)) @skip(reason="does not raise in numpy?") def test_complex(self): # See gh-22652 arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype="D") assert_raises(TypeError, np.quantile, arr_c, 0.5) arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype="F") assert_raises(TypeError, np.quantile, arr_c, 0.5) @skipif(numpy.__version__ < "1.22", reason="NP_VER: fails with NumPy 1.21.2 on CI") def test_no_p_overwrite(self): # this is worth retesting, because quantile does not make a copy p0 = np.array([0, 0.75, 0.25, 0.5, 1.0]) p = p0.copy() np.quantile(np.arange(100.0), p, method="midpoint") assert_array_equal(p, p0) p0 = p0.tolist() p = p.tolist() np.quantile(np.arange(100.0), p, method="midpoint") assert_array_equal(p, p0) @skip(reason="XXX: make quantile preserve integer dtypes") @parametrize("dtype", "Bbhil") # np.typecodes["AllInteger"]) def test_quantile_preserve_int_type(self, dtype): res = np.quantile(np.array([1, 2], dtype=dtype), [0.5], method="nearest") assert res.dtype == dtype @skipif(numpy.__version__ < "1.22", reason="NP_VER: fails with NumPy 1.21.2 on CI") @parametrize( "method", [ subtest( "inverted_cdf", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "averaged_inverted_cdf", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "closest_observation", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "interpolated_inverted_cdf", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "hazen", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "weibull", decorators=[ xpassIfTorchDynamo_np, ], ), "linear", subtest( "median_unbiased", decorators=[ xpassIfTorchDynamo_np, ], ), subtest( "normal_unbiased", decorators=[ xpassIfTorchDynamo_np, ], ), "nearest", "lower", "higher", "midpoint", ], ) def test_quantile_monotonic(self, method): # GH 14685 # test that the return value of quantile is monotonic if p0 is ordered # Also tests that the boundary values are not mishandled. p0 = np.linspace(0, 1, 101) quantile = np.quantile( np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9, 8, 8, 7]) * 0.1, p0, method=method, ) assert_equal(np.sort(quantile), quantile) # Also test one where the number of data points is clearly divisible: quantile = np.quantile([0.0, 1.0, 2.0, 3.0], p0, method=method) assert_equal(np.sort(quantile), quantile) @skip(reason="no hypothesis") @hypothesis.given( arr=arrays( dtype=np.float64, shape=st.integers(min_value=3, max_value=1000), elements=st.floats( allow_infinity=False, allow_nan=False, min_value=-1e300, max_value=1e300 ), ) ) def test_quantile_monotonic_hypo(self, arr): p0 = np.arange(0, 1, 0.01) quantile = np.quantile(arr, p0) assert_equal(np.sort(quantile), quantile) def test_quantile_scalar_nan(self): a = np.array([[10.0, 7.0, 4.0], [3.0, 2.0, 1.0]]) a[0][1] = np.nan assert_equal(np.quantile(a, 0.5), np.nan) @instantiate_parametrized_tests
TestQuantile
python
huggingface__transformers
src/transformers/models/emu3/modeling_emu3.py
{ "start": 16318, "end": 17161 }
class ____(nn.Module): def __init__( self, in_channel: int, out_channel: int, ): super().__init__() self.conv = Emu3VQVAEConv3d( in_channel, out_channel, kernel_size=(3, 3, 3), stride=(1, 1, 1), ) def forward(self, hidden_states: torch.Tensor): batch_size, channels, temporal, height, width = hidden_states.shape hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal) hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest") hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous() hidden_states = self.conv(hidden_states) return hidden_states
Emu3VQVAETemporalUpsample
python
falconry__falcon
tests/test_validators.py
{ "start": 1242, "end": 2268 }
class ____: @validators.jsonschema.validate(req_schema=_TEST_SCHEMA) async def request_validated(self, req, resp): # NOTE(kgriffs): Verify that we can await req.get_media() multiple times for i in range(3): m = await req.get_media() assert m == _VALID_MEDIA assert m is not None return resp @validators.jsonschema.validate(resp_schema=_TEST_SCHEMA) async def response_validated(self, req, resp): assert resp.media is not None return resp @validators.jsonschema.validate(req_schema=_TEST_SCHEMA, resp_schema=_TEST_SCHEMA) async def both_validated(self, req, resp): m = await req.get_media() assert m is not None assert resp.media is not None return req, resp @validators.jsonschema.validate(req_schema=_TEST_SCHEMA, resp_schema=_TEST_SCHEMA) async def on_put(self, req, resp): m = await req.get_media() assert m is not None resp.media = _VALID_MEDIA
ResourceAsync
python
Lightning-AI__lightning
examples/pytorch/basics/transformer.py
{ "start": 183, "end": 1913 }
class ____(L.LightningModule): def __init__(self, vocab_size): super().__init__() self.model = Transformer(vocab_size=vocab_size) def training_step(self, batch, batch_idx): input, target = batch output = self.model(input, target) loss = F.nll_loss(output, target.view(-1)) self.log("train_loss", loss, prog_bar=True) return loss def validation_step(self, batch, batch_idx): input, target = batch output = self.model(input, target) loss = F.nll_loss(output, target.view(-1)) self.log("val_loss", loss, prog_bar=True) return loss def test_step(self, batch, batch_idx): input, target = batch output = self.model(input, target) loss = F.nll_loss(output, target.view(-1)) self.log("test_loss", loss, prog_bar=True) return loss def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.1) def main(): L.seed_everything(42) # Data dataset = WikiText2() # Split data in to train, val, test n = len(dataset) train_dataset, val_dataset, test_dataset = random_split(dataset, [n - 4000, 2000, 2000]) train_dataloader = DataLoader(train_dataset, batch_size=20, shuffle=True) val_dataloader = DataLoader(val_dataset, batch_size=20, shuffle=False) test_dataloader = DataLoader(test_dataset, batch_size=20, shuffle=False) # Model model = LanguageModel(vocab_size=dataset.vocab_size) # Trainer trainer = L.Trainer(gradient_clip_val=0.25, max_epochs=20) trainer.fit(model, train_dataloader, val_dataloader) trainer.test(model, test_dataloader) if __name__ == "__main__": main()
LanguageModel
python
numpy__numpy
numpy/polynomial/tests/test_polynomial.py
{ "start": 15282, "end": 16948 }
class ____: # some random values in [-1, 1) x = np.random.random((3, 5)) * 2 - 1 def test_polyvander(self): # check for 1d x x = np.arange(3) v = poly.polyvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], poly.polyval(x, coef)) # check for 2d x x = np.array([[1, 2], [3, 4], [5, 6]]) v = poly.polyvander(x, 3) assert_(v.shape == (3, 2, 4)) for i in range(4): coef = [0] * i + [1] assert_almost_equal(v[..., i], poly.polyval(x, coef)) def test_polyvander2d(self): # also tests polyval2d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3)) van = poly.polyvander2d(x1, x2, [1, 2]) tgt = poly.polyval2d(x1, x2, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = poly.polyvander2d([x1], [x2], [1, 2]) assert_(van.shape == (1, 5, 6)) def test_polyvander3d(self): # also tests polyval3d for non-square coefficient array x1, x2, x3 = self.x c = np.random.random((2, 3, 4)) van = poly.polyvander3d(x1, x2, x3, [1, 2, 3]) tgt = poly.polyval3d(x1, x2, x3, c) res = np.dot(van, c.flat) assert_almost_equal(res, tgt) # check shape van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3]) assert_(van.shape == (1, 5, 24)) def test_polyvandernegdeg(self): x = np.arange(3) assert_raises(ValueError, poly.polyvander, x, -1)
TestVander
python
getsentry__sentry
src/sentry/cache/django.py
{ "start": 67, "end": 589 }
class ____(BaseCache): def set(self, key, value, timeout, version=None, raw=False): cache.set(key, value, timeout, version=version or self.version) self._mark_transaction("set") def delete(self, key, version=None): cache.delete(key, version=version or self.version) self._mark_transaction("delete") def get(self, key, version=None, raw=False): result = cache.get(key, version=version or self.version) self._mark_transaction("get") return result
DjangoCache
python
kubernetes-client__python
kubernetes/client/models/v1_storage_os_volume_source.py
{ "start": 383, "end": 8411 }
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. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'fs_type': 'str', 'read_only': 'bool', 'secret_ref': 'V1LocalObjectReference', 'volume_name': 'str', 'volume_namespace': 'str' } attribute_map = { 'fs_type': 'fsType', 'read_only': 'readOnly', 'secret_ref': 'secretRef', 'volume_name': 'volumeName', 'volume_namespace': 'volumeNamespace' } def __init__(self, fs_type=None, read_only=None, secret_ref=None, volume_name=None, volume_namespace=None, local_vars_configuration=None): # noqa: E501 """V1StorageOSVolumeSource - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._fs_type = None self._read_only = None self._secret_ref = None self._volume_name = None self._volume_namespace = None self.discriminator = None if fs_type is not None: self.fs_type = fs_type if read_only is not None: self.read_only = read_only if secret_ref is not None: self.secret_ref = secret_ref if volume_name is not None: self.volume_name = volume_name if volume_namespace is not None: self.volume_namespace = volume_namespace @property def fs_type(self): """Gets the fs_type of this V1StorageOSVolumeSource. # noqa: E501 fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. # noqa: E501 :return: The fs_type of this V1StorageOSVolumeSource. # noqa: E501 :rtype: str """ return self._fs_type @fs_type.setter def fs_type(self, fs_type): """Sets the fs_type of this V1StorageOSVolumeSource. fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. # noqa: E501 :param fs_type: The fs_type of this V1StorageOSVolumeSource. # noqa: E501 :type: str """ self._fs_type = fs_type @property def read_only(self): """Gets the read_only of this V1StorageOSVolumeSource. # noqa: E501 readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. # noqa: E501 :return: The read_only of this V1StorageOSVolumeSource. # noqa: E501 :rtype: bool """ return self._read_only @read_only.setter def read_only(self, read_only): """Sets the read_only of this V1StorageOSVolumeSource. readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. # noqa: E501 :param read_only: The read_only of this V1StorageOSVolumeSource. # noqa: E501 :type: bool """ self._read_only = read_only @property def secret_ref(self): """Gets the secret_ref of this V1StorageOSVolumeSource. # noqa: E501 :return: The secret_ref of this V1StorageOSVolumeSource. # noqa: E501 :rtype: V1LocalObjectReference """ return self._secret_ref @secret_ref.setter def secret_ref(self, secret_ref): """Sets the secret_ref of this V1StorageOSVolumeSource. :param secret_ref: The secret_ref of this V1StorageOSVolumeSource. # noqa: E501 :type: V1LocalObjectReference """ self._secret_ref = secret_ref @property def volume_name(self): """Gets the volume_name of this V1StorageOSVolumeSource. # noqa: E501 volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace. # noqa: E501 :return: The volume_name of this V1StorageOSVolumeSource. # noqa: E501 :rtype: str """ return self._volume_name @volume_name.setter def volume_name(self, volume_name): """Sets the volume_name of this V1StorageOSVolumeSource. volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace. # noqa: E501 :param volume_name: The volume_name of this V1StorageOSVolumeSource. # noqa: E501 :type: str """ self._volume_name = volume_name @property def volume_namespace(self): """Gets the volume_namespace of this V1StorageOSVolumeSource. # noqa: E501 volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created. # noqa: E501 :return: The volume_namespace of this V1StorageOSVolumeSource. # noqa: E501 :rtype: str """ return self._volume_namespace @volume_namespace.setter def volume_namespace(self, volume_namespace): """Sets the volume_namespace of this V1StorageOSVolumeSource. volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created. # noqa: E501 :param volume_namespace: The volume_namespace of this V1StorageOSVolumeSource. # noqa: E501 :type: str """ self._volume_namespace = volume_namespace def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1StorageOSVolumeSource): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1StorageOSVolumeSource): return True return self.to_dict() != other.to_dict()
V1StorageOSVolumeSource
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 40966, "end": 41932 }
class ____(PrefectFilterBaseModel): """DEPRECATED: Prefer `Deployment.concurrency_limit_id` over `Deployment.concurrency_limit`.""" ge_: Optional[int] = Field( default=None, description="Only include deployments with a concurrency limit greater than or equal to this value", ) le_: Optional[int] = Field( default=None, description="Only include deployments with a concurrency limit less than or equal to this value", ) is_null_: Optional[bool] = Field( default=None, description="If true, only include deployments without a concurrency limit", ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> list[sa.ColumnElement[bool]]: # This used to filter on an `int` column that was moved to a `ForeignKey` relationship # This filter is now deprecated rather than support filtering on the new relationship return []
DeploymentFilterConcurrencyLimit
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 12140, "end": 15036 }
class ____(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'lamda') set = Interval(0, 1) @staticmethod def check(alpha, beta, lamda): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(lamda >= 0, "Noncentrality parameter Lambda must be positive") def pdf(self, x): alpha, beta, lamda = self.alpha, self.beta, self.lamda k = Dummy("k") return Sum(exp(-lamda / 2) * (lamda / 2)**k * x**(alpha + k - 1) *( 1 - x)**(beta - 1) / (factorial(k) * beta_fn(alpha + k, beta)), (k, 0, oo)) def BetaNoncentral(name, alpha, beta, lamda): r""" Create a Continuous Random Variable with a Type I Noncentral Beta distribution. The density of the Noncentral Beta distribution is given by .. math:: f(x) := \sum_{k=0}^\infty e^{-\lambda/2}\frac{(\lambda/2)^k}{k!} \frac{x^{\alpha+k-1}(1-x)^{\beta-1}}{\mathrm{B}(\alpha+k,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape lamda : Real number, `\lambda \geq 0`, noncentrality parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaNoncentral, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> lamda = Symbol("lamda", nonnegative=True) >>> z = Symbol("z") >>> X = BetaNoncentral("x", alpha, beta, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) oo _____ \ ` \ -lamda \ k ------- \ k + alpha - 1 /lamda\ beta - 1 2 ) z *|-----| *(1 - z) *e / \ 2 / / ------------------------------------------------ / B(k + alpha, beta)*k! /____, k = 0 Compute cdf with specific 'x', 'alpha', 'beta' and 'lamda' values as follows: >>> cdf(BetaNoncentral("x", 1, 1, 1), evaluate=False)(2).doit() 2*exp(1/2) The argument evaluate=False prevents an attempt at evaluation of the sum for general x, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_beta_distribution .. [2] https://reference.wolfram.com/language/ref/NoncentralBetaDistribution.html """ return rv(name, BetaNoncentralDistribution, (alpha, beta, lamda)) #------------------------------------------------------------------------------- # Beta prime distribution ------------------------------------------------------
BetaNoncentralDistribution
python
numpy__numpy
numpy/_core/tests/test_arraymethod.py
{ "start": 1113, "end": 2565 }
class ____: # Test mainly error paths of the resolve_descriptors function, # note that the `casting_unittests` tests exercise this non-error paths. # Casting implementations are the main/only current user: method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f"))) @pytest.mark.parametrize(["args", "error"], [ ((True,), TypeError), # Not a tuple (((None,),), TypeError), # Too few elements ((None, None), TypeError), # Inputs are not arrays. (((None, None, None),), TypeError), # Too many (((np.arange(3), np.arange(3)),), TypeError), # Incorrect dtypes (((np.ones(3, dtype=">d"), np.ones(3, dtype="<f")),), TypeError), # Does not support byte-swapping (((np.ones((2, 2), dtype="d"), np.ones((2, 2), dtype="f")),), ValueError), # not 1-D (((np.ones(3, dtype="d"), np.ones(4, dtype="f")),), ValueError), # different length (((np.frombuffer(b"\0x00" * 3 * 2, dtype="d"), np.frombuffer(b"\0x00" * 3, dtype="f")),), ValueError), # output not writeable ]) def test_invalid_arguments(self, args, error): # This is private API, which may be modified freely with pytest.raises(error): self.method._simple_strided_call(*args) @pytest.mark.parametrize( "cls", [ np.ndarray, np.recarray, np.char.chararray, np.matrix, np.memmap ] )
TestSimpleStridedCall
python
sanic-org__sanic
sanic/models/futures.py
{ "start": 852, "end": 940 }
class ____(NamedTuple): middleware: MiddlewareType attach_to: str
FutureMiddleware
python
conda__conda
conda/exceptions.py
{ "start": 43224, "end": 44462 }
class ____(CondaError): def __init__( self, filename: str, exporters: Iterable[CondaEnvironmentExporter], *args, **kwargs, ): self.filename = filename supported_filenames: list[str] = [] available_formats: list[str] = [] for exporter in exporters: supported_filenames.extend( f"{filename:<20} (format: {exporter.name})" for filename in exporter.default_filenames ) available_formats.append( f"{exporter.name:<20} (aliases: {', '.join(exporter.aliases)})" if exporter.aliases else exporter.name ) msg = ( f"No environment exporter plugin found for filename '{filename}'.\n" f"\n" f"Supported filenames:{dashlist(supported_filenames)}\n" f"\n" f"Available formats:{dashlist(available_formats)}\n" f"\n" f"Use conda export --format=FORMAT to specify the export format explicitly, " f"or rename your file to match a supported filename pattern." ) super().__init__(msg, *args, **kwargs)
EnvironmentExporterNotDetected
python
lepture__authlib
authlib/oauth2/rfc9068/claims.py
{ "start": 95, "end": 1981 }
class ____(JWTClaims): REGISTERED_CLAIMS = JWTClaims.REGISTERED_CLAIMS + [ "client_id", "auth_time", "acr", "amr", "scope", "groups", "roles", "entitlements", ] def validate(self, **kwargs): self.validate_typ() super().validate(**kwargs) self.validate_client_id() self.validate_auth_time() self.validate_acr() self.validate_amr() self.validate_scope() self.validate_groups() self.validate_roles() self.validate_entitlements() def validate_typ(self): # The resource server MUST verify that the 'typ' header value is 'at+jwt' # or 'application/at+jwt' and reject tokens carrying any other value. # 'typ' is not a required claim, so we don't raise an error if it's missing. typ = self.header.get("typ") if typ and typ.lower() not in ("at+jwt", "application/at+jwt"): raise InvalidClaimError("typ") def validate_client_id(self): return self._validate_claim_value("client_id") def validate_auth_time(self): auth_time = self.get("auth_time") if auth_time and not isinstance(auth_time, (int, float)): raise InvalidClaimError("auth_time") def validate_acr(self): return self._validate_claim_value("acr") def validate_amr(self): amr = self.get("amr") if amr and not isinstance(self["amr"], list): raise InvalidClaimError("amr") def validate_scope(self): return self._validate_claim_value("scope") def validate_groups(self): return self._validate_claim_value("groups") def validate_roles(self): return self._validate_claim_value("roles") def validate_entitlements(self): return self._validate_claim_value("entitlements")
JWTAccessTokenClaims
python
keon__algorithms
tests/test_graph.py
{ "start": 5037, "end": 5560 }
class ____(unittest.TestCase): """ Test for the file def maximum_flow_dfs.py Arguments: unittest {[type]} -- [description] """ def test_maximum_flow_dfs(self): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0] ] maximum_flow = maximum_flow_dfs(graph) self.assertEqual(maximum_flow, 23)
TestMaximum_Flow_Dfs
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 3900, "end": 4095 }
class ____(_TestSchema): _schema = { "$schema": _JSON_SCHEMA_DRAFT_URL, "type": "array", "items": {"anyOf": [{"type": "integer"}, {"type": "string"}]}, }
SimpleArray
python
keras-team__keras
keras/src/backend/torch/optimizers/torch_rmsprop.py
{ "start": 147, "end": 2053 }
class ____( torch_parallel_optimizer.TorchParallelOptimizer, optimizers.RMSprop ): def _parallel_update_step( self, grads, variables, learning_rate, ): keras_variables = variables variables = [v.value for v in variables] dtype = variables[0].dtype lr = ops.cast(learning_rate, dtype) velocities = [ self._velocities[self._get_variable_index(variable)].value for variable in keras_variables ] rho = self.rho torch._foreach_mul_(velocities, rho) torch._foreach_add_( velocities, torch._foreach_mul(grads, grads), alpha=1 - rho ) denominators = torch._foreach_add(velocities, self.epsilon) if self.centered: average_grads = [ self._average_gradients[ self._get_variable_index(variable) ].value for variable in keras_variables ] torch._foreach_mul_(average_grads, rho) torch._foreach_add_(average_grads, grads, alpha=1 - rho) torch._foreach_add_( denominators, torch._foreach_mul(average_grads, average_grads), alpha=-1, ) torch._foreach_sqrt_(denominators) increments = torch._foreach_div( torch._foreach_mul(grads, lr), denominators ) if self.momentum > 0: momentum_list = [ self._momentums[self._get_variable_index(variable)].value for variable in keras_variables ] torch._foreach_mul_(momentum_list, self.momentum) torch._foreach_add_(momentum_list, increments) torch._foreach_add_(variables, momentum_list, alpha=-1) else: torch._foreach_add_(variables, increments, alpha=-1)
RMSprop
python
pypa__pip
src/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 12061, "end": 14324 }
class ____(Candidate): is_installed = True source_link = None def __init__( self, dist: BaseDistribution, template: InstallRequirement, factory: Factory, ) -> None: self.dist = dist self._ireq = _make_install_req_from_dist(dist, template) self._factory = factory self._version = None # This is just logging some messages, so we can do it eagerly. # The returned dist would be exactly the same as self.dist because we # set satisfied_by in _make_install_req_from_dist. # TODO: Supply reason based on force_reinstall and upgrade_strategy. skip_reason = "already satisfied" factory.preparer.prepare_installed_requirement(self._ireq, skip_reason) def __str__(self) -> str: return str(self.dist) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.dist!r})" def __eq__(self, other: object) -> bool: if not isinstance(other, AlreadyInstalledCandidate): return NotImplemented return self.name == other.name and self.version == other.version def __hash__(self) -> int: return hash((self.name, self.version)) @property def project_name(self) -> NormalizedName: return self.dist.canonical_name @property def name(self) -> str: return self.project_name @property def version(self) -> Version: if self._version is None: self._version = self.dist.version return self._version @property def is_editable(self) -> bool: return self.dist.editable def format_for_error(self) -> str: return f"{self.name} {self.version} (Installed)" def iter_dependencies(self, with_requires: bool) -> Iterable[Requirement | None]: if not with_requires: return try: for r in self.dist.iter_dependencies(): yield from self._factory.make_requirements_from_spec(str(r), self._ireq) except InvalidRequirement as exc: raise InvalidInstalledPackage(dist=self.dist, invalid_exc=exc) from None def get_install_requirement(self) -> InstallRequirement | None: return None
AlreadyInstalledCandidate
python
huggingface__transformers
src/transformers/models/xlm_roberta/modular_xlm_roberta.py
{ "start": 17514, "end": 20001 }
class ____(RobertaForTokenClassification): def __init__(self, config): super().__init__(config) del self.xlm_roberta self.roberta = XLMRobertaModel(config, add_pooling_layer=False) @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]: r""" token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value >= 2. All the value in this tensor should be always < type_vocab_size. [What are token type IDs?](../glossary#token-type-ids) labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ outputs = self.roberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, return_dict=True, **kwargs, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: # move labels to correct device labels = labels.to(logits.device) loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring
XLMRobertaForTokenClassification
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 222135, "end": 222584 }
class ____(sgqlc.types.Input): """Ordering options for deployment connections""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(DeploymentOrderField), graphql_name="field") """The field to order deployments by.""" direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction") """The ordering direction."""
DeploymentOrder
python
TheAlgorithms__Python
dynamic_programming/floyd_warshall.py
{ "start": 14, "end": 2177 }
class ____: def __init__(self, n=0): # a graph with Node 0,1,...,N-1 self.n = n self.w = [ [math.inf for j in range(n)] for i in range(n) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(n)] for i in range(n) ] # dp[i][j] stores minimum distance from i to j def add_edge(self, u, v, w): """ Adds a directed edge from node u to node v with weight w. >>> g = Graph(3) >>> g.add_edge(0, 1, 5) >>> g.dp[0][1] 5 """ self.dp[u][v] = w def floyd_warshall(self): """ Computes the shortest paths between all pairs of nodes using the Floyd-Warshall algorithm. >>> g = Graph(3) >>> g.add_edge(0, 1, 1) >>> g.add_edge(1, 2, 2) >>> g.floyd_warshall() >>> g.show_min(0, 2) 3 >>> g.show_min(2, 0) inf """ for k in range(self.n): for i in range(self.n): for j in range(self.n): self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j]) def show_min(self, u, v): """ Returns the minimum distance from node u to node v. >>> g = Graph(3) >>> g.add_edge(0, 1, 3) >>> g.add_edge(1, 2, 4) >>> g.floyd_warshall() >>> g.show_min(0, 2) 7 >>> g.show_min(1, 0) inf """ return self.dp[u][v] if __name__ == "__main__": import doctest doctest.testmod() # Example usage graph = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() print( graph.show_min(1, 4) ) # Should output the minimum distance from node 1 to node 4 print( graph.show_min(0, 3) ) # Should output the minimum distance from node 0 to node 3
Graph
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 32690, "end": 32880 }
class ____(Rank): """Maximum of multiple ranks""" ranks: List[Rank] def to_dict(self) -> Dict[str, Any]: return {"$max": [r.to_dict() for r in self.ranks]} @dataclass
Max
python
sympy__sympy
sympy/physics/biomechanics/curve.py
{ "start": 877, "end": 2297 }
class ____(Function): """Base class for all musculotendon characteristic curve functions.""" @classmethod def eval(cls): msg = ( f'Cannot directly instantiate {cls.__name__!r}, instances of ' f'characteristic curves must be of a concrete subclass.' ) raise TypeError(msg) def _print_code(self, printer): """Print code for the function defining the curve using a printer. Explanation =========== The order of operations may need to be controlled as constant folding the numeric terms within the equations of a musculotendon characteristic curve can sometimes results in a numerically-unstable expression. Parameters ========== printer : Printer The printer to be used to print a string representation of the characteristic curve as valid code in the target language. """ return printer._print(printer.parenthesize( self.doit(deep=False, evaluate=False), PRECEDENCE['Atom'], )) _ccode = _print_code _cupycode = _print_code _cxxcode = _print_code _fcode = _print_code _jaxcode = _print_code _lambdacode = _print_code _mpmathcode = _print_code _octave = _print_code _pythoncode = _print_code _numpycode = _print_code _scipycode = _print_code
CharacteristicCurveFunction
python
miyuchina__mistletoe
mistletoe/span_token.py
{ "start": 4851, "end": 5591 }
class ____(SpanToken): """ Link token. ("[name](target "title")") This is an inline token. Its children are inline (span) tokens holding the link text. One of the core tokens. Attributes: target (str): link target. title (str): link title (default to empty). label (str): link label, for reference links. """ repr_attributes = ("target", "title") def __init__(self, match): self.target = EscapeSequence.strip(match.group(2).strip()) self.title = EscapeSequence.strip(match.group(3)) self.dest_type = getattr(match, "dest_type", None) self.label = getattr(match, "label", None) self.title_delimiter = getattr(match, "title_delimiter", None)
Link
python
spack__spack
lib/spack/spack/detection/path.py
{ "start": 14435, "end": 15457 }
class ____(Finder): def default_path_hints(self) -> List[str]: return spack.util.environment.get_path("PATH") def search_patterns(self, *, pkg: Type["spack.package_base.PackageBase"]) -> List[str]: result = [] if hasattr(pkg, "executables") and hasattr(pkg, "platform_executables"): result = pkg.platform_executables() return result def candidate_files(self, *, patterns: List[str], paths: List[str]) -> List[str]: executables_by_path = executables_in_path(path_hints=paths) joined_pattern = re.compile(r"|".join(patterns)) result = [path for path, exe in executables_by_path.items() if joined_pattern.search(exe)] result.sort() return result def prefix_from_path(self, *, path: str) -> str: result = executable_prefix(path) if not result: msg = f"no bin/ dir found in {path}. Cannot add it as a Spack package" spack.llnl.util.tty.debug(msg) return result
ExecutablesFinder
python
celery__celery
t/unit/contrib/test_migrate.py
{ "start": 1524, "end": 3747 }
class ____: @contextmanager def move_context(self, **kwargs): with patch('celery.contrib.migrate.start_filter') as start: with patch('celery.contrib.migrate.republish') as republish: pred = Mock(name='predicate') move(pred, app=self.app, connection=self.app.connection(), **kwargs) start.assert_called() callback = start.call_args[0][2] yield callback, pred, republish def msgpair(self, **kwargs): body = dict({'task': 'add', 'id': 'id'}, **kwargs) return body, Message(body) def test_move(self): with self.move_context() as (callback, pred, republish): pred.return_value = None body, message = self.msgpair() callback(body, message) message.ack.assert_not_called() republish.assert_not_called() pred.return_value = 'foo' callback(body, message) message.ack.assert_called_with() republish.assert_called() def test_move_transform(self): trans = Mock(name='transform') trans.return_value = Queue('bar') with self.move_context(transform=trans) as (callback, pred, republish): pred.return_value = 'foo' body, message = self.msgpair() with patch('celery.contrib.migrate.maybe_declare') as maybed: callback(body, message) trans.assert_called_with('foo') maybed.assert_called() republish.assert_called() def test_limit(self): with self.move_context(limit=1) as (callback, pred, republish): pred.return_value = 'foo' body, message = self.msgpair() with pytest.raises(StopFiltering): callback(body, message) republish.assert_called() def test_callback(self): cb = Mock() with self.move_context(callback=cb) as (callback, pred, republish): pred.return_value = 'foo' body, message = self.msgpair() callback(body, message) republish.assert_called() cb.assert_called()
test_move
python
scipy__scipy
scipy/interpolate/tests/test_polyint.py
{ "start": 12734, "end": 20850 }
class ____: def setup_method(self): self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) self.test_xs = np.linspace(-1, 1, 100) self.xs = np.linspace(-1, 1, 5) self.ys = self.true_poly(self.xs) def test_lagrange(self): # Ensure backwards compatible post SPEC7 P = BarycentricInterpolator(self.xs, self.ys, random_state=1) xp_assert_close(P(self.test_xs), self.true_poly(self.test_xs)) def test_scalar(self): P = BarycentricInterpolator(self.xs, self.ys, rng=1) xp_assert_close(P(7), self.true_poly(7), check_0d=False) xp_assert_close(P(np.array(7)), self.true_poly(np.array(7)), check_0d=False) def test_derivatives(self): P = BarycentricInterpolator(self.xs, self.ys) D = P.derivatives(self.test_xs) for i in range(D.shape[0]): xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i]) def test_low_derivatives(self): P = BarycentricInterpolator(self.xs, self.ys) D = P.derivatives(self.test_xs, len(self.xs)+2) for i in range(D.shape[0]): xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i], atol=1e-12) def test_derivative(self): P = BarycentricInterpolator(self.xs, self.ys) m = 10 r = P.derivatives(self.test_xs, m) for i in range(m): xp_assert_close(P.derivative(self.test_xs, i), r[i]) def test_high_derivative(self): P = BarycentricInterpolator(self.xs, self.ys) for i in range(len(self.xs), 5*len(self.xs)): xp_assert_close(P.derivative(self.test_xs, i), np.zeros(len(self.test_xs))) def test_ndim_derivatives(self): poly1 = self.true_poly poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) P = BarycentricInterpolator(self.xs, ys, axis=0) D = P.derivatives(self.test_xs) for i in range(D.shape[0]): xp_assert_close(D[i], np.stack((poly1.deriv(i)(self.test_xs), poly2.deriv(i)(self.test_xs), poly3.deriv(i)(self.test_xs)), axis=-1), atol=1e-12) def test_ndim_derivative(self): poly1 = self.true_poly poly2 = np.polynomial.Polynomial([-2, 5, 3, -1]) poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6]) ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1) P = BarycentricInterpolator(self.xs, ys, axis=0) for i in range(P.n): xp_assert_close(P.derivative(self.test_xs, i), np.stack((poly1.deriv(i)(self.test_xs), poly2.deriv(i)(self.test_xs), poly3.deriv(i)(self.test_xs)), axis=-1), atol=1e-12) def test_delayed(self): P = BarycentricInterpolator(self.xs) P.set_yi(self.ys) assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) def test_append(self): P = BarycentricInterpolator(self.xs[:3], self.ys[:3]) P.add_xi(self.xs[3:], self.ys[3:]) assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs)) def test_vector(self): xs = [0, 1, 2] ys = np.array([[0, 1], [1, 0], [2, 1]]) BI = BarycentricInterpolator P = BI(xs, ys) Pi = [BI(xs, ys[:, i]) for i in range(ys.shape[1])] test_xs = np.linspace(-1, 3, 100) assert_almost_equal(P(test_xs), np.asarray([p(test_xs) for p in Pi]).T) def test_shapes_scalarvalue(self): P = BarycentricInterpolator(self.xs, self.ys) assert np.shape(P(0)) == () assert np.shape(P(np.array(0))) == () assert np.shape(P([0])) == (1,) assert np.shape(P([0, 1])) == (2,) def test_shapes_scalarvalue_derivative(self): P = BarycentricInterpolator(self.xs,self.ys) n = P.n assert np.shape(P.derivatives(0)) == (n,) assert np.shape(P.derivatives(np.array(0))) == (n,) assert np.shape(P.derivatives([0])) == (n,1) assert np.shape(P.derivatives([0,1])) == (n,2) def test_shapes_vectorvalue(self): P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3))) assert np.shape(P(0)) == (3,) assert np.shape(P([0])) == (1, 3) assert np.shape(P([0, 1])) == (2, 3) def test_shapes_1d_vectorvalue(self): P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1])) assert np.shape(P(0)) == (1,) assert np.shape(P([0])) == (1, 1) assert np.shape(P([0, 1])) == (2, 1) def test_shapes_vectorvalue_derivative(self): P = BarycentricInterpolator(self.xs,np.outer(self.ys,np.arange(3))) n = P.n assert np.shape(P.derivatives(0)) == (n, 3) assert np.shape(P.derivatives([0])) == (n, 1, 3) assert np.shape(P.derivatives([0, 1])) == (n, 2, 3) def test_wrapper(self): P = BarycentricInterpolator(self.xs, self.ys, rng=1) bi = barycentric_interpolate xp_assert_close(P(self.test_xs), bi(self.xs, self.ys, self.test_xs, rng=1)) xp_assert_close(P.derivative(self.test_xs, 2), bi(self.xs, self.ys, self.test_xs, der=2, rng=1)) xp_assert_close(P.derivatives(self.test_xs, 2), bi(self.xs, self.ys, self.test_xs, der=[0, 1], rng=1)) def test_int_input(self): x = 1000 * np.arange(1, 11) # np.prod(x[-1] - x[:-1]) overflows y = np.arange(1, 11) value = barycentric_interpolate(x, y, 1000 * 9.5) assert_almost_equal(value, np.asarray(9.5)) def test_large_chebyshev(self): # The weights for Chebyshev points of the second kind have analytically # solvable weights. Naive calculation of barycentric weights will fail # for large N because of numerical underflow and overflow. We test # correctness for large N against analytical Chebyshev weights. # Without capacity scaling or permutation, n=800 fails, # With just capacity scaling, n=1097 fails # With both capacity scaling and random permutation, n=30000 succeeds n = 1100 j = np.arange(n + 1).astype(np.float64) x = np.cos(j * np.pi / n) # See page 506 of Berrut and Trefethen 2004 for this formula w = (-1) ** j w[0] *= 0.5 w[-1] *= 0.5 P = BarycentricInterpolator(x) # It's okay to have a constant scaling factor in the weights because it # cancels out in the evaluation of the polynomial. factor = P.wi[0] assert_almost_equal(P.wi / (2 * factor), w) def test_warning(self): # Test if the divide-by-zero warning is properly ignored when computing # interpolated values equals to interpolation points P = BarycentricInterpolator([0, 1], [1, 2]) with np.errstate(divide='raise'): yi = P(P.xi) # Check if the interpolated values match the input values # at the nodes assert_almost_equal(yi, P.yi.ravel()) def test_repeated_node(self): # check that a repeated node raises a ValueError # (computing the weights requires division by xi[i] - xi[j]) xis = np.array([0.1, 0.5, 0.9, 0.5]) ys = np.array([1, 2, 3, 4]) with pytest.raises(ValueError, match="Interpolation points xi must be distinct."): BarycentricInterpolator(xis, ys) def test_concurrency(self): P = BarycentricInterpolator(self.xs, self.ys) def worker_fn(_, interp): interp(self.xs) _run_concurrent_barrier(10, worker_fn, P)
TestBarycentric
python
kamyu104__LeetCode-Solutions
Python/check-if-strings-can-be-made-equal-with-operations-i.py
{ "start": 63, "end": 412 }
class ____(object): def canBeEqual(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ return all(collections.Counter(s1[j] for j in xrange(i, len(s1), 2)) == collections.Counter(s2[j] for j in xrange(i, len(s2), 2)) for i in xrange(2)) # Time: O(1) # Space: O(1) # brute force
Solution
python
ray-project__ray
rllib/offline/estimators/off_policy_estimator.py
{ "start": 705, "end": 10124 }
class ____(OfflineEvaluator): """Interface for an off policy estimator for counterfactual evaluation.""" @DeveloperAPI def __init__( self, policy: Policy, gamma: float = 0.0, epsilon_greedy: float = 0.0, ): """Initializes an OffPolicyEstimator instance. Args: policy: Policy to evaluate. gamma: Discount factor of the environment. epsilon_greedy: The probability by which we act acording to a fully random policy during deployment. With 1-epsilon_greedy we act according the target policy. # TODO (kourosh): convert the input parameters to a config dict. """ super().__init__(policy) self.gamma = gamma self.epsilon_greedy = epsilon_greedy @DeveloperAPI def estimate_on_single_episode(self, episode: SampleBatch) -> Dict[str, Any]: """Returns off-policy estimates for the given one episode. Args: batch: The episode to calculate the off-policy estimates (OPE) on. The episode must be a sample batch type that contains the fields "obs", "actions", and "action_prob" and it needs to represent a complete trajectory. Returns: The off-policy estimates (OPE) calculated on the given episode. The returned dict can be any arbitrary mapping of strings to metrics. """ raise NotImplementedError @DeveloperAPI def estimate_on_single_step_samples( self, batch: SampleBatch, ) -> Dict[str, List[float]]: """Returns off-policy estimates for the batch of single timesteps. This is highly optimized for bandits assuming each episode is a single timestep. Args: batch: The batch to calculate the off-policy estimates (OPE) on. The batch must be a sample batch type that contains the fields "obs", "actions", and "action_prob". Returns: The off-policy estimates (OPE) calculated on the given batch of single time step samples. The returned dict can be any arbitrary mapping of strings to a list of floats capturing the values per each record. """ raise NotImplementedError def on_before_split_batch_by_episode( self, sample_batch: SampleBatch ) -> SampleBatch: """Called before the batch is split by episode. You can perform any preprocessing on the batch that you want here. e.g. adding done flags to the batch, or reseting some stats that you want to track per episode later during estimation, .etc. Args: sample_batch: The batch to split by episode. This contains multiple episodes. Returns: The modified batch before calling split_by_episode(). """ return sample_batch @OverrideToImplementCustomLogic def on_after_split_batch_by_episode( self, all_episodes: List[SampleBatch] ) -> List[SampleBatch]: """Called after the batch is split by episode. You can perform any postprocessing on each episode that you want here. e.g. computing advantage per episode, .etc. Args: all_episodes: The list of episodes in the original batch. Each element is a sample batch type that is a single episode. """ return all_episodes @OverrideToImplementCustomLogic def peek_on_single_episode(self, episode: SampleBatch) -> None: """This is called on each episode before it is passed to estimate_on_single_episode(). Using this method, you can get a peek at the entire validation dataset before runnining the estimation. For examlpe if you need to perform any normalizations of any sorts on the dataset, you can compute the normalization parameters here. Args: episode: The episode that is split from the original batch. This is a sample batch type that is a single episode. """ pass @DeveloperAPI def estimate( self, batch: SampleBatchType, split_batch_by_episode: bool = True ) -> Dict[str, Any]: """Compute off-policy estimates. Args: batch: The batch to calculate the off-policy estimates (OPE) on. The batch must contain the fields "obs", "actions", and "action_prob". split_batch_by_episode: Whether to split the batch by episode. Returns: The off-policy estimates (OPE) calculated on the given batch. The returned dict can be any arbitrary mapping of strings to metrics. The dict consists of the following metrics: - v_behavior: The discounted return averaged over episodes in the batch - v_behavior_std: The standard deviation corresponding to v_behavior - v_target: The estimated discounted return for `self.policy`, averaged over episodes in the batch - v_target_std: The standard deviation corresponding to v_target - v_gain: v_target / max(v_behavior, 1e-8) - v_delta: The difference between v_target and v_behavior. """ batch = convert_ma_batch_to_sample_batch(batch) self.check_action_prob_in_batch(batch) estimates_per_epsiode = [] if split_batch_by_episode: batch = self.on_before_split_batch_by_episode(batch) all_episodes = batch.split_by_episode() all_episodes = self.on_after_split_batch_by_episode(all_episodes) for episode in all_episodes: assert len(set(episode[SampleBatch.EPS_ID])) == 1, ( "The episode must contain only one episode id. For some reason " "the split_by_episode() method could not successfully split " "the batch by episodes. Each row in the dataset should be " "one episode. Check your evaluation dataset for errors." ) self.peek_on_single_episode(episode) for episode in all_episodes: estimate_step_results = self.estimate_on_single_episode(episode) estimates_per_epsiode.append(estimate_step_results) # turn a list of identical dicts into a dict of lists estimates_per_epsiode = tree.map_structure( lambda *x: list(x), *estimates_per_epsiode ) else: # the returned dict is a mapping of strings to a list of floats estimates_per_epsiode = self.estimate_on_single_step_samples(batch) estimates = { "v_behavior": np.mean(estimates_per_epsiode["v_behavior"]), "v_behavior_std": np.std(estimates_per_epsiode["v_behavior"]), "v_target": np.mean(estimates_per_epsiode["v_target"]), "v_target_std": np.std(estimates_per_epsiode["v_target"]), } estimates["v_gain"] = estimates["v_target"] / max(estimates["v_behavior"], 1e-8) estimates["v_delta"] = estimates["v_target"] - estimates["v_behavior"] return estimates @DeveloperAPI def check_action_prob_in_batch(self, batch: SampleBatchType) -> None: """Checks if we support off policy estimation (OPE) on given batch. Args: batch: The batch to check. Raises: ValueError: In case `action_prob` key is not in batch """ if "action_prob" not in batch: raise ValueError( "Off-policy estimation is not possible unless the inputs " "include action probabilities (i.e., the policy is stochastic " "and emits the 'action_prob' key). For DQN this means using " "`exploration_config: {type: 'SoftQ'}`. You can also set " "`off_policy_estimation_methods: {}` to disable estimation." ) @ExperimentalAPI def compute_action_probs(self, batch: SampleBatch): log_likelihoods = compute_log_likelihoods_from_input_dict(self.policy, batch) new_prob = np.exp(convert_to_numpy(log_likelihoods)) if self.epsilon_greedy > 0.0: if not isinstance(self.policy.action_space, gym.spaces.Discrete): raise ValueError( "Evaluation with epsilon-greedy exploration is only supported " "with discrete action spaces." ) eps = self.epsilon_greedy new_prob = new_prob * (1 - eps) + eps / self.policy.action_space.n return new_prob @DeveloperAPI def train(self, batch: SampleBatchType) -> Dict[str, Any]: """Train a model for Off-Policy Estimation. Args: batch: SampleBatch to train on Returns: Any optional metrics to return from the estimator """ return {} @Deprecated( old="OffPolicyEstimator.action_log_likelihood", new="ray.rllib.utils.policy.compute_log_likelihoods_from_input_dict", error=True, ) def action_log_likelihood(self, batch: SampleBatchType) -> TensorType: log_likelihoods = compute_log_likelihoods_from_input_dict(self.policy, batch) return convert_to_numpy(log_likelihoods)
OffPolicyEstimator
python
huggingface__transformers
src/transformers/models/ijepa/modeling_ijepa.py
{ "start": 7567, "end": 9874 }
class ____(nn.Module): def __init__(self, config: IJepaConfig): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size {config.hidden_size} is not a multiple of the number of attention " f"heads {config.num_attention_heads}." ) self.config = config self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.dropout_prob = config.attention_probs_dropout_prob self.scaling = self.attention_head_size**-0.5 self.is_causal = False self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias) def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: batch_size = hidden_states.shape[0] new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2) value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2) query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] context_layer, attention_probs = attention_interface( self, query_layer, key_layer, value_layer, None, is_causal=self.is_causal, scaling=self.scaling, dropout=0.0 if not self.training else self.dropout_prob, ) new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.reshape(new_context_layer_shape) return context_layer, attention_probs
IJepaSelfAttention
python
allegroai__clearml
examples/advanced/execute_remotely_example.py
{ "start": 915, "end": 6495 }
class ____(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4 * 4 * 50, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2, 2) x = x.view(-1, 4 * 4 * 50) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.log_softmax(x, dim=1) def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: Logger.current_logger().report_scalar( "train", "loss", iteration=(epoch * len(train_loader) + batch_idx), value=loss.item()) print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) def test(args, model, device, test_loader, epoch): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) Logger.current_logger().report_scalar( "test", "loss", iteration=epoch, value=test_loss) Logger.current_logger().report_scalar( "test", "accuracy", iteration=epoch, value=(correct / len(test_loader.dataset))) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset))) def main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name='examples', task_name='Remote_execution PyTorch MNIST train') # Training settings parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--momentum', type=float, default=0.5, metavar='M', help='SGD momentum (default: 0.5)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_true', default=True, help='For Saving the current Model') args = parser.parse_args() use_cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if use_cuda else "cpu") kwargs = {'num_workers': 4, 'pin_memory': True} if use_cuda else {} train_loader = torch.utils.data.DataLoader( datasets.MNIST(os.path.join('..', 'data'), train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.batch_size, shuffle=True, **kwargs) test_loader = torch.utils.data.DataLoader( datasets.MNIST(os.path.join('..', 'data'), train=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.test_batch_size, shuffle=True, **kwargs) model = Net().to(device) optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) for epoch in range(1, args.epochs + 1): if epoch > 1: # We run training for 1 epoch to make sure nothing crashes then local execution will be terminated. # Execution will switch to remote execution by the agent listening to specified queue task.execute_remotely(queue_name="default") train(args, model, device, train_loader, optimizer, epoch) test(args, model, device, test_loader, epoch) if args.save_model: torch.save(model.state_dict(), os.path.join(gettempdir(), "mnist_cnn_remote.pt")) if __name__ == '__main__': main()
Net
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 38498, "end": 42362 }
class ____(MimiAttention): """ Mimi attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from `MimiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to SDPA API. """ # Adapted from MimiAttention.forward def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: if output_attentions: logger.warning_once( f"{self.__class__.__name__} does not support `output_attentions=True`. The returned attention weights will " "be `None`. If you want to get attention weights, please set `attn_implementation='eager'` when loading the model." ) bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) cos, sin = self.rotary_emb(value_states, position_ids) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) causal_mask = attention_mask if attention_mask is not None: causal_mask = causal_mask[:, :, :, : key_states.shape[-2]] # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, # Reference: https://github.com/pytorch/pytorch/issues/112577. if query_states.device.type == "cuda" and causal_mask is not None: query_states = query_states.contiguous() key_states = key_states.contiguous() value_states = value_states.contiguous() # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. is_causal = causal_mask is None and q_len > 1 attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=causal_mask, dropout_p=self.attention_dropout if self.training else 0.0, is_causal=is_causal, ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.view(bsz, q_len, -1) attn_output = self.o_proj(attn_output) return attn_output, None MIMI_ATTENTION_CLASSES = { "eager": MimiAttention, "flash_attention_2": MimiFlashAttention2, "sdpa": MimiSdpaAttention, }
MimiSdpaAttention
python
getsentry__sentry
tests/sentry/api/endpoints/test_commit_filechange.py
{ "start": 335, "end": 3672 }
class ____(APITestCase): endpoint = "sentry-api-0-release-commitfilechange" def setUp(self) -> None: super().setUp() self.project = self.create_project(name="foo") self.release = Release.objects.create( organization_id=self.project.organization_id, version="1" ) self.release.add_project(self.project) self.repo = Repository.objects.create( organization_id=self.project.organization_id, name=self.project.name, external_id=123 ) Repository.objects.create( organization_id=self.project.organization_id, name=self.project.name, external_id=123, status=ObjectStatus.HIDDEN, ) commit = Commit.objects.create( organization_id=self.project.organization_id, repository_id=self.repo.id, key="a" * 40 ) commit2 = Commit.objects.create( organization_id=self.project.organization_id, repository_id=self.repo.id, key="b" * 40 ) ReleaseCommit.objects.create( organization_id=self.project.organization_id, release=self.release, commit=commit, order=1, ) ReleaseCommit.objects.create( organization_id=self.project.organization_id, release=self.release, commit=commit2, order=0, ) CommitFileChange.objects.create( organization_id=self.project.organization_id, commit_id=commit.id, filename=".gitignore", type="M", ) CommitFileChange.objects.create( organization_id=self.project.organization_id, commit_id=commit2.id, filename="/static/js/widget.js", type="A", ) self.login_as(user=self.user) def test_simple(self) -> None: response = self.get_success_response(self.project.organization.slug, self.release.version) assert len(response.data) == 2 assert response.data[0]["filename"] == ".gitignore" assert response.data[1]["filename"] == "/static/js/widget.js" def test_query_name(self) -> None: response = self.get_success_response( self.project.organization.slug, self.release.version, qs_params={"repo_name": self.repo.name}, ) assert response.data[0]["filename"] == ".gitignore" assert response.data[1]["filename"] == "/static/js/widget.js" def test_query_external_id(self) -> None: response = self.get_success_response( self.project.organization.slug, self.release.version, qs_params={"repo_id": self.repo.external_id}, ) assert response.data[0]["filename"] == ".gitignore" assert response.data[1]["filename"] == "/static/js/widget.js" def test_query_does_not_exist(self) -> None: self.get_error_response( self.project.organization.slug, self.release.version, status_code=404, qs_params={"repo_name": "hello"}, ) self.get_error_response( self.project.organization.slug, self.release.version, status_code=404, qs_params={"repo_id": "0"}, )
CommitFileChangeTest
python
django__django
tests/csrf_tests/tests.py
{ "start": 2561, "end": 6790 }
class ____(CsrfFunctionTestMixin, SimpleTestCase): def test_unmask_cipher_token(self): cases = [ (TEST_SECRET, MASKED_TEST_SECRET1), (TEST_SECRET, MASKED_TEST_SECRET2), ( 32 * "a", "vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs341ufzIE", ), (32 * "a", 64 * "a"), (32 * "a", 64 * "b"), (32 * "b", 32 * "a" + 32 * "b"), (32 * "b", 32 * "b" + 32 * "c"), (32 * "c", 32 * "a" + 32 * "c"), ] for secret, masked_secret in cases: with self.subTest(masked_secret=masked_secret): actual = _unmask_cipher_token(masked_secret) self.assertEqual(actual, secret) def test_mask_cipher_secret(self): cases = [ 32 * "a", TEST_SECRET, "da4SrUiHJYoJ0HYQ0vcgisoIuFOxx4ER", ] for secret in cases: with self.subTest(secret=secret): masked = _mask_cipher_secret(secret) self.assertMaskedSecretCorrect(masked, secret) def test_get_token_csrf_cookie_set(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) self.assertMaskedSecretCorrect(token, TEST_SECRET) # The existing cookie is preserved. self.assertEqual(request.META["CSRF_COOKIE"], TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_get_token_csrf_cookie_not_set(self): request = HttpRequest() self.assertNotIn("CSRF_COOKIE", request.META) self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) cookie = request.META["CSRF_COOKIE"] self.assertMaskedSecretCorrect(token, cookie) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_rotate_token(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) rotate_token(request) # The underlying secret was changed. cookie = request.META["CSRF_COOKIE"] self.assertEqual(len(cookie), CSRF_SECRET_LENGTH) self.assertNotEqual(cookie, TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_check_token_format_valid(self): cases = [ # A token of length CSRF_SECRET_LENGTH. TEST_SECRET, # A token of length CSRF_TOKEN_LENGTH. MASKED_TEST_SECRET1, 64 * "a", ] for token in cases: with self.subTest(token=token): actual = _check_token_format(token) self.assertIsNone(actual) def test_check_token_format_invalid(self): cases = [ (64 * "*", "has invalid characters"), (16 * "a", "has incorrect length"), ] for token, expected_message in cases: with self.subTest(token=token): with self.assertRaisesMessage(InvalidTokenFormat, expected_message): _check_token_format(token) def test_does_token_match(self): cases = [ # Masked tokens match. ((MASKED_TEST_SECRET1, TEST_SECRET), True), ((MASKED_TEST_SECRET2, TEST_SECRET), True), ((64 * "a", _unmask_cipher_token(64 * "a")), True), # Unmasked tokens match. ((TEST_SECRET, TEST_SECRET), True), ((32 * "a", 32 * "a"), True), # Incorrect tokens don't match. ((32 * "a", TEST_SECRET), False), ((64 * "a", TEST_SECRET), False), ] for (token, secret), expected in cases: with self.subTest(token=token, secret=secret): actual = _does_token_match(token, secret) self.assertIs(actual, expected) def test_does_token_match_wrong_token_length(self): with self.assertRaises(AssertionError): _does_token_match(16 * "a", TEST_SECRET)
CsrfFunctionTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 505, "end": 605 }
class ____(ParentClosed1, extra_items=Never): pass # This should generate an error.
ChildClosed1_1
python
pydantic__pydantic
pydantic-core/tests/validators/test_dataclasses.py
{ "start": 60152, "end": 66322 }
class ____: a: str def test_alias_allow_pop(py_and_json: PyAndJson): schema = core_schema.dataclass_schema( BasicDataclass, core_schema.dataclass_args_schema( 'BasicDataclass', [ core_schema.dataclass_field(name='a', schema=core_schema.str_schema(), validation_alias='FieldA'), ], ), ['a'], config=core_schema.CoreConfig(validate_by_name=True, validate_by_alias=True), ) v = py_and_json(schema) assert v.validate_test({'FieldA': 'hello'}) == BasicDataclass(a='hello') assert v.validate_test({'a': 'hello'}) == BasicDataclass(a='hello') assert v.validate_test( { 'FieldA': 'hello', 'a': 'world', } ) == BasicDataclass(a='hello') with pytest.raises(ValidationError, match=r'FieldA\n +Field required \[type=missing,'): assert v.validate_test({'foobar': 'hello'}) def test_only_validate_by_name(py_and_json) -> None: schema = core_schema.dataclass_schema( BasicDataclass, core_schema.dataclass_args_schema( 'BasicDataclass', [ core_schema.dataclass_field(name='a', schema=core_schema.str_schema(), validation_alias='FieldA'), ], ), ['a'], config=core_schema.CoreConfig(validate_by_name=True, validate_by_alias=False), ) v = py_and_json(schema) assert v.validate_test({'a': 'hello'}) == BasicDataclass(a='hello') with pytest.raises(ValidationError, match=r'a\n +Field required \[type=missing,'): assert v.validate_test({'FieldA': 'hello'}) def test_only_allow_alias(py_and_json) -> None: schema = core_schema.dataclass_schema( BasicDataclass, core_schema.dataclass_args_schema( 'BasicDataclass', [ core_schema.dataclass_field(name='a', schema=core_schema.str_schema(), validation_alias='FieldA'), ], ), ['a'], config=core_schema.CoreConfig(validate_by_name=False, validate_by_alias=True), ) v = py_and_json(schema) assert v.validate_test({'FieldA': 'hello'}) == BasicDataclass(a='hello') with pytest.raises(ValidationError, match=r'FieldA\n +Field required \[type=missing,'): assert v.validate_test({'a': 'hello'}) @pytest.mark.parametrize('config_by_alias', [None, True, False]) @pytest.mark.parametrize('config_by_name', [None, True, False]) @pytest.mark.parametrize('runtime_by_alias', [None, True, False]) @pytest.mark.parametrize('runtime_by_name', [None, True, False]) def test_by_alias_and_name_config_interaction( config_by_alias: Union[bool, None], config_by_name: Union[bool, None], runtime_by_alias: Union[bool, None], runtime_by_name: Union[bool, None], ) -> None: """This test reflects the priority that applies for config vs runtime validation alias configuration. Runtime values take precedence over config values, when set. By default, by_alias is True and by_name is False. """ if config_by_alias is False and config_by_name is False and runtime_by_alias is False and runtime_by_name is False: pytest.skip("Can't have both by_alias and by_name as effectively False") core_config = { **({'validate_by_alias': config_by_alias} if config_by_alias is not None else {}), **({'validate_by_name': config_by_name} if config_by_name is not None else {}), } @dataclasses.dataclass class MyDataclass: my_field: int schema = core_schema.dataclass_schema( MyDataclass, core_schema.dataclass_args_schema( 'MyDataclass', [ core_schema.dataclass_field( name='my_field', schema=core_schema.int_schema(), validation_alias='my_alias' ), ], ), ['my_field'], config=core_schema.CoreConfig(**core_config), ) s = SchemaValidator(schema) alias_allowed = next(x for x in (runtime_by_alias, config_by_alias, True) if x is not None) name_allowed = next(x for x in (runtime_by_name, config_by_name, False) if x is not None) if alias_allowed: assert dataclasses.asdict( s.validate_python({'my_alias': 1}, by_alias=runtime_by_alias, by_name=runtime_by_name) ) == {'my_field': 1} if name_allowed: assert dataclasses.asdict( s.validate_python({'my_field': 1}, by_alias=runtime_by_alias, by_name=runtime_by_name) ) == {'my_field': 1} def test_dataclass_json_duplicate_keys(): """Test that duplicate keys in JSON are handled correctly (last value wins). We want to ensure that: 1. The last value for a duplicate key is used (standard JSON behavior) 2. We don't waste work creating Python objects for values that get overwritten """ @dataclasses.dataclass class MyDataclass: name: str age: int schema = core_schema.dataclass_schema( MyDataclass, core_schema.dataclass_args_schema( 'MyDataclass', [ core_schema.dataclass_field(name='name', schema=core_schema.str_schema()), core_schema.dataclass_field(name='age', schema=core_schema.int_schema()), ], ), ['name', 'age'], ) v = SchemaValidator(schema) # json with duplicate keys - the last value should win json_with_duplicates = '{"name": "Alice", "age": 30, "name": "Bob", "age": 25}' result = v.validate_json(json_with_duplicates) assert result.name == 'Bob', "Last value for 'name' should win" assert result.age == 25, "Last value for 'age' should win" assert dataclasses.asdict(result) == {'name': 'Bob', 'age': 25} # test with multiple duplicates of the same key json_multiple_duplicates = '{"name": "First", "age": 1, "name": "Second", "name": "Third", "age": 3}' result2 = v.validate_json(json_multiple_duplicates) assert result2.name == 'Third', 'Last value among multiple duplicates should win' assert result2.age == 3 assert dataclasses.asdict(result2) == {'name': 'Third', 'age': 3}
BasicDataclass
python
getsentry__sentry
src/sentry/notifications/api/endpoints/user_notification_settings_options_detail.py
{ "start": 534, "end": 1573 }
class ____(UserEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ALERTS_NOTIFICATIONS def convert_args( self, request: Request, user_id: int | str | None = None, *args, notification_option_id: int, **kwargs, ): args, kwargs = super().convert_args(request, user_id, *args, **kwargs) user = kwargs["user"] try: option = NotificationSettingOption.objects.get(id=notification_option_id, user=user) except NotificationSettingOption.DoesNotExist: raise NotFound(detail="User notification setting does not exist") kwargs["notification_setting_option"] = option return args, kwargs def delete( self, request: Request, user: User, notification_setting_option: NotificationSettingOption ) -> Response: notification_setting_option.delete() return Response(status=status.HTTP_204_NO_CONTENT)
UserNotificationSettingsOptionsDetailEndpoint
python
pytorch__pytorch
test/quantization/eager/test_quantize_eager_qat.py
{ "start": 9738, "end": 10872 }
class ____(_ReferenceConvBnNd, nn.Conv2d): _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvBn2d def __init__( self, # ConvNd args in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=None, padding_mode="zeros", # BatchNorm2d args # num_features: out_channels eps=1e-05, momentum=0.1, # affine: True # track_running_stats: True # Args for this module freeze_bn=False, qconfig=None, ): kernel_size = _pair(kernel_size) stride = _pair(stride) padding = _pair(padding) dilation = _pair(dilation) _ReferenceConvBnNd.__init__( self, in_channels, out_channels, kernel_size, stride, padding, dilation, False, _pair(0), groups, bias, padding_mode, eps, momentum, freeze_bn, qconfig, )
_ReferenceConvBn2d
python
walkccc__LeetCode
solutions/2475. Number of Unequal Triplets in Array/2475.py
{ "start": 525, "end": 779 }
class ____: def unequalTriplets(self, nums: list[int]) -> int: ans = 0 prev = 0 next = len(nums) for freq in collections.Counter(nums).values(): next -= freq ans += prev * freq * next prev += freq return ans
Solution
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 30572, "end": 31223 }
class ____(DictDot): def __init__( self, graph: Optional[dict] = None, ): self.graph = graph @override def __repr__(self) -> str: return json.dumps(self.to_json_dict(), indent=2) @override def __str__(self) -> str: return json.dumps(self.to_json_dict(), indent=2) def to_json_dict(self) -> Optional[dict[str, JSONValues]]: """Returns a JSON-serializable dict representation of this RenderedAtomicValueGraph. Returns: A JSON-serializable dict representation of this RenderedAtomicValueGraph. """ return self.graph
RenderedAtomicValueGraph
python
django__django
django/forms/fields.py
{ "start": 33018, "end": 34594 }
class ____(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_list": _("Enter a list of values."), } def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] def validate(self, value): """Validate that the input is a list or tuple.""" if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") # Validate that each value in the value list is in self.choices. for val in value: if not self.valid_value(val): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in initial} data_set = {str(value) for value in data} return data_set != initial_set
MultipleChoiceField
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 16269, "end": 17388 }
class ____(BaseSafeMigrationTest): app = "good_flow_delete_field_simple_app" migrate_from = "0001" migrate_to = "0003" def test(self) -> None: with override_settings( ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT="5s", ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT="5s", ): self._run_migration(self.app, "0001_initial") migration_sql = self.sql_migrate(self.app, "0002_set_pending") assert split_sql_queries(migration_sql) == [] self._run_migration(self.app, "0002_set_pending") migration_sql = self.sql_migrate(self.app, "0003_delete") # This should set both the lock and statement timeouts assert split_sql_queries(migration_sql) == [ "SET statement_timeout TO '5s';", "SET lock_timeout TO '5s';", 'ALTER TABLE "good_flow_delete_field_simple_app_testtable" DROP COLUMN "field" CASCADE;', "SET statement_timeout TO '0ms';", "SET lock_timeout TO '0ms';", ]
DeletionFieldGoodDeleteSimpleLockTimeoutTest
python
RaRe-Technologies__gensim
gensim/models/callbacks.py
{ "start": 22550, "end": 24318 }
class ____: """Base class to build callbacks for :class:`~gensim.models.word2vec.Word2Vec` & subclasses. Callbacks are used to apply custom functions over the model at specific points during training (epoch start, batch end etc.). This is a base class and its purpose is to be inherited by custom Callbacks that implement one or more of its methods (depending on the point during training where they want some action to be taken). See examples at the module level docstring for how to define your own callbacks by inheriting from this class. As of gensim 4.0.0, the following callbacks are no longer supported, and overriding them will have no effect: - on_batch_begin - on_batch_end """ def on_epoch_begin(self, model): """Method called at the start of each epoch. Parameters ---------- model : :class:`~gensim.models.word2vec.Word2Vec` or subclass Current model. """ pass def on_epoch_end(self, model): """Method called at the end of each epoch. Parameters ---------- model : :class:`~gensim.models.word2vec.Word2Vec` or subclass Current model. """ pass def on_train_begin(self, model): """Method called at the start of the training process. Parameters ---------- model : :class:`~gensim.models.word2vec.Word2Vec` or subclass Current model. """ pass def on_train_end(self, model): """Method called at the end of the training process. Parameters ---------- model : :class:`~gensim.models.word2vec.Word2Vec` or subclass Current model. """ pass
CallbackAny2Vec
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_from_sparse_op_test.py
{ "start": 1182, "end": 4482 }
class ____(test_util.TensorFlowTestCase): def testDocStringExample(self): st = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1], [0, 2], [1, 0], [3, 0]], values=[1, 2, 3, 4, 5], dense_shape=[4, 3]) rt = RaggedTensor.from_sparse(st) self.assertAllEqual(rt, [[1, 2, 3], [4], [], [5]]) def testEmpty(self): st = sparse_tensor.SparseTensor( indices=array_ops.zeros([0, 2], dtype=dtypes.int64), values=[], dense_shape=[4, 3]) rt = RaggedTensor.from_sparse(st) self.assertAllEqual(rt, [[], [], [], []]) def testBadSparseTensorRank(self): st1 = sparse_tensor.SparseTensor(indices=[[0]], values=[0], dense_shape=[3]) self.assertRaisesRegex(ValueError, r'rank\(st_input\) must be 2', RaggedTensor.from_sparse, st1) st2 = sparse_tensor.SparseTensor( indices=[[0, 0, 0]], values=[0], dense_shape=[3, 3, 3]) self.assertRaisesRegex(ValueError, r'rank\(st_input\) must be 2', RaggedTensor.from_sparse, st2) if not context.executing_eagerly(): st3 = sparse_tensor.SparseTensor( indices=array_ops.placeholder(dtypes.int64), values=[0], dense_shape=array_ops.placeholder(dtypes.int64)) self.assertRaisesRegex(ValueError, r'rank\(st_input\) must be 2', RaggedTensor.from_sparse, st3) def testGoodPartialSparseTensorRank(self): if not context.executing_eagerly(): st1 = sparse_tensor.SparseTensor( indices=[[0, 0]], values=[0], dense_shape=array_ops.placeholder(dtypes.int64)) st2 = sparse_tensor.SparseTensor( indices=array_ops.placeholder(dtypes.int64), values=[0], dense_shape=[4, 3]) # Shouldn't throw ValueError RaggedTensor.from_sparse(st1) RaggedTensor.from_sparse(st2) def testNonRaggedSparseTensor(self): # "index_suffix" means the value of the innermost dimension of the index # (i.e., indices[i][-1]). # See comments in _assert_sparse_indices_are_ragged_right() for more # details/background. # index_suffix of first index is not zero. st1 = sparse_tensor.SparseTensor( indices=[[0, 1], [0, 2], [2, 0]], values=[1, 2, 3], dense_shape=[3, 3]) with self.assertRaisesRegex(errors.InvalidArgumentError, r'.*SparseTensor is not right-ragged'): self.evaluate(RaggedTensor.from_sparse(st1)) # index_suffix of an index that starts a new row is not zero. st2 = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1], [2, 1]], values=[1, 2, 3], dense_shape=[3, 3]) with self.assertRaisesRegex(errors.InvalidArgumentError, r'.*SparseTensor is not right-ragged'): self.evaluate(RaggedTensor.from_sparse(st2)) # index_suffix of an index that continues a row skips a cell. st3 = sparse_tensor.SparseTensor( indices=[[0, 1], [0, 1], [0, 3]], values=[1, 2, 3], dense_shape=[3, 3]) with self.assertRaisesRegex(errors.InvalidArgumentError, r'.*SparseTensor is not right-ragged'): self.evaluate(RaggedTensor.from_sparse(st3)) if __name__ == '__main__': googletest.main()
RaggedTensorToSparseOpTest
python
pandas-dev__pandas
pandas/tests/extension/test_string.py
{ "start": 3025, "end": 10335 }
class ____(base.ExtensionTests): def test_combine_le(self, data_repeated): dtype = next(iter(data_repeated(2))).dtype if dtype.storage == "pyarrow" and dtype.na_value is pd.NA: self._combine_le_expected_dtype = "bool[pyarrow]" else: self._combine_le_expected_dtype = "bool" return super().test_combine_le(data_repeated) def test_eq_with_str(self, dtype): super().test_eq_with_str(dtype) if dtype.na_value is pd.NA: # only the NA-variant supports parametrized string alias assert dtype == f"string[{dtype.storage}]" elif dtype.storage == "pyarrow": assert dtype == "str" def test_is_not_string_type(self, dtype): # Different from BaseDtypeTests.test_is_not_string_type # because StringDtype is a string type assert is_string_dtype(dtype) def test_is_dtype_from_name(self, dtype, using_infer_string): if dtype.na_value is np.nan and not using_infer_string: result = type(dtype).is_dtype(dtype.name) assert result is False else: super().test_is_dtype_from_name(dtype) def test_construct_from_string_own_name(self, dtype, using_infer_string): if dtype.na_value is np.nan and not using_infer_string: with pytest.raises(TypeError, match="Cannot construct a 'StringDtype'"): dtype.construct_from_string(dtype.name) else: super().test_construct_from_string_own_name(dtype) def test_view(self, data): if data.dtype.storage == "pyarrow": pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_view(data) def test_from_dtype(self, data): # base test uses string representation of dtype pass def test_transpose(self, data): if data.dtype.storage == "pyarrow": pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_transpose(data) def test_setitem_preserves_views(self, data): if data.dtype.storage == "pyarrow": pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_setitem_preserves_views(data) def test_dropna_array(self, data_missing): result = data_missing.dropna() expected = data_missing[[1]] tm.assert_extension_array_equal(result, expected) def test_fillna_no_op_returns_copy(self, data): data = data[~data.isna()] valid = data[0] result = data.fillna(valid) assert result is not data tm.assert_extension_array_equal(result, data) def test_fillna_readonly(self, data_missing): data = data_missing.copy() data._readonly = True # by default fillna(copy=True), then this works fine result = data.fillna(data_missing[1]) assert result[0] == data_missing[1] tm.assert_extension_array_equal(data, data_missing) # fillna(copy=False) is generally not honored by Arrow-backed array, # but always returns new data -> same result as above if data.dtype.storage == "pyarrow": result = data.fillna(data_missing[1]) assert result[0] == data_missing[1] else: with pytest.raises(ValueError, match="Cannot modify read-only array"): data.fillna(data_missing[1], copy=False) tm.assert_extension_array_equal(data, data_missing) def _get_expected_exception( self, op_name: str, obj, other ) -> type[Exception] | tuple[type[Exception], ...] | None: if op_name in [ "__mod__", "__rmod__", "__divmod__", "__rdivmod__", "__pow__", "__rpow__", ]: return TypeError elif op_name in ["__mul__", "__rmul__"]: # Can only multiply strings by integers return TypeError elif op_name in [ "__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__", "__sub__", "__rsub__", ]: return TypeError return None def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool: return op_name in ["min", "max", "sum"] or ( ser.dtype.na_value is np.nan # type: ignore[union-attr] and op_name in ("any", "all") ) def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool: assert isinstance(ser.dtype, StorageExtensionDtype) return op_name in ["cummin", "cummax", "cumsum"] def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result): dtype = cast(StringDtype, tm.get_dtype(obj)) if op_name in ["__add__", "__radd__"]: cast_to = dtype dtype_other = tm.get_dtype(other) if not isinstance(other, str) else None if isinstance(dtype_other, StringDtype): cast_to = string_dtype_highest_priority(dtype, dtype_other) elif dtype.na_value is np.nan: cast_to = np.bool_ # type: ignore[assignment] elif dtype.storage == "pyarrow": cast_to = "bool[pyarrow]" # type: ignore[assignment] else: cast_to = "boolean" # type: ignore[assignment] return pointwise_result.astype(cast_to) def test_compare_scalar(self, data, comparison_op): ser = pd.Series(data) self._compare_other(ser, data, comparison_op, "abc") def test_groupby_extension_apply(self, data_for_grouping, groupby_apply_op): super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op) def test_combine_add(self, data_repeated, using_infer_string, request): dtype = next(data_repeated(1)).dtype if not using_infer_string and dtype.storage == "python": mark = pytest.mark.xfail( reason="The pointwise operation result will be inferred to " "string[nan, pyarrow], which does not match the input dtype" ) request.applymarker(mark) super().test_combine_add(data_repeated) def test_arith_series_with_array( self, data, all_arithmetic_operators, using_infer_string, request ): dtype = data.dtype if ( using_infer_string and all_arithmetic_operators == "__radd__" and dtype.na_value is pd.NA and (HAS_PYARROW or dtype.storage == "pyarrow") ): # TODO(infer_string) mark = pytest.mark.xfail( reason="The pointwise operation result will be inferred to " "string[nan, pyarrow], which does not match the input dtype" ) request.applymarker(mark) super().test_arith_series_with_array(data, all_arithmetic_operators) def test_loc_setitem_with_expansion_preserves_ea_index_dtype( self, data, request, using_infer_string ): if not using_infer_string and data.dtype.storage == "python": mark = pytest.mark.xfail(reason="Casts to object") request.applymarker(mark) super().test_loc_setitem_with_expansion_preserves_ea_index_dtype(data)
TestStringArray
python
miyuchina__mistletoe
mistletoe/core_tokens.py
{ "start": 16703, "end": 17339 }
class ____: def __init__(self, start, end, *fields): self._start = start self._end = end self.fields = fields def start(self, n=0): if n == 0: return self._start return self.fields[n - 1][0] def end(self, n=0): if n == 0: return self._end return self.fields[n - 1][1] def group(self, n=0): if n == 0: return ''.join([field[2] for field in self.fields]) return self.fields[n - 1][2] def __repr__(self): return '<MatchObj fields={} start={} end={}>'.format(self.fields, self._start, self._end)
MatchObj
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 756640, "end": 764796 }
class ____( DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefnumber ): """ StrokeWidthDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and at the middle of the band if set to ``0.5``. condition : dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalParameterValueDefnumberExprRef`, :class:`ConditionalPredicateValueDefnumberExprRef`, Sequence[dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalParameterValueDefnumberExprRef`, :class:`ConditionalPredicateValueDefnumberExprRef`] One or more value definition(s) with `a parameter or a test predicate <https://vega.github.io/vega-lite/docs/condition.html>`__. **Note:** A field definition's ``condition`` property can only contain `conditional value definitions <https://vega.github.io/vega-lite/docs/condition.html#value>`__ since Vega-Lite only allows at most one encoded field per encoding channel. datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None A constant value in data domain. title : str, :class:`Text`, Sequence[str], None A title for the field. If ``null``, the title will be removed. **Default value:** derived from the field's name and transformation function (``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function, the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``). Otherwise, the title is simply the field name. **Notes**: 1) You can customize the default field title format by providing the `fieldTitle <https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle function via the compile function's options <https://vega.github.io/vega-lite/usage/compile.html#field-title>`__. 2) If both field definition's ``title`` and axis, header, or legend ``title`` are defined, axis/header/legend title will be used. type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson'] The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or ``"nominal"``) for the encoded field or constant value (``datum``). It can also be a ``"geojson"`` type for encoding `'geoshape' <https://vega.github.io/vega-lite/docs/geoshape.html>`__. Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if: (1) the field is not nominal and the field encoding has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal scale for a field with ``bin`` or ``timeUnit``. **Default value:** 1) For a data ``field``, ``"nominal"`` is the default data type unless the field encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or ``timeUnit`` that satisfies the following criteria: * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__. * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` or (2) the specified scale type is a time or utc scale * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort order <https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__, (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is ``order``. 2) For a constant value in data domain (``datum``): * ``"quantitative"`` if the datum is a number * ``"nominal"`` if the datum is a string * ``"temporal"`` if the datum is `a date time object <https://vega.github.io/vega-lite/docs/datetime.html>`__ **Note:** * Data ``type`` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data. * Data values for a temporal field can be either a date-time string (e.g., ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a timestamp number (e.g., ``1552199579097``). * When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) or `"ordinal" (for using an ordinal bin scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" (for using an ordinal scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property refers to the post-aggregation data type. For example, we can calculate count ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have ``type`` as they must have exactly the same type as their primary channels (e.g., ``x``, ``y``). **See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__ documentation. """ _class_is_valid_at_instantiation = False _encoding_name = "strokeWidth" @overload def bandPosition(self, _: float, /) -> StrokeWidthDatum: ... @overload def condition( self, *, test: Optional[str | SchemaBase | Map] = Undefined, value: Optional[float | Parameter | SchemaBase | Map] = Undefined, ) -> StrokeWidthDatum: ... @overload def condition( self, *, empty: Optional[bool] = Undefined, param: Optional[str | SchemaBase] = Undefined, value: Optional[float | Parameter | SchemaBase | Map] = Undefined, ) -> StrokeWidthDatum: ... @overload def condition( self, _: list[core.ConditionalValueDefnumberExprRef], / ) -> StrokeWidthDatum: ... @overload def title(self, _: str | Sequence[str] | None, /) -> StrokeWidthDatum: ... @overload def type(self, _: Type_T, /) -> StrokeWidthDatum: ... def __init__( self, datum, bandPosition: Optional[float] = Undefined, condition: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | Type_T] = Undefined, **kwds, ): super().__init__( datum=datum, bandPosition=bandPosition, condition=condition, title=title, type=type, **kwds, ) @with_property_setters
StrokeWidthDatum
python
apache__airflow
providers/odbc/src/airflow/providers/odbc/hooks/odbc.py
{ "start": 1152, "end": 9840 }
class ____(DbApiHook): """ Interact with odbc data sources using pyodbc. To configure driver, in addition to supplying as constructor arg, the following are also supported: * set ``driver`` parameter in ``hook_params`` dictionary when instantiating hook by SQL operators. * set ``driver`` extra in the connection and set ``allow_driver_in_extra`` to True in section ``providers.odbc`` section of airflow config. * patch ``OdbcHook.default_driver`` in ``local_settings.py`` file. See :doc:`/connections/odbc` for full documentation. :param args: passed to DbApiHook :param database: database to use -- overrides connection ``schema`` :param driver: name of driver or path to driver. see above for more info :param dsn: name of DSN to use. overrides DSN supplied in connection ``extra`` :param connect_kwargs: keyword arguments passed to ``pyodbc.connect`` :param sqlalchemy_scheme: Scheme sqlalchemy connection. Default is ``mssql+pyodbc`` Only used for ``get_sqlalchemy_engine`` and ``get_sqlalchemy_connection`` methods. :param kwargs: passed to DbApiHook """ DEFAULT_SQLALCHEMY_SCHEME = "mssql+pyodbc" conn_name_attr = "odbc_conn_id" default_conn_name = "odbc_default" conn_type = "odbc" hook_name = "ODBC" supports_autocommit = True supports_executemany = True default_driver: str | None = None def __init__( self, *args, database: str | None = None, driver: str | None = None, dsn: str | None = None, connect_kwargs: dict | None = None, sqlalchemy_scheme: str | None = None, **kwargs, ) -> None: super().__init__(*args, **kwargs) self._database = database self._driver = driver self._dsn = dsn self._conn_str = None self._sqlalchemy_scheme = sqlalchemy_scheme self._connection = None self._connect_kwargs = connect_kwargs @property def database(self) -> str | None: """Database provided in init if exists; otherwise, ``schema`` from ``Connection`` object.""" return self._database or self.connection.schema @property def sqlalchemy_scheme(self) -> str: """SQLAlchemy scheme either from constructor, connection extras or default.""" extra_scheme = self.connection_extra_lower.get("sqlalchemy_scheme") if not self._sqlalchemy_scheme and extra_scheme and (":" in extra_scheme or "/" in extra_scheme): raise RuntimeError("sqlalchemy_scheme in connection extra should not contain : or / characters") return self._sqlalchemy_scheme or extra_scheme or self.DEFAULT_SQLALCHEMY_SCHEME @property def driver(self) -> str | None: """Driver from init param if given; else try to find one in connection extra.""" extra_driver = self.connection_extra_lower.get("driver") from airflow.configuration import conf if extra_driver and conf.getboolean("providers.odbc", "allow_driver_in_extra", fallback=False): self._driver = extra_driver else: self.log.warning( "You have supplied 'driver' via connection extra but it will not be used. In order to " "use 'driver' from extra you must set airflow config setting `allow_driver_in_extra = True` " "in section `providers.odbc`. Alternatively you may specify driver via 'driver' parameter of " "the hook constructor or via 'hook_params' dictionary with key 'driver' if using SQL " "operators." ) if not self._driver: self._driver = self.default_driver return self._driver.strip().lstrip("{").rstrip("}").strip() if self._driver else None @property def dsn(self) -> str | None: """DSN from init param if given; else try to find one in connection extra.""" if not self._dsn: dsn = self.connection_extra_lower.get("dsn") if dsn: self._dsn = dsn.strip() return self._dsn @property def odbc_connection_string(self): """ ODBC connection string. We build connection string instead of using ``pyodbc.connect`` params because, for example, there is no param representing ``ApplicationIntent=ReadOnly``. Any key-value pairs provided in ``Connection.extra`` will be added to the connection string. """ if not self._conn_str: conn_str = "" if self.driver: conn_str += f"DRIVER={{{self.driver}}};" if self.dsn: conn_str += f"DSN={self.dsn};" if self.connection.host: conn_str += f"SERVER={self.connection.host};" database = self.database or self.connection.schema if database: conn_str += f"DATABASE={database};" if self.connection.login: conn_str += f"UID={self.connection.login};" if self.connection.password: conn_str += f"PWD={self.connection.password};" if self.connection.port: conn_str += f"PORT={self.connection.port};" extra_exclude = {"driver", "dsn", "connect_kwargs", "sqlalchemy_scheme", "placeholder"} extra_params = {k: v for k, v in self.connection_extra.items() if k.lower() not in extra_exclude} for k, v in extra_params.items(): conn_str += f"{k}={v};" self._conn_str = conn_str return self._conn_str @property def connect_kwargs(self) -> dict: """ Effective kwargs to be passed to ``pyodbc.connect``. The kwargs are merged from connection extra, ``connect_kwargs``, and the hook's init arguments. Values received to the hook precede those from the connection. If ``attrs_before`` is provided, keys and values are converted to int, as required by pyodbc. """ conn_connect_kwargs = self.connection_extra_lower.get("connect_kwargs", {}) hook_connect_kwargs = self._connect_kwargs or {} merged_connect_kwargs = merge_dicts(conn_connect_kwargs, hook_connect_kwargs) if "attrs_before" in merged_connect_kwargs: merged_connect_kwargs["attrs_before"] = { int(k): int(v) for k, v in merged_connect_kwargs["attrs_before"].items() } return merged_connect_kwargs def get_sqlalchemy_engine(self, engine_kwargs=None): """ Get an sqlalchemy_engine object. :param engine_kwargs: Kwargs used in :func:`~sqlalchemy.create_engine`. :return: the created engine. """ if engine_kwargs is None: engine_kwargs = {} engine_kwargs["creator"] = self.get_conn return super().get_sqlalchemy_engine(engine_kwargs) def get_conn(self) -> Connection: """Return ``pyodbc`` connection object.""" conn = connect(self.odbc_connection_string, **self.connect_kwargs) return conn def get_uri(self) -> str: """URI invoked in :meth:`~airflow.providers.common.sql.hooks.sql.DbApiHook.get_sqlalchemy_engine`.""" quoted_conn_str = quote_plus(self.odbc_connection_string) uri = f"{self.sqlalchemy_scheme}:///?odbc_connect={quoted_conn_str}" return uri def get_sqlalchemy_connection( self, connect_kwargs: dict | None = None, engine_kwargs: dict | None = None ) -> Any: """SQLAlchemy connection object.""" engine = self.get_sqlalchemy_engine(engine_kwargs=engine_kwargs) cnx = engine.connect(**(connect_kwargs or {})) return cnx def _make_common_data_structure(self, result: Sequence[Row] | Row) -> list[tuple] | tuple: """Transform the pyodbc.Row objects returned from an SQL command into namedtuples.""" # Below ignored lines respect namedtuple docstring, but mypy do not support dynamically # instantiated namedtuple, and will never do: https://github.com/python/mypy/issues/848 field_names: list[tuple[str, type]] | None = None if not result: return [] if isinstance(result, Sequence): field_names = [col[0] for col in result[0].cursor_description] row_object = namedtuple("Row", field_names, rename=True) # type: ignore return cast("list[tuple]", [row_object(*row) for row in result]) field_names = [col[0] for col in result.cursor_description] return cast("tuple", namedtuple("Row", field_names, rename=True)(*result)) # type: ignore
OdbcHook
python
gevent__gevent
src/greentest/3.9/test_signal.py
{ "start": 14682, "end": 20428 }
class ____(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_socket(self): # use a subprocess to have only one thread code = """if 1: import signal import socket import struct import _testcapi signum = signal.SIGINT signals = (signum,) def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() write.setblocking(False) signal.set_wakeup_fd(write.fileno()) signal.raise_signal(signum) data = read.recv(1) if not data: raise Exception("no signum written") raised = struct.unpack('B', data) if raised != signals: raise Exception("%r != %r" % (raised, signals)) read.close() write.close() """ assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_send_error(self): # Use a subprocess to have only one thread. if os.name == 'nt': action = 'send' else: action = 'write' code = """if 1: import errno import signal import socket import sys import time import _testcapi from test.support import captured_stderr signum = signal.SIGINT def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() read.setblocking(False) write.setblocking(False) signal.set_wakeup_fd(write.fileno()) # Close sockets: send() will fail read.close() write.close() with captured_stderr() as err: signal.raise_signal(signum) err = err.getvalue() if ('Exception ignored when trying to {action} to the signal wakeup fd' not in err): raise AssertionError(err) """.format(action=action) assert_python_ok('-c', code) @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_warn_on_full_buffer(self): # Use a subprocess to have only one thread. if os.name == 'nt': action = 'send' else: action = 'write' code = """if 1: import errno import signal import socket import sys import time import _testcapi from test.support import captured_stderr signum = signal.SIGINT # This handler will be called, but we intentionally won't read from # the wakeup fd. def handler(signum, frame): pass signal.signal(signum, handler) read, write = socket.socketpair() # Fill the socketpair buffer if sys.platform == 'win32': # bpo-34130: On Windows, sometimes non-blocking send fails to fill # the full socketpair buffer, so use a timeout of 50 ms instead. write.settimeout(0.050) else: write.setblocking(False) # Start with large chunk size to reduce the # number of send needed to fill the buffer. written = 0 for chunk_size in (2 ** 16, 2 ** 8, 1): chunk = b"x" * chunk_size try: while True: write.send(chunk) written += chunk_size except (BlockingIOError, socket.timeout): pass print(f"%s bytes written into the socketpair" % written, flush=True) write.setblocking(False) try: write.send(b"x") except BlockingIOError: # The socketpair buffer seems full pass else: raise AssertionError("%s bytes failed to fill the socketpair " "buffer" % written) # By default, we get a warning when a signal arrives msg = ('Exception ignored when trying to {action} ' 'to the signal wakeup fd') signal.set_wakeup_fd(write.fileno()) with captured_stderr() as err: signal.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("first set_wakeup_fd() test failed, " "stderr: %r" % err) # And also if warn_on_full_buffer=True signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=True) with captured_stderr() as err: signal.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("set_wakeup_fd(warn_on_full_buffer=True) " "test failed, stderr: %r" % err) # But not if warn_on_full_buffer=False signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False) with captured_stderr() as err: signal.raise_signal(signum) err = err.getvalue() if err != "": raise AssertionError("set_wakeup_fd(warn_on_full_buffer=False) " "test failed, stderr: %r" % err) # And then check the default again, to make sure warn_on_full_buffer # settings don't leak across calls. signal.set_wakeup_fd(write.fileno()) with captured_stderr() as err: signal.raise_signal(signum) err = err.getvalue() if msg not in err: raise AssertionError("second set_wakeup_fd() test failed, " "stderr: %r" % err) """.format(action=action) assert_python_ok('-c', code) @unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
WakeupSocketSignalTests
python
ZoranPandovski__al-go-rithms
data_structures/doubly_linked_list/python/main.py
{ "start": 234, "end": 1583 }
class ____: def __init__(self): self.head = None # the head is being created as soon as the classs is invoked def append(self, data): # insertion or addition of the nodess new_node = Node(data) # creation of the node if self.head is None: # The list is checked wheater it is empty or not new_node.prev = None self.head = new_node else: cur = self.head while cur.next: cur = cur.next cur.next = new_node new_node.prev = cur new_node.next = None def traverse(self): # The tree is traversed and all the nodess are printed cur = self.head while cur: print(cur.data) cur = cur.next def remove(self): # deletio of nodes if self.head == None: # if empty is notified that it is empty print("Non node is present") else: cur = self.head while cur.next: prev = cur cur = cur.next prev.next = None # cur.next = None # creation of the class and being invoked ddlist = DoubleLinkedList() ddlist.append(1) ddlist.append(2) ddlist.append(3) ddlist.append(4) ddlist.append(5) ddlist.append(6) ddlist.traverse() ddlist.remove() ddlist.traverse()
DoubleLinkedList
python
PyCQA__pylint
tests/functional/a/access/access_to_protected_members.py
{ "start": 1501, "end": 3014 }
class ____: """Test for GitHub issue 1802""" def __init__(self, value): self._foo = value self.__private = 2 * value def __eq__(self, other): """Test a correct access as the access to protected member is in a special method""" if isinstance(other, self.__class__): answer = self._foo == other._foo return answer and self.__private == other.__private # [protected-access] return False def not_in_special(self, other): """ Test an incorrect access as the access to protected member is not inside a special method """ if isinstance(other, self.__class__): return self._foo == other._foo # [protected-access] return False def __le__(self, other): """ Test a correct access as the access to protected member is inside a special method even if it is deeply nested """ if 2 > 1: # pylint: disable=comparison-of-constants if isinstance(other, self.__class__): if "answer" == "42": # pylint: disable=comparison-of-constants return self._foo == other._foo return False def __fake_special__(self, other): """ Test an incorrect access as the access to protected member is not inside a licit special method """ if isinstance(other, self.__class__): return self._foo == other._foo # [protected-access] return False
Issue1802
python
pypa__warehouse
tests/unit/helpdesk/test_services.py
{ "start": 1485, "end": 2377 }
class ____: def test_create_service(self): service = ConsoleHelpDeskService.create_service(None, None) assert isinstance(service, ConsoleHelpDeskService) def test_create_conversation(self, capsys): service = ConsoleHelpDeskService() service.create_conversation( request_json={ "email": "foo@example.com", "name": "Foo Bar", "subject": "Test", "message": "Hello, World!", } ) captured = capsys.readouterr() expected = dedent( """\ Observation created request_json: {'email': 'foo@example.com', 'message': 'Hello, World!', 'name': 'Foo Bar', 'subject': 'Test'} """ ) assert captured.out == expected
TestConsoleHelpDeskService
python
ray-project__ray
python/ray/data/_internal/cluster_autoscaler/default_cluster_autoscaler.py
{ "start": 547, "end": 4179 }
class ____(ClusterAutoscaler): # Min number of seconds between two autoscaling requests. MIN_GAP_BETWEEN_AUTOSCALING_REQUESTS = 20 def __init__( self, topology: "Topology", resource_manager: "ResourceManager", *, execution_id: str, ): super().__init__(topology, resource_manager, execution_id) # Last time when a request was sent to Ray's autoscaler. self._last_request_time = 0 def try_trigger_scaling(self): """Try to scale up the cluster to accommodate the provided in-progress workload. This makes a resource request to Ray's autoscaler consisting of the current, aggregate usage of all operators in the DAG + the incremental usage of all operators that are ready for dispatch (i.e. that have inputs queued). If the autoscaler were to grant this resource request, it would allow us to dispatch one task for every ready operator. Note that this resource request does not take the global resource limits or the liveness policy into account; it only tries to make the existing resource usage + one more task per ready operator feasible in the cluster. """ # Limit the frequency of autoscaling requests. now = time.time() if now - self._last_request_time < self.MIN_GAP_BETWEEN_AUTOSCALING_REQUESTS: return # Scale up the cluster, if no ops are allowed to run, but there are still data # in the input queues. no_runnable_op = all( not op_state._scheduling_status.runnable for _, op_state in self._topology.items() ) any_has_input = any( op_state.has_pending_bundles() for _, op_state in self._topology.items() ) if not (no_runnable_op and any_has_input): return self._last_request_time = now # Get resource usage for all ops + additional resources needed to launch one # more task for each ready op. resource_request = [] def to_bundle(resource: ExecutionResources) -> Dict: req = {} if resource.cpu: req["CPU"] = math.ceil(resource.cpu) if resource.gpu: req["GPU"] = math.ceil(resource.gpu) return req for op, state in self._topology.items(): per_task_resource = op.incremental_resource_usage() task_bundle = to_bundle(per_task_resource) resource_request.extend([task_bundle] * op.num_active_tasks()) # Only include incremental resource usage for ops that are ready for # dispatch. if state.has_pending_bundles(): # TODO(Clark): Scale up more aggressively by adding incremental resource # usage for more than one bundle in the queue for this op? resource_request.append(task_bundle) self._send_resource_request(resource_request) def _send_resource_request(self, resource_request): # Make autoscaler resource request. actor = get_or_create_autoscaling_requester_actor() actor.request_resources.remote(resource_request, self._execution_id) def on_executor_shutdown(self): # Make request for zero resources to autoscaler for this execution. actor = get_or_create_autoscaling_requester_actor() actor.request_resources.remote({}, self._execution_id) def get_total_resources(self) -> ExecutionResources: return ExecutionResources.from_resource_dict(ray.cluster_resources())
DefaultClusterAutoscaler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 702, "end": 737 }
class ____(Generic[T_co]): ...
Class3
python
numba__numba
numba/tests/test_sys_monitoring.py
{ "start": 34693, "end": 35472 }
class ____(TestCase): @TestCase.run_test_in_subprocess( envvars={"NUMBA_ENABLE_SYS_MONITORING": ''}) def test_default_off(self): @jit def foo(x): return x + 1 self.assertFalse(foo._enable_sysmon) @TestCase.run_test_in_subprocess( envvars={"NUMBA_ENABLE_SYS_MONITORING": '0'}) def test_override_off(self): @jit def foo(x): return x + 1 self.assertFalse(foo._enable_sysmon) @TestCase.run_test_in_subprocess( envvars={"NUMBA_ENABLE_SYS_MONITORING": '1'}) def test_override_on(self): @jit def foo(x): return x + 1 self.assertTrue(foo._enable_sysmon) if __name__ == '__main__': unittest.main()
TestMonitoringEnvVarControl
python
PyCQA__pylint
pylint/testutils/_run.py
{ "start": 847, "end": 1430 }
class ____(LintRun): """Like Run, but we're using an explicitly set empty pylintrc. We don't want to use the project's pylintrc during tests, because it means that a change in our config could break tests. But we want to see if the changes to the default break tests. """ def __init__( self, args: Sequence[str], reporter: BaseReporter | None = None, exit: bool = True, # pylint: disable=redefined-builtin ) -> None: args = _add_rcfile_default_pylintrc(list(args)) super().__init__(args, reporter, exit)
_Run
python
kamyu104__LeetCode-Solutions
Python/count-nodes-equal-to-average-of-subtree.py
{ "start": 165, "end": 1158 }
class ____(object): def averageOfSubtree(self, root): """ :type root: Optional[TreeNode] :rtype: int """ def iter_dfs(root): result = 0 stk = [(1, (root, [0]*2))] while stk: step, args = stk.pop() if step == 1: node, ret = args if not node: continue ret1, ret2 = [0]*2, [0]*2 stk.append((2, (node, ret1, ret2, ret))) stk.append((1, (node.right, ret2))) stk.append((1, (node.left, ret1))) elif step == 2: node, ret1, ret2, ret = args ret[0] = ret1[0]+ret2[0]+node.val ret[1] = ret1[1]+ret2[1]+1 result += int(ret[0]//ret[1] == node.val) return result return iter_dfs(root) # Time: O(n) # Space: O(h) # dfs
Solution
python
pandas-dev__pandas
asv_bench/benchmarks/rolling.py
{ "start": 6754, "end": 7384 }
class ____: params = ( ["DataFrame", "Series"], [10, 1000], ["int", "float"], [0, 0.5, 1], ["linear", "nearest", "lower", "higher", "midpoint"], ) param_names = ["constructor", "window", "dtype", "percentile"] def setup(self, constructor, window, dtype, percentile, interpolation): N = 10**5 arr = np.random.random(N).astype(dtype) self.roll = getattr(pd, constructor)(arr).rolling(window) def time_quantile(self, constructor, window, dtype, percentile, interpolation): self.roll.quantile(percentile, interpolation=interpolation)
Quantile
python
getsentry__sentry
src/sentry/models/dashboard.py
{ "start": 6940, "end": 8127 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Organization user_id = HybridCloudForeignKey("sentry.User", on_delete="CASCADE") organization = FlexibleForeignKey("sentry.Organization") dashboard = FlexibleForeignKey("sentry.Dashboard", on_delete=models.CASCADE) position = models.PositiveSmallIntegerField(null=True) objects: ClassVar[DashboardFavoriteUserManager] = DashboardFavoriteUserManager() class Meta: app_label = "sentry" db_table = "sentry_dashboardfavoriteuser" constraints = [ # A user can only favorite a dashboard once UniqueConstraint( fields=["user_id", "dashboard"], name="sentry_dashboardfavoriteuser_user_id_dashboard_id_2c7267a5_uniq", ), # A user can only have one starred dashboard in a specific position UniqueConstraint( fields=["user_id", "organization_id", "position"], name="sentry_dashboardfavoriteuser_user_org_position_uniq_deferred", deferrable=models.Deferrable.DEFERRED, ), ] @region_silo_model
DashboardFavoriteUser
python
apache__airflow
airflow-core/tests/unit/core/test_example_dags_system.py
{ "start": 2534, "end": 4909 }
class ____(SystemTest): @pytest.mark.parametrize( "module", ["example_bash_operator", "example_branch_operator", "tutorial_dag", "example_dag_decorator"], ) def test_dag_example(self, module): test_run = import_string(f"airflow.example_dags.{module}.test_run") test_run() @pytest.mark.parametrize( ("factory", "expected"), [ (get_dag_fail, "failed"), (get_dag_fail_root, "failed"), (get_dag_success, "success"), ], ) def test_dag_run_final_state(self, factory, expected, dag_maker, session): """ These tests are migrated tests that were added in PR #1289 which was fixing issue #1225. I would be very surprised if these things were not covered elsewhere already but, just in case, I'm migrating them to system tests. """ dag = factory(dag_maker) run = get_test_run(dag) with pytest.raises(AssertionError, match="The system test failed"): run() dr = session.scalar(select(DagRun)) assert dr.state == "failed" def test_dag_root_task_start_date_future(self, dag_maker, session): """ These tests are migrated tests that were added in PR #1289 which was fixing issue #1225. This one tests what happens when there's a dag with a root task with future start date. The dag should run, but no TI should be created for the task where start date in future. """ exec_date = pendulum.datetime(2021, 1, 1) fut_start_date = pendulum.datetime(2021, 2, 1) with dag_maker( dag_id="dagrun_states_root_future", schedule=timedelta(days=1), catchup=False, ) as dag: PythonOperator( task_id="current", python_callable=lambda: print("hello"), ) PythonOperator( task_id="future", python_callable=lambda: print("hello"), start_date=fut_start_date, ) run = get_test_run(dag, logical_date=exec_date) run() dr = session.scalar(select(DagRun)) tis = dr.task_instances assert dr.state == DagRunState.SUCCESS assert len(tis) == 1 assert tis[0].task_id == "current"
TestExampleDagsSystem
python
walkccc__LeetCode
solutions/935. Knight Dialer/935.py
{ "start": 0, "end": 806 }
class ____: def knightDialer(self, n: int) -> int: DIRS = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)) MOD = 1_000_000_007 # dp[i][j] := the number of ways stand on (i, j) dp = [[1] * 3 for _ in range(4)] dp[3][0] = dp[3][2] = 0 for _ in range(n - 1): newDp = [[0] * 3 for _ in range(4)] for i in range(4): for j in range(3): if (i, j) in ((3, 0), (3, 2)): continue for dx, dy in DIRS: x = i + dx y = j + dy if x < 0 or x >= 4 or y < 0 or y >= 3: continue if (x, y) in ((3, 0), (3, 2)): continue newDp[x][y] = (newDp[x][y] + dp[i][j]) % MOD dp = newDp return sum(map(sum, dp)) % MOD
Solution
python
pypa__virtualenv
tasks/make_zipapp.py
{ "start": 11545, "end": 11844 }
class ____: def __init__(self, wheel=None, versions=None) -> None: self.wheel = wheel self.versions = versions or [] def __repr__(self) -> str: return f"{self.__class__.__name__}({self.wheel!r}, {self.versions!r})" if __name__ == "__main__": main()
WheelForVersion
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-hire-k-workers.py
{ "start": 67, "end": 672 }
class ____(object): def mincostToHireWorkers(self, quality, wage, K): """ :type quality: List[int] :type wage: List[int] :type K: int :rtype: float """ result, qsum = float("inf"), 0 max_heap = [] for r, q in sorted([float(w)/q, q] for w, q in itertools.izip(wage, quality)): qsum += q heapq.heappush(max_heap, -q) if len(max_heap) > K: qsum -= -heapq.heappop(max_heap) if len(max_heap) == K: result = min(result, qsum*r) return result
Solution
python
facelessuser__pymdown-extensions
pymdownx/__meta__.py
{ "start": 820, "end": 6788 }
class ____(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])): """ Get the version (PEP 440). A biased approach to the PEP 440 semantic version. Provides a tuple structure which is sorted for comparisons `v1 > v2` etc. (major, minor, micro, release type, pre-release build, post-release build, development release build) Release types are named in is such a way they are comparable with ease. Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get development status for setup files. How it works (currently): - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`. - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`. The dot is used to ensure all development specifiers are sorted before `alpha`. You can specify a `dev` number for development builds, but do not have to as implicit development releases are allowed. - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not allow implicit prereleases. - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically does not allow implicit post releases. - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`. Acceptable version releases: ``` Version(1, 0, 0, "final") 1.0 Version(1, 2, 0, "final") 1.2 Version(1, 2, 3, "final") 1.2.3 Version(1, 2, 0, "alpha", pre=4) 1.2a4 Version(1, 2, 0, "beta", pre=4) 1.2b4 Version(1, 2, 0, "candidate", pre=4) 1.2rc4 Version(1, 2, 0, "final", post=1) 1.2.post1 Version(1, 2, 3, ".dev") 1.2.3.dev0 Version(1, 2, 3, ".dev", dev=1) 1.2.3.dev1 ``` """ def __new__( cls, major: int, minor: int, micro: int, release: str = "final", pre: int = 0, post: int = 0, dev: int = 0 ) -> Version: """Validate version info.""" # Ensure all parts are positive integers. for value in (major, minor, micro, pre, post): if not (isinstance(value, int) and value >= 0): raise ValueError("All version parts except 'release' should be integers.") if release not in REL_MAP: raise ValueError(f"'{release}' is not a valid release type.") # Ensure valid pre-release (we do not allow implicit pre-releases). if ".dev-candidate" < release < "final": if pre == 0: raise ValueError("Implicit pre-releases not allowed.") elif dev: raise ValueError("Version is not a development release.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure valid development or development/pre release elif release < "alpha": if release > ".dev" and pre == 0: raise ValueError("Implicit pre-release not allowed.") elif post: raise ValueError("Post-releases are not allowed with pre-releases.") # Ensure a valid normal release else: if pre: raise ValueError("Version is not a pre-release.") elif dev: raise ValueError("Version is not a development release.") return super().__new__(cls, major, minor, micro, release, pre, post, dev) def _is_pre(self) -> bool: """Is prerelease.""" return bool(self.pre > 0) def _is_dev(self) -> bool: """Is development.""" return bool(self.release < "alpha") def _is_post(self) -> bool: """Is post.""" return bool(self.post > 0) def _get_dev_status(self) -> str: # pragma: no cover """Get development status string.""" return DEV_STATUS[self.release] def _get_canonical(self) -> str: """Get the canonical output string.""" # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed.. if self.micro == 0 and self.major != 0: ver = f"{self.major}.{self.minor}" else: ver = f"{self.major}.{self.minor}.{self.micro}" if self._is_pre(): ver += f'{REL_MAP[self.release]}{self.pre}' if self._is_post(): ver += f".post{self.post}" if self._is_dev(): ver += f".dev{self.dev}" return ver def parse_version(ver: str) -> Version: """Parse version into a comparable Version tuple.""" m = RE_VER.match(ver) if m is None: raise ValueError(f"'{ver}' is not a valid version") # Handle major, minor, micro major = int(m.group('major')) minor = int(m.group('minor')) if m.group('minor') else 0 micro = int(m.group('micro')) if m.group('micro') else 0 # Handle pre releases if m.group('type'): release = PRE_REL_MAP[m.group('type')] pre = int(m.group('pre')) else: release = "final" pre = 0 # Handle development releases dev = m.group('dev') if m.group('dev') else 0 if m.group('dev'): dev = int(m.group('dev')) release = '.dev-' + release if pre else '.dev' else: dev = 0 # Handle post post = int(m.group('post')) if m.group('post') else 0 return Version(major, minor, micro, release, pre, post, dev) __version_info__ = Version(10, 18, 0, "final") __version__ = __version_info__._get_canonical()
Version
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/utils.py
{ "start": 3144, "end": 3597 }
class ____(AirbyteTracedException): """Raises the error when Shopify resources couldn't be accessed because of the ConnectionError occured (100-x)""" def __init__(self, details, **kwargs) -> None: self.message = f"Invalid `Shopify Store` name used or `host` couldn't be verified by Shopify. Details: {details}" super().__init__(internal_message=self.message, failure_type=FailureType.config_error, **kwargs)
ShopifyConnectionError
python
buildout__buildout
src/zc/buildout/configparser.py
{ "start": 1010, "end": 1842 }
class ____(Exception): """Base class for ConfigParser exceptions.""" def _get_message(self): """Getter for 'message'; needed only to override deprecation in BaseException.""" return self.__message def _set_message(self, value): """Setter for 'message'; needed only to override deprecation in BaseException.""" self.__message = value # BaseException.message has been deprecated since Python 2.6. To prevent # DeprecationWarning from popping up over this pre-existing attribute, use # a new property that takes lookup precedence. message = property(_get_message, _set_message) def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) def __repr__(self): return self.message __str__ = __repr__
Error
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 68516, "end": 72303 }
class ____(GoogleCloudBaseOperator): """ Finds potentially sensitive info in content; limits input size, processing time, and output size. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPInspectContentOperator` :param project_id: (Optional) Google Cloud project ID where the DLP Instance exists. If set to None or missing, the default project_id from the Google Cloud connection is used. :param inspect_config: (Optional) Configuration for the inspector. Items specified here will override the template referenced by the inspect_template_name argument. :param item: (Optional) The item to de-identify. Will be treated as text. :param inspect_template_name: (Optional) Optional template to use. Any configuration directly specified in inspect_config will override those set in the template. :param retry: (Optional) A retry object used to retry requests. If None is specified, requests will not be retried. :param timeout: (Optional) The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: (Optional) Additional metadata that is provided to the method. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "project_id", "inspect_config", "item", "inspect_template_name", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, project_id: str = PROVIDE_PROJECT_ID, inspect_config: dict | InspectConfig | None = None, item: dict | ContentItem | None = None, inspect_template_name: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.project_id = project_id self.inspect_config = inspect_config self.item = item self.inspect_template_name = inspect_template_name self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = CloudDLPHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) response = hook.inspect_content( project_id=self.project_id, inspect_config=self.inspect_config, item=self.item, inspect_template_name=self.inspect_template_name, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) return InspectContentResponse.to_dict(response)
CloudDLPInspectContentOperator
python
pypa__build
src/build/_exceptions.py
{ "start": 876, "end": 1151 }
class ____(BuildException): """ Exception raised when the ``[build-system]`` table in pyproject.toml is invalid. """ def __str__(self) -> str: return f'Failed to validate `build-system` in pyproject.toml: {self.args[0]}'
BuildSystemTableValidationError