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
mlflow__mlflow
tests/langchain/test_langchain_model_export.py
{ "start": 31898, "end": 82983 }
class ____(SimpleChatModel): def _call(self, messages, stop, run_manager, **kwargs): return "\n".join([f"{message.type}: {message.content}" for message in messages]) @property def _llm_type(self) -> str: return "chat model" @skip_if_v1 def test_predict_with_builtin_pyfunc_chat_conversion(spark): # TODO: Migrate to models-from-code input_example = { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "assistant", "content": "What would you like to ask?"}, {"role": "user", "content": "Who owns MLflow?"}, ] } content = ( "system: You are a helpful assistant.\n" "ai: What would you like to ask?\n" "human: Who owns MLflow?" ) chain = ChatModel() | StrOutputParser() assert chain.invoke([HumanMessage(content="Who owns MLflow?")]) == "human: Who owns MLflow?" with pytest.raises(ValueError, match="Invalid input type"): chain.invoke(input_example) with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain, name="model_path", input_example=input_example ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert ( loaded_model.invoke([HumanMessage(content="Who owns MLflow?")]) == "human: Who owns MLflow?" ) pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) expected_chat_response = { "id": None, "object": "chat.completion", "created": 1677858242, "model": "", "choices": [ { "index": 0, "message": { "role": "assistant", "content": content, }, "finish_reason": None, } ], "usage": { "prompt_tokens": None, "completion_tokens": None, "total_tokens": None, }, } with mock.patch("time.time", return_value=1677858242): result1 = pyfunc_loaded_model.predict(input_example) result1[0]["id"] = None assert result1 == [expected_chat_response] result2 = pyfunc_loaded_model.predict([input_example, input_example]) result2[0]["id"] = None result2[1]["id"] = None assert result2 == [ expected_chat_response, expected_chat_response, ] with pytest.raises(MlflowException, match="Unrecognized chat message role"): pyfunc_loaded_model.predict({"messages": [{"role": "foobar", "content": "test content"}]}) @skip_if_v1 def test_predict_with_builtin_pyfunc_chat_conversion_for_aimessage_response(): class ChatModel(SimpleChatModel): def _call(self, messages, stop, run_manager, **kwargs): return "You own MLflow" @property def _llm_type(self) -> str: return "chat model" input_example = { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "assistant", "content": "What would you like to ask?"}, {"role": "user", "content": "Who owns MLflow?"}, ] } chain = ChatModel() result = chain.invoke([HumanMessage(content="Who owns MLflow?")]) assert isinstance(result, AIMessage) assert result.content == "You own MLflow" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain, name="model_path", input_example=input_example ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) result = loaded_model.invoke([HumanMessage(content="Who owns MLflow?")]) assert isinstance(result, AIMessage) assert result.content == "You own MLflow" pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) with mock.patch("time.time", return_value=1677858242): result = pyfunc_loaded_model.predict(input_example) assert "id" in result[0], "Response message id is lost." result[0]["id"] = None assert result == [ { "id": None, "object": "chat.completion", "created": 1677858242, "model": "", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "You own MLflow", }, "finish_reason": None, } ], "usage": { "prompt_tokens": None, "completion_tokens": None, "total_tokens": None, }, } ] @skip_if_v1 def test_pyfunc_builtin_chat_request_conversion_fails_gracefully(): chain = RunnablePassthrough() | itemgetter("messages") # Ensure we're going to test that "messages" remains intact & unchanged even if it # doesn't appear explicitly in the chain's input schema assert "messages" not in chain.input_schema().model_fields with mlflow.start_run(): model_info = mlflow.langchain.log_model(chain, name="model_path") pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert pyfunc_loaded_model.predict({"messages": "not an array"}) == "not an array" # Verify that messages aren't converted to LangChain format if extra keys are present, # under the assumption that additional keys can't be specified when calling LangChain invoke() # / batch() with chat messages assert pyfunc_loaded_model.predict( { "messages": [{"role": "user", "content": "blah"}], "extrakey": "extra", } ) == [ {"role": "user", "content": "blah"}, ] # Verify that messages aren't converted to LangChain format if role / content are missing # or extra keys are present in the message assert pyfunc_loaded_model.predict( { "messages": [{"content": "blah"}], } ) == [ {"content": "blah"}, ] assert pyfunc_loaded_model.predict( { "messages": [{"role": "user", "content": "blah"}, {}], } ) == [ {"role": "user", "content": "blah"}, {}, ] assert pyfunc_loaded_model.predict( { "messages": [{"role": "user", "content": 123}], } ) == [ {"role": "user", "content": 123}, ] # Verify behavior for batches of message histories assert pyfunc_loaded_model.predict( [ { "messages": "not an array", }, { "messages": [{"role": "user", "content": "content"}], }, ] ) == [ "not an array", [{"role": "user", "content": "content"}], ] assert pyfunc_loaded_model.predict( [ { "messages": [{"role": "user", "content": "content"}], }, {"messages": [{"role": "user", "content": "content"}], "extrakey": "extra"}, ] ) == [ [{"role": "user", "content": "content"}], [{"role": "user", "content": "content"}], ] assert pyfunc_loaded_model.predict( [ { "messages": [{"role": "user", "content": "content"}], }, { "messages": [ {"role": "user", "content": "content"}, {"role": "user", "content": 123}, ], }, ] ) == [ [{"role": "user", "content": "content"}], [{"role": "user", "content": "content"}, {"role": "user", "content": 123}], ] @skip_if_v1 def test_save_load_chain_that_relies_on_pickle_serialization(monkeypatch, model_path): from langchain_community.llms.databricks import Databricks monkeypatch.setattr( "langchain_community.llms.databricks._DatabricksServingEndpointClient", mock.MagicMock(), ) monkeypatch.setenv("DATABRICKS_HOST", "test-host") monkeypatch.setenv("DATABRICKS_TOKEN", "test-token") llm_kwargs = {"endpoint_name": "test-endpoint", "temperature": 0.9} if IS_PICKLE_SERIALIZATION_RESTRICTED: llm_kwargs["allow_dangerous_deserialization"] = True llm = Databricks(**llm_kwargs) prompt = PromptTemplate(input_variables=["question"], template="I have a question: {question}") chain = prompt | llm | StrOutputParser() # Not passing an input_example to avoid triggering prediction mlflow.langchain.save_model(chain, model_path) loaded_model = mlflow.langchain.load_model(model_path) # Check if the deserialized model has the same endpoint and temperature loaded_databricks_llm = loaded_model.middle[0] assert loaded_databricks_llm.endpoint_name == "test-endpoint" assert loaded_databricks_llm.temperature == 0.9 def _get_message_content(predictions): return predictions[0]["choices"][0]["message"]["content"] @pytest.mark.parametrize( ("chain_path", "model_config"), [ ( os.path.abspath("tests/langchain/sample_code/chain.py"), os.path.abspath("tests/langchain/sample_code/config.yml"), ), ( "tests/langchain/../langchain/sample_code/chain.py", "tests/langchain/../langchain/sample_code/config.yml", ), ], ) def test_save_load_chain_as_code(chain_path, model_config, monkeypatch): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } artifact_path = "model_path" with mlflow.start_run() as run: model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, model_config=model_config, ) client = mlflow.tracking.MlflowClient() run_id = run.info.run_id assert client.get_run(run_id).data.params == { "llm_prompt_template": "Answer the following question based on " "the context: {context}\nQuestion: {question}", "embedding_size": "5", "not_used_array": "[1, 2, 3]", "response": "Databricks", } assert mlflow.models.model_config.__mlflow_model_config__ is None loaded_model = mlflow.langchain.load_model(model_info.model_uri) # During the loading process, MLflow executes the chain.py file to # load the model class. It should not generate any traces even if # the code enables autologging and invoke chain. assert len(get_traces()) == 0 assert mlflow.models.model_config.__mlflow_model_config__ is None answer = "Databricks" assert loaded_model.invoke(input_example) == answer pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert answer == _get_message_content(pyfunc_loaded_model.predict(input_example)) inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) predictions = json.loads(response.content.decode("utf-8")) # Mock out the `created` timestamp as it is not deterministic expected = [{**try_transform_response_to_chat_format(answer), "created": mock.ANY}] assert expected == predictions pyfunc_model_path = _download_artifact_from_uri(model_info.model_uri) reloaded_model = Model.load(os.path.join(pyfunc_model_path, "MLmodel")) assert reloaded_model.resources["databricks"] == { "serving_endpoint": [{"name": "fake-endpoint"}] } assert reloaded_model.metadata["dependencies_schemas"] == { DependenciesSchemasType.RETRIEVERS.value: [ { "doc_uri": "doc-uri", "name": "retriever", "other_columns": ["column1", "column2"], "primary_key": "primary-key", "text_column": "text-column", } ] } # Emulate the model serving environment monkeypatch.setenv("IS_IN_DB_MODEL_SERVING_ENV", "true") monkeypatch.setenv("ENABLE_MLFLOW_TRACING", "true") mlflow.tracing.reset() request_id = "mock_request_id" tracer = MlflowLangchainTracer(prediction_context=Context(request_id)) input_example = {"messages": [{"role": "user", "content": TEST_CONTENT}]} response = pyfunc_loaded_model._model_impl._predict_with_callbacks( data=input_example, callback_handlers=[tracer] ) assert response["choices"][0]["message"]["content"] == "Databricks" trace = pop_trace(request_id) assert trace["info"]["tags"][DependenciesSchemasType.RETRIEVERS.value] == json.dumps( [ { "doc_uri": "doc-uri", "name": "retriever", "other_columns": ["column1", "column2"], "primary_key": "primary-key", "text_column": "text-column", } ] ) @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/chain.py"), "tests/langchain/../langchain/sample_code/chain.py", ], ) def test_save_load_chain_as_code_model_config_dict(chain_path): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name="model_path", input_example=input_example, model_config={ "response": "modified response", "embedding_size": 5, "llm_prompt_template": "answer the question", }, ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) answer = "modified response" assert loaded_model.invoke(input_example) == answer pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert answer == _get_message_content(pyfunc_loaded_model.predict(input_example)) @pytest.mark.parametrize( "model_config", [ os.path.abspath("tests/langchain/sample_code/config.yml"), "tests/langchain/../langchain/sample_code/config.yml", ], ) def test_save_load_chain_as_code_with_different_names(tmp_path, model_config): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } # Read the contents of the original chain file with open("tests/langchain/sample_code/chain.py") as chain_file: chain_file_content = chain_file.read() temp_file = tmp_path / "model.py" temp_file.write_text(chain_file_content) with mlflow.start_run(): model_info = mlflow.langchain.log_model( str(temp_file), name="model_path", input_example=input_example, model_config=model_config, ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) answer = "Databricks" assert loaded_model.invoke(input_example) == answer pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert answer == _get_message_content(pyfunc_loaded_model.predict(input_example)) @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/chain.py"), "tests/langchain/../langchain/sample_code/chain.py", ], ) @pytest.mark.parametrize( "model_config", [ os.path.abspath("tests/langchain/sample_code/config.yml"), "tests/langchain/../langchain/sample_code/config.yml", ], ) def test_save_load_chain_as_code_multiple_times(tmp_path, chain_path, model_config): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name="model_path", input_example=input_example, model_config=model_config, ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) with open(model_config) as f: base_config = yaml.safe_load(f) assert loaded_model.middle[0].messages[0].prompt.template == base_config["llm_prompt_template"] file_name = "config_updated.yml" new_config_file = str(tmp_path.joinpath(file_name)) new_config = base_config.copy() new_config["llm_prompt_template"] = "new_template" with open(new_config_file, "w") as f: yaml.dump(new_config, f) with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name="model_path", input_example=input_example, model_config=new_config_file, ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert loaded_model.middle[0].messages[0].prompt.template == new_config["llm_prompt_template"] @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/chain.py"), "tests/langchain/../langchain/sample_code/chain.py", ], ) def test_save_load_chain_as_code_with_model_paths(chain_path): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } artifact_path = "model_path" with ( mlflow.start_run(), mock.patch("mlflow.langchain.model._add_code_from_conf_to_system_path") as add_mock, ): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, code_paths=[__file__], model_config={ "response": "modified response", "embedding_size": 5, "llm_prompt_template": "answer the question", }, ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) answer = "modified response" _compare_logged_code_paths(__file__, model_info.model_uri, mlflow.langchain.FLAVOR_NAME) assert loaded_model.invoke(input_example) == answer add_mock.assert_called() @pytest.mark.parametrize("chain_path", [os.path.abspath("tests/langchain1/sample_code/chain.py")]) def test_save_load_chain_errors(chain_path): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } with mlflow.start_run(): with pytest.raises( MlflowException, match=f"The provided model path '{chain_path}' does not exist. " "Ensure the file path is valid and try again.", ): mlflow.langchain.log_model( chain_path, name="model_path", input_example=input_example, model_config="tests/langchain/state_of_the_union.txt", ) @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/no_config/chain.py"), "tests/langchain/../langchain/sample_code/no_config/chain.py", ], ) def test_save_load_chain_as_code_optional_code_path(chain_path): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } artifact_path = "new_model_path" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, ) assert mlflow.models.model_config.__mlflow_model_config__ is None loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert mlflow.models.model_config.__mlflow_model_config__ is None answer = "Databricks" assert loaded_model.invoke(input_example) == answer pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert ( pyfunc_loaded_model.predict(input_example)[0] .get("choices")[0] .get("message") .get("content") == answer ) inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) # avoid minor diff of created time in the response prediction_result = json.loads(response.content.decode("utf-8")) prediction_result[0]["created"] = 123 expected_prediction = try_transform_response_to_chat_format(answer) expected_prediction["created"] = 123 assert prediction_result == [expected_prediction] pyfunc_model_path = _download_artifact_from_uri(model_info.model_uri) reloaded_model = Model.load(os.path.join(pyfunc_model_path, "MLmodel")) assert reloaded_model.resources["databricks"] == { "serving_endpoint": [{"name": "fake-endpoint"}] } assert reloaded_model.metadata is None @pytest.fixture def fake_chat_stream_model(): class FakeChatStreamModel(SimpleChatModel): """Fake Chat Stream Model wrapper for testing purposes.""" endpoint_name: str = "fake-stream-endpoint" def _call( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> str: return "Databricks" def _stream( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> Iterator[ChatGenerationChunk]: for chunk_content, finish_reason in [ ("Da", None), ("tab", None), ("ricks", "stop"), ]: chunk = ChatGenerationChunk( message=AIMessageChunk(content=chunk_content), generation_info={"finish_reason": finish_reason}, ) if run_manager: run_manager.on_llm_new_token(chunk.text, chunk=chunk) yield chunk @property def _llm_type(self) -> str: return "fake chat model" return FakeChatStreamModel(endpoint_name="fake-stream-endpoint") @skip_if_v1 @pytest.mark.parametrize("provide_signature", [True, False]) def test_simple_chat_model_stream_inference(fake_chat_stream_model, provide_signature): # TODO: Migrate to models-from-code input_example = { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "assistant", "content": "What would you like to ask?"}, {"role": "user", "content": "Who owns MLflow?"}, ] } with mlflow.start_run(): model_info = mlflow.langchain.log_model( fake_chat_stream_model, name="model", ) if provide_signature: signature = infer_signature(model_input=input_example) with mlflow.start_run(): model_with_siginature_info = mlflow.langchain.log_model( fake_chat_stream_model, name="model", signature=signature ) else: with mlflow.start_run(): model_with_siginature_info = mlflow.langchain.log_model( fake_chat_stream_model, name="model", input_example=input_example ) for model_uri in [model_info.model_uri, model_with_siginature_info.model_uri]: loaded_model = mlflow.pyfunc.load_model(model_uri) chunk_iter = loaded_model.predict_stream(input_example) finish_reason = "stop" with mock.patch("time.time", return_value=1677858242): chunks = list(chunk_iter) for chunk in chunks: assert "id" in chunk, "chunk id is lost." chunk["id"] = None assert chunks == [ { "id": None, "object": "chat.completion.chunk", "created": 1677858242, "model": "", "choices": [ { "index": 0, "finish_reason": None, "delta": {"role": "assistant", "content": "Da"}, } ], }, { "id": None, "object": "chat.completion.chunk", "created": 1677858242, "model": "", "choices": [ { "index": 0, "finish_reason": None, "delta": {"role": "assistant", "content": "tab"}, } ], }, { "id": None, "object": "chat.completion.chunk", "created": 1677858242, "model": "", "choices": [ { "index": 0, "finish_reason": finish_reason, "delta": {"role": "assistant", "content": "ricks"}, } ], }, ] @skip_if_v1 def test_simple_chat_model_stream_with_callbacks(fake_chat_stream_model): # TODO: Migrate to models-from-code class TestCallbackHandler(BaseCallbackHandler): def __init__(self): super().__init__() self.num_llm_start_calls = 0 def on_llm_start( self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any, ) -> Any: self.num_llm_start_calls += 1 prompt = ChatPromptTemplate.from_template("What's your favorite {industry} company?") chain = prompt | fake_chat_stream_model | StrOutputParser() # Test the basic functionality of the chain assert chain.invoke({"industry": "tech"}) == "Databricks" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain, name="model_path", input_example={"industry": "tech"} ) pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) callback_handler1 = TestCallbackHandler() callback_handler2 = TestCallbackHandler() # Ensure handlers have not been called yet assert callback_handler1.num_llm_start_calls == 0 assert callback_handler2.num_llm_start_calls == 0 stream = pyfunc_loaded_model._model_impl._predict_stream_with_callbacks( {"industry": "tech"}, callback_handlers=[callback_handler1, callback_handler2], ) assert list(stream) == ["Da", "tab", "ricks"] # Test that the callback handlers were called assert callback_handler1.num_llm_start_calls == 1 assert callback_handler2.num_llm_start_calls == 1 @skip_if_v1 def test_langchain_model_save_load_with_listeners(fake_chat_model): # Migrate this to models-from-code prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant."), MessagesPlaceholder(variable_name="history"), ("human", "{question}"), ] ) def retrieve_history(input): return {"history": [], "question": input["question"], "name": input["name"]} chain = ( {"question": itemgetter("question"), "name": itemgetter("name")} | (RunnableLambda(retrieve_history) | prompt | fake_chat_model).with_listeners() | StrOutputParser() | RunnablePassthrough() ) input_example = {"question": "Who owns MLflow?", "name": ""} assert chain.invoke(input_example) == "Databricks" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain, name="model_path", input_example=input_example ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert loaded_model.invoke(input_example) == "Databricks" pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert pyfunc_loaded_model.predict(input_example) == ["Databricks"] inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) assert PredictionsResponse.from_json(response.content.decode("utf-8")) == { "predictions": ["Databricks"] } @pytest.mark.parametrize("env_var", ["MLFLOW_ENABLE_TRACE_IN_SERVING", "ENABLE_MLFLOW_TRACING"]) def test_langchain_model_not_inject_callback_when_disabled(monkeypatch, model_path, env_var): # Emulate the model serving environment monkeypatch.setenv("IS_IN_DB_MODEL_SERVING_ENV", "true") # Disable tracing monkeypatch.setenv(env_var, "false") mlflow.langchain.save_model(SIMPLE_MODEL_CODE_PATH, model_path) loaded_model = mlflow.pyfunc.load_model(model_path) loaded_model.predict({"product": "shoe"}) # Trace should be logged to the inference table from mlflow.tracing.export.inference_table import _TRACE_BUFFER assert _TRACE_BUFFER == {} @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/no_config/chain.py"), "tests/langchain/../langchain/sample_code/no_config/chain.py", ], ) def test_save_model_as_code_correct_streamable(chain_path): input_example = {"messages": [{"role": "user", "content": "Who owns MLflow?"}]} answer = "Databricks" artifact_path = "model_path" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, ) assert model_info.flavors["langchain"]["streamable"] is True pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) with mock.patch("time.time", return_value=1677858242): assert pyfunc_loaded_model._model_impl._predict_with_callbacks(input_example) == { "id": None, "object": "chat.completion", "created": 1677858242, "model": "", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Databricks", }, "finish_reason": None, } ], "usage": { "prompt_tokens": None, "completion_tokens": None, "total_tokens": None, }, } inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) # avoid minor diff of created time in the response prediction_result = json.loads(response.content.decode("utf-8")) prediction_result[0]["created"] = 123 expected_prediction = try_transform_response_to_chat_format(answer) expected_prediction["created"] = 123 assert prediction_result == [expected_prediction] pyfunc_model_path = _download_artifact_from_uri(model_info.model_uri) reloaded_model = Model.load(os.path.join(pyfunc_model_path, "MLmodel")) assert reloaded_model.resources["databricks"] == { "serving_endpoint": [{"name": "fake-endpoint"}] } @skip_if_v1 def test_save_load_langchain_binding(fake_chat_model): runnable_binding = RunnableBinding(bound=fake_chat_model, kwargs={"stop": ["-"]}) model = runnable_binding | StrOutputParser() assert model.invoke("Say something") == "Databricks" with mlflow.start_run(): model_info = mlflow.langchain.log_model( model, name="model_path", input_example="Say something" ) loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert loaded_model.first.kwargs == {"stop": ["-"]} assert loaded_model.invoke("hello") == "Databricks" pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert pyfunc_loaded_model.predict("hello") == ["Databricks"] inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) assert PredictionsResponse.from_json(response.content.decode("utf-8")) == { "predictions": ["Databricks"] } @skip_if_v1 def test_save_load_langchain_binding_llm_with_tool(): from langchain_core.tools import tool # We need to use ChatOpenAI from langchain_openai as community one does not support bind_tools from langchain_openai import ChatOpenAI @tool def add(a: int, b: int) -> int: """Adds a and b. Args: a: first int b: second int """ return a + b runnable_binding = ChatOpenAI(temperature=0.9).bind_tools([add]) model = runnable_binding | StrOutputParser() expected_output = '[{"role": "user", "content": "hello"}]' assert model.invoke("hello") == expected_output with mlflow.start_run(): model_info = mlflow.langchain.log_model(model, name="model_path", input_example="hello") loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert loaded_model.invoke("hello") == expected_output pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert pyfunc_loaded_model.predict("hello") == [expected_output] @skip_if_v1 def test_langchain_bindings_save_load_with_config_and_types(fake_chat_model): class CustomCallbackHandler(BaseCallbackHandler): def __init__(self): self.count = 0 def on_chain_start( self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any ) -> None: self.count += 1 def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None: self.count += 1 model = fake_chat_model | StrOutputParser() callback = CustomCallbackHandler() model = model.with_config(run_name="test_run", callbacks=[callback]).with_types( input_type=str, output_type=str ) assert model.invoke("Say something") == "Databricks" assert callback.count == 4 with mlflow.start_run(): model_info = mlflow.langchain.log_model(model, name="model_path", input_example="hello") loaded_model = mlflow.langchain.load_model(model_info.model_uri) assert loaded_model.config["run_name"] == "test_run" assert loaded_model.custom_input_type == str assert loaded_model.custom_output_type == str callback = loaded_model.config["callbacks"][0] assert loaded_model.invoke("hello") == "Databricks" assert callback.count > 8 # accumulated count (inside model logging we also call the callbacks) pyfunc_loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) assert pyfunc_loaded_model.predict("hello") == ["Databricks"] inference_payload = load_serving_example(model_info.model_uri) response = pyfunc_serve_and_score_model( model_info.model_uri, data=inference_payload, content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON, extra_args=["--env-manager", "local"], ) assert PredictionsResponse.from_json(response.content.decode("utf-8")) == { "predictions": ["Databricks"] } @pytest.mark.parametrize( "chain_path", [ os.path.abspath("tests/langchain/sample_code/chain.py"), "tests/langchain/../langchain/sample_code/chain.py", ], ) @pytest.mark.parametrize( "model_config", [ os.path.abspath("tests/langchain/sample_code/config.yml"), "tests/langchain/../langchain/sample_code/config.yml", ], ) def test_load_chain_with_model_config_overrides_saved_config(chain_path, model_config): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } artifact_path = "model_path" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, model_config=model_config, ) with mock.patch("mlflow.langchain.model._load_model_code_path") as load_model_code_path_mock: mlflow.pyfunc.load_model(model_info.model_uri, model_config={"embedding_size": 2}) args, kwargs = load_model_code_path_mock.call_args assert args[1] == { "embedding_size": 2, "llm_prompt_template": "Answer the following question based on the " "context: {context}\nQuestion: {question}", "not_used_array": [ 1, 2, 3, ], "response": "Databricks", } @pytest.mark.parametrize("streamable", [True, False, None]) def test_langchain_model_streamable_param_in_log_model(streamable, fake_chat_model): # TODO: Migrate to models-from-code prompt = ChatPromptTemplate.from_template("What's your favorite {industry} company?") chain = prompt | fake_chat_model | StrOutputParser() runnable = RunnableParallel({"llm": lambda _: "completion"}) for model in [chain, runnable]: with mock.patch("mlflow.langchain.model._save_model"), mlflow.start_run(): model_info = mlflow.langchain.log_model( model, name="model", streamable=streamable, pip_requirements=[], ) expected = (streamable is None) or streamable assert model_info.flavors["langchain"]["streamable"] is expected @pytest.fixture def model_type(request): return lc_runnables_types()[request.param] @skip_if_v1 @pytest.mark.parametrize("streamable", [True, False, None]) @pytest.mark.parametrize("model_type", range(len(lc_runnables_types())), indirect=True) def test_langchain_model_streamable_param_in_log_model_for_lc_runnable_types( streamable, model_type ): with mock.patch("mlflow.langchain.model._save_model"), mlflow.start_run(): model = mock.MagicMock(spec=model_type) assert hasattr(model, "stream") is True model_info = mlflow.langchain.log_model( model, name="model", streamable=streamable, pip_requirements=[], ) expected = (streamable is None) or streamable assert model_info.flavors["langchain"]["streamable"] is expected del model.stream assert hasattr(model, "stream") is False model_info = mlflow.langchain.log_model( model, name="model", streamable=streamable, pip_requirements=[], ) assert model_info.flavors["langchain"]["streamable"] is bool(streamable) @skip_if_v1 def test_agent_executor_model_with_messages_input(): question = {"messages": [{"role": "user", "content": "Who owns MLflow?"}]} with mlflow.start_run(): model_info = mlflow.langchain.log_model( os.path.abspath("tests/langchain/agent_executor/chain.py"), name="model_path", input_example=question, model_config=os.path.abspath("tests/langchain/agent_executor/config.yml"), ) native_model = mlflow.langchain.load_model(model_info.model_uri) assert native_model.invoke(question)["output"] == "Databricks" pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) # TODO: in the future we should fix this and output shouldn't be wrapped # The result is wrapped in a list because during signature enforcement we convert # input data to pandas dataframe, then inside _convert_llm_input_data # we convert pandas dataframe back to records, and a single row will be # wrapped inside a list. assert pyfunc_model.predict(question) == ["Databricks"] # Test stream output response = pyfunc_model.predict_stream(question) assert inspect.isgenerator(response) expected_response = [ { "output": "Databricks", "messages": [ { "additional_kwargs": {}, "content": "Databricks", "example": False, "id": None, "invalid_tool_calls": [], "name": None, "response_metadata": {}, "tool_calls": [], "type": "ai", "usage_metadata": None, } ], } ] assert list(response) == expected_response def test_invoking_model_with_params(): with mlflow.start_run(): model_info = mlflow.langchain.log_model( os.path.abspath("tests/langchain/sample_code/model_with_config.py"), name="model", ) pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) data = {"x": 0} pyfunc_model.predict(data) params = {"config": {"temperature": 3.0}} with mock.patch("mlflow.pyfunc._validate_prediction_input", return_value=(data, params)): # This proves the temperature is passed to the model with pytest.raises(MlflowException, match=r"Input should be less than or equal to 2"): pyfunc_model.predict(data=data, params=params) def test_custom_resources(tmp_path): input_example = { "messages": [ { "role": "user", "content": "What is a good name for a company that makes MLflow?", } ] } expected_resources = { "api_version": "1", "databricks": { "serving_endpoint": [ {"name": "databricks-mixtral-8x7b-instruct"}, {"name": "databricks-bge-large-en"}, {"name": "azure-eastus-model-serving-2_vs_endpoint"}, ], "vector_search_index": [{"name": "rag.studio_bugbash.databricks_docs_index"}], "sql_warehouse": [{"name": "testid"}], "function": [ {"name": "rag.studio.test_function_a"}, {"name": "rag.studio.test_function_b"}, ], }, } artifact_path = "model_path" chain_path = "tests/langchain/sample_code/chain.py" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path, input_example=input_example, model_config="tests/langchain/sample_code/config.yml", resources=[ DatabricksServingEndpoint(endpoint_name="databricks-mixtral-8x7b-instruct"), DatabricksServingEndpoint(endpoint_name="databricks-bge-large-en"), DatabricksServingEndpoint(endpoint_name="azure-eastus-model-serving-2_vs_endpoint"), DatabricksVectorSearchIndex(index_name="rag.studio_bugbash.databricks_docs_index"), DatabricksSQLWarehouse(warehouse_id="testid"), DatabricksFunction(function_name="rag.studio.test_function_a"), DatabricksFunction(function_name="rag.studio.test_function_b"), ], ) model_path = _download_artifact_from_uri(model_info.model_uri) reloaded_model = Model.load(os.path.join(model_path, "MLmodel")) assert reloaded_model.resources == expected_resources yaml_file = tmp_path.joinpath("resources.yaml") with open(yaml_file, "w") as f: f.write( """ api_version: "1" databricks: vector_search_index: - name: rag.studio_bugbash.databricks_docs_index serving_endpoint: - name: databricks-mixtral-8x7b-instruct - name: databricks-bge-large-en - name: azure-eastus-model-serving-2_vs_endpoint sql_warehouse: - name: testid function: - name: rag.studio.test_function_a - name: rag.studio.test_function_b """ ) artifact_path_2 = "model_path_2" with mlflow.start_run(): model_info = mlflow.langchain.log_model( chain_path, name=artifact_path_2, input_example=input_example, model_config="tests/langchain/sample_code/config.yml", resources=yaml_file, ) model_path = _download_artifact_from_uri(model_info.model_uri) reloaded_model = Model.load(os.path.join(model_path, "MLmodel")) assert reloaded_model.resources == expected_resources def test_pyfunc_converts_chat_request_for_non_chat_model(): input_example = {"messages": [{"role": "user", "content": "Hello"}]} with mlflow.start_run(): model_info = mlflow.langchain.log_model( lc_model=SIMPLE_MODEL_CODE_PATH, input_example=input_example, ) pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) result = pyfunc_model.predict(input_example) # output are converted to chatResponse format assert isinstance(result[0]["choices"][0]["message"]["content"], str) response = pyfunc_model.predict_stream(input_example) assert inspect.isgenerator(response) assert isinstance(list(response)[0]["choices"][0]["delta"]["content"], str) @skip_if_v1 def test_pyfunc_should_not_convert_chat_request_if_env_var_is_set_to_false(monkeypatch): monkeypatch.setenv(MLFLOW_CONVERT_MESSAGES_DICT_FOR_LANGCHAIN.name, "false") # This model is an example when the model expects a chat request # format input, but the input should not be converted to List[BaseMessage] model = RunnablePassthrough.assign(problem=lambda x: x["messages"][-1]["content"]) | itemgetter( "problem" ) input_example = {"messages": [{"role": "user", "content": "Databricks"}]} assert model.invoke(input_example) == "Databricks" # pyfunc model can accepts chat request format even the chain # itself does not accept it, but we need to use the correct # input example to infer model signature with mlflow.start_run(): model_info = mlflow.langchain.log_model(model, input_example=input_example) pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) result = pyfunc_model.predict(input_example) assert result == ["Databricks"] # Test stream output response = pyfunc_model.predict_stream(input_example) assert inspect.isgenerator(response) assert list(response) == ["Databricks"], list(response) def test_log_langchain_model_with_prompt(): mlflow.register_prompt( name="qa_prompt", template="What is a good name for a company that makes {{product}}?", commit_message="Prompt for generating company names", ) mlflow.set_prompt_alias("qa_prompt", alias="production", version=1) mlflow.register_prompt(name="another_prompt", template="Hi") # If the model code involves `mlflow.load_prompt()` call, the prompt version # should be automatically logged to the Run with mlflow.start_run(): model_info = mlflow.langchain.log_model( os.path.abspath("tests/langchain/sample_code/chain_with_mlflow_prompt.py"), name="model", # Manually associate another prompt prompts=["prompts:/another_prompt/1"], ) # Check that prompts were linked to the run via the linkedPrompts tag from mlflow.prompt.constants import LINKED_PROMPTS_TAG_KEY run = mlflow.MlflowClient().get_run(model_info.run_id) linked_prompts_tag = run.data.tags.get(LINKED_PROMPTS_TAG_KEY) assert linked_prompts_tag is not None linked_prompts = json.loads(linked_prompts_tag) assert len(linked_prompts) == 2 assert {p["name"] for p in linked_prompts} == {"qa_prompt", "another_prompt"} prompt = mlflow.load_prompt("qa_prompt", 1) assert prompt.aliases == ["production"] prompt = mlflow.load_prompt("another_prompt", 1) pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) response = pyfunc_model.predict({"product": "shoe"}) # Fake OpenAI server echo the input assert ( response == '[{"role": "user", "content": "What is a good name for a company that makes shoe?"}]' ) def test_predict_with_callbacks_with_tracing(monkeypatch): # Simulate the model serving environment monkeypatch.setenv("IS_IN_DB_MODEL_SERVING_ENV", "true") monkeypatch.setenv("ENABLE_MLFLOW_TRACING", "true") mlflow.tracing.reset() model_info = mlflow.langchain.log_model( os.path.abspath("tests/langchain/sample_code/workflow.py"), name="model_path", input_example={"messages": [{"role": "user", "content": "What is MLflow?"}]}, ) # serving environment only reads from this environment variable monkeypatch.setenv("MLFLOW_EXPERIMENT_ID", mlflow.last_logged_model().experiment_id) pyfunc_model = mlflow.pyfunc.load_model(model_info.model_uri) request_id = "mock_request_id" tracer = MlflowLangchainTracer(prediction_context=Context(request_id)) input_example = {"messages": [{"role": "user", "content": TEST_CONTENT}]} with mock.patch("mlflow.tracing.client.TracingClient.start_trace") as mock_start_trace: pyfunc_model._model_impl._predict_with_callbacks( data=input_example, callback_handlers=[tracer] ) mlflow.flush_trace_async_logging() mock_start_trace.assert_called_once() trace_info = mock_start_trace.call_args[0][0] assert trace_info.client_request_id == request_id assert trace_info.request_metadata[TraceMetadataKey.MODEL_ID] == model_info.model_id
ChatModel
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_custom_job.py
{ "start": 12075, "end": 20357 }
class ____: @pytest.mark.asyncio @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_pipeline_service_client")) async def test_get_training_pipeline( self, mock_pipeline_service_client, test_async_hook, test_training_pipeline_name ): mock_pipeline_service_client.return_value.training_pipeline_path = mock.MagicMock( return_value=test_training_pipeline_name ) await test_async_hook.get_training_pipeline( project_id=TEST_PROJECT_ID, location=TEST_REGION, pipeline_id=TEST_PIPELINE_JOB_ID, ) mock_pipeline_service_client.assert_awaited_once_with(region=TEST_REGION) mock_pipeline_service_client.return_value.get_training_pipeline.assert_awaited_once_with( request={"name": test_training_pipeline_name}, retry=DEFAULT, timeout=DEFAULT, metadata=(), ) @pytest.mark.asyncio @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_job_service_client")) async def test_get_custom_job( self, mock_get_job_service_client, test_async_hook, test_custom_job_name, ): mock_get_job_service_client.return_value.custom_job_path = mock.MagicMock( return_value=test_custom_job_name ) await test_async_hook.get_custom_job( project_id=TEST_PROJECT_ID, location=TEST_REGION, job_id=TEST_PIPELINE_JOB_ID, ) mock_get_job_service_client.assert_awaited_once_with(region=TEST_REGION) mock_get_job_service_client.return_value.get_custom_job.assert_awaited_once_with( request={"name": test_custom_job_name}, retry=DEFAULT, timeout=DEFAULT, metadata=(), ) @pytest.mark.asyncio @pytest.mark.parametrize( "pipeline_state_value", [ PipelineState.PIPELINE_STATE_CANCELLED, PipelineState.PIPELINE_STATE_FAILED, PipelineState.PIPELINE_STATE_PAUSED, PipelineState.PIPELINE_STATE_SUCCEEDED, ], ) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_training_pipeline")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_pipeline_service_client")) async def test_wait_for_training_pipeline_returns_pipeline_if_in_complete_state( self, mock_get_pipeline_service_client, mock_get_training_pipeline, pipeline_state_value, test_async_hook, test_training_pipeline_name, ): expected_obj = types.TrainingPipeline( state=pipeline_state_value, name=test_training_pipeline_name, ) mock_get_training_pipeline.return_value = expected_obj actual_obj = await test_async_hook.wait_for_training_pipeline( project_id=TEST_PROJECT_ID, location=TEST_REGION, pipeline_id=TEST_PIPELINE_JOB_ID, ) mock_get_pipeline_service_client.assert_awaited_once_with(region=TEST_REGION) assert actual_obj == expected_obj @pytest.mark.asyncio @pytest.mark.parametrize( "job_state_value", [ JobState.JOB_STATE_CANCELLED, JobState.JOB_STATE_FAILED, JobState.JOB_STATE_PAUSED, JobState.JOB_STATE_SUCCEEDED, ], ) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_custom_job")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_job_service_client")) async def test_wait_for_custom_job_returns_job_if_in_complete_state( self, mock_get_job_service_client, mock_get_custom_job, job_state_value, test_async_hook, test_custom_job_name, ): expected_obj = types.CustomJob( state=job_state_value, name=test_custom_job_name, ) mock_get_custom_job.return_value = expected_obj actual_obj = await test_async_hook.wait_for_custom_job( project_id=TEST_PROJECT_ID, location=TEST_REGION, job_id=TEST_PIPELINE_JOB_ID, ) mock_get_job_service_client.assert_awaited_once_with(region=TEST_REGION) assert actual_obj == expected_obj @pytest.mark.asyncio @pytest.mark.parametrize( "pipeline_state_value", [ PipelineState.PIPELINE_STATE_CANCELLING, PipelineState.PIPELINE_STATE_PENDING, PipelineState.PIPELINE_STATE_QUEUED, PipelineState.PIPELINE_STATE_RUNNING, PipelineState.PIPELINE_STATE_UNSPECIFIED, ], ) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_training_pipeline")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_pipeline_service_client")) async def test_wait_for_training_pipeline_loop_is_still_running_if_in_incomplete_state( self, mock_get_pipeline_service_client, mock_get_training_pipeline, pipeline_state_value, test_async_hook, ): mock_get_training_pipeline.return_value = types.TrainingPipeline(state=pipeline_state_value) task = asyncio.create_task( test_async_hook.wait_for_training_pipeline( project_id=TEST_PROJECT_ID, location=TEST_REGION, pipeline_id=TEST_PIPELINE_JOB_ID, ) ) await asyncio.sleep(0.5) mock_get_pipeline_service_client.assert_awaited_once_with(region=TEST_REGION) assert task.done() is False task.cancel() @pytest.mark.asyncio @pytest.mark.parametrize( "job_state_value", [ JobState.JOB_STATE_CANCELLING, JobState.JOB_STATE_PENDING, JobState.JOB_STATE_QUEUED, JobState.JOB_STATE_RUNNING, JobState.JOB_STATE_UNSPECIFIED, ], ) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_custom_job")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_job_service_client")) async def test_wait_for_custom_job_loop_is_still_running_if_in_incomplete_state( self, mock_get_job_service_client, mock_get_custom_job, job_state_value, test_async_hook, ): mock_get_custom_job.return_value = types.CustomJob(state=job_state_value) task = asyncio.create_task( test_async_hook.wait_for_custom_job( project_id=TEST_PROJECT_ID, location=TEST_REGION, job_id=TEST_PIPELINE_JOB_ID, ) ) await asyncio.sleep(0.5) mock_get_job_service_client.assert_awaited_once_with(region=TEST_REGION) assert task.done() is False task.cancel() @pytest.mark.asyncio @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_credentials")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_training_pipeline")) async def test_wait_for_training_pipeline_raises_exception( self, mock_get_training_pipeline, mock_get_credentials, test_async_hook ): mock_get_training_pipeline.side_effect = mock.AsyncMock(side_effect=Exception()) mock_get_credentials.return_value = mock.AsyncMock() with pytest.raises(AirflowException): await test_async_hook.wait_for_training_pipeline( project_id=TEST_PROJECT_ID, location=TEST_REGION, pipeline_id=TEST_PIPELINE_JOB_ID, ) @pytest.mark.asyncio @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_credentials")) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobAsyncHook.get_custom_job")) async def test_wait_for_custom_job_raises_exception( self, mock_get_custom_job, mock_get_credentials, test_async_hook ): mock_get_custom_job.side_effect = mock.AsyncMock(side_effect=Exception()) mock_get_credentials.return_value = mock.AsyncMock() with pytest.raises(AirflowException): await test_async_hook.wait_for_custom_job( project_id=TEST_PROJECT_ID, location=TEST_REGION, job_id=TEST_PIPELINE_JOB_ID, )
TestCustomJobAsyncHook
python
readthedocs__readthedocs.org
readthedocs/builds/querysets.py
{ "start": 5131, "end": 9546 }
class ____(NoReprQuerySet, models.QuerySet): """ Build objects that are privacy aware. i.e. they take into account the privacy of the Version that they relate to. """ use_for_related_fields = True def _add_from_user_projects(self, queryset, user, admin=False, member=False): """Add related objects from projects where `user` is an `admin` or a `member`.""" if user and user.is_authenticated: projects_pk = AdminPermission.projects( user=user, admin=admin, member=member, ).values_list("pk", flat=True) user_queryset = self.filter(project__in=projects_pk) queryset = user_queryset | queryset return queryset def public(self, user=None, project=None): """ Get all allowed builds. Builds are public if the linked version and project are public. .. note:: External versions use the `Project.external_builds_privacy_level` field instead of its `privacy_level` field. """ queryset = self.filter( version__privacy_level=constants.PUBLIC, version__project__privacy_level=constants.PUBLIC, ).exclude(version__type=EXTERNAL) queryset |= self.filter( version__type=EXTERNAL, project__external_builds_privacy_level=constants.PUBLIC, project__privacy_level=constants.PUBLIC, ) if user: if user.is_superuser: queryset = self.all() else: queryset = self._add_from_user_projects( queryset, user, admin=True, member=True, ) if project: queryset = queryset.filter(project=project) return queryset.distinct() def api(self, user=None): return self.public(user) def api_v2(self, *args, **kwargs): # API v2 is the same as API v3 for .org, but it's # different for .com, this method is overridden there. return self.api(*args, **kwargs) def concurrent(self, project): """ Check if the max build concurrency for this project was reached. - regular project: counts concurrent builds - translation: concurrent builds of all the translations + builds of main project .. note:: If the project/translation belongs to an organization, we count all concurrent builds for all the projects from the organization. :rtype: tuple :returns: limit_reached, number of concurrent builds, number of max concurrent """ limit_reached = False query = Q( project=project, ) if project.main_language_project: # Project is a translation, counts all builds of all the translations query |= Q(project__main_language_project=project.main_language_project) query |= Q(project__slug=project.main_language_project.slug) elif project.translations.exists(): # The project has translations, counts their builds as well query |= Q(project__in=project.translations.all()) # If the project belongs to an organization, count all the projects # from this organization as well organization = project.organizations.first() if organization: query |= Q(project__in=organization.projects.all()) # Limit builds to 5 hours ago to speed up the query query &= Q(date__gt=timezone.now() - datetime.timedelta(hours=5)) concurrent = ( ( self.filter(query).exclude( state__in=[ BUILD_STATE_TRIGGERED, BUILD_STATE_FINISHED, BUILD_STATE_CANCELLED, ] ) ) .distinct() .count() ) max_concurrent = Project.objects.max_concurrent_builds(project) log.info( "Concurrent builds.", project_slug=project.slug, concurrent=concurrent, max_concurrent=max_concurrent, ) if concurrent >= max_concurrent: limit_reached = True return (limit_reached, concurrent, max_concurrent)
BuildQuerySet
python
Textualize__textual
src/textual/app.py
{ "start": 6719, "end": 6812 }
class ____(ModeError): """Raised if there is an issue with a mode name."""
InvalidModeError
python
getsentry__sentry
src/sentry/snuba/metrics/query.py
{ "start": 3240, "end": 3958 }
class ____(MetricActionByField): alias: str = "" def __post_init__(self) -> None: if not self.alias: if isinstance(self.field, str): alias = self.field else: assert self.field.alias is not None alias = self.field.alias object.__setattr__(self, "alias", alias) @property def name(self) -> str: if isinstance(self.field, str): return self.field if isinstance(self.field, MetricField): assert self.field.alias is not None return self.field.alias raise InvalidParams(f"Invalid groupBy field type: {self.field}") @dataclass(frozen=True)
MetricGroupByField
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/liveness.py
{ "start": 1327, "end": 3309 }
class ____(cfg.GraphVisitor): """CFG visitor that performs liveness analysis at statement level.""" def __init__(self, graph, include_annotations): super(Analyzer, self).__init__(graph) self.include_annotations = include_annotations def init_state(self, _): return set() def lamba_check(self, fn_ast_node): if isinstance(fn_ast_node, gast.Lambda): # Exception: lambda functions are assumed to be used only in the # place where they are defined, and not later. return True return False def visit_node(self, node): prev_live_in = self.in_[node] if anno.hasanno(node.ast_node, anno.Static.SCOPE): node_scope = anno.getanno(node.ast_node, anno.Static.SCOPE) gen = node_scope.read if not self.include_annotations: gen -= node_scope.annotations # TODO(mdan): verify whether composites' parents need to be added. # E.g. whether x needs to be added if x.y is live. Theoretically the # activity analysis should have both so that wouldn't be needed. kill = node_scope.modified | node_scope.deleted live_out = set() for n in node.next: live_out |= self.in_[n] live_in = gen | (live_out - kill) reaching_functions = anno.getanno( node.ast_node, anno.Static.DEFINED_FNS_IN) for fn_ast_node in reaching_functions: if self.lamba_check(fn_ast_node): continue fn_scope = anno.getanno(fn_ast_node, annos.NodeAnno.ARGS_AND_BODY_SCOPE) # Any closure of a reaching function definition is conservatively # considered live. live_in |= (fn_scope.read - fn_scope.bound) else: assert self.can_ignore(node), (node.ast_node, node) live_out = set() for n in node.next: live_out |= self.in_[n] live_in = live_out self.in_[node] = live_in self.out[node] = live_out # TODO(mdan): Move this to the superclass? return prev_live_in != live_in
Analyzer
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_date_range.py
{ "start": 36145, "end": 39120 }
class ____: def test_constructor(self): bdate_range(START, END, freq=BDay()) bdate_range(START, periods=20, freq=BDay()) bdate_range(end=START, periods=20, freq=BDay()) msg = "periods must be an integer, got B" with pytest.raises(TypeError, match=msg): date_range("2011-1-1", "2012-1-1", "B") with pytest.raises(TypeError, match=msg): bdate_range("2011-1-1", "2012-1-1", "B") msg = "freq must be specified for bdate_range; use date_range instead" with pytest.raises(TypeError, match=msg): bdate_range(START, END, periods=10, freq=None) def test_misc(self): end = datetime(2009, 5, 13) dr = bdate_range(end=end, periods=20) firstDate = end - 19 * BDay() assert len(dr) == 20 assert dr[0] == firstDate assert dr[-1] == end def test_date_parse_failure(self): badly_formed_date = "2007/100/1" msg = "Unknown datetime string format, unable to parse: 2007/100/1" with pytest.raises(ValueError, match=msg): Timestamp(badly_formed_date) with pytest.raises(ValueError, match=msg): bdate_range(start=badly_formed_date, periods=10) with pytest.raises(ValueError, match=msg): bdate_range(end=badly_formed_date, periods=10) with pytest.raises(ValueError, match=msg): bdate_range(badly_formed_date, badly_formed_date) def test_daterange_bug_456(self): # GH #456 rng1 = bdate_range("12/5/2011", "12/5/2011") rng2 = bdate_range("12/2/2011", "12/5/2011") assert rng2._data.freq == BDay() result = rng1.union(rng2) assert isinstance(result, DatetimeIndex) def test_bdays_and_open_boundaries(self, inclusive_endpoints_fixture): # GH 6673 start = "2018-07-21" # Saturday end = "2018-07-29" # Sunday result = date_range(start, end, freq="B", inclusive=inclusive_endpoints_fixture) bday_start = "2018-07-23" # Monday bday_end = "2018-07-27" # Friday expected = date_range(bday_start, bday_end, freq="D") tm.assert_index_equal(result, expected) # Note: we do _not_ expect the freqs to match here def test_bday_near_overflow(self): # GH#24252 avoid doing unnecessary addition that _would_ overflow start = Timestamp.max.floor("D").to_pydatetime() rng = date_range(start, end=None, periods=1, freq="B") expected = DatetimeIndex([start], freq="B") tm.assert_index_equal(rng, expected) def test_bday_overflow_error(self): # GH#24252 check that we get OutOfBoundsDatetime and not OverflowError msg = "Out of bounds nanosecond timestamp" start = Timestamp.max.floor("D").to_pydatetime() with pytest.raises(OutOfBoundsDatetime, match=msg): date_range(start, periods=2, freq="B", unit="ns")
TestBusinessDateRange
python
TheAlgorithms__Python
electronics/electric_power.py
{ "start": 117, "end": 1951 }
class ____(NamedTuple): name: str value: float def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) Result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) Result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) Result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): ... ValueError: Exactly one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): ... ValueError: Exactly one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): ... ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) Result(name='power', value=4.84) >>> electric_power(current=0, power=6, voltage=2) Result(name='current', value=3.0) """ if (voltage, current, power).count(0) != 1: raise ValueError("Exactly one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return Result("voltage", power / current) elif current == 0: return Result("current", power / voltage) elif power == 0: return Result("power", float(round(abs(voltage * current), 2))) else: raise AssertionError if __name__ == "__main__": import doctest doctest.testmod()
Result
python
getsentry__sentry
src/sentry/api/endpoints/project_plugins.py
{ "start": 468, "end": 907 }
class ____(ProjectEndpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, project) -> Response: context = serialize( [plugin for plugin in plugins.configurable_for_project(project, version=None)], request.user, PluginSerializer(project), ) return Response(context)
ProjectPluginsEndpoint
python
huggingface__transformers
tests/models/roc_bert/test_modeling_roc_bert.py
{ "start": 32386, "end": 33520 }
class ____(unittest.TestCase): @slow def test_inference_masked_lm(self): model = RoCBertForMaskedLM.from_pretrained("weiweishi/roc-bert-base-zh") # input_text: ['[CLS]', 'b', 'a', '里', '系', '[MASK]', '国', '的', '首', '都', '[SEP]'] is the adversarial text # of ['[CLS]', '巴', '黎', '是', '[MASK]', '国', '的', '首', '都', '[SEP]'], means # "Paris is the [MASK] of France" in English input_ids = torch.tensor([[101, 144, 143, 7027, 5143, 103, 1744, 4638, 7674, 6963, 102]]) input_shape_ids = torch.tensor([[2, 20324, 23690, 8740, 706, 1, 10900, 23343, 20205, 5850, 2]]) input_pronunciation_ids = torch.tensor([[2, 718, 397, 52, 61, 1, 168, 273, 180, 243, 2]]) output = model(input_ids, input_shape_ids, input_pronunciation_ids) output_ids = torch.argmax(output.logits, dim=2) # convert to tokens is: ['[CLS]', '巴', '*', '黎', '是', '法', '国', '的', '首', '都', '[SEP]'] expected_output = torch.tensor([[101, 2349, 115, 7944, 3221, 3791, 1744, 4638, 7674, 6963, 102]]) assert torch.allclose(output_ids, expected_output)
RoCBertModelIntegrationTest
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 45622, "end": 48125 }
class ____(Request): """ Get an attachment containing the task's log :param task: Task ID :type task: str :param line_type: Line format type :type line_type: str :param line_format: Line string format. Used if the line type is 'text' :type line_format: str """ _service = "events" _action = "download_task_log" _version = "2.9" _schema = { "definitions": {}, "properties": { "line_format": { "default": "{asctime} {worker} {level} {msg}", "description": "Line string format. Used if the line type is 'text'", "type": "string", }, "line_type": { "description": "Line format type", "enum": ["json", "text"], "type": "string", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task"], "type": "object", } def __init__( self, task: str, line_type: Optional[str] = None, line_format: Optional[str] = "{asctime} {worker} {level} {msg}", **kwargs: Any ) -> None: super(DownloadTaskLogRequest, self).__init__(**kwargs) self.task = task self.line_type = line_type self.line_format = line_format @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("line_type") def line_type(self) -> Optional[str]: return self._property_line_type @line_type.setter def line_type(self, value: Optional[str]) -> None: if value is None: self._property_line_type = None return self.assert_isinstance(value, "line_type", six.string_types) self._property_line_type = value @schema_property("line_format") def line_format(self) -> Optional[str]: return self._property_line_format @line_format.setter def line_format(self, value: Optional[str]) -> None: if value is None: self._property_line_format = None return self.assert_isinstance(value, "line_format", six.string_types) self._property_line_format = value
DownloadTaskLogRequest
python
pyca__cryptography
tests/hazmat/primitives/test_poly1305.py
{ "start": 924, "end": 4820 }
class ____: @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("poly1305", "rfc7539.txt"), load_nist_vectors ), ) def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) msg = binascii.unhexlify(vector["msg"]) tag = binascii.unhexlify(vector["tag"]) poly = Poly1305(key) poly.update(msg) assert poly.finalize() == tag assert Poly1305.generate_tag(key, msg) == tag Poly1305.verify_tag(key, msg, tag) def test_key_with_no_additional_references(self, backend): poly = Poly1305(os.urandom(32)) assert len(poly.finalize()) == 16 def test_raises_after_finalize(self, backend): poly = Poly1305(b"0" * 32) poly.finalize() with pytest.raises(AlreadyFinalized): poly.update(b"foo") with pytest.raises(AlreadyFinalized): poly.finalize() def test_reject_unicode(self, backend): poly = Poly1305(b"0" * 32) with pytest.raises(TypeError): poly.update("") # type:ignore[arg-type] with pytest.raises(TypeError): Poly1305.generate_tag(b"0" * 32, "") # type:ignore[arg-type] def test_verify(self, backend): poly = Poly1305(b"0" * 32) poly.update(b"msg") tag = poly.finalize() with pytest.raises(AlreadyFinalized): poly.verify(b"") poly2 = Poly1305(b"0" * 32) poly2.update(b"msg") poly2.verify(tag) Poly1305.verify_tag(b"0" * 32, b"msg", tag) def test_invalid_verify(self, backend): poly = Poly1305(b"0" * 32) poly.update(b"msg") with pytest.raises(InvalidSignature): poly.verify(b"") p2 = Poly1305(b"0" * 32) p2.update(b"msg") with pytest.raises(InvalidSignature): p2.verify(b"\x00" * 16) with pytest.raises(InvalidSignature): Poly1305.verify_tag(b"0" * 32, b"msg", b"\x00" * 16) def test_verify_reject_unicode(self, backend): poly = Poly1305(b"0" * 32) with pytest.raises(TypeError): poly.verify("") # type:ignore[arg-type] with pytest.raises(TypeError): Poly1305.verify_tag(b"0" * 32, b"msg", "") # type:ignore[arg-type] def test_invalid_key_type(self, backend): with pytest.raises(TypeError): Poly1305(object()) # type:ignore[arg-type] with pytest.raises(TypeError): Poly1305.generate_tag(object(), b"msg") # type:ignore[arg-type] def test_invalid_key_length(self, backend): with pytest.raises(ValueError): Poly1305(b"0" * 31) with pytest.raises(ValueError): Poly1305.generate_tag(b"0" * 31, b"msg") with pytest.raises(ValueError): Poly1305(b"0" * 33) with pytest.raises(ValueError): Poly1305.generate_tag(b"0" * 33, b"msg") def test_buffer_protocol(self, backend): key = binascii.unhexlify( b"1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0" ) msg = binascii.unhexlify( b"2754776173206272696c6c69672c20616e642074686520736c69746" b"87920746f7665730a446964206779726520616e642067696d626c65" b"20696e2074686520776162653a0a416c6c206d696d7379207765726" b"52074686520626f726f676f7665732c0a416e6420746865206d6f6d" b"65207261746873206f757467726162652e" ) buffer_key = bytearray(key) poly = Poly1305(buffer_key) poly.update(bytearray(msg)) assert poly.finalize() == binascii.unhexlify( b"4541669a7eaaee61e708dc7cbcc5eb62" ) assert Poly1305.generate_tag(buffer_key, msg) == binascii.unhexlify( b"4541669a7eaaee61e708dc7cbcc5eb62" )
TestPoly1305
python
huggingface__transformers
src/transformers/models/zoedepth/modeling_zoedepth.py
{ "start": 30624, "end": 31590 }
class ____(nn.Module): def __init__(self, in_features, out_features, mlp_dim=128): """Projector MLP. Args: in_features (`int`): Number of input channels. out_features (`int`): Number of output channels. mlp_dim (`int`, *optional*, defaults to 128): Hidden dimension. """ super().__init__() self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0) self.act = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(mlp_dim, out_features, 1, 1, 0) def forward(self, hidden_state: torch.Tensor) -> torch.Tensor: hidden_state = self.conv1(hidden_state) hidden_state = self.act(hidden_state) hidden_state = self.conv2(hidden_state) return hidden_state # Copied from transformers.models.grounding_dino.modeling_grounding_dino.GroundingDinoMultiheadAttention with GroundingDino->ZoeDepth
ZoeDepthProjector
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 834844, "end": 835232 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("PinnableItem", graphql_name="node") """The item at the end of the edge."""
PinnableItemEdge
python
walkccc__LeetCode
solutions/1644. Lowest Common Ancestor of a Binary Tree II/1644-2.py
{ "start": 0, "end": 725 }
class ____: def lowestCommonAncestor( self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode', ) -> 'TreeNode': def getLCA(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if not root or root == p or root == q: return root left = getLCA(root.left, p, q) right = getLCA(root.right, p, q) if left and right: return root return left or right ans = getLCA(root, p, q) if ans == p: # Search q in the subtree rooted at p. return ans if getLCA(p, q, q) else None if ans == q: # Search p in the subtree rooted at q. return ans if getLCA(q, p, p) else None return ans # (ans != p and ans != q) or ans is None
Solution
python
huggingface__transformers
src/transformers/models/idefics/modeling_idefics.py
{ "start": 12725, "end": 15282 }
class ____(nn.Linear): # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear """ Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0, then it will create `out_additional_features * in_features` additional parameters that are always trained. If `out_additional_features=0`, then the module defaults back to the regular behavior of `nn.Linear`. """ def __init__( self, in_features: int, out_features: int, out_additional_features: int = 0, bias: bool = True, partially_freeze: bool = True, device=None, dtype=None, ) -> None: """ out_additional_features: int. Number of additional trainable dimensions. Only makes sense when `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear. """ super().__init__(in_features, out_features, bias, device, dtype) self.out_additional_features = out_additional_features self.partially_freeze = partially_freeze self.in_features = in_features self.out_features = out_features if partially_freeze: self.weight.requires_grad_(False) if bias: self.bias.requires_grad_(False) if out_additional_features > 0: self.additional_fc = nn.Linear( in_features=in_features, out_features=out_additional_features, bias=bias, device=device, dtype=dtype, ) def forward(self, input: torch.Tensor) -> torch.Tensor: output = F.linear(input, self.weight, self.bias) if self.out_additional_features > 0: additional_features = self.additional_fc(input) output = torch.cat((output, additional_features), -1) return output def extra_repr(self) -> str: """Overwriting `nn.Linear.extra_repr` to include new parameters.""" return f"in_features={self.in_features}, out_features={self.out_features}, out_additional_features={self.out_additional_features}, bias={self.bias is not None}, partially_freeze={self.partially_freeze}" # this was adapted from LlamaRMSNorm
IdeficsDecoupledLinear
python
bokeh__bokeh
tests/unit/bokeh/embed/test_elements.py
{ "start": 1800, "end": 2712 }
class ____: def test_issue_13629(self) -> None: bundle = Bundle(js_files=[ URL(url='http://localhost:5006/static/js/bokeh.js'), ]) render_item = RenderItem(docid=ID("doc123"), elementid=ID("foo123")) docs_json = { ID("doc123"): DocJson( version="3.4", title="Bokeh Plot", roots=[], ), } html = bee.html_page_for_render_items(bundle, docs_json, [render_item], None) script_pattern = re.compile(r'<script\s*type="application/json"\s*id="([^"]*)"\s*>') uuid_pattern = re.compile(r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$") result = script_pattern.search(html) assert result is not None (id,) = result.groups() result = uuid_pattern.match(id) assert result is not None
Test_html_page_for_render_items
python
mlflow__mlflow
tests/langgraph/sample_code/langgraph_chat_agent_custom_inputs.py
{ "start": 4024, "end": 6391 }
class ____(ChatAgent): def __init__(self, agent: CompiledStateGraph): self.agent = agent def predict( self, messages: list[ChatAgentMessage], context: ChatContext | None = None, custom_inputs: dict[str, Any] | None = None, ) -> ChatAgentResponse: request = { "messages": self._convert_messages_to_dict(messages), **({"custom_inputs": custom_inputs} if custom_inputs else {}), **({"context": context.model_dump()} if context else {}), } response = ChatAgentResponse(messages=[]) for event in self.agent.stream(request, stream_mode="updates"): for node_data in event.values(): if not node_data: continue for msg in node_data.get("messages", []): response.messages.append(ChatAgentMessage(**msg)) if "custom_outputs" in node_data: response.custom_outputs = node_data["custom_outputs"] return response def predict_stream( self, messages: list[ChatAgentMessage], context: ChatContext | None = None, custom_inputs: dict[str, Any] | None = None, ) -> Generator[ChatAgentChunk, None, None]: request = { "messages": self._convert_messages_to_dict(messages), **({"custom_inputs": custom_inputs} if custom_inputs else {}), **({"context": context.model_dump()} if context else {}), } last_message = None last_custom_outputs = None for event in self.agent.stream(request, stream_mode="updates"): for node_data in event.values(): if not node_data: continue messages = node_data.get("messages", []) custom_outputs = node_data.get("custom_outputs") for message in messages: if last_message: yield ChatAgentChunk(delta=last_message) last_message = message if custom_outputs: last_custom_outputs = custom_outputs if last_message: yield ChatAgentChunk(delta=last_message, custom_outputs=last_custom_outputs) chat_agent = LangGraphChatAgent(graph) mlflow.models.set_model(chat_agent)
LangGraphChatAgent
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 193296, "end": 213429 }
class ____(TestCase): # Calls to super() in dynamically created classes are a bit odd. # See https://github.com/pytorch/pytorch/pull/118586 for more info # Subclassing this class and then calling super(TestCaseBase) will run # TestCase's setUp, tearDown etc functions pass def download_file(url, binary=True): from urllib.parse import urlsplit from urllib import request, error filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data')) path = os.path.join(data_dir, filename) if os.path.exists(path): return path try: data = request.urlopen(url, timeout=15).read() with open(path, 'wb' if binary else 'w') as f: f.write(data) return path except error.URLError as e: msg = f"could not download test file '{url}'" warnings.warn(msg, RuntimeWarning, stacklevel=2) raise unittest.SkipTest(msg) from e def find_free_port(): """ Finds an available port and returns that port number. NOTE: If this function is being used to allocate a port to Store (or indirectly via init_process_group or init_rpc), it should be used in conjunction with the `retry_on_connect_failures` decorator as there is a potential race condition where the allocated port may become unavailable before it can be used """ with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('localhost', 0)) _, port = sock.getsockname() return port # Errors that we can get in c10d initialization for which we should retry tests for. ADDRESS_IN_USE = "Address already in use" CONNECT_TIMEOUT = "connect() timed out." def retry_on_connect_failures(func=None, connect_errors=(ADDRESS_IN_USE)): """Reruns a test if the test returns a RuntimeError and the exception contains one of the strings in connect_errors.""" # This if block is executed when using this function as a decorator with arguments. if func is None: return partial(retry_on_connect_failures, connect_errors=connect_errors) @wraps(func) def wrapper(*args, **kwargs): n_retries = 10 tries_remaining = n_retries while True: try: return func(*args, **kwargs) except RuntimeError as error: if any(connect_error in str(error) for connect_error in connect_errors): tries_remaining -= 1 if tries_remaining == 0: raise RuntimeError(f"Failing after {n_retries} retries with error: {str(error)}") from error time.sleep(random.random()) continue raise return wrapper # Decorator to retry upon certain Exceptions. def retry(ExceptionToCheck, tries=3, delay=3, skip_after_retries=False): def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return f(*args, **kwargs) except ExceptionToCheck as e: msg = f"{e}, Retrying in {mdelay:d} seconds..." print(msg) time.sleep(mdelay) mtries -= 1 try: return f(*args, **kwargs) except ExceptionToCheck as e: raise unittest.SkipTest(f"Skipping after {tries} consecutive {str(e)}") from e if skip_after_retries else e return f_retry # true decorator return deco_retry # FIXME: modernize these to be consistent with make_tensor # and review including them in torch.testing # Methods for matrix generation def random_square_matrix_of_rank(l, rank, dtype=torch.double, device='cpu'): assert rank <= l A = torch.randn(l, l, dtype=dtype, device=device) u, s, vh = torch.linalg.svd(A, full_matrices=False) for i in range(l): if i >= rank: s[i] = 0 elif s[i] == 0: s[i] = 1 return (u * s.to(dtype).unsqueeze(-2)) @ vh def random_well_conditioned_matrix(*shape, dtype, device, mean=1.0, sigma=0.001): """ Returns a random rectangular matrix (batch of matrices) with singular values sampled from a Gaussian with mean `mean` and standard deviation `sigma`. The smaller the `sigma`, the better conditioned the output matrix is. """ primitive_dtype = { torch.float: torch.float, torch.double: torch.double, torch.cfloat: torch.float, torch.cdouble: torch.double } x = torch.rand(shape, dtype=dtype, device=device) m = x.size(-2) n = x.size(-1) u, _, vh = torch.linalg.svd(x, full_matrices=False) s = (torch.randn(*(shape[:-2] + (min(m, n),)), dtype=primitive_dtype[dtype], device=device) * sigma + mean) \ .sort(-1, descending=True).values.to(dtype) return (u * s.unsqueeze(-2)) @ vh # Returns a noncontiguous (tensor with the same shape and values as t # The noncontiguous tensor is constructed such that elements in the innermost # dimension are separated by zeros or (whenever possible) nans # TODO: consider more complicated noncontiguity schemes def noncontiguous_like(t): # Short-circuits if t is already noncontiguous if not t.is_contiguous(): return t # Choose a "weird" value that won't be accessed if t.dtype.is_floating_point or t.dtype.is_complex: value = math.nan elif t.dtype == torch.bool: value = True else: value = 12 result = t.new_empty(t.shape + (2,)) result[..., 0] = value result[..., 1] = t.detach() result = result[..., 1] result.requires_grad_(t.requires_grad) return result # TODO: remove this (prefer make_symmetric_matrices below) def random_symmetric_matrix(l, *batches, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device) A = (A + A.mT).div_(2) return A # Creates a symmetric matrix or batch of symmetric matrices # Shape must be a square matrix or batch of square matrices def make_symmetric_matrices(*shape, device, dtype): assert shape[-1] == shape[-2] t = make_tensor(shape, device=device, dtype=dtype) t = (t + t.mT).div_(2) return t def random_hermitian_matrix(l, *batches, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device) A = (A + A.mH).div_(2) return A def random_symmetric_psd_matrix(l, *batches, **kwargs): """ Returns a batch of random symmetric positive-semi-definite matrices. The shape of the result is batch_dims + (matrix_size, matrix_size) The following example creates a tensor of size 2 x 4 x 3 x 3 >>> # xdoctest: +SKIP("undefined variables") >>> matrices = random_symmetric_psd_matrix(3, 2, 4, dtype=dtype, device=device) """ dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batches + (l, l)), dtype=dtype, device=device) return A @ A.mT def random_hermitian_psd_matrix(matrix_size, *batch_dims, dtype=torch.double, device='cpu'): """ Returns a batch of random Hermitian positive-semi-definite matrices. The shape of the result is batch_dims + (matrix_size, matrix_size) The following example creates a tensor of size 2 x 4 x 3 x 3 >>> # xdoctest: +SKIP("undefined variables") >>> matrices = random_hermitian_psd_matrix(3, 2, 4, dtype=dtype, device=device) """ A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device) return A @ A.mH # TODO: remove this (prefer make_symmetric_pd_matrices below) def random_symmetric_pd_matrix(matrix_size, *batch_dims, **kwargs): dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device) return torch.matmul(A, A.mT) \ + torch.eye(matrix_size, dtype=dtype, device=device) * 1e-5 # Creates a symmetric positive-definite matrix or batch of # such matrices def make_symmetric_pd_matrices(*shape, device, dtype): assert shape[-1] == shape[-2] t = make_tensor(shape, device=device, dtype=dtype) i = torch.eye(shape[-1], device=device, dtype=dtype) * 1e-5 return t @ t.mT + i def random_hermitian_pd_matrix(matrix_size, *batch_dims, dtype, device): """ Returns a batch of random Hermitian positive-definite matrices. The shape of the result is batch_dims + (matrix_size, matrix_size) The following example creates a tensor of size 2 x 4 x 3 x 3 >>> # xdoctest: +SKIP("undefined variables") >>> matrices = random_hermitian_pd_matrix(3, 2, 4, dtype=dtype, device=device) """ A = torch.randn(*(batch_dims + (matrix_size, matrix_size)), dtype=dtype, device=device) return A @ A.mH + torch.eye(matrix_size, dtype=dtype, device=device) # Creates a full rank matrix with distinct singular values or # a batch of such matrices def make_fullrank_matrices_with_distinct_singular_values(*shape, device, dtype, requires_grad=False): with torch.no_grad(): t = make_tensor(shape, device=device, dtype=dtype) u, _, vh = torch.linalg.svd(t, full_matrices=False) real_dtype = t.real.dtype if t.dtype.is_complex else t.dtype k = min(shape[-1], shape[-2]) # We choose the singular values to be "around one" # This is to make the matrix well conditioned # s = [2, 3, ..., k+1] s = torch.arange(2, k + 2, dtype=real_dtype, device=device) # s = [2, -3, 4, ..., (-1)^k k+1] s[1::2] *= -1. # 1 + 1/s so that the singular values are in the range [2/3, 3/2] # This gives a condition number of 9/4, which should be good enough s.reciprocal_().add_(1.) # Note that the singular values need not be ordered in an SVD so # we don't need need to sort S x = (u * s.to(u.dtype)) @ vh x.requires_grad_(requires_grad) return x def random_matrix(rows, columns, *batch_dims, **kwargs): """Return rectangular matrix or batches of rectangular matrices. Parameters: dtype - the data type device - the device kind singular - when True, the output will be singular """ dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') silent = kwargs.get("silent", False) singular = kwargs.get("singular", False) if silent and not torch._C.has_lapack: return torch.ones(rows, columns, dtype=dtype, device=device) A = torch.randn(batch_dims + (rows, columns), dtype=dtype, device=device) if A.numel() == 0: return A u, _, vh = torch.linalg.svd(A, full_matrices=False) k = min(rows, columns) s = torch.linspace(1 / (k + 1), 1, k, dtype=dtype, device=device) if singular: # make matrix singular s[k - 1] = 0 if k > 2: # increase the order of singularity so that the pivoting # in LU factorization will be non-trivial s[0] = 0 return (u * s.unsqueeze(-2)) @ vh def random_lowrank_matrix(rank, rows, columns, *batch_dims, **kwargs): """Return rectangular matrix or batches of rectangular matrices with given rank. """ B = random_matrix(rows, rank, *batch_dims, **kwargs) C = random_matrix(rank, columns, *batch_dims, **kwargs) return B.matmul(C) def _generate_indices_prefer_all_rows(rows: int, cols: int, num_indices: int) -> torch.Tensor: """Generate indices for a row x cols matrix, preferring at least one index per row if possible.""" indices = [] # type: ignore[var-annotated] n_per_row = math.ceil(num_indices / rows) col_indices = list(range(cols)) for r in range(rows): # Note that this can yield overlapping indices indices.extend((r, c) for c in random.choices(col_indices, k=n_per_row)) return torch.tensor(indices[:num_indices]) def random_sparse_matrix(rows, columns, density=0.01, **kwargs): """Return rectangular random sparse matrix within given density. The density of the result approaches to given density as the size of the matrix is increased and a relatively small value of density is specified but higher than min(rows, columns)/(rows * columns) for non-singular matrices. """ dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') nonzero_elements = max(min(rows, columns), int(rows * columns * density)) indices = _generate_indices_prefer_all_rows(rows, columns, nonzero_elements) values = torch.randn(nonzero_elements, dtype=dtype, device=device) # ensure that the diagonal dominates values *= torch.tensor([-float(i - j)**2 for i, j in indices], dtype=dtype, device=device).exp() A = torch.sparse_coo_tensor(indices.t(), values, (rows, columns), device=device) return A.coalesce() def random_sparse_pd_matrix(matrix_size, density=0.01, **kwargs): """Return random sparse positive-definite matrix with given density. The eigenvalues of the matrix are defined as:: arange(1, matrix_size+1)/matrix_size Algorithm: A = diag(arange(1, matrix_size+1)/matrix_size) while <A density is smaller than required>: <choose random i, j in range(matrix_size), theta in [0, 2*pi]> R = <rotation matrix (i,j,theta)> A = R^T A R """ import math torch = kwargs.get('torch', globals()['torch']) dtype = kwargs.get('dtype', torch.double) device = kwargs.get('device', 'cpu') data = {(i, i): float(i + 1) / matrix_size for i in range(matrix_size)} def multiply(data, N, i, j, cs, sn, left=True): for k in range(N): if left: ik, jk = (k, i), (k, j) else: ik, jk = (i, k), (j, k) aik, ajk = data.get(ik, 0), data.get(jk, 0) aik, ajk = cs * aik + sn * ajk, -sn * aik + cs * ajk if aik: data[ik] = aik else: data.pop(ik, None) if ajk: data[jk] = ajk else: data.pop(jk, None) target_nnz = density * matrix_size * matrix_size while len(data) < target_nnz: i = random.randint(0, matrix_size - 1) j = random.randint(0, matrix_size - 1) if i != j: theta = random.uniform(0, 2 * math.pi) cs = math.cos(theta) sn = math.sin(theta) multiply(data, matrix_size, i, j, cs, sn, left=True) multiply(data, matrix_size, i, j, cs, sn, left=False) icoords, jcoords, values = [], [], [] for (i, j), v in sorted(data.items()): icoords.append(i) jcoords.append(j) values.append(v) indices_tensor = torch.tensor([icoords, jcoords]) return torch.sparse_coo_tensor(indices_tensor, values, (matrix_size, matrix_size), dtype=dtype, device=device) # FIXME: remove this by updating test suites using it def do_test_dtypes(self, dtypes, layout, device): for dtype in dtypes: if dtype != torch.float16: out = torch.zeros((2, 3), dtype=dtype, layout=layout, device=device) self.assertIs(dtype, out.dtype) self.assertIs(layout, out.layout) self.assertEqual(device, out.device) # FIXME: remove this by updating test suites using it def do_test_empty_full(self, dtypes, layout, device): shape = torch.Size([2, 3]) def check_value(tensor, dtype, layout, device, value, requires_grad): self.assertEqual(shape, tensor.shape) self.assertIs(dtype, tensor.dtype) self.assertIs(layout, tensor.layout) self.assertEqual(tensor.requires_grad, requires_grad) if tensor.is_cuda and device is not None: self.assertEqual(device, tensor.device) if value is not None: fill = tensor.new(shape).fill_(value) self.assertEqual(tensor, fill) def get_int64_dtype(dtype): module = '.'.join(str(dtype).split('.')[1:-1]) if not module: return torch.int64 return operator.attrgetter(module)(torch).int64 default_dtype = torch.get_default_dtype() check_value(torch.empty(shape), default_dtype, torch.strided, -1, None, False) check_value(torch.full(shape, -5.), default_dtype, torch.strided, -1, None, False) for dtype in dtypes: for rg in {dtype.is_floating_point, False}: int64_dtype = get_int64_dtype(dtype) v = torch.empty(shape, dtype=dtype, device=device, layout=layout, requires_grad=rg) check_value(v, dtype, layout, device, None, rg) out = v.new() check_value(torch.empty(shape, out=out, device=device, layout=layout, requires_grad=rg), dtype, layout, device, None, rg) check_value(v.new_empty(shape), dtype, layout, device, None, False) check_value(v.new_empty(shape, dtype=int64_dtype, device=device, requires_grad=False), int64_dtype, layout, device, None, False) check_value(torch.empty_like(v), dtype, layout, device, None, False) check_value(torch.empty_like(v, dtype=int64_dtype, layout=layout, device=device, requires_grad=False), int64_dtype, layout, device, None, False) if dtype is not torch.float16 and layout != torch.sparse_coo: fv = 3 v = torch.full(shape, fv, dtype=dtype, layout=layout, device=device, requires_grad=rg) check_value(v, dtype, layout, device, fv, rg) check_value(v.new_full(shape, fv + 1), dtype, layout, device, fv + 1, False) out = v.new() check_value(torch.full(shape, fv + 2, out=out, device=device, layout=layout, requires_grad=rg), dtype, layout, device, fv + 2, rg) check_value(v.new_full(shape, fv + 3, dtype=int64_dtype, device=device, requires_grad=False), int64_dtype, layout, device, fv + 3, False) check_value(torch.full_like(v, fv + 4), dtype, layout, device, fv + 4, False) check_value(torch.full_like(v, fv + 5, dtype=int64_dtype, layout=layout, device=device, requires_grad=False), int64_dtype, layout, device, fv + 5, False) # FIXME: improve load_tests() documentation here running_script_path = None # type: ignore[var-annotated] def set_running_script_path(): global running_script_path try: running_file = os.path.abspath(os.path.realpath(sys.argv[0])) if running_file.endswith('.py'): # skip if the running file is not a script running_script_path = running_file except Exception: pass def check_test_defined_in_running_script(test_case): if running_script_path is None: return test_case_class_file = os.path.abspath(os.path.realpath(inspect.getfile(test_case.__class__))) assert test_case_class_file == running_script_path, f'Class of loaded TestCase "{test_case.id()}" ' \ f'is not defined in the running script "{running_script_path}", but in "{test_case_class_file}". Did you ' \ "accidentally import a unittest.TestCase from another file?" def load_tests(loader, tests, pattern): set_running_script_path() test_suite = unittest.TestSuite() for test_group in tests: if not DISABLE_RUNNING_SCRIPT_CHK: for test in test_group: check_test_defined_in_running_script(test) if test_group._tests: test_suite.addTest(test_group) return test_suite # FIXME: document this and move it to test_serialization
TestCaseBase
python
keon__algorithms
tests/test_strings.py
{ "start": 7252, "end": 7827 }
class ____(unittest.TestCase): """[summary] Test for the file license_number.py Arguments: unittest {[type]} -- [description] """ def test_license_number(self): self.assertEqual("a-b-c-d-f-d-d-f", license_number("a-bc-dfd-df", 1)) self.assertEqual("ab-cd-fd-df", license_number("a-bc-dfd-df", 2)) self.assertEqual("ab-cdf-ddf", license_number("a-bc-dfd-df", 3)) self.assertEqual("abcd-fddf", license_number("a-bc-dfd-df", 4)) self.assertEqual("abc-dfddf", license_number("a-bc-dfd-df", 5))
TestLicenseNumber
python
doocs__leetcode
solution/0700-0799/0775.Global and Local Inversions/Solution2.py
{ "start": 343, "end": 722 }
class ____: def isIdealPermutation(self, nums: List[int]) -> bool: n = len(nums) tree = BinaryIndexedTree(n) cnt = 0 for i, v in enumerate(nums): cnt += i < n - 1 and v > nums[i + 1] cnt -= i - tree.query(v) if cnt < 0: return False tree.update(v + 1, 1) return True
Solution
python
gevent__gevent
src/greentest/3.12/test_interpreters.py
{ "start": 25267, "end": 25804 }
class ____(TestBase): def test_create(self): r, s = interpreters.create_channel() self.assertIsInstance(r, interpreters.RecvChannel) self.assertIsInstance(s, interpreters.SendChannel) def test_list_all(self): self.assertEqual(interpreters.list_all_channels(), []) created = set() for _ in range(3): ch = interpreters.create_channel() created.add(ch) after = set(interpreters.list_all_channels()) self.assertEqual(after, created)
TestChannels
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 882, "end": 2094 }
class ____(util.MdCase): """Test that highlighting works with guessing for block.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'guess_lang': "block" } } def test_guess_block(self): """Test guessing for block.""" self.check_markdown( r''' ``` import test test.test() ``` ''', ''' <div class="highlight"><pre><span></span><code><span class="kn">import</span><span class="w"> </span><span class="nn">test</span> <span class="n">test</span><span class="o">.</span><span class="n">test</span><span class="p">()</span> </code></pre></div> ''', # noqa: E501 True ) def test_no_guess_inline(self): """Test inline code is not language guessed.""" self.check_markdown( r''' `int i = std::numeric_limits<int>::min();` ''', ''' <p><code>int i = std::numeric_limits&lt;int&gt;::min();</code></p> ''', True )
TestHighlightGuessBlock
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 54759, "end": 60716 }
class ____(SimpleElement): """ COOSYS_ element: defines a coordinate system. The keyword arguments correspond to setting members of the same name, documented below. """ _attr_list = ["ID", "equinox", "epoch", "system", "refposition"] _element_name = "COOSYS" _reference_frames = None def __init__( self, ID=None, equinox=None, epoch=None, system=None, id=None, config=None, pos=None, refposition=None, **extra, ): if config is None: config = {} self._config = config self._pos = pos # COOSYS was deprecated in 1.2 but then re-instated in 1.3 if config.get("version_1_2_or_later") and not config.get( "version_1_3_or_later" ): warn_or_raise(W27, W27, (), config, pos) SimpleElement.__init__(self) self.ID = resolve_id(ID, id, config, pos) self.equinox = equinox self.epoch = epoch self.system = system self.refposition = refposition # refposition introduced in v1.5. if self.refposition is not None and not config.get("version_1_5_or_later"): warn_or_raise(W57, W57, (), config, pos) warn_unknown_attrs("COOSYS", extra.keys(), config, pos) @property def ID(self): """ [*required*] The XML ID of the COOSYS_ element, used for cross-referencing. May be `None` or a string conforming to XML ID_ syntax. """ return self._ID @ID.setter def ID(self, ID): if self._config.get("version_1_1_or_later"): if ID is None: vo_raise(E15, (), self._config, self._pos) xmlutil.check_id(ID, "ID", self._config, self._pos) self._ID = ID @property def system(self): """Specifies the type of coordinate system. Valid choices are given by `~astropy.io.votable.tree.CooSys.reference_frames` """ return self._system @system.setter def system(self, system): if system not in self.reference_frames: warn_or_raise(E16, E16, system, self._config, self._pos) self._system = system @system.deleter def system(self): self._system = None @property def reference_frames(self): """The list of reference frames recognized in the IVOA vocabulary. This is described at http://www.ivoa.net/rdf/refframe Returns ------- set[str] The labels of the IVOA reference frames. """ # since VOTable version 1.5, the 'system' in COOSYS follow the RDF vocabulary # for reference frames. If this is updated upstream, the json version can be # downloaded at the bottom of the page and replaced here. if self._reference_frames is None: with open( get_pkg_data_filename("data/ivoa-vocalubary_refframe-v20220222.json") ) as f: self._reference_frames = set(json.load(f)["terms"].keys()) return self._reference_frames @property def equinox(self): """ A parameter required to fix the equatorial or ecliptic systems (as e.g. "J2000" as the default "eq_FK5" or "B1950" as the default "eq_FK4"). """ return self._equinox @equinox.setter def equinox(self, equinox): check_astroyear(equinox, "equinox", self._config, self._pos) self._equinox = equinox @equinox.deleter def equinox(self): self._equinox = None @property def epoch(self): """ Specifies the epoch of the positions. It must be a string specifying an astronomical year. """ return self._epoch @epoch.setter def epoch(self, epoch): check_astroyear(epoch, "epoch", self._config, self._pos) self._epoch = epoch @epoch.deleter def epoch(self): self._epoch = None def to_astropy_frame(self): """Convert the coosys element into an astropy built-in frame. This only reads the system and equinox attributes. Returns ------- `~astropy.coordinates.BaseCoordinateFrame` An astropy built-in frame corresponding to the frame described by the COOSYS element. Examples -------- >>> from astropy.io.votable.tree import CooSys >>> coosys = CooSys(system="ICRS", epoch="J2020") >>> # note that coosys elements also contain the epoch >>> coosys.to_astropy_frame() <ICRS Frame> Notes ----- If the correspondence is not straightforward, this method raises an error. In that case, you can refer to the `IVOA reference frames definition <http://www.ivoa.net/rdf/refframe>`_ and the list of `astropy's frames <https://docs.astropy.org/en/stable/coordinates/frames.html>`_ and deal with the conversion manually. """ # the import has to be here due to circular dependencies issues from astropy.coordinates import FK4, FK5, ICRS, AltAz, Galactic, Supergalactic match_frames = { "ICRS": ICRS(), "FK4": FK4(equinox=self.equinox), "FK5": FK5(equinox=self.equinox), "eq_FK4": FK4(equinox=self.equinox), "eq_FK5": FK5(equinox=self.equinox), "GALACTIC": Galactic(), "galactic": Galactic(), "SUPER_GALACTIC": Supergalactic(), "supergalactic": Supergalactic(), "AZ_EL": AltAz(), } if self.system not in set(match_frames.keys()): raise ValueError( f"There is no direct correspondence between '{self.system}' and an " "astropy frame. This method cannot return a frame." ) return match_frames[self.system]
CooSys
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/processors.py
{ "start": 30030, "end": 31343 }
class ____(Processor): """ Processor that applies another processor, according to a certain condition. Example:: # Create a function that returns whether or not the processor should # currently be applied. def highlight_enabled(): return true_or_false # Wrapped it in a `ConditionalProcessor` for usage in a `BufferControl`. BufferControl(input_processors=[ ConditionalProcessor(HighlightSearchProcessor(), Condition(highlight_enabled))]) :param processor: :class:`.Processor` instance. :param filter: :class:`~prompt_toolkit.filters.Filter` instance. """ def __init__(self, processor: Processor, filter: FilterOrBool) -> None: self.processor = processor self.filter = to_filter(filter) def apply_transformation( self, transformation_input: TransformationInput ) -> Transformation: # Run processor when enabled. if self.filter(): return self.processor.apply_transformation(transformation_input) else: return Transformation(transformation_input.fragments) def __repr__(self) -> str: return f"{self.__class__.__name__}(processor={self.processor!r}, filter={self.filter!r})"
ConditionalProcessor
python
jina-ai__jina
jina/parsers/helper.py
{ "start": 11009, "end": 12230 }
class ____(argparse.Action): """argparse action to cast potential inputs to `peer-ports` argument""" def __call__(self, parser, args, values, option_string=None): """ call the CastPeerPorts .. # noqa: DAR401 :param parser: the parser :param args: args to initialize the values :param values: the values to add to the parser :param option_string: inherited, not used """ import json d = {0: []} for value in values: if isinstance(value, str): value = json.loads(value) if isinstance(value, dict): for k, vlist in value.items(): d[k] = [] for v in vlist: d[k].append(_port_to_int(v)) elif isinstance(value, int): d[0].append(value) else: d[0] = [_port_to_int(port) for port in value] setattr(args, self.dest, d) def _port_to_int(port): try: return int(port) except ValueError: default_logger.warning( f'port {port} is not an integer and cannot be cast to one' ) return port
CastPeerPorts
python
google__jax
jax/_src/interpreters/ad.py
{ "start": 36942, "end": 50460 }
class ____(Trace): def __init__(self, parent_trace, tangent_trace, tag=None): super().__init__() self.tag = core.TraceTag() if tag is None else tag self.parent_trace = parent_trace self.tangent_trace = tangent_trace self._name_stack_prefix_len = len(source_info_util.current_name_stack()) self.requires_low = False def _name_stack_suffix(self): return source_info_util.current_name_stack()[self._name_stack_prefix_len:] def to_primal_tangent_pair(self, val): if isinstance(val, LinearizeTracer) and val._trace.tag is self.tag: return (val.primal, val.tangent) else: tangent_zero = Zero.from_primal_value(val) return (val, tangent_zero) def process_primitive(self, primitive, args, params): primals_in, tangents_in = unzip2(map(self.to_primal_tangent_pair, args)) tangent_nzs = [type(t) is not Zero for t in tangents_in] if (all(type(t) is Zero for t in tangents_in) and primitive is not core.ref_p and not any(isinstance(core.typeof(x), AbstractRef) for x in primals_in)): return primitive.bind_with_trace(self.parent_trace, primals_in, params) fallback = partial(fallback_linearize_rule, primitive) lin = primitive_linearizations.get(primitive, fallback) with core.set_current_trace(self.parent_trace): primal_out, tangent_nzs_out, residuals, linearized = lin( tangent_nzs, *primals_in, **params) with (core.set_current_trace(self.tangent_trace), source_info_util.set_name_stack(self._name_stack_suffix())): tangent_out = linearized(residuals, *tangents_in) if primitive.multiple_results: return [maybe_linearize_tracer(self, x, nz, t) for x, nz, t in zip(primal_out, tangent_nzs_out, tangent_out)] else: return maybe_linearize_tracer(self, primal_out, tangent_nzs_out, tangent_out) def cur_qdd(self, x): p, _ = self.to_primal_tangent_pair(x) with core.set_current_trace(self.parent_trace): return core.cur_qdd(p) def process_custom_jvp_call(self, prim, fun: lu.WrappedFun, f_jvp: lu.WrappedFun, tracers, *, symbolic_zeros: bool): primals_in, tangents_in = unzip2(map(self.to_primal_tangent_pair, tracers)) if all(type(t) is Zero for t in tangents_in): return prim.bind_with_trace(self.parent_trace, (fun, f_jvp, *primals_in), dict(symbolic_zeros=symbolic_zeros)) @partial(lu.wrap_init, debug_info=f_jvp.debug_info) def _f_jvp(primals, tangents): outs = f_jvp.call_wrapped(*primals, *tangents) primals_out, tangents_out = split_list(outs, [len(outs) // 2]) return primals_out, tangents_out with core.set_current_trace(self.parent_trace): instantiate_zeros = not symbolic_zeros nonzeros_in = [type(t) is not Zero for t in tangents_in] primals_out, tangent_nzs_out, residuals, linearized = linearize_from_jvp( _f_jvp, True, nonzeros_in, symbolic_zeros, instantiate_zeros, primals_in, {}) with core.set_current_trace(self.tangent_trace): tangents_out = linearized(residuals, *tangents_in) tangents_out = map(replace_rule_output_symbolic_zeros, tangents_out) return [maybe_linearize_tracer(self, x, nz, t) for x, nz, t in zip(primals_out, tangent_nzs_out, tangents_out)] def process_custom_vjp_call(self, prim, fun, fwd, bwd: lu.WrappedFun, tracers, out_trees: Callable[[], tuple[PyTreeDef, PyTreeDef, list[int | None]]], symbolic_zeros: bool): primals_in, tangents_in = unzip2(map(self.to_primal_tangent_pair, tracers)) if all(type(t) is Zero for t in tangents_in): return prim.bind_with_trace(self.parent_trace, (fun, fwd, bwd, *primals_in), dict(out_trees=out_trees, symbolic_zeros=symbolic_zeros)) fwd_in = [(p, type(t) is not Zero) for p, t in zip(primals_in, tangents_in)] fwd_in_flat = [x for pair in fwd_in for x in pair] # flatten with core.set_current_trace(self.parent_trace): res_and_primals_out = fwd.call_wrapped(*fwd_in_flat) _, res_tree, input_fwds = out_trees() num_res_out = res_tree.num_leaves - sum(f is not None for f in input_fwds) res_out, primals_out = split_list(res_and_primals_out, [num_res_out]) res_out_ = iter(res_out) res = [next(res_out_) if f is None else primals_in[f] for f in input_fwds] assert next(res_out_, None) is None avals_out = [core.get_aval(x).to_tangent_aval() for x in primals_out] in_zeros = [type(t) is Zero for t in tangents_in] nz_tangents_in = [t for z, t in zip(in_zeros, tangents_in) if not z] with core.set_current_trace(self.tangent_trace): tangents_out = custom_lin_p.bind( *res, *nz_tangents_in, num_res=res_tree.num_leaves, bwd=bwd, out_avals=avals_out, symbolic_zeros=symbolic_zeros, in_zeros=in_zeros) tangent_nzs_out = [type(t) is not Zero for t in tangents_out] return map(partial(maybe_linearize_tracer, self), primals_out, tangent_nzs_out, tangents_out) def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params): assert call_primitive.multiple_results primals, tangents = unzip2(map(self.to_primal_tangent_pair, tracers)) nzs_in = tuple(type(t) is not Zero for t in tangents) f_primal, linearize_outs_thunk = linearize_subtrace( f, self.tag, nzs_in, f.debug_info) if isinstance(call_primitive, core.MapPrimitive): out_axes_thunk = params['out_axes_thunk'] @as_hashable_function(closure=out_axes_thunk) def new_out_axes_thunk(): _, _, _, _, in_fwd, out_fwd = linearize_outs_thunk() num_res_out = sum(f1 is None and f2 is None for f1, f2 in zip(in_fwd, out_fwd)) out_axes = out_axes_thunk() return (*(0 for _ in range(num_res_out)), *out_axes) primal_params = dict(params, out_axes_thunk=new_out_axes_thunk) else: primal_params = params all_primal_results = call_primitive.bind_with_trace( self.parent_trace, (f_primal, *primals), primal_params) residual_avals, nzs_out, lin_jaxpr, env, in_fwd, out_fwd = linearize_outs_thunk() num_res_out = sum(f1 is None and f2 is None for f1, f2 in zip(in_fwd, out_fwd)) non_fwd_res = all_primal_results[:num_res_out] primals_out = all_primal_results[num_res_out:] residuals = subs_list2(in_fwd, out_fwd, primals, primals_out, non_fwd_res) if isinstance(call_primitive, core.MapPrimitive): in_axes = params['in_axes'] out_axes = params['out_axes_thunk']() residual_avals = map(get_aval, residuals) residual_axes = [in_axes[f1] if f1 is not None else out_axes[f2] if f2 is not None else 0 for f1, f2 in zip(in_fwd, out_fwd)] new_in_axes = (*residual_axes, *(None for _ in range(len(env))), *(ax for ax, nz in zip(in_axes, nzs_in) if nz)) new_out_axes = (*(ax for ax, nz in zip(out_axes, nzs_out) if nz),) # NOTE: This assumes that the output tangents being zero is a # deterministic function of which input tangents were zero. @as_hashable_function(closure=new_out_axes) def new_out_axes_thunk(): return new_out_axes params = dict(params, in_axes=new_in_axes, out_axes_thunk=new_out_axes_thunk) update_params = call_linearize_param_updaters.get(call_primitive) num_new_args = len(residuals) + len(env) new_params = (update_params(params, num_new_args, nzs_in) if update_params else params) num_residuals = len(residual_avals) # TODO(mattjj,dougalm): this tag is read by DynamicJaxprTrace.process_map to # avoid round-tripping the jaxpr and thus getting grad-of-pmap cache misses. # Remove the `if` branch when we replace the pmap implementation. if isinstance(call_primitive, core.MapPrimitive): @as_hashable_function(closure=(num_residuals, lin_jaxpr)) def f_tangent(*args): consts = args[:num_residuals] nz_tangents = args[num_residuals:] return core.eval_jaxpr(lin_jaxpr, consts, *nz_tangents) f_tangent._pmap_tag = isinstance(call_primitive, core.MapPrimitive) else: f_tangent = _get_f_tangent(lin_jaxpr, num_residuals) nz_tangents_in = [t for (t, nz) in zip(tangents, nzs_in) if nz] nz_tangents_out = call_primitive.bind_with_trace( self.tangent_trace, (lu.wrap_init(f_tangent, debug_info=lin_jaxpr.debug_info), *residuals, *env, *nz_tangents_in), new_params) nz_tangents_out_iter = iter(nz_tangents_out) tangents_out = [next(nz_tangents_out_iter) if nz else Zero.from_primal_value(primal) for nz, primal in zip(nzs_out, primals_out)] return map(partial(maybe_linearize_tracer, self), primals_out, nzs_out, tangents_out) # The only difference between process_map and process_call is that # the `in_axes` and `out_axes_thunk` params must be updated; # that's handled in process_call. process_map = process_call @weakref_lru_cache def _get_f_tangent(lin_jaxpr, num_residuals): def _f(*args): consts = args[:num_residuals] nz_tangents = args[num_residuals:] return core.eval_jaxpr(lin_jaxpr, consts, *nz_tangents) return _f def maybe_linearize_tracer(trace, primal, is_nonzero, tangent): if is_nonzero: assert not type(tangent) is Zero return LinearizeTracer(trace, primal, tangent) else: assert type(tangent) is Zero return primal def fallback_linearize_rule(_prim: core.Primitive, _nonzeros: Sequence[bool], *primals, **params): jvp = primitive_jvps.get(_prim) if not jvp: msg = f"Differentiation rule for '{_prim}' not implemented" raise NotImplementedError(msg) debug_jvp = debug_info("linearize_prim_jvp", jvp, primals, params) return linearize_from_jvp(lu.wrap_init(jvp, debug_info=debug_jvp), _prim.multiple_results, _nonzeros, False, False, primals, params) def linearize_from_jvp(jvp: lu.WrappedFun, multiple_results: bool, nonzeros: Sequence[bool], user_facing_symbolic_zeros: bool, instantiate_input_zeros: bool, primals, params): current_name_stack = source_info_util.current_name_stack() with core.take_current_trace() as parent_trace: trace = pe.JaxprTrace(parent_trace, current_name_stack, core.TraceTag()) tangent_avals = [get_aval(p).to_tangent_aval() for p in primals] # map tangents with float0 dtype to symbolic zeros nonzeros = [nz and not (isinstance(a, core.ShapedArray) and a.dtype == float0) for a, nz in zip(tangent_avals, nonzeros)] def make_zero(aval): if instantiate_input_zeros: return zeros_like_aval(aval) elif user_facing_symbolic_zeros: return SymbolicZero(aval) else: return Zero(aval) if user_facing_symbolic_zeros: zero_type = SymbolicZero else: zero_type = Zero # type: ignore[assignment] with core.set_current_trace(trace): tangent_args = [trace.new_arg(pe.PartialVal.unknown(a)) if nz else make_zero(a) for a, nz in zip(tangent_avals, nonzeros)] out_primals, out_tangents = jvp.call_wrapped( tuple(primals), tuple(tangent_args), **params) if not multiple_results: out_primals = [out_primals] out_tangents = [out_tangents] out_primals = [trace.to_jaxpr_tracer(p).pval.get_known() for p in out_primals] if any(p is None for p in out_primals): raise ValueError( "Linearization failed to produce known values for all output primals. " "This is typically caused by attempting to differentiate a function " "uses an operation that does not support reverse-mode autodiff.") out_nzs = [type(t) is not zero_type and not trace.to_jaxpr_tracer(t).is_known() for t in out_tangents] out_tangent_avals = [get_aval(p).to_tangent_aval() for p in out_primals] out_nz_tracers = [trace.to_jaxpr_tracer(r) for (r, nz) in zip(out_tangents, out_nzs) if nz] in_tracers = [t for t, nz in zip(tangent_args, nonzeros) if nz] jaxpr, out_consts, _ = pe.tracers_to_jaxpr( in_tracers, out_nz_tracers, trace.effect_handles, jvp.debug_info.with_unknown_names()) jaxpr, used_consts, _ = pe.dce_jaxpr_consts( jaxpr, [True] * len(jaxpr.outvars), [False] * len(jaxpr.constvars) + [True] * len(jaxpr.invars)) out_consts = [c for used, c in zip(used_consts, out_consts) if used] def linearized(residuals, *tangents): nz_tangents_in = [t for (t, nz) in zip(tangents, nonzeros) if nz] nz_tangents_out = core.eval_jaxpr(jaxpr, residuals, *nz_tangents_in) nz_tangents_out_iter = iter(nz_tangents_out) all_out_tangents = [next(nz_tangents_out_iter) if nz else Zero(aval) for (aval, nz) in zip(out_tangent_avals, out_nzs)] if multiple_results: return all_out_tangents else: out_tangent, = all_out_tangents return out_tangent if multiple_results: return out_primals, out_nzs, out_consts, linearized else: out_primal, = out_primals out_nz, = out_nzs return out_primal, out_nz, out_consts, linearized
LinearizeTrace
python
run-llama__llama_index
llama-index-core/llama_index/core/prompts/base.py
{ "start": 7163, "end": 11323 }
class ____(BasePromptTemplate): # type: ignore[no-redef] message_templates: List[ChatMessage] def __init__( self, message_templates: Sequence[ChatMessage], prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, **kwargs: Any, ): if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type template_vars = [] for message_template in message_templates: template_vars.extend(get_template_vars(message_template.content or "")) super().__init__( message_templates=message_templates, kwargs=kwargs, metadata=metadata, output_parser=output_parser, template_vars=template_vars, template_var_mappings=template_var_mappings, function_mappings=function_mappings, ) @classmethod def from_messages( cls, message_templates: Union[List[Tuple[str, str]], List[ChatMessage]], **kwargs: Any, ) -> "ChatPromptTemplate": """From messages.""" if isinstance(message_templates[0], tuple): message_templates = [ ChatMessage.from_str(role=role, content=content) # type: ignore[arg-type] for role, content in message_templates ] return cls(message_templates=message_templates, **kwargs) # type: ignore[arg-type] def partial_format(self, **kwargs: Any) -> "ChatPromptTemplate": prompt = deepcopy(self) prompt.kwargs.update(kwargs) return prompt def format( self, llm: Optional[BaseLLM] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, **kwargs: Any, ) -> str: del llm # unused messages = self.format_messages(**kwargs) if messages_to_prompt is not None: return messages_to_prompt(messages) return default_messages_to_prompt(messages) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: del llm # unused """Format the prompt into a list of chat messages.""" all_kwargs = { **self.kwargs, **kwargs, } mapped_all_kwargs = self._map_all_vars(all_kwargs) messages: List[ChatMessage] = [] for message_template in self.message_templates: # Handle messages with multiple blocks if message_template.blocks: formatted_blocks: List[ContentBlock] = [] for block in message_template.blocks: if isinstance(block, TextBlock): template_vars = get_template_vars(block.text) relevant_kwargs = { k: v for k, v in mapped_all_kwargs.items() if k in template_vars } formatted_text = format_string(block.text, **relevant_kwargs) formatted_blocks.append(TextBlock(text=formatted_text)) else: # For non-text blocks (like images), keep them as is # TODO: can images be formatted as variables? formatted_blocks.append(block) message = message_template.model_copy() message.blocks = formatted_blocks messages.append(message) else: # Handle empty messages (if any) messages.append(message_template.model_copy()) if self.output_parser is not None: messages = self.output_parser.format_messages(messages) return messages def get_template(self, llm: Optional[BaseLLM] = None) -> str: return default_messages_to_prompt(self.message_templates)
ChatPromptTemplate
python
spyder-ide__spyder
spyder/plugins/updatemanager/workers.py
{ "start": 2280, "end": 8229 }
class ____(TypedDict): """Schema for asset information.""" # Version version: Version # Filename with extension of the release asset to download. filename: str # Type of update update_type: UpdateType # Download URL for the asset. url: str # File sha256 checksum checksum: str def get_github_releases( tags: str | tuple[str] | None = None, updater: bool = False ) -> dict[Version, dict]: """ Get Github release information Parameters ---------- tags : str | tuple[str] | (None) If tags is provided, only release information for the requested tags is retrieved. Otherwise, the most recent 20 releases are retrieved. This is only used to retrieve a known set of releases for unit testing. updater : bool (False) Whether to get Spyder-updater releases (True) or Spyder releases (False). Returns ------- releases : dict[packaging.version.Version, dict] Dictionary of release information. """ url = "https://api.github.com/repos/{}/releases".format( "spyder-ide/spyder-updater" if updater else "spyder-ide/spyder" ) if tags is None: # Get 20 most recent releases url += "?per_page=20&page=1" logger.info(f"Getting release info from {url}") page = requests.get(url, headers=GH_HEADERS) page.raise_for_status() data = page.json() else: # Get specified releases tags = [tags] if isinstance(tags, str) else tags url += "/tags/" data = [] with requests.Session() as session: session.headers = GH_HEADERS logger.info(f"Getting release info for {tags}") for tag in tags: _url = url + tag page = session.get(_url) page.raise_for_status() data.append(page.json()) return {parse(item['tag_name']): item for item in data} def get_asset_info( release_info: dict, current_version: Version, updater: bool ) -> AssetInfo | None: """ Get the version, name, update type, download URL, and digest for the asset of the given release. Parameters ---------- release_info: dict Release information from Github for a single release. current_version: Version Current version. updater: bool Whether Spyder-updater (True) or Spyder (False). Returns ------- asset_info: AssetInfo | None Information about the asset. """ release = parse(release_info["tag_name"]) if current_version.major < release.major or not is_conda_based_app(): update_type = UpdateType.Major elif current_version.minor < release.minor or current_version.is_prerelease: update_type = UpdateType.Minor else: update_type = UpdateType.Micro if updater: filename = "spyder-updater.zip" elif update_type != UpdateType.Major: filename = "spyder-conda-lock.zip" else: machine = platform.machine().lower().replace("amd64", "x86_64") if os.name == 'nt': filename = f"Spyder-Windows-{machine}.exe" if sys.platform == 'darwin': filename = f"Spyder-macOS-{machine}.pkg" if sys.platform.startswith('linux'): filename = f"Spyder-Linux-{machine}.sh" asset_info = None for asset in release_info["assets"]: if asset["name"] == filename: asset_info = AssetInfo( version=release, update_type=update_type, filename=asset["name"], url=asset["browser_download_url"], checksum=asset["digest"], ) break return asset_info def _check_asset_available( releases: dict[Version, dict], current_version: Version, updater: bool = False ) -> AssetInfo | None: latest_release = max(releases) if releases else current_version update_available = current_version < latest_release asset_info = None logger.debug(f"Latest release: {latest_release}") logger.debug(f"Update available: {update_available}") # Check if the asset is available for download. # If the asset is not available, then check the next latest # release, and so on until either a new asset is available or there # is no update available. while update_available: asset_info = get_asset_info( releases.get(latest_release), current_version, updater ) if asset_info is not None: break # The asset is not available logger.debug(f"Asset not available: {latest_release}") releases.pop(latest_release) latest_release = max(releases) if releases else current_version update_available = current_version < latest_release logger.debug(f"Latest release: {latest_release}") logger.debug(f"Update available: {update_available}") return asset_info def validate_download(file: str, checksum: str) -> bool: """ Compute the sha256 checksum of the provided file and compare against the provided checksum. Parameters ---------- file : str Full path to the file to be verified. checksum : str sha256 checksum to match against the computed checksum. Returns ------- valid : bool True if the file's computed checksum matches the provided checksum, False otherwise. """ with open(file, "rb") as f: _checksum = sha256() while chunk := f.read(8192): _checksum.update(chunk) valid = checksum.endswith(_checksum.hexdigest()) logger.debug(f"Valid {file}: {valid}") # Extract validated zip files if valid and file.endswith('.zip'): with ZipFile(file, 'r') as f: f.extractall(osp.dirname(file)) logger.debug(f"{file} extracted.") return valid
AssetInfo
python
pytransitions__transitions
transitions/extensions/factory.py
{ "start": 2252, "end": 2508 }
class ____(LockedMachine, HierarchicalMachine): """ A threadsafe hierarchical machine. """ event_cls = NestedEvent def _get_qualified_state_name(self, state): return self.get_global_name(state.name)
LockedHierarchicalMachine
python
google__jax
jax/_src/pallas/core.py
{ "start": 9357, "end": 9896 }
class ____: index: jax_typing.Array size: int # Stores the kernel execution position and the size along grid axes. GridEnv = Sequence[GridAxis] @contextlib.contextmanager def grid_env(env: GridEnv) -> Iterator[None]: _pallas_tracing_env.grid_env_stack.append(env) try: yield finally: _pallas_tracing_env.grid_env_stack.pop() def current_grid_env() -> GridEnv | None: if not _pallas_tracing_env.grid_env_stack: return None return _pallas_tracing_env.grid_env_stack[-1] @dataclasses.dataclass(frozen=True)
GridAxis
python
walkccc__LeetCode
solutions/1828. Queries on Number of Points Inside a Circle/1828.py
{ "start": 0, "end": 327 }
class ____: def countPoints( self, points: list[list[int]], queries: list[list[int]], ) -> list[int]: ans = [] for xj, yj, rj in queries: count = 0 for xi, yi in points: if (xi - xj)**2 + (yi - yj)**2 <= rj**2: count += 1 ans.append(count) return ans
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 776379, "end": 777269 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "allow_list_value", "created_at", "is_active", "name", "owner", "updated_at", ) allow_list_value = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="allowListValue" ) created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) is_active = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="isActive" ) name = sgqlc.types.Field(String, graphql_name="name") owner = sgqlc.types.Field( sgqlc.types.non_null("IpAllowListOwner"), graphql_name="owner" ) updated_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="updatedAt" )
IpAllowListEntry
python
getsentry__sentry
src/sentry/notifications/platform/target.py
{ "start": 2272, "end": 2940 }
class ____(GenericNotificationTarget): """ Adds necessary properties and methods to designate a target within an integration. Accepts the renderable object type that matches the connected provider. """ integration_id: int organization_id: int def to_dict(self) -> dict[str, Any]: base_data = super().to_dict() return { **base_data, "integration_id": self.integration_id, "organization_id": self.organization_id, } @classmethod def from_dict(cls, data: dict[str, Any]) -> Self: return cls(**data) @dataclass(kw_only=True, frozen=True)
IntegrationNotificationTarget
python
scrapy__scrapy
scrapy/core/engine.py
{ "start": 2935, "end": 23858 }
class ____: _SLOT_HEARTBEAT_INTERVAL: float = 5.0 def __init__( self, crawler: Crawler, spider_closed_callback: Callable[ [Spider], Coroutine[Any, Any, None] | Deferred[None] | None ], ) -> None: self.crawler: Crawler = crawler self.settings: Settings = crawler.settings self.signals: SignalManager = crawler.signals assert crawler.logformatter self.logformatter: LogFormatter = crawler.logformatter self._slot: _Slot | None = None self.spider: Spider | None = None self.running: bool = False self.paused: bool = False self._spider_closed_callback: Callable[ [Spider], Coroutine[Any, Any, None] | Deferred[None] | None ] = spider_closed_callback self.start_time: float | None = None self._start: AsyncIterator[Any] | None = None self._closewait: Deferred[None] | None = None self._start_request_processing_awaitable: ( asyncio.Future[None] | Deferred[None] | None ) = None downloader_cls: type[Downloader] = load_object(self.settings["DOWNLOADER"]) try: self.scheduler_cls: type[BaseScheduler] = self._get_scheduler_class( crawler.settings ) self.downloader: Downloader = downloader_cls(crawler) self._downloader_fetch_needs_spider: bool = argument_is_required( self.downloader.fetch, "spider" ) if self._downloader_fetch_needs_spider: warnings.warn( f"The fetch() method of {global_object_name(downloader_cls)} requires a spider argument," f" this is deprecated and the argument will not be passed in future Scrapy versions.", ScrapyDeprecationWarning, stacklevel=2, ) self.scraper: Scraper = Scraper(crawler) except Exception: if hasattr(self, "downloader"): self.downloader.close() raise def _get_scheduler_class(self, settings: BaseSettings) -> type[BaseScheduler]: scheduler_cls: type[BaseScheduler] = load_object(settings["SCHEDULER"]) if not issubclass(scheduler_cls, BaseScheduler): raise TypeError( f"The provided scheduler class ({settings['SCHEDULER']})" " does not fully implement the scheduler interface" ) return scheduler_cls def start(self, _start_request_processing=True) -> Deferred[None]: warnings.warn( "ExecutionEngine.start() is deprecated, use start_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro( self.start_async(_start_request_processing=_start_request_processing) ) async def start_async(self, *, _start_request_processing: bool = True) -> None: """Start the execution engine. .. versionadded:: VERSION """ if self.running: raise RuntimeError("Engine already running") self.start_time = time() await self.signals.send_catch_log_async(signal=signals.engine_started) if _start_request_processing and self.spider is None: # require an opened spider when not run in scrapy shell return self.running = True self._closewait = Deferred() if _start_request_processing: coro = self._start_request_processing() if is_asyncio_available(): # not wrapping in a Deferred here to avoid https://github.com/twisted/twisted/issues/12470 # (can happen when this is cancelled, e.g. in test_close_during_start_iteration()) self._start_request_processing_awaitable = asyncio.ensure_future(coro) else: self._start_request_processing_awaitable = Deferred.fromCoroutine(coro) await maybe_deferred_to_future(self._closewait) def stop(self) -> Deferred[None]: warnings.warn( "ExecutionEngine.stop() is deprecated, use stop_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro(self.stop_async()) async def stop_async(self) -> None: """Gracefully stop the execution engine. .. versionadded:: VERSION """ if not self.running: raise RuntimeError("Engine not running") self.running = False if self._start_request_processing_awaitable is not None: self._start_request_processing_awaitable.cancel() self._start_request_processing_awaitable = None if self.spider is not None: await self.close_spider_async(reason="shutdown") await self.signals.send_catch_log_async(signal=signals.engine_stopped) if self._closewait: self._closewait.callback(None) def close(self) -> Deferred[None]: warnings.warn( "ExecutionEngine.close() is deprecated, use close_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro(self.close_async()) async def close_async(self) -> None: """ Gracefully close the execution engine. If it has already been started, stop it. In all cases, close the spider and the downloader. """ if self.running: await self.stop_async() # will also close spider and downloader elif self.spider is not None: await self.close_spider_async( reason="shutdown" ) # will also close downloader elif hasattr(self, "downloader"): self.downloader.close() def pause(self) -> None: self.paused = True def unpause(self) -> None: self.paused = False async def _process_start_next(self): """Processes the next item or request from Spider.start(). If a request, it is scheduled. If an item, it is sent to item pipelines. """ try: item_or_request = await self._start.__anext__() except StopAsyncIteration: self._start = None except Exception as exception: self._start = None exception_traceback = format_exc() logger.error( f"Error while reading start items and requests: {exception}.\n{exception_traceback}", exc_info=True, ) else: if not self.spider: return # spider already closed if isinstance(item_or_request, Request): self.crawl(item_or_request) else: _schedule_coro( self.scraper.start_itemproc_async(item_or_request, response=None) ) self._slot.nextcall.schedule() async def _start_request_processing(self) -> None: """Starts consuming Spider.start() output and sending scheduled requests.""" # Starts the processing of scheduled requests, as well as a periodic # call to that processing method for scenarios where the scheduler # reports having pending requests but returns none. try: assert self._slot is not None # typing self._slot.nextcall.schedule() self._slot.heartbeat.start(self._SLOT_HEARTBEAT_INTERVAL) while self._start and self.spider: await self._process_start_next() if not self.needs_backout(): # Give room for the outcome of self._process_start_next() to be # processed before continuing with the next iteration. self._slot.nextcall.schedule() await self._slot.nextcall.wait() except (asyncio.exceptions.CancelledError, CancelledError): # self.stop() has cancelled us, nothing to do return except Exception: # an error happened, log it and stop the engine self._start_request_processing_awaitable = None logger.error( "Error while processing requests from start()", exc_info=True, extra={"spider": self.spider}, ) await self.stop_async() def _start_scheduled_requests(self) -> None: if self._slot is None or self._slot.closing is not None or self.paused: return while not self.needs_backout(): if not self._start_scheduled_request(): break if self.spider_is_idle() and self._slot.close_if_idle: self._spider_idle() def needs_backout(self) -> bool: """Returns ``True`` if no more requests can be sent at the moment, or ``False`` otherwise. See :ref:`start-requests-lazy` for an example. """ assert self.scraper.slot is not None # typing return ( not self.running or not self._slot or bool(self._slot.closing) or self.downloader.needs_backout() or self.scraper.slot.needs_backout() ) def _start_scheduled_request(self) -> bool: assert self._slot is not None # typing assert self.spider is not None # typing request = self._slot.scheduler.next_request() if request is None: self.signals.send_catch_log(signals.scheduler_empty) return False d: Deferred[Response | Request] = self._download(request) d.addBoth(self._handle_downloader_output, request) d.addErrback( lambda f: logger.info( "Error while handling downloader output", exc_info=failure_to_exc_info(f), extra={"spider": self.spider}, ) ) def _remove_request(_: Any) -> None: assert self._slot self._slot.remove_request(request) d2: Deferred[None] = d.addBoth(_remove_request) d2.addErrback( lambda f: logger.info( "Error while removing request from slot", exc_info=failure_to_exc_info(f), extra={"spider": self.spider}, ) ) slot = self._slot d2.addBoth(lambda _: slot.nextcall.schedule()) d2.addErrback( lambda f: logger.info( "Error while scheduling new request", exc_info=failure_to_exc_info(f), extra={"spider": self.spider}, ) ) return True @inlineCallbacks def _handle_downloader_output( self, result: Request | Response | Failure, request: Request ) -> Generator[Deferred[Any], Any, None]: if not isinstance(result, (Request, Response, Failure)): raise TypeError( f"Incorrect type: expected Request, Response or Failure, got {type(result)}: {result!r}" ) # downloader middleware can return requests (for example, redirects) if isinstance(result, Request): self.crawl(result) return try: yield self.scraper.enqueue_scrape(result, request) except Exception: assert self.spider is not None logger.error( "Error while enqueuing scrape", exc_info=True, extra={"spider": self.spider}, ) def spider_is_idle(self) -> bool: if self._slot is None: raise RuntimeError("Engine slot not assigned") if not self.scraper.slot.is_idle(): # type: ignore[union-attr] return False if self.downloader.active: # downloader has pending requests return False if self._start is not None: # not all start requests are handled return False return not self._slot.scheduler.has_pending_requests() def crawl(self, request: Request) -> None: """Inject the request into the spider <-> downloader pipeline""" if self.spider is None: raise RuntimeError(f"No open spider to crawl: {request}") self._schedule_request(request) self._slot.nextcall.schedule() # type: ignore[union-attr] def _schedule_request(self, request: Request) -> None: request_scheduled_result = self.signals.send_catch_log( signals.request_scheduled, request=request, spider=self.spider, dont_log=IgnoreRequest, ) for handler, result in request_scheduled_result: if isinstance(result, Failure) and isinstance(result.value, IgnoreRequest): return if not self._slot.scheduler.enqueue_request(request): # type: ignore[union-attr] self.signals.send_catch_log( signals.request_dropped, request=request, spider=self.spider ) def download(self, request: Request) -> Deferred[Response]: """Return a Deferred which fires with a Response as result, only downloader middlewares are applied""" warnings.warn( "ExecutionEngine.download() is deprecated, use download_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro(self.download_async(request)) async def download_async(self, request: Request) -> Response: """Return a coroutine which fires with a Response as result. Only downloader middlewares are applied. .. versionadded:: VERSION """ if self.spider is None: raise RuntimeError(f"No open spider to crawl: {request}") try: response_or_request = await maybe_deferred_to_future( self._download(request) ) finally: assert self._slot is not None self._slot.remove_request(request) if isinstance(response_or_request, Request): return await self.download_async(response_or_request) return response_or_request @inlineCallbacks def _download( self, request: Request ) -> Generator[Deferred[Any], Any, Response | Request]: assert self._slot is not None # typing assert self.spider is not None self._slot.add_request(request) try: result: Response | Request if self._downloader_fetch_needs_spider: result = yield self.downloader.fetch(request, self.spider) else: result = yield self.downloader.fetch(request) if not isinstance(result, (Response, Request)): raise TypeError( f"Incorrect type: expected Response or Request, got {type(result)}: {result!r}" ) if isinstance(result, Response): if result.request is None: result.request = request logkws = self.logformatter.crawled(result.request, result, self.spider) if logkws is not None: logger.log( *logformatter_adapter(logkws), extra={"spider": self.spider} ) self.signals.send_catch_log( signal=signals.response_received, response=result, request=result.request, spider=self.spider, ) return result finally: self._slot.nextcall.schedule() def open_spider(self, spider: Spider, close_if_idle: bool = True) -> Deferred[None]: warnings.warn( "ExecutionEngine.open_spider() is deprecated, use open_spider_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro(self.open_spider_async(close_if_idle=close_if_idle)) async def open_spider_async(self, *, close_if_idle: bool = True) -> None: assert self.crawler.spider if self._slot is not None: raise RuntimeError( f"No free spider slot when opening {self.crawler.spider.name!r}" ) logger.info("Spider opened", extra={"spider": self.crawler.spider}) self.spider = self.crawler.spider nextcall = CallLaterOnce(self._start_scheduled_requests) scheduler = build_from_crawler(self.scheduler_cls, self.crawler) self._slot = _Slot(close_if_idle, nextcall, scheduler) self._start = await self.scraper.spidermw.process_start() if hasattr(scheduler, "open") and (d := scheduler.open(self.crawler.spider)): await maybe_deferred_to_future(d) await self.scraper.open_spider_async() assert self.crawler.stats self.crawler.stats.open_spider() await self.signals.send_catch_log_async( signals.spider_opened, spider=self.crawler.spider ) def _spider_idle(self) -> None: """ Called when a spider gets idle, i.e. when there are no remaining requests to download or schedule. It can be called multiple times. If a handler for the spider_idle signal raises a DontCloseSpider exception, the spider is not closed until the next loop and this function is guaranteed to be called (at least) once again. A handler can raise CloseSpider to provide a custom closing reason. """ assert self.spider is not None # typing expected_ex = (DontCloseSpider, CloseSpider) res = self.signals.send_catch_log( signals.spider_idle, spider=self.spider, dont_log=expected_ex ) detected_ex = { ex: x.value for _, x in res for ex in expected_ex if isinstance(x, Failure) and isinstance(x.value, ex) } if DontCloseSpider in detected_ex: return if self.spider_is_idle(): ex = detected_ex.get(CloseSpider, CloseSpider(reason="finished")) assert isinstance(ex, CloseSpider) # typing _schedule_coro(self.close_spider_async(reason=ex.reason)) def close_spider(self, spider: Spider, reason: str = "cancelled") -> Deferred[None]: warnings.warn( "ExecutionEngine.close_spider() is deprecated, use close_spider_async() instead", ScrapyDeprecationWarning, stacklevel=2, ) return deferred_from_coro(self.close_spider_async(reason=reason)) async def close_spider_async(self, *, reason: str = "cancelled") -> None: """Close (cancel) spider and clear all its outstanding requests. .. versionadded:: VERSION """ if self.spider is None: raise RuntimeError("Spider not opened") if self._slot is None: raise RuntimeError("Engine slot not assigned") if self._slot.closing is not None: await maybe_deferred_to_future(self._slot.closing) return spider = self.spider logger.info( "Closing spider (%(reason)s)", {"reason": reason}, extra={"spider": spider} ) def log_failure(msg: str) -> None: logger.error(msg, exc_info=True, extra={"spider": spider}) # noqa: LOG014 try: await self._slot.close() except Exception: log_failure("Slot close failure") try: self.downloader.close() except Exception: log_failure("Downloader close failure") try: await self.scraper.close_spider_async() except Exception: log_failure("Scraper close failure") if hasattr(self._slot.scheduler, "close"): try: if (d := self._slot.scheduler.close(reason)) is not None: await maybe_deferred_to_future(d) except Exception: log_failure("Scheduler close failure") try: await self.signals.send_catch_log_async( signal=signals.spider_closed, spider=spider, reason=reason, ) except Exception: log_failure("Error while sending spider_close signal") assert self.crawler.stats try: self.crawler.stats.close_spider(reason=reason) except Exception: log_failure("Stats close failure") logger.info( "Spider closed (%(reason)s)", {"reason": reason}, extra={"spider": spider}, ) self._slot = None self.spider = None try: await ensure_awaitable(self._spider_closed_callback(spider)) except Exception: log_failure("Error running spider_closed_callback")
ExecutionEngine
python
aio-libs__aiohttp
aiohttp/client_exceptions.py
{ "start": 3308, "end": 3399 }
class ____(ClientError): """Base class for client socket errors."""
ClientConnectionError
python
huggingface__transformers
src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py
{ "start": 115485, "end": 120552 }
class ____(BigBirdPegasusPreTrainedModel): def __init__(self, config): super().__init__(config) config.num_labels = 2 self.num_labels = config.num_labels self.model = BigBirdPegasusModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, encoder_outputs: Optional[list[torch.FloatTensor]] = None, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[tuple, Seq2SeqQuestionAnsweringModelOutput]: r""" decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Provide for translation and summarization training. By default, the model will create this tensor by shifting the `input_ids` to the right, following the paper. decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. If you want to change padding behavior, you should read [`modeling_bigbird_pegasus._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more information on the default strategy. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if start_positions is not None and end_positions is not None: use_cache = False outputs = self.model( input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, decoder_attention_mask=decoder_attention_mask, encoder_outputs=encoder_outputs, inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = ( start_logits, end_logits, ) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return Seq2SeqQuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) # Copied from transformers.models.pegasus.modeling_pegasus.PegasusDecoderWrapper with Pegasus->BigBirdPegasus
BigBirdPegasusForQuestionAnswering
python
sympy__sympy
sympy/core/exprtools.py
{ "start": 26677, "end": 51352 }
class ____: """Efficient representation of ``coeff*(numer/denom)``. """ __slots__ = ('coeff', 'numer', 'denom') def __init__(self, term, numer=None, denom=None): # Term if numer is None and denom is None: if not term.is_commutative: raise NonCommutativeExpression( 'commutative expression expected') coeff, factors = term.as_coeff_mul() numer, denom = defaultdict(int), defaultdict(int) for factor in factors: base, exp = decompose_power(factor) if base.is_Add: cont, base = base.primitive() coeff *= cont**exp if exp > 0: numer[base] += exp else: denom[base] += -exp numer = Factors(numer) denom = Factors(denom) else: coeff = term if numer is None: numer = Factors() if denom is None: denom = Factors() self.coeff = coeff self.numer = numer self.denom = denom def __hash__(self): # Term return hash((self.coeff, self.numer, self.denom)) def __repr__(self): # Term return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom) def as_expr(self): # Term return self.coeff*(self.numer.as_expr()/self.denom.as_expr()) def mul(self, other): # Term coeff = self.coeff*other.coeff numer = self.numer.mul(other.numer) denom = self.denom.mul(other.denom) numer, denom = numer.normal(denom) return Term(coeff, numer, denom) def inv(self): # Term return Term(1/self.coeff, self.denom, self.numer) def quo(self, other): # Term return self.mul(other.inv()) def pow(self, other): # Term if other < 0: return self.inv().pow(-other) else: return Term(self.coeff ** other, self.numer.pow(other), self.denom.pow(other)) def gcd(self, other): # Term return Term(self.coeff.gcd(other.coeff), self.numer.gcd(other.numer), self.denom.gcd(other.denom)) def lcm(self, other): # Term return Term(self.coeff.lcm(other.coeff), self.numer.lcm(other.numer), self.denom.lcm(other.denom)) def __mul__(self, other): # Term if isinstance(other, Term): return self.mul(other) else: return NotImplemented def __truediv__(self, other): # Term if isinstance(other, Term): return self.quo(other) else: return NotImplemented def __pow__(self, other): # Term if isinstance(other, SYMPY_INTS): return self.pow(other) else: return NotImplemented def __eq__(self, other): # Term return (self.coeff == other.coeff and self.numer == other.numer and self.denom == other.denom) def __ne__(self, other): # Term return not self == other def _gcd_terms(terms, isprimitive=False, fraction=True): """Helper function for :func:`gcd_terms`. Parameters ========== isprimitive : boolean, optional If ``isprimitive`` is True then the call to primitive for an Add will be skipped. This is useful when the content has already been extracted. fraction : boolean, optional If ``fraction`` is True then the expression will appear over a common denominator, the lcm of all term denominators. """ if isinstance(terms, Basic) and not isinstance(terms, Tuple): terms = Add.make_args(terms) terms = list(map(Term, [t for t in terms if t])) # there is some simplification that may happen if we leave this # here rather than duplicate it before the mapping of Term onto # the terms if len(terms) == 0: return S.Zero, S.Zero, S.One if len(terms) == 1: cont = terms[0].coeff numer = terms[0].numer.as_expr() denom = terms[0].denom.as_expr() else: cont = terms[0] for term in terms[1:]: cont = cont.gcd(term) for i, term in enumerate(terms): terms[i] = term.quo(cont) if fraction: denom = terms[0].denom for term in terms[1:]: denom = denom.lcm(term.denom) numers = [] for term in terms: numer = term.numer.mul(denom.quo(term.denom)) numers.append(term.coeff*numer.as_expr()) else: numers = [t.as_expr() for t in terms] denom = Term(S.One).numer cont = cont.as_expr() numer = Add(*numers) denom = denom.as_expr() if not isprimitive and numer.is_Add: _cont, numer = numer.primitive() cont *= _cont return cont, numer, denom def gcd_terms(terms, isprimitive=False, clear=True, fraction=True): """Compute the GCD of ``terms`` and put them together. Parameters ========== terms : Expr Can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum. isprimitive : bool, optional If ``isprimitive`` is True the _gcd_terms will not run the primitive method on the terms. clear : bool, optional It controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1. fraction : bool, optional When True (default), will put the expression over a common denominator. Examples ======== >>> from sympy import gcd_terms >>> from sympy.abc import x, y >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x >>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False) (x**2/2 + 1)/(x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False) (x/2 + 1/x)/y The ``clear`` flag was ignored in this case because the returned expression was a rational expression, not a simple sum. See Also ======== factor_terms, sympy.polys.polytools.terms_gcd """ def mask(terms): """replace nc portions of each term with a unique Dummy symbols and return the replacements to restore them""" args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms] reps = [] for i, (c, nc) in enumerate(args): if nc: nc = Mul(*nc) d = Dummy() reps.append((d, nc)) c.append(d) args[i] = Mul(*c) else: args[i] = c return args, dict(reps) isadd = isinstance(terms, Add) addlike = isadd or not isinstance(terms, Basic) and \ is_sequence(terms, include=set) and \ not isinstance(terms, Dict) if addlike: if isadd: # i.e. an Add terms = list(terms.args) else: terms = sympify(terms) terms, reps = mask(terms) cont, numer, denom = _gcd_terms(terms, isprimitive, fraction) numer = numer.xreplace(reps) coeff, factors = cont.as_coeff_Mul() if not clear: c, _coeff = coeff.as_coeff_Mul() if not c.is_Integer and not clear and numer.is_Add: n, d = c.as_numer_denom() _numer = numer/d if any(a.as_coeff_Mul()[0].is_Integer for a in _numer.args): numer = _numer coeff = n*_coeff return _keep_coeff(coeff, factors*numer/denom, clear=clear) if not isinstance(terms, Basic): return terms if terms.is_Atom: return terms if terms.is_Mul: c, args = terms.as_coeff_mul() return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction) for i in args]), clear=clear) def handle(a): # don't treat internal args like terms of an Add if not isinstance(a, Expr): if isinstance(a, Basic): if not a.args: return a return a.func(*[handle(i) for i in a.args]) return type(a)([handle(i) for i in a]) return gcd_terms(a, isprimitive, clear, fraction) if isinstance(terms, Dict): return Dict(*[(k, handle(v)) for k, v in terms.args]) return terms.func(*[handle(i) for i in terms.args]) def _factor_sum_int(expr, **kwargs): """Return Sum or Integral object with factors that are not in the wrt variables removed. In cases where there are additive terms in the function of the object that are independent, the object will be separated into two objects. Examples ======== >>> from sympy import Sum, factor_terms >>> from sympy.abc import x, y >>> factor_terms(Sum(x + y, (x, 1, 3))) y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3)) >>> factor_terms(Sum(x*y, (x, 1, 3))) y*Sum(x, (x, 1, 3)) Notes ===== If a function in the summand or integrand is replaced with a symbol, then this simplification should not be done or else an incorrect result will be obtained when the symbol is replaced with an expression that depends on the variables of summation/integration: >>> eq = Sum(y, (x, 1, 3)) >>> factor_terms(eq).subs(y, x).doit() 3*x >>> eq.subs(y, x).doit() 6 """ result = expr.function if result == 0: return S.Zero limits = expr.limits # get the wrt variables wrt = {i.args[0] for i in limits} # factor out any common terms that are independent of wrt f = factor_terms(result, **kwargs) i, d = f.as_independent(*wrt) if isinstance(f, Add): return i * expr.func(1, *limits) + expr.func(d, *limits) else: return i * expr.func(d, *limits) def factor_terms(expr: Expr | complex, radical=False, clear=False, fraction=False, sign=True) -> Expr: """Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed. Parameters ========== radical: bool, optional If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr. clear : bool, optional If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients. fraction : bool, optional If fraction=True (default is False) then a common denominator will be constructed for the expression. sign : bool, optional If sign=True (default) then even if the only factor in common is a -1, it will be factored out of the expression. Examples ======== >>> from sympy import factor_terms, Symbol >>> from sympy.abc import x, y >>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A) When ``clear`` is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions: >>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2 If a -1 is all that can be factored out, to *not* factor it out, the flag ``sign`` must be False: >>> factor_terms(-x - y) -(x + y) >>> factor_terms(-x - y, sign=False) -x - y >>> factor_terms(-2*x - 2*y, sign=False) -2*(x + y) See Also ======== gcd_terms, sympy.polys.polytools.terms_gcd """ def do(expr): from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral is_iterable = iterable(expr) if not isinstance(expr, Basic) or expr.is_Atom: if is_iterable: return type(expr)([do(i) for i in expr]) return expr if expr.is_Pow or expr.is_Function or \ is_iterable or not hasattr(expr, 'args_cnc'): args = expr.args newargs = tuple([do(i) for i in args]) if newargs == args: return expr return expr.func(*newargs) if isinstance(expr, (Sum, Integral)): return _factor_sum_int(expr, radical=radical, clear=clear, fraction=fraction, sign=sign) cont, p = expr.as_content_primitive(radical=radical, clear=clear) if p.is_Add: list_args = [do(a) for a in Add.make_args(p)] # get a common negative (if there) which gcd_terms does not remove if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None for a in list_args): cont = -cont list_args = [-a for a in list_args] # watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2) special = {} for i, a in enumerate(list_args): b, e = a.as_base_exp() if e.is_Mul and e != Mul(*e.args): list_args[i] = Dummy() special[list_args[i]] = a # rebuild p not worrying about the order which gcd_terms will fix p = Add._from_args(list_args) p = gcd_terms(p, isprimitive=True, clear=clear, fraction=fraction).xreplace(special) elif p.args: p = p.func( *[do(a) for a in p.args]) rv = _keep_coeff(cont, p, clear=clear, sign=sign) return rv expr2 = sympify(expr) return do(expr2) def _mask_nc(eq, name=None): """ Return ``eq`` with non-commutative objects replaced with Dummy symbols. A dictionary that can be used to restore the original values is returned: if it is None, the expression is noncommutative and cannot be made commutative. The third value returned is a list of any non-commutative symbols that appear in the returned equation. Explanation =========== All non-commutative objects other than Symbols are replaced with a non-commutative Symbol. Identical objects will be identified by identical symbols. If there is only 1 non-commutative object in an expression it will be replaced with a commutative symbol. Otherwise, the non-commutative entities are retained and the calling routine should handle replacements in this case since some care must be taken to keep track of the ordering of symbols when they occur within Muls. Parameters ========== name : str ``name``, if given, is the name that will be used with numbered Dummy variables that will replace the non-commutative objects and is mainly used for doctesting purposes. Examples ======== >>> from sympy.physics.secondquant import Commutator, NO, F, Fd >>> from sympy import symbols >>> from sympy.core.exprtools import _mask_nc >>> from sympy.abc import x, y >>> A, B, C = symbols('A,B,C', commutative=False) One nc-symbol: >>> _mask_nc(A**2 - x**2, 'd') (_d0**2 - x**2, {_d0: A}, []) Multiple nc-symbols: >>> _mask_nc(A**2 - B**2, 'd') (A**2 - B**2, {}, [A, B]) An nc-object with nc-symbols but no others outside of it: >>> _mask_nc(1 + x*Commutator(A, B), 'd') (_d0*x + 1, {_d0: Commutator(A, B)}, []) >>> _mask_nc(NO(Fd(x)*F(y)), 'd') (_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, []) Multiple nc-objects: >>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B) >>> _mask_nc(eq, 'd') (x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1]) Multiple nc-objects and nc-symbols: >>> eq = A*Commutator(A, B) + B*Commutator(A, C) >>> _mask_nc(eq, 'd') (A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B]) """ name = name or 'mask' # Make Dummy() append sequential numbers to the name def numbered_names(): i = 0 while True: yield name + str(i) i += 1 names = numbered_names() def Dummy(*args, **kwargs): from .symbol import Dummy return Dummy(next(names), *args, **kwargs) expr = eq if expr.is_commutative: return eq, {}, [] # identify nc-objects; symbols and other rep = [] nc_obj = set() nc_syms = set() pot = preorder_traversal(expr, keys=default_sort_key) for a in pot: if any(a == r[0] for r in rep): pot.skip() elif not a.is_commutative: if a.is_symbol: nc_syms.add(a) pot.skip() elif not (a.is_Add or a.is_Mul or a.is_Pow): nc_obj.add(a) pot.skip() # If there is only one nc symbol or object, it can be factored regularly # but polys is going to complain, so replace it with a Dummy. if len(nc_obj) == 1 and not nc_syms: rep.append((nc_obj.pop(), Dummy())) elif len(nc_syms) == 1 and not nc_obj: rep.append((nc_syms.pop(), Dummy())) # Any remaining nc-objects will be replaced with an nc-Dummy and # identified as an nc-Symbol to watch out for nc_obj = sorted(nc_obj, key=default_sort_key) for n in nc_obj: nc = Dummy(commutative=False) rep.append((n, nc)) nc_syms.add(nc) expr = expr.subs(rep) nc_syms = list(nc_syms) nc_syms.sort(key=default_sort_key) return expr, {v: k for k, v in rep}, nc_syms def factor_nc(expr): """Return the factored form of ``expr`` while handling non-commutative expressions. Examples ======== >>> from sympy import factor_nc, Symbol >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> B = Symbol('B', commutative=False) >>> factor_nc((x**2 + 2*A*x + A**2).expand()) (x + A)**2 >>> factor_nc(((x + A)*(x + B)).expand()) (x + A)*(x + B) """ expr = sympify(expr) if not isinstance(expr, Expr) or not expr.args: return expr if not expr.is_Add: return expr.func(*[factor_nc(a) for a in expr.args]) expr = expr.func(*[expand_power_exp(i) for i in expr.args]) from sympy.polys.polytools import gcd, factor expr, rep, nc_symbols = _mask_nc(expr) if rep: return factor(expr).subs(rep) else: args = [a.args_cnc() for a in Add.make_args(expr)] c = g = l = r = S.One hit = False # find any commutative gcd term for i, a in enumerate(args): if i == 0: c = Mul._from_args(a[0]) elif a[0]: c = gcd(c, Mul._from_args(a[0])) else: c = S.One if c is not S.One: hit = True c, g = c.as_coeff_Mul() if g is not S.One: for i, (cc, _) in enumerate(args): cc = list(Mul.make_args(Mul._from_args(list(cc))/g)) args[i][0] = cc for i, (cc, _) in enumerate(args): if cc: cc[0] = cc[0]/c else: cc = [1/c] args[i][0] = cc # find any noncommutative common prefix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_prefix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][0].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][0].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True l = b**e il = b**-e for _ in args: _[1][0] = il*_[1][0] break if not ok: break else: hit = True lenn = len(n) l = Mul(*n) for _ in args: _[1] = _[1][lenn:] # find any noncommutative common suffix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_suffix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][-1].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][-1].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True r = b**e il = b**-e for _ in args: _[1][-1] = _[1][-1]*il break if not ok: break else: hit = True lenn = len(n) r = Mul(*n) for _ in args: _[1] = _[1][:len(_[1]) - lenn] if hit: mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args]) else: mid = expr from sympy.simplify.powsimp import powsimp # sort the symbols so the Dummys would appear in the same # order as the original symbols, otherwise you may introduce # a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2 # and the former factors into two terms, (A - B)*(A + B) while the # latter factors into 3 terms, (-1)*(x - y)*(x + y) rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)] unrep1 = [(v, k) for k, v in rep1] unrep1.reverse() new_mid, r2, _ = _mask_nc(mid.subs(rep1)) new_mid = powsimp(factor(new_mid)) new_mid = new_mid.subs(r2).subs(unrep1) if new_mid.is_Pow: return _keep_coeff(c, g*l*new_mid*r) if new_mid.is_Mul: def _pemexpand(expr): "Expand with the minimal set of hints necessary to check the result." return expr.expand(deep=True, mul=True, power_exp=True, power_base=False, basic=False, multinomial=True, log=False) # XXX TODO there should be a way to inspect what order the terms # must be in and just select the plausible ordering without # checking permutations cfac = [] ncfac = [] for f in new_mid.args: if f.is_commutative: cfac.append(f) else: b, e = f.as_base_exp() if e.is_Integer: ncfac.extend([b]*e) else: ncfac.append(f) pre_mid = g*Mul(*cfac)*l target = _pemexpand(expr/c) for s in variations(ncfac, len(ncfac)): ok = pre_mid*Mul(*s)*r if _pemexpand(ok) == target: return _keep_coeff(c, ok) # mid was an Add that didn't factor successfully return _keep_coeff(c, g*l*mid*r)
Term
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 37590, "end": 38838 }
class ____(Base): """SQLAlchemy model of a work queue""" name: Mapped[str] filter: Mapped[Optional[schemas.core.QueueFilter]] = mapped_column( Pydantic(schemas.core.QueueFilter) ) description: Mapped[str] = mapped_column(default="", server_default="") is_paused: Mapped[bool] = mapped_column(server_default="0", default=False) concurrency_limit: Mapped[Optional[int]] priority: Mapped[int] last_polled: Mapped[Optional[DateTime]] status: Mapped[WorkQueueStatus] = mapped_column( sa.Enum(WorkQueueStatus, name="work_queue_status"), default=WorkQueueStatus.NOT_READY, server_default=WorkQueueStatus.NOT_READY, ) work_pool_id: Mapped[uuid.UUID] = mapped_column( sa.ForeignKey("work_pool.id", ondelete="cascade"), index=True ) work_pool: Mapped["WorkPool"] = relationship( lazy="selectin", foreign_keys=[work_pool_id] ) __table_args__: ClassVar[Any] = ( sa.UniqueConstraint("work_pool_id", "name"), sa.Index("ix_work_queue__work_pool_id_priority", "work_pool_id", "priority"), sa.Index("trgm_ix_work_queue_name", "name", postgresql_using="gin").ddl_if( dialect="postgresql" ), )
WorkQueue
python
doocs__leetcode
solution/2700-2799/2784.Check if Array is Good/Solution.py
{ "start": 0, "end": 181 }
class ____: def isGood(self, nums: List[int]) -> bool: cnt = Counter(nums) n = len(nums) - 1 return cnt[n] == 2 and all(cnt[i] for i in range(1, n))
Solution
python
wandb__wandb
wandb/vendor/pygments/formatters/img.py
{ "start": 19455, "end": 19780 }
class ____(ImageFormatter): """ Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code. .. versionadded:: 1.0 """ name = 'img_bmp' aliases = ['bmp', 'bitmap'] filenames = ['*.bmp'] default_image_format = 'bmp'
BmpImageFormatter
python
hynek__structlog
tests/test_threadlocal.py
{ "start": 1649, "end": 3128 }
class ____: def test_bind(self, log): """ tmp_bind does not modify the thread-local state. """ log = log.bind(y=23) with pytest.deprecated_call(), tmp_bind(log, x=42, y="foo") as tmp_log: assert ( {"y": "foo", "x": 42} == tmp_log._context._dict == log._context._dict ) assert {"y": 23} == log._context._dict def test_bind_exc(self, log): """ tmp_bind cleans up properly on exceptions. """ log = log.bind(y=23) with ( # noqa: PT012 pytest.raises(CustomError), pytest.deprecated_call(), tmp_bind(log, x=42, y="foo") as tmp_log, ): assert ( {"y": "foo", "x": 42} == tmp_log._context._dict == log._context._dict ) raise CustomError assert {"y": 23} == log._context._dict def test_tmp_bind_lazy(self): """ tmp_bind works with a BoundLoggerLazyProxy -- i.e. before the first bind. """ with pytest.deprecated_call(): structlog.configure(context_class=wrap_dict(dict)) log = get_logger() assert isinstance(log, BoundLoggerLazyProxy) with pytest.deprecated_call(), tmp_bind(log, x=42) as tmp_log: assert {"x": 42} == tmp_log._context._dict assert {} == log._context
TestTmpBind
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_all_reduce_strategy.py
{ "start": 9369, "end": 9807 }
class ____(type): @classmethod def __instancecheck__(cls, instance): # This is to make isinstance(tf.distribute.MultiWorkerMirroredStrategy(), # tf.distribute.experimental.MultiWorkerMirroredStrategy). Some libraries is # performing such check. return isinstance(instance, CollectiveAllReduceStrategy) @tf_export("distribute.experimental.MultiWorkerMirroredStrategy", v1=[])
_CollectiveAllReduceStrategyExperimentalMeta
python
spack__spack
var/spack/test_repos/spack_repo/duplicates_test/packages/py_setuptools/package.py
{ "start": 216, "end": 552 }
class ____(Package): """Build tool for an extendable package""" homepage = "http://www.example.com" url = "http://www.example.com/tdep-1.0.tar.gz" tags = ["build-tools"] extends("python") version("60", md5="0123456789abcdef0123456789abcdef") version("59", md5="0123456789abcdef0123456789abcdef")
PySetuptools
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 376079, "end": 376744 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateSubscription""" __schema__ = github_schema __field_names__ = ("subscribable_id", "state", "client_mutation_id") subscribable_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subscribableId") """The Node ID of the subscribable object to modify.""" state = sgqlc.types.Field(sgqlc.types.non_null(SubscriptionState), graphql_name="state") """The new state of the subscription.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
UpdateSubscriptionInput
python
apache__airflow
providers/google/tests/unit/google/common/hooks/test_base_google.py
{ "start": 5013, "end": 5391 }
class ____: def __init__(self, project_id): self.mock = mock.Mock() self.fixture_project_id = project_id @hook.GoogleBaseHook.fallback_to_default_project_id def method(self, project_id=None): self.mock(project_id=project_id) @property def project_id(self): return self.fixture_project_id
FallbackToDefaultProjectIdFixtureClass
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 85138, "end": 88479 }
class ____: Py_single_input = 256 Py_file_input = 257 Py_eval_input = 258 def malloc(self, size): chunk = (gdb.parse_and_eval("(void *) malloc((size_t) %d)" % size)) pointer = pointervalue(chunk) if pointer == 0: raise gdb.GdbError("No memory could be allocated in the inferior.") return pointer def alloc_string(self, string): pointer = self.malloc(len(string)) get_selected_inferior().write_memory(pointer, string) return pointer def alloc_pystring(self, string): stringp = self.alloc_string(string) PyString_FromStringAndSize = 'PyString_FromStringAndSize' try: gdb.parse_and_eval(PyString_FromStringAndSize) except RuntimeError: # Python 3 PyString_FromStringAndSize = ('PyUnicode%s_FromStringAndSize' % (get_inferior_unicode_postfix(),)) try: result = gdb.parse_and_eval( '(PyObject *) %s((char *) %d, (size_t) %d)' % ( PyString_FromStringAndSize, stringp, len(string))) finally: self.free(stringp) pointer = pointervalue(result) if pointer == 0: raise gdb.GdbError("Unable to allocate Python string in " "the inferior.") return pointer def free(self, pointer): gdb.parse_and_eval("(void) free((void *) %d)" % pointer) def incref(self, pointer): "Increment the reference count of a Python object in the inferior." gdb.parse_and_eval('Py_IncRef((PyObject *) %d)' % pointer) def xdecref(self, pointer): "Decrement the reference count of a Python object in the inferior." # Py_DecRef is like Py_XDECREF, but a function. So we don't have # to check for NULL. This should also decref all our allocated # Python strings. gdb.parse_and_eval('Py_DecRef((PyObject *) %d)' % pointer) def evalcode(self, code, input_type, global_dict=None, local_dict=None): """ Evaluate python code `code` given as a string in the inferior and return the result as a gdb.Value. Returns a new reference in the inferior. Of course, executing any code in the inferior may be dangerous and may leave the debuggee in an unsafe state or terminate it altogether. """ if '\0' in code: raise gdb.GdbError("String contains NUL byte.") code += '\0' pointer = self.alloc_string(code) globalsp = pointervalue(global_dict) localsp = pointervalue(local_dict) if globalsp == 0 or localsp == 0: raise gdb.GdbError("Unable to obtain or create locals or globals.") code = """ PyRun_String( (char *) %(code)d, (int) %(start)d, (PyObject *) %(globals)s, (PyObject *) %(locals)d) """ % dict(code=pointer, start=input_type, globals=globalsp, locals=localsp) with FetchAndRestoreError(): try: pyobject_return_value = gdb.parse_and_eval(code) finally: self.free(pointer) return pyobject_return_value
PythonCodeExecutor
python
encode__django-rest-framework
rest_framework/generics.py
{ "start": 6926, "end": 7158 }
class ____(mixins.ListModelMixin, GenericAPIView): """ Concrete view for listing a queryset. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs)
ListAPIView
python
getsentry__sentry
tests/sentry/new_migrations/monkey/test_executor.py
{ "start": 470, "end": 636 }
class ____(AppConfig): name = "getsentry" label = "getsentry" verbose_name = "Dummy Getsentry App" path = "/tmp/dummy_getsentry"
DummyGetsentryAppConfig
python
huggingface__transformers
src/transformers/models/squeezebert/modeling_squeezebert.py
{ "start": 5371, "end": 9365 }
class ____(nn.Module): def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1): """ config = used for some things; ignored for others (work in progress...) cin = input channels = output channels groups = number of groups to use in conv1d layers """ super().__init__() if cin % config.num_attention_heads != 0: raise ValueError( f"cin ({cin}) is not a multiple of the number of attention heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(cin / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=q_groups) self.key = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=k_groups) self.value = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=v_groups) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.softmax = nn.Softmax(dim=-1) self.matmul_qk = MatMulWrapper() self.matmul_qkv = MatMulWrapper() def transpose_for_scores(self, x): """ - input: [N, C, W] - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents """ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W] x = x.view(*new_x_shape) return x.permute(0, 1, 3, 2) # [N, C1, C2, W] --> [N, C1, W, C2] def transpose_key_for_scores(self, x): """ - input: [N, C, W] - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents """ new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W] x = x.view(*new_x_shape) # no `permute` needed return x def transpose_output(self, x): """ - input: [N, C1, W, C2] - output: [N, C, W] """ x = x.permute(0, 1, 3, 2).contiguous() # [N, C1, C2, W] new_x_shape = (x.size()[0], self.all_head_size, x.size()[3]) # [N, C, W] x = x.view(*new_x_shape) return x def forward(self, hidden_states, attention_mask, output_attentions): """ expects hidden_states in [N, C, W] data layout. The attention_mask data layout is [N, W], and it does not need to be transposed. """ mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_key_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_score = self.matmul_qk(query_layer, key_layer) attention_score = attention_score / math.sqrt(self.attention_head_size) # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_score = attention_score + attention_mask # Normalize the attention scores to probabilities. attention_probs = self.softmax(attention_score) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = self.matmul_qkv(attention_probs, value_layer) context_layer = self.transpose_output(context_layer) result = {"context_layer": context_layer} if output_attentions: result["attention_score"] = attention_score return result
SqueezeBertSelfAttention
python
PyCQA__pyflakes
pyflakes/checker.py
{ "start": 16897, "end": 16932 }
class ____(Scope): pass
TypeScope
python
optuna__optuna
optuna/storages/_rdb/models.py
{ "start": 3180, "end": 4239 }
class ____(BaseModel): __tablename__ = "study_user_attributes" __table_args__: Any = (UniqueConstraint("study_id", "key"),) study_user_attribute_id = _Column(Integer, primary_key=True) study_id = _Column(Integer, ForeignKey("studies.study_id")) key = _Column(String(MAX_INDEXED_STRING_LENGTH)) value_json = _Column(Text()) study = orm.relationship( StudyModel, backref=orm.backref("user_attributes", cascade="all, delete-orphan") ) @classmethod def find_by_study_and_key( cls, study: StudyModel, key: str, session: orm.Session ) -> "StudyUserAttributeModel" | None: attribute = ( session.query(cls) .filter(cls.study_id == study.study_id) .filter(cls.key == key) .one_or_none() ) return attribute @classmethod def where_study_id( cls, study_id: int, session: orm.Session ) -> list["StudyUserAttributeModel"]: return session.query(cls).filter(cls.study_id == study_id).all()
StudyUserAttributeModel
python
jina-ai__jina
tests/integration/docarray_v2/test_streaming.py
{ "start": 3592, "end": 5519 }
class ____(Executor): @requests(on='/hello') async def task(self, doc: MyDocument, **kwargs) -> MyDocument: for i in range(5): yield MyDocument(text=f'{doc.text} {doc.number + i}') await asyncio.sleep(0.5) @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) @pytest.mark.parametrize('include_gateway', [False, True]) async def test_streaming_delay(protocol, include_gateway): from jina import Deployment port = random_port() with Deployment( uses=WaitStreamExecutor, timeout_ready=-1, protocol=protocol, port=port, include_gateway=include_gateway, ): client = Client(port=port, protocol=protocol, asyncio=True) i = 0 start_time = time.time() async for doc in client.stream_doc( on='/hello', inputs=MyDocument(text='hello world', number=i), return_type=MyDocument, ): assert doc.text == f'hello world {i}' i += 1 # 0.5 seconds between each request + 0.5 seconds tolerance interval assert time.time() - start_time < (0.5 * i) + 0.6 @pytest.mark.asyncio @pytest.mark.parametrize('protocol', ['http', 'grpc']) @pytest.mark.parametrize('endpoint', ['task1', 'task2', 'task3']) async def test_streaming_custom_response_flow_one_executor(protocol, endpoint): port = random_port() with Flow( protocol=protocol, cors=True, port=port, ).add(uses=CustomResponseExecutor): client = Client(port=port, protocol=protocol, cors=True, asyncio=True) i = 0 async for doc in client.stream_doc( on=f'/{endpoint}', inputs=MyDocument(text='hello world', number=5), return_type=OutputDocument, ): assert doc.text == f'hello world 5-{i}-{endpoint}' i += 1
WaitStreamExecutor
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 90476, "end": 92029 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) host_private_ip: Optional[str] = Field( None, description="The private IP address of the host instance." ) instance_id: Optional[str] = Field( None, description=( "Globally unique identifier for the host instance from the cloud provider." ), ) node_aws_attributes: Optional[SparkNodeAwsAttributes] = Field( None, description="Attributes specific to AWS for a Spark node." ) node_id: Optional[str] = Field( None, description="Globally unique identifier for this node." ) private_ip: Optional[str] = Field( None, description=( "Private IP address (typically a 10.x.x.x address) of the Spark node. This" " is different from the private IP address of the host instance." ), ) public_dns: Optional[str] = Field( None, description=( "Public DNS address of this node. This address can be used to access the" " Spark JDBC server on the driver node. To communicate with the JDBC" " server, traffic must be manually authorized by adding security group" " rules to the “worker-unmanaged” security group via the AWS console." ), ) start_timestamp: Optional[int] = Field( None, description="The timestamp (in millisecond) when the Spark node is launched.", )
SparkNode
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 138032, "end": 138504 }
class ____(ColumnDefault): """default generator for a fixed scalar Python value .. versionadded:: 2.0 """ is_scalar = True has_arg = True def __init__(self, arg: Any, for_update: bool = False) -> None: self.for_update = for_update self.arg = arg def _copy(self) -> ScalarElementColumnDefault: return ScalarElementColumnDefault( arg=self.arg, for_update=self.for_update )
ScalarElementColumnDefault
python
django__django
tests/m2m_recursive/models.py
{ "start": 777, "end": 1118 }
class ____(models.Model): name = models.CharField(max_length=20) friends = models.ManyToManyField("self") colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague") idols = models.ManyToManyField("self", symmetrical=False, related_name="stalkers") def __str__(self): return self.name
Person
python
pytorch__pytorch
torch/_dynamo/device_interface.py
{ "start": 17818, "end": 19464 }
class ____(DeviceInterface): # pyrefly: ignore [bad-override] class Event(torch.Event): def __init__(self, enable_timing: bool = True) -> None: self.time = 0.0 def elapsed_time(self, end_event: Any) -> float: return (end_event.time - self.time) * 1000 def record(self, stream: Any = None) -> None: self.time = time.perf_counter() # pyrefly: ignore [bad-override] class Worker: @staticmethod def get_device_properties( device: torch.types.Device = None, ) -> CpuDeviceProperties: import multiprocessing cpu_count = multiprocessing.cpu_count() return CpuDeviceProperties(cpu_count) @staticmethod def is_available() -> bool: return True @staticmethod def is_bf16_supported(including_emulation: bool = False) -> bool: return True @staticmethod def get_compute_capability(device: torch.types.Device = None) -> str: return "" @staticmethod def get_raw_stream(device_idx: Any) -> int: return 0 @staticmethod def current_device() -> int: return 0 @staticmethod def synchronize(device: torch.types.Device = None) -> None: pass @staticmethod def is_triton_capable(device: torch.types.Device = None) -> bool: return True @staticmethod def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: import triton.backends if "cpu" not in triton.backends.backends: raise RuntimeError("triton not built with the 'cpu' backend")
CpuInterface
python
Netflix__metaflow
metaflow/parameters.py
{ "start": 2770, "end": 3214 }
class ____(click.ParamType): name = "JSON" def convert(self, value, param, ctx): if not isinstance(value, strtype): # Already a correct type return value try: return json.loads(value) except: self.fail("%s is not a valid JSON object" % value, param, ctx) def __str__(self): return repr(self) def __repr__(self): return "JSON"
JSONTypeClass
python
Textualize__textual
src/textual/widgets/_button.py
{ "start": 1052, "end": 15330 }
class ____(Widget, can_focus=True): """A simple clickable button. Clicking the button will send a [Button.Pressed][textual.widgets.Button.Pressed] message, unless the `action` parameter is provided. """ ALLOW_SELECT = False DEFAULT_CSS = """ Button { width: auto; min-width: 16; height:auto; line-pad: 1; text-align: center; content-align: center middle; &.-style-flat { text-style: bold; color: auto 90%; background: $surface; border: block $surface; &:hover { background: $primary; border: block $primary; } &:focus { text-style: $button-focus-text-style; } &.-active { background: $surface; border: block $surface; tint: $background 30%; } &:disabled { color: auto 50%; } &.-primary { background: $primary-muted; border: block $primary-muted; color: $text-primary; &:hover { color: $text; background: $primary; border: block $primary; } } &.-success { background: $success-muted; border: block $success-muted; color: $text-success; &:hover { color: $text; background: $success; border: block $success; } } &.-warning { background: $warning-muted; border: block $warning-muted; color: $text-warning; &:hover { color: $text; background: $warning; border: block $warning; } } &.-error { background: $error-muted; border: block $error-muted; color: $text-error; &:hover { color: $text; background: $error; border: block $error; } } } &.-style-default { text-style: bold; color: $button-foreground; background: $surface; border: none; border-top: tall $surface-lighten-1; border-bottom: tall $surface-darken-1; &.-textual-compact { border: none !important; } &:disabled { text-opacity: 0.6; } &:focus { text-style: $button-focus-text-style; background-tint: $foreground 5%; } &:hover { border-top: tall $surface; background: $surface-darken-1; } &.-active { background: $surface; border-bottom: tall $surface-lighten-1; border-top: tall $surface-darken-1; tint: $background 30%; } &.-primary { color: $button-color-foreground; background: $primary; border-top: tall $primary-lighten-3; border-bottom: tall $primary-darken-3; &:hover { background: $primary-darken-2; border-top: tall $primary; } &.-active { background: $primary; border-bottom: tall $primary-lighten-3; border-top: tall $primary-darken-3; } } &.-success { color: $button-color-foreground; background: $success; border-top: tall $success-lighten-2; border-bottom: tall $success-darken-3; &:hover { background: $success-darken-2; border-top: tall $success; } &.-active { background: $success; border-bottom: tall $success-lighten-2; border-top: tall $success-darken-2; } } &.-warning{ color: $button-color-foreground; background: $warning; border-top: tall $warning-lighten-2; border-bottom: tall $warning-darken-3; &:hover { background: $warning-darken-2; border-top: tall $warning; } &.-active { background: $warning; border-bottom: tall $warning-lighten-2; border-top: tall $warning-darken-2; } } &.-error { color: $button-color-foreground; background: $error; border-top: tall $error-lighten-2; border-bottom: tall $error-darken-3; &:hover { background: $error-darken-1; border-top: tall $error; } &.-active { background: $error; border-bottom: tall $error-lighten-2; border-top: tall $error-darken-2; } } } } """ BINDINGS = [Binding("enter", "press", "Press button", show=False)] label: reactive[ContentText] = reactive[ContentText](Content.empty()) """The text label that appears within the button.""" variant = reactive("default", init=False) """The variant name for the button.""" compact = reactive(False, toggle_class="-textual-compact") """Make the button compact (without borders).""" flat = reactive(False) """Enable alternative flat button style.""" class Pressed(Message): """Event sent when a `Button` is pressed and there is no Button action. Can be handled using `on_button_pressed` in a subclass of [`Button`][textual.widgets.Button] or in a parent widget in the DOM. """ def __init__(self, button: Button) -> None: self.button: Button = button """The button that was pressed.""" super().__init__() @property def control(self) -> Button: """An alias for [Pressed.button][textual.widgets.Button.Pressed.button]. This will be the same value as [Pressed.button][textual.widgets.Button.Pressed.button]. """ return self.button def __init__( self, label: ContentText | None = None, variant: ButtonVariant = "default", *, name: str | None = None, id: str | None = None, classes: str | None = None, disabled: bool = False, tooltip: RenderableType | None = None, action: str | None = None, compact: bool = False, flat: bool = False, ): """Create a Button widget. Args: label: The text that appears within the button. variant: The variant of the button. name: The name of the button. id: The ID of the button in the DOM. classes: The CSS classes of the button. disabled: Whether the button is disabled or not. tooltip: Optional tooltip. action: Optional action to run when clicked. compact: Enable compact button style. flat: Enable alternative flat look buttons. """ super().__init__(name=name, id=id, classes=classes, disabled=disabled) if label is None: label = self.css_identifier_styled self.variant = variant self.flat = flat self.compact = compact self.set_reactive(Button.label, Content.from_text(label)) self.action = action self.active_effect_duration = 0.2 """Amount of time in seconds the button 'press' animation lasts.""" if tooltip is not None: self.tooltip = tooltip def get_content_width(self, container: Size, viewport: Size) -> int: assert isinstance(self.label, Content) try: return max([cell_len(line) for line in self.label.plain.splitlines()]) + 2 except ValueError: # Empty string label return 2 def __rich_repr__(self) -> rich.repr.Result: yield from super().__rich_repr__() yield "variant", self.variant, "default" def validate_variant(self, variant: str) -> str: if variant not in _VALID_BUTTON_VARIANTS: raise InvalidButtonVariant( f"Valid button variants are {friendly_list(_VALID_BUTTON_VARIANTS)}" ) return variant def watch_variant(self, old_variant: str, variant: str): self.remove_class(f"-{old_variant}") self.add_class(f"-{variant}") def watch_flat(self, flat: bool) -> None: self.set_class(flat, "-style-flat") self.set_class(not flat, "-style-default") def validate_label(self, label: ContentText) -> Content: """Parse markup for self.label""" return Content.from_text(label) def render(self) -> RenderResult: assert isinstance(self.label, Content) return self.label def post_render( self, renderable: RenderableType, base_style: Style ) -> ConsoleRenderable: return cast(ConsoleRenderable, renderable) async def _on_click(self, event: events.Click) -> None: event.stop() if not self.has_class("-active"): self.press() def press(self) -> Self: """Animate the button and send the [Pressed][textual.widgets.Button.Pressed] message. Can be used to simulate the button being pressed by a user. Returns: The button instance. """ if self.disabled or not self.display: return self # Manage the "active" effect: self._start_active_affect() # ...and let other components know that we've just been clicked: if self.action is None: self.post_message(Button.Pressed(self)) else: self.call_later( self.app.run_action, self.action, default_namespace=self._parent ) return self def _start_active_affect(self) -> None: """Start a small animation to show the button was clicked.""" if self.active_effect_duration > 0: self.add_class("-active") self.set_timer( self.active_effect_duration, partial(self.remove_class, "-active") ) def action_press(self) -> None: """Activate a press of the button.""" if not self.has_class("-active"): self.press() @classmethod def success( cls, label: ContentText | None = None, *, name: str | None = None, id: str | None = None, classes: str | None = None, disabled: bool = False, flat: bool = False, ) -> Button: """Utility constructor for creating a success Button variant. Args: label: The text that appears within the button. name: The name of the button. id: The ID of the button in the DOM. classes: The CSS classes of the button. disabled: Whether the button is disabled or not. flat: Enable alternative flat look buttons. Returns: A [`Button`][textual.widgets.Button] widget of the 'success' [variant][textual.widgets.button.ButtonVariant]. """ return Button( label=label, variant="success", name=name, id=id, classes=classes, disabled=disabled, flat=flat, ) @classmethod def warning( cls, label: ContentText | None = None, *, name: str | None = None, id: str | None = None, classes: str | None = None, disabled: bool = False, flat: bool = False, ) -> Button: """Utility constructor for creating a warning Button variant. Args: label: The text that appears within the button. name: The name of the button. id: The ID of the button in the DOM. classes: The CSS classes of the button. disabled: Whether the button is disabled or not. flat: Enable alternative flat look buttons. Returns: A [`Button`][textual.widgets.Button] widget of the 'warning' [variant][textual.widgets.button.ButtonVariant]. """ return Button( label=label, variant="warning", name=name, id=id, classes=classes, disabled=disabled, flat=flat, ) @classmethod def error( cls, label: ContentText | None = None, *, name: str | None = None, id: str | None = None, classes: str | None = None, disabled: bool = False, flat: bool = False, ) -> Button: """Utility constructor for creating an error Button variant. Args: label: The text that appears within the button. name: The name of the button. id: The ID of the button in the DOM. classes: The CSS classes of the button. disabled: Whether the button is disabled or not. flat: Enable alternative flat look buttons. Returns: A [`Button`][textual.widgets.Button] widget of the 'error' [variant][textual.widgets.button.ButtonVariant]. """ return Button( label=label, variant="error", name=name, id=id, classes=classes, disabled=disabled, flat=flat, )
Button
python
PrefectHQ__prefect
tests/utilities/test_asyncutils.py
{ "start": 3695, "end": 10092 }
class ____: attr = 4 @staticmethod @sync_compatible async def static_method(x, y, z=3): assert SyncCompatibleClass.attr == 4, "Can access class attributes" return x + y + z @classmethod @sync_compatible async def class_method(cls, x, y, z=3): assert cls.attr == 4, "`cls` is sent correctly`" return x + y + z @sync_compatible async def instance_method(self, x, y, z=3): assert self.attr == 4, "`self` is sent correctly" return x + y + z SYNC_COMPAT_TEST_CASES = [ sync_compatible_fn, SyncCompatibleClass.static_method, SyncCompatibleClass.class_method, SyncCompatibleClass().instance_method, ] @pytest.mark.skip( reason="Not supported with new engine", ) @pytest.mark.parametrize("fn", SYNC_COMPAT_TEST_CASES) def test_sync_compatible_call_from_sync(fn): assert fn(1, y=2) == 6 @pytest.mark.parametrize("fn", SYNC_COMPAT_TEST_CASES) async def test_sync_compatible_call_from_async(fn): assert await fn(1, y=2) == 6 async def test_sync_compatible_call_from_sync_in_async_thread(): # Here we are in the async main thread def run_fn(): # Here we are back in a sync context but still in the async main thread return sync_compatible_fn(1, y=2) # Returns a coroutine coro = run_fn() assert await coro == 6 async def test_sync_compatible_call_with_taskgroup(): # Checks for an async caller by inspecting the caller's frame can fail when using # task groups due to internal mechanisms in anyio results = [] @sync_compatible async def sync_compatible_fn(*args, task_status=None): if task_status is not None: task_status.started() result = sum(args) results.append(result) async with anyio.create_task_group() as tg: await tg.start(sync_compatible_fn, 1, 2) tg.start_soon(sync_compatible_fn, 1, 2) assert results == [3, 3] @pytest.mark.skip( reason="Not supported with new engine", ) @pytest.mark.parametrize("fn", SYNC_COMPAT_TEST_CASES) async def test_sync_compatible_call_from_worker(fn): def run_fn(): return fn(1, y=2) assert await run_sync_in_worker_thread(run_fn) == 6 def test_sync_compatible_allows_direct_access_to_async_fn(): async def foo(): pass assert sync_compatible(foo).aio is foo def test_sync_compatible_allows_forced_behavior_sync(): async def foo(): return 42 assert sync_compatible(foo)(_sync=True) == 42 async def test_sync_compatible_allows_forced_behavior_sync_and_async(): async def foo(): return 42 assert sync_compatible(foo)(_sync=True) == 42 assert await sync_compatible(foo)(_sync=False) == 42 assert await sync_compatible(foo)() == 42 def test_sync_compatible_requires_async_function(): with pytest.raises(TypeError, match="must be async"): @sync_compatible def foo(): pass def test_sync_compatible_with_async_context_manager(): with pytest.raises(ValueError, match="Async generators cannot yet be marked"): @sync_compatible @asynccontextmanager async def foo(): yield "bar" def test_add_event_loop_shutdown_callback_is_called_with_asyncio_run(): callback_called = threading.Event() async def set_event(): callback_called.set() async def run_test(): await add_event_loop_shutdown_callback(set_event) thread = threading.Thread(target=asyncio.run(run_test())) thread.start() assert callback_called.wait(timeout=1) thread.join(timeout=1) def test_add_event_loop_shutdown_callback_is_called_with_anyio_run(): callback_called = threading.Event() async def set_event(): callback_called.set() async def run_test(): await add_event_loop_shutdown_callback(set_event) thread = threading.Thread(target=anyio.run(run_test)) thread.start() assert callback_called.wait(timeout=1) thread.join(timeout=1) def test_add_event_loop_shutdown_callback_is_not_called_with_loop_run_until_complete(): callback_called = threading.Event() async def set_event(): # Should not occur in this test callback_called.set() async def run_test(): await add_event_loop_shutdown_callback(set_event) loop = asyncio.new_event_loop() try: thread = threading.Thread(target=loop.run_until_complete(run_test())) thread.start() assert not callback_called.wait(timeout=1) thread.join(timeout=1) finally: loop.close() async def test_gather(): async def foo(i): return i + 1 results = await gather(*[partial(foo, i) for i in range(10)]) assert results == [await foo(i) for i in range(10)] async def test_gather_is_robust_with_return_types_that_break_equality_checks(): """ Some libraries like pandas override the equality operator and can fail if gather performs an __eq__ check with the GatherIncomplete type """ class Foo: def __eq__(self, __o: object) -> bool: raise ValueError() async def foo(): return Foo() results = await gather(*[partial(foo) for _ in range(2)]) assert len(results) == 2 assert all(isinstance(x, Foo) for x in results) async def test_gather_task_group_get_result(): async def foo(): await anyio.sleep(0.1) return 1 async with create_gather_task_group() as tg: k = tg.start_soon(foo) with pytest.raises(GatherIncomplete): tg.get_result(k) assert tg.get_result(k) == 1 async def test_gather_task_group_get_result_bad_uuid(): async with create_gather_task_group() as tg: pass with pytest.raises(KeyError): tg.get_result(uuid.uuid4()) async def test_lazy_semaphore_initialization(): initial_value = 5 lazy_semaphore = LazySemaphore(lambda: initial_value) assert lazy_semaphore._semaphore is None lazy_semaphore._initialize_semaphore() assert lazy_semaphore._semaphore._value == initial_value async with lazy_semaphore as semaphore: assert lazy_semaphore._semaphore is not None assert isinstance(semaphore, asyncio.Semaphore) assert lazy_semaphore._semaphore._value == initial_value - 1 assert lazy_semaphore._semaphore._value == initial_value
SyncCompatibleClass
python
bokeh__bokeh
tests/unit/bokeh/embed/test_notebook__embed.py
{ "start": 1464, "end": 3675 }
class ____(object): @patch('bokeh.embed.notebook.standalone_docs_json_and_render_items') def test_notebook_content(self, mock_sdjari: MagicMock, test_plot: MagicMock) -> None: (docs_json, render_items) = ("DOC_JSON", [RenderItem(docid="foo", elementid="bar")]) mock_sdjari.return_value = (docs_json, render_items) expected_script = DOC_NB_JS.render(docs_json=serialize_json(docs_json), render_items=serialize_json(render_items)) expected_div = PLOT_DIV.render(elementid=render_items[0]['elementid']) (script, div, _) = ben.notebook_content(test_plot) assert script == expected_script assert div == expected_div @patch('bokeh.embed.notebook.standalone_docs_json_and_render_items') def test_notebook_content_with_notebook_comms_target(self, mock_sdjari: MagicMock, test_plot: MagicMock) -> None: (docs_json, render_items) = ("DOC_JSON", [RenderItem(docid="foo", elementid="bar")]) mock_sdjari.return_value = (docs_json, render_items) comms_target = "NOTEBOOK_COMMS_TARGET" ## assert that NOTEBOOK_COMMS_TARGET is added to render_items bundle assert 'notebook_comms_target' not in render_items[0] (script, _, _) = ben.notebook_content(test_plot, notebook_comms_target=comms_target) assert 'notebook_comms_target' in render_items[0] ## assert that NOTEBOOK_COMMS_TARGET ends up in generated script expected_script = DOC_NB_JS.render(docs_json=serialize_json(docs_json), render_items=serialize_json(render_items)) assert script == expected_script """ #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Test_notebook_content
python
astropy__astropy
astropy/utils/masked/tests/test_table.py
{ "start": 820, "end": 1022 }
class ____(MaskedArrayTableSetup): @classmethod def setup_arrays(cls): cls.a = np.array([3.0, 5.0, 0.0]) << u.m cls.mask_a = np.array([True, False, False])
MaskedQuantityTableSetup
python
celery__celery
celery/bin/base.py
{ "start": 7855, "end": 8120 }
class ____(ParamType): """ISO 8601 Date Time argument.""" name = "iso-86091" def convert(self, value, param, ctx): try: return maybe_iso8601(value) except (TypeError, ValueError) as e: self.fail(e)
ISO8601DateTime
python
ApeWorX__ape
src/ape/types/private_mempool.py
{ "start": 3170, "end": 3326 }
class ____(BaseModel): """ A nested bundle request. """ bundle: "Bundle" """ A bundle request of type Bundle """
BundleNestedItem
python
doocs__leetcode
solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/Solution.py
{ "start": 0, "end": 202 }
class ____: def countTriplets(self, nums: List[int]) -> int: cnt = Counter(x & y for x in nums for y in nums) return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0)
Solution
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qconv_test.py
{ "start": 161, "end": 1277 }
class ____(op_bench.TorchBenchmarkBase): # def init(self, N, IC, OC, L, G, kernel, stride, pad): def init(self, IC, OC, kernel, stride, N, L, device): G = 1 pad = 0 self.scale = 1.0 / 255 self.zero_point = 0 X = torch.randn(N, IC, L, dtype=torch.float32) qX = torch.quantize_per_tensor( X, scale=self.scale, zero_point=self.zero_point, dtype=torch.quint8 ) # Convert the tensor to NHWC format W = torch.randn(OC, IC // G, kernel, dtype=torch.float32) self.qW = torch.quantize_per_tensor( W, scale=self.scale, zero_point=0, dtype=torch.qint8 ) self.inputs = {"input": qX} self.qconv1d = nnq.Conv1d(IC, OC, kernel, stride=stride, padding=pad, groups=G) self.qconv1d.set_weight_bias(self.qW, None) self.qconv1d.scale = torch.tensor(self.scale, dtype=torch.double) self.qconv1d.zero_point = torch.tensor(self.zero_point, dtype=torch.int) self.set_module_name("QConv1d") def forward(self, input): return self.qconv1d(input)
QConv1dBenchmark
python
huggingface__transformers
src/transformers/models/dpt/modeling_dpt.py
{ "start": 19487, "end": 20320 }
class ____(nn.Module): def __init__(self, config: DPTConfig): super().__init__() self.config = config self.layer = nn.ModuleList([DPTViTLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, hidden_states: torch.Tensor, output_hidden_states: bool = False) -> BaseModelOutput: all_hidden_states = [hidden_states] if output_hidden_states else None for i, layer_module in enumerate(self.layer): hidden_states = layer_module(hidden_states) if all_hidden_states: all_hidden_states.append(hidden_states) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=tuple(all_hidden_states) if all_hidden_states else None, )
DPTViTEncoder
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 22055, "end": 22139 }
class ____(AutomationCore, ActionBaseModel, extra="forbid"): pass
AutomationUpdate
python
openai__openai-python
src/openai/types/completion_choice.py
{ "start": 244, "end": 466 }
class ____(BaseModel): text_offset: Optional[List[int]] = None token_logprobs: Optional[List[float]] = None tokens: Optional[List[str]] = None top_logprobs: Optional[List[Dict[str, float]]] = None
Logprobs
python
gevent__gevent
src/greentest/3.10/test_httplib.py
{ "start": 57411, "end": 58919 }
class ____(TestCase): PORT = None def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TimeoutTest.PORT = socket_helper.bind_port(self.serv) self.serv.listen() def tearDown(self): self.serv.close() self.serv = None def testTimeoutAttribute(self): # This will prove that the timeout gets through HTTPConnection # and into the socket. # default -- use global socket timeout self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() # no timeout -- do not use global socket default self.assertIsNone(socket.getdefaulttimeout()) socket.setdefaulttimeout(30) try: httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=None) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), None) httpConn.close() # a value httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) httpConn.connect() self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close()
TimeoutTest
python
langchain-ai__langchain
libs/langchain/tests/unit_tests/chains/test_sequential.py
{ "start": 556, "end": 10153 }
class ____(Chain): """Fake Chain for testing purposes.""" input_variables: list[str] output_variables: list[str] @property def input_keys(self) -> list[str]: """Input keys this chain returns.""" return self.input_variables @property def output_keys(self) -> list[str]: """Input keys this chain returns.""" return self.output_variables @override def _call( self, inputs: dict[str, str], run_manager: CallbackManagerForChainRun | None = None, ) -> dict[str, str]: outputs = {} for var in self.output_variables: variables = [inputs[k] for k in self.input_variables] outputs[var] = f"{' '.join(variables)}foo" return outputs @override async def _acall( self, inputs: dict[str, str], run_manager: AsyncCallbackManagerForChainRun | None = None, ) -> dict[str, str]: outputs = {} for var in self.output_variables: variables = [inputs[k] for k in self.input_variables] outputs[var] = f"{' '.join(variables)}foo" return outputs def test_sequential_usage_single_inputs() -> None: """Test sequential on single input chains.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) chain = SequentialChain(chains=[chain_1, chain_2], input_variables=["foo"]) # type: ignore[call-arg] output = chain({"foo": "123"}) expected_output = {"baz": "123foofoo", "foo": "123"} assert output == expected_output def test_sequential_usage_multiple_inputs() -> None: """Test sequential on multiple input chains.""" chain_1 = FakeChain(input_variables=["foo", "test"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar", "foo"], output_variables=["baz"]) chain = SequentialChain(chains=[chain_1, chain_2], input_variables=["foo", "test"]) # type: ignore[call-arg] output = chain({"foo": "123", "test": "456"}) expected_output = { "baz": "123 456foo 123foo", "foo": "123", "test": "456", } assert output == expected_output def test_sequential_usage_memory() -> None: """Test sequential usage with memory.""" memory = SimpleMemory(memories={"zab": "rab"}) chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) chain = SequentialChain( # type: ignore[call-arg] memory=memory, chains=[chain_1, chain_2], input_variables=["foo"], ) output = chain({"foo": "123"}) expected_output = {"baz": "123foofoo", "foo": "123", "zab": "rab"} assert output == expected_output memory = SimpleMemory(memories={"zab": "rab", "foo": "rab"}) chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) with pytest.raises( ValueError, match=re.escape( "Value error, The input key(s) foo are found in the Memory keys" ), ): SequentialChain( # type: ignore[call-arg] memory=memory, chains=[chain_1, chain_2], input_variables=["foo"], ) def test_sequential_internal_chain_use_memory() -> None: """Test sequential usage with memory for one of the internal chains.""" memory = ConversationBufferMemory(memory_key="bla") memory.save_context({"input": "yo"}, {"output": "ya"}) chain_1 = FakeChain( input_variables=["foo", "bla"], output_variables=["bar"], memory=memory, ) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) chain = SequentialChain(chains=[chain_1, chain_2], input_variables=["foo"]) # type: ignore[call-arg] output = chain({"foo": "123"}) print("HEYYY OUTPUT", output) # noqa: T201 expected_output = {"foo": "123", "baz": "123 Human: yo\nAI: yafoofoo"} assert output == expected_output def test_sequential_usage_multiple_outputs() -> None: """Test sequential usage on multiple output chains.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar", "test"]) chain_2 = FakeChain(input_variables=["bar", "foo"], output_variables=["baz"]) chain = SequentialChain(chains=[chain_1, chain_2], input_variables=["foo"]) # type: ignore[call-arg] output = chain({"foo": "123"}) expected_output = { "baz": "123foo 123foo", "foo": "123", } assert output == expected_output def test_sequential_missing_inputs() -> None: """Test error is raised when input variables are missing.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar", "test"], output_variables=["baz"]) with pytest.raises( ValueError, match=re.escape("Value error, Missing required input keys: {'test'}"), ): # Also needs "test" as an input SequentialChain(chains=[chain_1, chain_2], input_variables=["foo"]) # type: ignore[call-arg] def test_sequential_bad_outputs() -> None: """Test error is raised when bad outputs are specified.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) with pytest.raises( ValueError, match=re.escape( "Value error, Expected output variables that were not found: {'test'}." ), ): # "test" is not present as an output variable. SequentialChain( chains=[chain_1, chain_2], input_variables=["foo"], output_variables=["test"], ) def test_sequential_valid_outputs() -> None: """Test chain runs when valid outputs are specified.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) chain = SequentialChain( chains=[chain_1, chain_2], input_variables=["foo"], output_variables=["bar", "baz"], ) output = chain({"foo": "123"}, return_only_outputs=True) expected_output = {"baz": "123foofoo", "bar": "123foo"} assert output == expected_output def test_sequential_overlapping_inputs() -> None: """Test error is raised when input variables are overlapping.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar", "test"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) with pytest.raises( ValueError, match="Value error, Chain returned keys that already exist" ): # "test" is specified as an input, but also is an output of one step SequentialChain(chains=[chain_1, chain_2], input_variables=["foo", "test"]) # type: ignore[call-arg] def test_simple_sequential_functionality() -> None: """Test simple sequential functionality.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) chain = SimpleSequentialChain(chains=[chain_1, chain_2]) output = chain({"input": "123"}) expected_output = {"output": "123foofoo", "input": "123"} assert output == expected_output @pytest.mark.parametrize("is_async", [False, True]) async def test_simple_sequential_functionality_with_callbacks( *, is_async: bool ) -> None: """Test simple sequential functionality.""" handler_1 = FakeCallbackHandler() handler_2 = FakeCallbackHandler() handler_3 = FakeCallbackHandler() chain_1 = FakeChain( input_variables=["foo"], output_variables=["bar"], callbacks=[handler_1], ) chain_2 = FakeChain( input_variables=["bar"], output_variables=["baz"], callbacks=[handler_2], ) chain_3 = FakeChain( input_variables=["jack"], output_variables=["baf"], callbacks=[handler_3], ) chain = SimpleSequentialChain(chains=[chain_1, chain_2, chain_3]) if is_async: output = await chain.ainvoke({"input": "123"}) else: output = chain({"input": "123"}) expected_output = {"output": "123foofoofoo", "input": "123"} assert output == expected_output # Check that each of the callbacks were invoked once per the entire run for handler in [handler_1, handler_2, handler_3]: assert handler.starts == 1 assert handler.ends == 1 assert handler.errors == 0 def test_multi_input_errors() -> None: """Test simple sequential errors if multiple input variables are expected.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar"]) chain_2 = FakeChain(input_variables=["bar", "foo"], output_variables=["baz"]) with pytest.raises( ValueError, match="Value error, Chains used in SimplePipeline should all have one input", ): SimpleSequentialChain(chains=[chain_1, chain_2]) def test_multi_output_errors() -> None: """Test simple sequential errors if multiple output variables are expected.""" chain_1 = FakeChain(input_variables=["foo"], output_variables=["bar", "grok"]) chain_2 = FakeChain(input_variables=["bar"], output_variables=["baz"]) with pytest.raises( ValueError, match="Value error, Chains used in SimplePipeline should all have one output", ): SimpleSequentialChain(chains=[chain_1, chain_2])
FakeChain
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/lexers/pygments.py
{ "start": 1910, "end": 4070 }
class ____(SyntaxSync): """ Synchronize by starting at a line that matches the given regex pattern. """ # Never go more than this amount of lines backwards for synchronization. # That would be too CPU intensive. MAX_BACKWARDS = 500 # Start lexing at the start, if we are in the first 'n' lines and no # synchronization position was found. FROM_START_IF_NO_SYNC_POS_FOUND = 100 def __init__(self, pattern: str) -> None: self._compiled_pattern = re.compile(pattern) def get_sync_start_position( self, document: Document, lineno: int ) -> tuple[int, int]: """ Scan backwards, and find a possible position to start. """ pattern = self._compiled_pattern lines = document.lines # Scan upwards, until we find a point where we can start the syntax # synchronization. for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1): match = pattern.match(lines[i]) if match: return i, match.start() # No synchronization point found. If we aren't that far from the # beginning, start at the very beginning, otherwise, just try to start # at the current line. if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND: return 0, 0 else: return lineno, 0 @classmethod def from_pygments_lexer_cls(cls, lexer_cls: type[PygmentsLexerCls]) -> RegexSync: """ Create a :class:`.RegexSync` instance for this Pygments lexer class. """ patterns = { # For Python, start highlighting at any class/def block. "Python": r"^\s*(class|def)\s+", "Python 3": r"^\s*(class|def)\s+", # For HTML, start at any open/close tag definition. "HTML": r"<[/a-zA-Z]", # For javascript, start at a function. "JavaScript": r"\bfunction\b", # TODO: Add definitions for other languages. # By default, we start at every possible line. } p = patterns.get(lexer_cls.name, "^") return cls(p)
RegexSync
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 38714, "end": 41663 }
class ____(_InverseTrigonometric1D): """ One dimensional ArcCosine returning values between 0 and pi only. Parameters ---------- amplitude : float Oscillation amplitude for corresponding Cosine frequency : float Oscillation frequency for corresponding Cosine phase : float Oscillation phase for corresponding Cosine See Also -------- Cosine1D, ArcSine1D, ArcTangent1D Notes ----- Model formula: .. math:: f(x) = ((arccos(x / A) / 2pi) - p) / f The arccos function being used for this model will only accept inputs in [-A, A]; otherwise, a runtime warning will be thrown and the result will be NaN. To avoid this, the bounding_box has been properly set to accommodate this; therefore, it is recommended that this model always be evaluated with the ``with_bounding_box=True`` option. Examples -------- .. plot:: :include-source: import numpy as np import matplotlib.pyplot as plt from astropy.modeling.models import ArcCosine1D plt.figure() s1 = ArcCosine1D(amplitude=1, frequency=.25) r=np.arange(-1, 1, .01) for amplitude in range(1,4): s1.amplitude = amplitude plt.plot(r, s1(r), color=str(0.25 * amplitude), lw=2) plt.axis([-1, 1, 0, np.pi]) plt.show() """ @staticmethod def evaluate(x, amplitude, frequency, phase): """One dimensional ArcCosine model function.""" # Note: If frequency and x are quantities, they should normally have # inverse units, so that argument ends up being dimensionless. However, # np.sin of a dimensionless quantity will crash, so we remove the # quantity-ness from argument in this case (another option would be to # multiply by * u.rad but this would be slower overall). argument = x / amplitude if isinstance(argument, Quantity): argument = argument.value arc_cos = np.arccos(argument) / TWOPI return (arc_cos - phase) / frequency @staticmethod def fit_deriv(x, amplitude, frequency, phase): """One dimensional ArcCosine model derivative.""" d_amplitude = x / ( TWOPI * frequency * amplitude**2 * np.sqrt(1 - (x / amplitude) ** 2) ) d_frequency = (phase - (np.arccos(x / amplitude) / TWOPI)) / frequency**2 d_phase = -1 / frequency * np.ones(x.shape) return [d_amplitude, d_frequency, d_phase] def bounding_box(self): """ Tuple defining the default ``bounding_box`` limits, ``(x_low, x_high)``. """ return -1 * self.amplitude, 1 * self.amplitude @property def inverse(self): """One dimensional inverse of ArcCosine.""" return Cosine1D( amplitude=self.amplitude, frequency=self.frequency, phase=self.phase )
ArcCosine1D
python
allegroai__clearml
clearml/utilities/pyhocon/converter.py
{ "start": 340, "end": 13100 }
class ____(object): _number_re = r'[+-]?(\d*\.\d+|\d+(\.\d+)?)([eE][+\-]?\d+)?(?=$|[ \t]*([\$\}\],#\n\r]|//))' _number_re_matcher = re.compile(_number_re) @classmethod def to_json(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a JSON output :return: JSON string representation :type return: basestring """ lines = "" if isinstance(config, ConfigTree): if len(config) == 0: lines += '{}' else: lines += '{\n' bet_lines = [] for key, item in config.items(): bet_lines.append('{indent}"{key}": {value}'.format( indent=''.rjust((level + 1) * indent, ' '), key=key.strip('"'), # for dotted keys enclosed with "" to not be interpreted as nested key value=cls.to_json(item, compact, indent, level + 1)) ) lines += ',\n'.join(bet_lines) lines += '\n{indent}}}'.format(indent=''.rjust(level * indent, ' ')) elif isinstance(config, list): if len(config) == 0: lines += '[]' else: lines += '[\n' bet_lines = [] for item in config: bet_lines.append('{indent}{value}'.format( indent=''.rjust((level + 1) * indent, ' '), value=cls.to_json(item, compact, indent, level + 1)) ) lines += ',\n'.join(bet_lines) lines += '\n{indent}]'.format(indent=''.rjust(level * indent, ' ')) elif isinstance(config, basestring): lines = json.dumps(config) elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' elif config is False: lines = 'false' else: lines = str(config) return lines @staticmethod def _auto_indent(lines, section): # noinspection PyBroadException try: indent = len(lines) - lines.rindex('\n') except Exception: indent = len(lines) # noinspection PyBroadException try: section_indent = section.index('\n') except Exception: section_indent = len(section) if section_indent < 3: return lines + section indent = '\n' + ''.rjust(indent, ' ') return lines + indent.join([sec.strip() for sec in section.split('\n')]) # indent = ''.rjust(indent, ' ') # return lines + section.replace('\n', '\n'+indent) @classmethod def to_hocon(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a HOCON output :return: JSON string representation :type return: basestring """ lines = "" if isinstance(config, ConfigTree): if len(config) == 0: lines += '{}' else: if level > 0: # don't display { at root level lines += '{\n' bet_lines = [] for key, item in config.items(): if compact: full_key = key while isinstance(item, ConfigTree) and len(item) == 1: key, item = next(iter(item.items())) full_key += '.' + key else: full_key = key if isinstance(full_key, float) or \ (isinstance(full_key, (basestring, unicode)) and cls._number_re_matcher.match(full_key)): # if key can be casted to float, and it is a string, make sure we quote it full_key = '\"{}\"'.format(full_key) bet_line = ('{indent}{key}{assign_sign} '.format( indent=''.rjust(level * indent, ' '), key=full_key, assign_sign='' if isinstance(item, dict) else ' =',) ) value_line = cls.to_hocon(item, compact, indent, level + 1) if isinstance(item, (list, tuple)): bet_lines.append(cls._auto_indent(bet_line, value_line)) else: bet_lines.append(bet_line + value_line) lines += '\n'.join(bet_lines) if level > 0: # don't display { at root level lines += '\n{indent}}}'.format(indent=''.rjust((level - 1) * indent, ' ')) elif isinstance(config, (list, tuple)): if len(config) == 0: lines += '[]' else: # lines += '[\n' lines += '[' bet_lines = [] base_len = len(lines) skip_comma = False for i, item in enumerate(config): if 0 < i and not skip_comma: # if not isinstance(item, (str, int, float)): # lines += ',\n{indent}'.format(indent=''.rjust(level * indent, ' ')) # else: # lines += ', ' lines += ', ' skip_comma = False new_line = cls.to_hocon(item, compact, indent, level + 1) lines += new_line if '\n' in new_line or len(lines) - base_len > 80: if i < len(config) - 1: lines += ',\n{indent}'.format(indent=''.rjust(level * indent, ' ')) base_len = len(lines) skip_comma = True # bet_lines.append('{value}'.format(value=cls.to_hocon(item, compact, indent, level + 1))) # lines += '\n'.join(bet_lines) # lines += ', '.join(bet_lines) # lines += '\n{indent}]'.format(indent=''.rjust((level - 1) * indent, ' ')) lines += ']' elif isinstance(config, basestring): if '\n' in config and len(config) > 1: lines = '"""{value}"""'.format(value=config) # multilines else: lines = '"{value}"'.format(value=cls.__escape_string(config)) elif isinstance(config, ConfigValues): lines = ''.join(cls.to_hocon(o, compact, indent, level) for o in config.tokens) elif isinstance(config, ConfigSubstitution): lines = '${' if config.optional: lines += '?' lines += config.variable + '}' + config.ws elif isinstance(config, ConfigQuotedString): if '\n' in config.value and len(config.value) > 1: lines = '"""{value}"""'.format(value=config.value) # multilines else: lines = '"{value}"'.format(value=cls.__escape_string(config.value)) elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' elif config is False: lines = 'false' else: lines = str(config) return lines @classmethod def to_yaml(cls, config, compact=False, indent=2, level=0): """Convert HOCON input into a YAML output :return: YAML string representation :type return: basestring """ lines = "" if isinstance(config, ConfigTree): if len(config) > 0: if level > 0: lines += '\n' bet_lines = [] for key, item in config.items(): bet_lines.append('{indent}{key}: {value}'.format( indent=''.rjust(level * indent, ' '), key=key.strip('"'), # for dotted keys enclosed with "" to not be interpreted as nested key, value=cls.to_yaml(item, compact, indent, level + 1)) ) lines += '\n'.join(bet_lines) elif isinstance(config, list): config_list = [line for line in config if line is not None] if len(config_list) == 0: lines += '[]' else: lines += '\n' bet_lines = [] for item in config_list: bet_lines.append('{indent}- {value}'.format(indent=''.rjust(level * indent, ' '), value=cls.to_yaml(item, compact, indent, level + 1))) lines += '\n'.join(bet_lines) elif isinstance(config, basestring): # if it contains a \n then it's multiline lines = config.split('\n') if len(lines) == 1: lines = config else: lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines]) elif config is None or isinstance(config, NoneValue): lines = 'null' elif config is True: lines = 'true' elif config is False: lines = 'false' else: lines = str(config) return lines @classmethod def to_properties(cls, config, compact=False, indent=2, key_stack=[]): """Convert HOCON input into a .properties output :return: .properties string representation :type return: basestring :return: """ def escape_value(value): return value.replace('=', '\\=').replace('!', '\\!').replace('#', '\\#').replace('\n', '\\\n') stripped_key_stack = [key.strip('"') for key in key_stack] lines = [] if isinstance(config, ConfigTree): for key, item in config.items(): if item is not None: lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [key])) elif isinstance(config, list): for index, item in enumerate(config): if item is not None: lines.append(cls.to_properties(item, compact, indent, stripped_key_stack + [str(index)])) elif isinstance(config, basestring): lines.append('.'.join(stripped_key_stack) + ' = ' + escape_value(config)) elif config is True: lines.append('.'.join(stripped_key_stack) + ' = true') elif config is False: lines.append('.'.join(stripped_key_stack) + ' = false') elif config is None or isinstance(config, NoneValue): pass else: lines.append('.'.join(stripped_key_stack) + ' = ' + str(config)) return '\n'.join([line for line in lines if len(line) > 0]) @classmethod def convert(cls, config, output_format='json', indent=2, compact=False): converters = { 'json': cls.to_json, 'properties': cls.to_properties, 'yaml': cls.to_yaml, 'hocon': cls.to_hocon, } if output_format in converters: return converters[output_format](config, compact, indent) else: raise Exception("Invalid format '{format}'. Format must be 'json', 'properties', 'yaml' or 'hocon'".format( format=output_format)) @classmethod def convert_from_file(cls, input_file=None, output_file=None, output_format='json', indent=2, compact=False): """Convert to json, properties or yaml :param input_file: input file, if not specified stdin :param output_file: output file, if not specified stdout :param output_format: json, properties or yaml :return: json, properties or yaml string representation """ if input_file is None: content = sys.stdin.read() config = ConfigFactory.parse_string(content) else: config = ConfigFactory.parse_file(input_file) res = cls.convert(config, output_format, indent, compact) if output_file is None: print(res) else: with open(output_file, "w") as fd: fd.write(res) @classmethod def __escape_match(cls, match): char = match.group(0) return { '\b': r'\b', '\t': r'\t', '\n': r'\n', '\f': r'\f', '\r': r'\r', '"': r'\"', '\\': r'\\', }.get(char) or (r'\u%04x' % ord(char)) @classmethod def __escape_string(cls, string): return re.sub(r'[\x00-\x1F"\\]', cls.__escape_match, string)
HOCONConverter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/slice_generators.py
{ "start": 444, "end": 810 }
class ____: """ Base class for slice generators. """ _start_date: DateTime = None _end_data: DateTime = None def __init__(self, start_date: DateTime, end_date: Optional[DateTime] = None): self._start_date = start_date self._end_date = end_date or pendulum.now("UTC") def __iter__(self): return self
SliceGenerator
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py
{ "start": 8176, "end": 10125 }
class ____(BaseTrigger): """ RedshiftClusterTrigger is fired as deferred class with params to run the task in trigger worker. :param aws_conn_id: Reference to AWS connection id for redshift :param cluster_identifier: unique identifier of a cluster :param target_status: Reference to the status which needs to be checked :param poke_interval: polling period in seconds to check for the status """ def __init__( self, aws_conn_id: str | None, cluster_identifier: str, target_status: str, poke_interval: float, ): super().__init__() self.aws_conn_id = aws_conn_id self.cluster_identifier = cluster_identifier self.target_status = target_status self.poke_interval = poke_interval def serialize(self) -> tuple[str, dict[str, Any]]: """Serialize RedshiftClusterTrigger arguments and classpath.""" return ( "airflow.providers.amazon.aws.triggers.redshift_cluster.RedshiftClusterTrigger", { "aws_conn_id": self.aws_conn_id, "cluster_identifier": self.cluster_identifier, "target_status": self.target_status, "poke_interval": self.poke_interval, }, ) async def run(self) -> AsyncIterator[TriggerEvent]: """Run async until the cluster status matches the target status.""" try: hook = RedshiftHook(aws_conn_id=self.aws_conn_id) while True: status = await hook.cluster_status_async(self.cluster_identifier) if status == self.target_status: yield TriggerEvent({"status": "success", "message": "target state met"}) return await asyncio.sleep(self.poke_interval) except Exception as e: yield TriggerEvent({"status": "error", "message": str(e)})
RedshiftClusterTrigger
python
geekcomputers__Python
insta_monitering/insta_datafetcher.py
{ "start": 12622, "end": 15836 }
class ____: def __init__(self, user, tags, type, productId): try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) db = self.mon[productId + ":" + user + ":insta"] self._collection = db[tags] except Exception as err: print(f"exception : {err}\n") print("error::DBDataFetcher.init>>", sys.exc_info()[1]) def dbFetcher(self, limit=20): mainlist = [] try: records = self._collection.find().sort("id", -1).limit(limit) for i in records: del i["_id"] mainlist.append(i) except Exception as err: print(f"exception : {err}\n") print("error::dbFetcher>>", sys.exc_info()[1]) finally: return ujson.dumps(mainlist) def DBFetcherGreater(self, limit, date): mainlist = [] postval = {} try: postval["posts"] = None if limit.isdigit() == False and date.isdigit() == False: raise Exception limit = int(limit) date = int(date) if date != 0: doc = ( self._collection.find({"date": {"$gt": date}}) .sort("date", pymongo.ASCENDING) .limit(limit) ) else: doc = ( self._collection.find().sort("date", pymongo.ASCENDING).limit(limit) ) for i in doc: del i["_id"] mainlist.append(i) postval["posts"] = mainlist postval["status"] = True except Exception as err: print(f"exception : {err}\n") print("error::", sys.exc_info()[1]) postval["status"] = False finally: return ujson.dumps(postval) def DBFetcherLess(self, limit, date): mainlist = [] postval = {} try: postval["posts"] = None if limit.isdigit() == False and date.isdigit() == False: raise Exception limit = int(limit) date = int(date) doc = ( self._collection.find({"date": {"$lt": date}}) .limit(limit) .sort("date", pymongo.DESCENDING) ) for i in doc: del i["_id"] mainlist.append(i) postval["posts"] = mainlist[::-1] postval["status"] = True except Exception as err: print(f"error : {err}\n") print("error::", sys.exc_info()[1]) postval["status"] = False finally: return ujson.dumps(postval) def __del__(self): self.mon.close() def main(): try: user = sys.argv[1] tags = sys.argv[2] type = sys.argv[3] productId = sys.argv[4] obj = InstaPorcessClass() obj.startprocess(user=user, tags=tags, type=type, productId=productId) except Exception as err: print(f"exception : {err}") print("error::main>>", sys.exc_info()[1]) if __name__ == "__main__": main()
DBDataFetcher
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 651, "end": 1420 }
class ____(object): """ Base class for all renderers """ def activate(self): pass def __repr__(self): try: init_sig = inspect.signature(self.__init__) init_args = list(init_sig.parameters.keys()) except AttributeError: # Python 2.7 argspec = inspect.getargspec(self.__init__) init_args = [a for a in argspec.args if a != "self"] return "{cls}({attrs})\n{doc}".format( cls=self.__class__.__name__, attrs=", ".join("{}={!r}".format(k, self.__dict__[k]) for k in init_args), doc=self.__doc__, ) def __hash__(self): # Constructor args fully define uniqueness return hash(repr(self))
BaseRenderer
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 51965, "end": 52270 }
class ____(TestOnlySetsInBinaryOps, TestCase): def setUp(self): super().setUp() self.OrderedSet = OrderedSet((1, 2, 3)) self.other = (2, 4, 6) self.otherIsIterable = True # ------------------------------------------------------------------------------
TestOnlySetsTuple
python
ray-project__ray
python/ray/data/_internal/execution/operators/sub_progress.py
{ "start": 72, "end": 806 }
class ____(ABC): """Abstract class for operators that support sub-progress bars""" @abstractmethod def get_sub_progress_bar_names(self) -> Optional[List[str]]: """ Returns list of sub-progress bar names This is used to create the sub-progress bars in the progress manager. Note that sub-progress bars will be created in the order returned by this method. """ ... @abstractmethod def set_sub_progress_bar(self, name, pg): """ Sets sub-progress bars name: name of sub-progress bar pg: SubProgressBar instance (progress_manager.py) """ # Skipping type-checking for circular imports ...
SubProgressBarMixin
python
pennersr__django-allauth
allauth/mfa/totp/views.py
{ "start": 2720, "end": 4515 }
class ____(FormView): form_class = DeactivateTOTPForm template_name = "mfa/totp/deactivate_form." + account_settings.TEMPLATE_EXTENSION success_url = reverse_lazy("mfa_index") def dispatch(self, request, *args, **kwargs): self.authenticator = get_object_or_404( Authenticator, user=self.request.user, type=Authenticator.Type.TOTP, ) if not is_mfa_enabled(request.user, [Authenticator.Type.TOTP]): return HttpResponseRedirect(reverse("mfa_activate_totp")) return self._dispatch(request, *args, **kwargs) @method_decorator(reauthentication_required) def _dispatch(self, request, *args, **kwargs): """There's no point to reauthenticate when MFA is not enabled, so the `is_mfa_enabled` check needs to go first, which is why we cannot slap a `reauthentication_required` decorator on the `dispatch` directly. """ return super().dispatch(request, *args, **kwargs) def get_form_kwargs(self): ret = super().get_form_kwargs() ret["authenticator"] = self.authenticator # The deactivation form does not require input, yet, can generate # validation errors in case deactivation is not allowed. We want to # immediately present such errors even before the user actually posts # the form, which is why we put an empty data payload in here. ret.setdefault("data", {}) return ret def get_form_class(self): return get_form_class(app_settings.FORMS, "deactivate_totp", self.form_class) def form_valid(self, form): flows.deactivate_totp(self.request, self.authenticator) return super().form_valid(form) deactivate_totp = DeactivateTOTPView.as_view()
DeactivateTOTPView
python
apache__airflow
providers/standard/src/airflow/providers/standard/operators/python.py
{ "start": 51481, "end": 53758 }
class ____(BaseBranchOperator, ExternalPythonOperator): """ A workflow can "branch" or follow a path after the execution of this task. Extends ExternalPythonOperator, so expects to get Python: virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path, so it can run on separate virtual environment similarly to ExternalPythonOperator. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:BranchExternalPythonOperator` """ def choose_branch(self, context: Context) -> str | Iterable[str]: return ExternalPythonOperator.execute(self, context) def get_current_context() -> Mapping[str, Any]: """ Retrieve the execution context dictionary without altering user method's signature. This is the simplest method of retrieving the execution context dictionary. **Old style:** .. code:: python def my_task(**context): ti = context["ti"] **New style:** .. code:: python from airflow.providers.standard.operators.python import get_current_context def my_task(): context = get_current_context() ti = context["ti"] Current context will only have value if this method was called after an operator was starting to execute. """ if AIRFLOW_V_3_0_PLUS: warnings.warn( "Using get_current_context from standard provider is deprecated and will be removed." "Please import `from airflow.sdk import get_current_context` and use it instead.", AirflowProviderDeprecationWarning, stacklevel=2, ) from airflow.sdk import get_current_context return get_current_context() return _get_current_context() def _get_current_context() -> Mapping[str, Any]: # Airflow 2.x # TODO: To be removed when Airflow 2 support is dropped from airflow.models.taskinstance import _CURRENT_CONTEXT # type: ignore[attr-defined] if not _CURRENT_CONTEXT: raise RuntimeError( "Current context was requested but no context was found! Are you running within an Airflow task?" ) return _CURRENT_CONTEXT[-1]
BranchExternalPythonOperator
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 25940, "end": 26553 }
class ____(MixinSequenceOfValues): """ Facet labels along the vertical axis Parameters ---------- theme_element : element_text """ _omit = ["margin", "ha", "va"] def apply_figure(self, figure: Figure, targets: ThemeTargets): super().apply_figure(figure, targets) if texts := targets.strip_text_y: self.set(texts) def blank_figure(self, figure: Figure, targets: ThemeTargets): super().blank_figure(figure, targets) if texts := targets.strip_text_y: for text in texts: text.set_visible(False)
strip_text_y
python
openai__openai-python
src/openai/resources/uploads/uploads.py
{ "start": 24876, "end": 25443 }
class ____: def __init__(self, uploads: AsyncUploads) -> None: self._uploads = uploads self.create = async_to_streamed_response_wrapper( uploads.create, ) self.cancel = async_to_streamed_response_wrapper( uploads.cancel, ) self.complete = async_to_streamed_response_wrapper( uploads.complete, ) @cached_property def parts(self) -> AsyncPartsWithStreamingResponse: return AsyncPartsWithStreamingResponse(self._uploads.parts)
AsyncUploadsWithStreamingResponse
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 33534, "end": 35481 }
class ____(rv_discrete): r"""A Boltzmann (Truncated Discrete Exponential) random variable. %(before_notes)s Notes ----- The probability mass function for `boltzmann` is: .. math:: f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N)) for :math:`k = 0,..., N-1`. `boltzmann` takes :math:`\lambda > 0` and :math:`N > 0` as shape parameters. %(after_notes)s %(example)s """ def _shape_info(self): return [_ShapeInfo("lambda_", False, (0, np.inf), (False, False)), _ShapeInfo("N", True, (0, np.inf), (False, False))] def _argcheck(self, lambda_, N): return (lambda_ > 0) & (N > 0) & _isintegral(N) def _get_support(self, lambda_, N): return self.a, N - 1 def _pmf(self, k, lambda_, N): # boltzmann.pmf(k) = # (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N)) fact = (1-exp(-lambda_))/(1-exp(-lambda_*N)) return fact*exp(-lambda_*k) def _cdf(self, x, lambda_, N): k = floor(x) return (1-exp(-lambda_*(k+1)))/(1-exp(-lambda_*N)) def _ppf(self, q, lambda_, N): qnew = q*(1-exp(-lambda_*N)) vals = ceil(-1.0/lambda_ * log(1-qnew)-1) vals1 = (vals-1).clip(0.0, np.inf) temp = self._cdf(vals1, lambda_, N) return np.where(temp >= q, vals1, vals) def _stats(self, lambda_, N): z = exp(-lambda_) zN = exp(-lambda_*N) mu = z/(1.0-z)-N*zN/(1-zN) var = z/(1.0-z)**2 - N*N*zN/(1-zN)**2 trm = (1-zN)/(1-z) trm2 = (z*trm**2 - N*N*zN) g1 = z*(1+z)*trm**3 - N**3*zN*(1+zN) g1 = g1 / trm2**(1.5) g2 = z*(1+4*z+z*z)*trm**4 - N**4 * zN*(1+4*zN+zN*zN) g2 = g2 / trm2 / trm2 return mu, var, g1, g2 boltzmann = boltzmann_gen(name='boltzmann', a=0, longname='A truncated discrete exponential ')
boltzmann_gen
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/win32.py
{ "start": 20476, "end": 24576 }
class ____: """ Similar to `ConsoleInputReader`, but for usage when `ENABLE_VIRTUAL_TERMINAL_INPUT` is enabled. This assumes that Windows sends us the right vt100 escape sequences and we parse those with our vt100 parser. (Using this instead of `ConsoleInputReader` results in the "data" attribute from the `KeyPress` instances to be more correct in edge cases, because this responds to for instance the terminal being in application cursor keys mode.) """ def __init__(self) -> None: self._fdcon = None self._buffer: list[KeyPress] = [] # Buffer to collect the Key objects. self._vt100_parser = Vt100Parser( lambda key_press: self._buffer.append(key_press) ) # When stdin is a tty, use that handle, otherwise, create a handle from # CONIN$. self.handle: HANDLE if sys.stdin.isatty(): self.handle = HANDLE(windll.kernel32.GetStdHandle(STD_INPUT_HANDLE)) else: self._fdcon = os.open("CONIN$", os.O_RDWR | os.O_BINARY) self.handle = HANDLE(msvcrt.get_osfhandle(self._fdcon)) def close(self) -> None: "Close fdcon." if self._fdcon is not None: os.close(self._fdcon) def read(self) -> Iterable[KeyPress]: """ Return a list of `KeyPress` instances. It won't return anything when there was nothing to read. (This function doesn't block.) http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx """ max_count = 2048 # Max events to read at the same time. read = DWORD(0) arrtype = INPUT_RECORD * max_count input_records = arrtype() # Check whether there is some input to read. `ReadConsoleInputW` would # block otherwise. # (Actually, the event loop is responsible to make sure that this # function is only called when there is something to read, but for some # reason this happened in the asyncio_win32 loop, and it's better to be # safe anyway.) if not wait_for_handles([self.handle], timeout=0): return [] # Get next batch of input event. windll.kernel32.ReadConsoleInputW( self.handle, pointer(input_records), max_count, pointer(read) ) # First, get all the keys from the input buffer, in order to determine # whether we should consider this a paste event or not. for key_data in self._get_keys(read, input_records): self._vt100_parser.feed(key_data) # Return result. result = self._buffer self._buffer = [] return result def flush_keys(self) -> list[KeyPress]: """ Flush pending keys and return them. (Used for flushing the 'escape' key.) """ # Flush all pending keys. (This is most important to flush the vt100 # 'Escape' key early when nothing else follows.) self._vt100_parser.flush() # Return result. result = self._buffer self._buffer = [] return result def _get_keys( self, read: DWORD, input_records: Array[INPUT_RECORD] ) -> Iterator[str]: """ Generator that yields `KeyPress` objects from the input records. """ for i in range(read.value): ir = input_records[i] # Get the right EventType from the EVENT_RECORD. # (For some reason the Windows console application 'cmder' # [http://gooseberrycreative.com/cmder/] can return '0' for # ir.EventType. -- Just ignore that.) if ir.EventType in EventTypes: ev = getattr(ir.Event, EventTypes[ir.EventType]) # Process if this is a key event. (We also have mouse, menu and # focus events.) if isinstance(ev, KEY_EVENT_RECORD) and ev.KeyDown: u_char = ev.uChar.UnicodeChar if u_char != "\x00": yield u_char
Vt100ConsoleInputReader
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 33323, "end": 35337 }
class ____(LossFunctionWrapper): """Computes the categorical hinge loss between `y_true` and `y_pred`. `loss = maximum(neg - pos + 1, 0)` where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)` Standalone usage: >>> y_true = [[0, 1], [0, 0]] >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] >>> # Using 'auto'/'sum_over_batch_size' reduction type. >>> h = tf.keras.losses.CategoricalHinge() >>> h(y_true, y_pred).numpy() 1.4 >>> # Calling with 'sample_weight'. >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy() 0.6 >>> # Using 'sum' reduction type. >>> h = tf.keras.losses.CategoricalHinge( ... reduction=tf.keras.losses.Reduction.SUM) >>> h(y_true, y_pred).numpy() 2.8 >>> # Using 'none' reduction type. >>> h = tf.keras.losses.CategoricalHinge( ... reduction=tf.keras.losses.Reduction.NONE) >>> h(y_true, y_pred).numpy() array([1.2, 1.6], dtype=float32) Usage with the `compile()` API: ```python model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalHinge()) ``` """ def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='categorical_hinge'): """Initializes `CategoricalHinge` instance. Args: reduction: Type of `tf.keras.losses.Reduction` to apply to loss. Default value is `AUTO`. `AUTO` indicates that the reduction option will be determined by the usage context. For almost all cases this defaults to `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of built-in training loops such as `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` will raise an error. Please see this custom training [tutorial]( https://www.tensorflow.org/tutorials/distribute/custom_training) for more details. name: Optional name for the instance. Defaults to 'categorical_hinge'. """ super().__init__(categorical_hinge, name=name, reduction=reduction)
CategoricalHinge
python
ethereum__web3.py
web3/types.py
{ "start": 13728, "end": 13885 }
class ____(TypedDict): blockOverrides: NotRequired[BlockData] stateOverrides: NotRequired[StateOverride] calls: Sequence[TxParams]
BlockStateCallV1
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py
{ "start": 2323, "end": 3574 }
class ____(Benchmark): r""" Ackley03 [1]_ objective function. The Ackley03 global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{Ackley03}}(x) = -200 e^{-0.02 \sqrt{x_1^2 + x_2^2}} + 5e^{\cos(3x_1) + \sin(3x_2)} with :math:`x_i \in [-32, 32]` for :math:`i=1, 2`. *Global optimum*: :math:`f(x) = -195.62902825923879` for :math:`x = [-0.68255758, -0.36070859]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO: I think the minus sign is missing in front of the first term in eqn3 in [1]_. This changes the global minimum """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-32.0] * self.N, [32.0] * self.N)) self.global_optimum = [[-0.68255758, -0.36070859]] self.fglob = -195.62902825923879 def fun(self, x, *args): self.nfev += 1 a = -200 * exp(-0.02 * sqrt(x[0] ** 2 + x[1] ** 2)) a += 5 * exp(cos(3 * x[0]) + sin(3 * x[1])) return a
Ackley03
python
getsentry__sentry
tests/sentry/notifications/notification_action/test_metric_alert_registry_handlers.py
{ "start": 10274, "end": 25466 }
class ____(MetricAlertHandlerBase): def setUp(self) -> None: super().setUp() self.action = self.create_action( type=Action.Type.DISCORD, integration_id="1234567890", config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC}, data={"tags": "environment,user,my_tag"}, ) self.handler = TestHandler() def test_missing_occurrence_raises_value_error(self) -> None: self.event_data = WorkflowEventData( event=GroupEvent(self.project.id, "test", self.group, NodeData("test-id")), group=self.group, ) with pytest.raises(ValueError): self.handler.invoke_legacy_registry(self.event_data, self.action, self.detector) def test_get_incident_status(self) -> None: # Initial priority is high -> incident is critical group, _, group_event = self.create_group_event( group_type_id=MetricIssue.type_id, occurrence=self.create_issue_occurrence( priority=PriorityLevel.HIGH.value, level="error", ), ) assert group_event.occurrence is not None assert group_event.occurrence.priority is not None assert ( MetricIssueContext._get_new_status( group, DetectorPriorityLevel(group_event.occurrence.priority) ) == IncidentStatus.CRITICAL ) # Initial priority is medium -> incident is warning group, _, group_event = self.create_group_event( group_type_id=MetricIssue.type_id, occurrence=self.create_issue_occurrence( priority=PriorityLevel.MEDIUM.value, level="warning", ), ) assert group_event.occurrence is not None assert group_event.occurrence.priority is not None assert ( MetricIssueContext._get_new_status( group, DetectorPriorityLevel(group_event.occurrence.priority) ) == IncidentStatus.WARNING ) # Resolved group -> incident is closed group, _, group_event = self.create_group_event( group_type_id=MetricIssue.type_id, occurrence=self.create_issue_occurrence( priority=PriorityLevel.MEDIUM.value, level="warning", ), ) assert group_event.occurrence is not None assert group_event.occurrence.priority is not None # Set the group to resolved -> incident is closed group.status = GroupStatus.RESOLVED assert ( MetricIssueContext._get_new_status( group, DetectorPriorityLevel(group_event.occurrence.priority) ) == IncidentStatus.CLOSED ) def test_build_notification_context(self) -> None: notification_context = self.handler.build_notification_context(self.action) assert isinstance(notification_context, NotificationContext) assert notification_context.target_identifier == "channel456" assert notification_context.integration_id == "1234567890" assert notification_context.sentry_app_config is None def test_build_alert_context(self) -> None: assert self.group_event.occurrence is not None assert self.group_event.occurrence.priority is not None alert_context = self.handler.build_alert_context( self.detector, self.evidence_data, self.group_event.group.status, DetectorPriorityLevel(self.group_event.occurrence.priority), ) assert isinstance(alert_context, AlertContext) assert alert_context.name == self.detector.name assert alert_context.action_identifier_id == self.detector.id assert alert_context.threshold_type == AlertRuleThresholdType.ABOVE assert alert_context.comparison_delta is None def test_build_alert_context_anomaly_detection(self) -> None: assert self.group_event.occurrence is not None assert self.group_event.occurrence.priority is not None alert_context = self.handler.build_alert_context( self.detector, self.anomaly_detection_evidence_data, self.group_event.group.status, DetectorPriorityLevel(self.group_event.occurrence.priority), ) assert isinstance(alert_context, AlertContext) assert alert_context.name == self.detector.name assert alert_context.action_identifier_id == self.detector.id assert alert_context.threshold_type == AnomalyDetectionThresholdType.ABOVE_AND_BELOW assert alert_context.comparison_delta is None assert alert_context.alert_threshold == 0 assert alert_context.resolve_threshold == 0 def test_get_new_status(self) -> None: assert self.group_event.occurrence is not None assert self.group_event.occurrence.priority is not None status = MetricIssueContext._get_new_status( self.group_event.group, DetectorPriorityLevel(self.group_event.occurrence.priority) ) assert status == IncidentStatus.CRITICAL _, _, group_event = self.create_group_event( group_type_id=MetricIssue.type_id, occurrence=self.create_issue_occurrence( priority=PriorityLevel.MEDIUM.value, level="warning", evidence_data={"snuba_query_id": self.snuba_query.id}, ), ) assert group_event.occurrence is not None assert group_event.occurrence.priority is not None status = MetricIssueContext._get_new_status( group_event.group, DetectorPriorityLevel(group_event.occurrence.priority) ) assert status == IncidentStatus.WARNING @mock.patch.object(TestHandler, "send_alert") def test_invoke_legacy_registry(self, mock_send_alert: mock.MagicMock) -> None: self.handler.invoke_legacy_registry(self.event_data, self.action, self.detector) assert mock_send_alert.call_count == 1 _, kwargs = mock_send_alert.call_args notification_context = kwargs["notification_context"] alert_context = kwargs["alert_context"] metric_issue_context = kwargs["metric_issue_context"] organization = kwargs["organization"] notification_uuid = kwargs["notification_uuid"] self.assert_notification_context( notification_context, integration_id=self.action.integration_id, target_identifier=self.action.config["target_identifier"], target_display=None, sentry_app_config=None, sentry_app_id=None, ) self.assert_alert_context( alert_context, name=self.detector.name, action_identifier_id=self.detector.id, threshold_type=AlertRuleThresholdType.ABOVE, detection_type=AlertRuleDetectionType.STATIC, comparison_delta=None, sensitivity=None, resolve_threshold=None, alert_threshold=self.evidence_data.conditions[0]["comparison"], ) self.assert_metric_issue_context( metric_issue_context, open_period_identifier=self.open_period.id, snuba_query=self.snuba_query, new_status=IncidentStatus.CRITICAL, metric_value=self.evidence_data.value, title=self.group_event.group.title, group=self.group_event.group, subscription=self.subscription, ) assert organization == self.detector.project.organization assert isinstance(notification_uuid, str) def test_send_alert_not_implemented(self) -> None: with pytest.raises(NotImplementedError): BaseMetricAlertHandler().send_alert( notification_context=mock.MagicMock(), alert_context=mock.MagicMock(), metric_issue_context=mock.MagicMock(), open_period_context=mock.MagicMock(), trigger_status=TriggerStatus.ACTIVE, organization=mock.MagicMock(), project=mock.MagicMock(), notification_uuid="test-uuid", ) @mock.patch.object(TestHandler, "send_alert") def test_invoke_legacy_registry_with_activity(self, mock_send_alert: mock.MagicMock) -> None: # Create an Activity instance with evidence data and priority activity_data = asdict(self.evidence_data) activity = Activity( project=self.project, group=self.group, type=ActivityType.SET_RESOLVED.value, data=activity_data, ) activity.save() # Create event data with Activity instead of GroupEvent event_data_with_activity = WorkflowEventData( event=activity, workflow_env=self.workflow.environment, group=self.group, ) self.handler.invoke_legacy_registry(event_data_with_activity, self.action, self.detector) assert mock_send_alert.call_count == 1 _, kwargs = mock_send_alert.call_args notification_context = kwargs["notification_context"] alert_context = kwargs["alert_context"] metric_issue_context = kwargs["metric_issue_context"] organization = kwargs["organization"] notification_uuid = kwargs["notification_uuid"] # Verify that the same data is extracted from Activity.data as from GroupEvent.occurrence.evidence_data self.assert_notification_context( notification_context, integration_id=self.action.integration_id, target_identifier=self.action.config["target_identifier"], target_display=None, sentry_app_config=None, sentry_app_id=None, ) self.assert_alert_context( alert_context, name=self.detector.name, action_identifier_id=self.detector.id, threshold_type=AlertRuleThresholdType.BELOW, detection_type=AlertRuleDetectionType.STATIC, comparison_delta=None, sensitivity=None, resolve_threshold=None, alert_threshold=self.evidence_data.conditions[2]["comparison"], ) self.assert_metric_issue_context( metric_issue_context, open_period_identifier=self.open_period.id, snuba_query=self.snuba_query, new_status=IncidentStatus.CLOSED, metric_value=self.evidence_data.value, title=self.group.title, group=self.group, subscription=self.subscription, ) assert organization == self.detector.project.organization assert isinstance(notification_uuid, str) @mock.patch.object(TestHandler, "send_alert") def test_invoke_legacy_registry_with_activity_anomaly_detection( self, mock_send_alert: mock.MagicMock ) -> None: # Create an Activity instance with evidence data and priority activity_data = asdict(self.anomaly_detection_evidence_data) activity = Activity( project=self.project, group=self.group, type=ActivityType.SET_RESOLVED.value, data=activity_data, ) activity.save() # Create event data with Activity instead of GroupEvent event_data_with_activity = WorkflowEventData( event=activity, workflow_env=self.workflow.environment, group=self.group, ) self.handler.invoke_legacy_registry(event_data_with_activity, self.action, self.detector) assert mock_send_alert.call_count == 1 _, kwargs = mock_send_alert.call_args notification_context = kwargs["notification_context"] alert_context = kwargs["alert_context"] metric_issue_context = kwargs["metric_issue_context"] organization = kwargs["organization"] notification_uuid = kwargs["notification_uuid"] # Verify that the same data is extracted from Activity.data as from GroupEvent.occurrence.evidence_data self.assert_notification_context( notification_context, integration_id=self.action.integration_id, target_identifier=self.action.config["target_identifier"], target_display=None, sentry_app_config=None, sentry_app_id=None, ) self.assert_alert_context( alert_context, name=self.detector.name, action_identifier_id=self.detector.id, threshold_type=AnomalyDetectionThresholdType.ABOVE_AND_BELOW, detection_type=AlertRuleDetectionType.STATIC, comparison_delta=None, sensitivity=AnomalyDetectionSensitivity.MEDIUM, resolve_threshold=0, alert_threshold=0, ) assert type(self.anomaly_detection_evidence_data.value) is dict self.assert_metric_issue_context( metric_issue_context, open_period_identifier=self.open_period.id, snuba_query=self.snuba_query, new_status=IncidentStatus.CLOSED, metric_value=self.anomaly_detection_evidence_data.value["value"], title=self.group.title, group=self.group, subscription=self.subscription, ) assert organization == self.detector.project.organization assert isinstance(notification_uuid, str) def test_invoke_legacy_registry_activity_missing_data(self) -> None: # Test with Activity that has no data field activity = Activity.objects.create( project=self.project, group=self.group, type=1, data=None, # Missing data ) event_data_with_activity = WorkflowEventData( event=activity, workflow_env=self.workflow.environment, group=self.group, ) with pytest.raises(ValueError, match="Activity data is required for alert context"): self.handler.invoke_legacy_registry( event_data_with_activity, self.action, self.detector ) def test_invoke_legacy_registry_activity_empty_data(self) -> None: # Test with Activity that has non-empty but insufficient data for MetricIssueEvidenceData activity = Activity( project=self.project, group=self.group, type=1, data={"priority": PriorityLevel.HIGH.value}, # Only priority, missing required fields ) activity.save() event_data_with_activity = WorkflowEventData( event=activity, workflow_env=self.workflow.environment, group=self.group, ) with pytest.raises( TypeError ): # MetricIssueEvidenceData will raise TypeError for missing args self.handler.invoke_legacy_registry( event_data_with_activity, self.action, self.detector )
TestBaseMetricAlertHandler
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_eks.py
{ "start": 4748, "end": 7398 }
class ____: @pytest.fixture(autouse=True) def _setup_test_cases(self): self.target_state = FargateProfileStates.ACTIVE self.sensor = EksFargateProfileStateSensor( task_id=TASK_ID, cluster_name=CLUSTER_NAME, fargate_profile_name=FARGATE_PROFILE_NAME, target_state=self.target_state, ) @pytest.mark.db_test def test_region_argument(self): with pytest.warns(AirflowProviderDeprecationWarning) as w: w.sensor = EksFargateProfileStateSensor( task_id=TASK_ID, cluster_name=CLUSTER_NAME, fargate_profile_name=FARGATE_PROFILE_NAME, target_state=self.target_state, region="us-east-2", ) assert w.sensor.region_name == "us-east-2" @mock.patch.object(EksHook, "get_fargate_profile_state", return_value=FargateProfileStates.ACTIVE) def test_poke_reached_target_state(self, mock_get_fargate_profile_state): assert self.sensor.poke({}) is True mock_get_fargate_profile_state.assert_called_once_with( clusterName=CLUSTER_NAME, fargateProfileName=FARGATE_PROFILE_NAME ) @mock.patch("airflow.providers.amazon.aws.hooks.eks.EksHook.get_fargate_profile_state") @pytest.mark.parametrize("pending_state", FARGATE_PENDING_STATES) def test_poke_reached_pending_state(self, mock_get_fargate_profile_state, pending_state): mock_get_fargate_profile_state.return_value = pending_state assert self.sensor.poke({}) is False mock_get_fargate_profile_state.assert_called_once_with( clusterName=CLUSTER_NAME, fargateProfileName=FARGATE_PROFILE_NAME ) @mock.patch("airflow.providers.amazon.aws.hooks.eks.EksHook.get_fargate_profile_state") @pytest.mark.parametrize("unexpected_terminal_state", FARGATE_UNEXPECTED_TERMINAL_STATES) def test_poke_reached_unexpected_terminal_state( self, mock_get_fargate_profile_state, unexpected_terminal_state ): expected_message = ( f"Terminal state reached. Current state: {unexpected_terminal_state}, " f"Expected state: {self.target_state}" ) mock_get_fargate_profile_state.return_value = unexpected_terminal_state with pytest.raises(AirflowException) as raised_exception: self.sensor.poke({}) assert str(raised_exception.value) == expected_message mock_get_fargate_profile_state.assert_called_once_with( clusterName=CLUSTER_NAME, fargateProfileName=FARGATE_PROFILE_NAME )
TestEksFargateProfileStateSensor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/cloud_storage_transfer.py
{ "start": 1975, "end": 2220 }
class ____(BaseGoogleLink): """Helper class for constructing Cloud Storage Transfer Link.""" name = "Cloud Storage Transfer" key = "cloud_storage_transfer" format_str = CLOUD_STORAGE_TRANSFER_LIST_LINK
CloudStorageTransferListLink
python
getsentry__sentry
src/sentry/workflow_engine/models/data_source.py
{ "start": 909, "end": 4023 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Organization # DataSource.source_id dynamically references different models based on the 'type' field. # We declare all possible dependencies here to ensure proper import ordering. __relocation_dependencies__ = { "monitors.monitor", # For DATA_SOURCE_CRON_MONITOR "sentry.querysubscription", # For DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION "uptime.uptimesubscription", # For DATA_SOURCE_UPTIME_SUBSCRIPTION } organization = FlexibleForeignKey("sentry.Organization") # source_id is used in a composite index with type to dynamically lookup the data source source_id = models.TextField() # This is a dynamic field, depending on the type in the data_source_type_registry type = models.TextField() detectors = models.ManyToManyField("workflow_engine.Detector", through=DataSourceDetector) class Meta: indexes = [ models.Index(fields=("organization", "type", "source_id")), ] constraints = [ models.UniqueConstraint(fields=["type", "source_id"], name="unique_type_source_id"), ] @property def type_handler(self) -> builtins.type[DataSourceTypeHandler]: handler = data_source_type_registry.get(self.type) if not handler: raise ValueError(f"Unknown data source type: {self.type}") return handler def normalize_before_relocation_import( self, pk_map: PrimaryKeyMap, scope: ImportScope, flags: ImportFlags ) -> int | None: old_pk = super().normalize_before_relocation_import(pk_map, scope, flags) if old_pk is None: return None # Map source_id based on the data source type try: handler = data_source_type_registry.get(self.type) model_name = NormalizedModelName(handler.get_relocation_model_name()) old_source_id = int(self.source_id) new_source_id = pk_map.get_pk(model_name, old_source_id) if new_source_id is None: # Referenced model not in pk_map - the source was filtered out or failed to import. return None self.source_id = str(new_source_id) except Exception: logger.exception( "DataSource.normalize_before_relocation_import failed", extra={"data_source_id": old_pk, "type": self.type, "source_id": self.source_id}, ) return None return old_pk @receiver(pre_save, sender=DataSource) def ensure_type_handler_registered(sender, instance: DataSource, **kwargs): """ Ensure that the type of the data source is valid and registered in the data_source_type_registry """ data_source_type = instance.type if not data_source_type: raise ValueError(f"No group type found with type {instance.type}") try: data_source_type_registry.get(data_source_type) except NoRegistrationExistsError: raise ValueError(f"No data source type found with type {data_source_type}")
DataSource
python
huggingface__transformers
src/transformers/models/rag/retrieval_rag.py
{ "start": 1366, "end": 3007 }
class ____: """ A base class for the Indices encapsulated by the [`RagRetriever`]. """ def get_doc_dicts(self, doc_ids: np.ndarray) -> list[dict]: """ Returns a list of dictionaries, containing titles and text of the retrieved documents. Args: doc_ids (`np.ndarray` of shape `(batch_size, n_docs)`): A tensor of document indices. """ raise NotImplementedError def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> tuple[np.ndarray, np.ndarray]: """ For each query in the batch, retrieves `n_docs` documents. Args: question_hidden_states (`np.ndarray` of shape `(batch_size, vector_size)`): An array of query vectors. n_docs (`int`): The number of docs retrieved per query. Returns: `np.ndarray` of shape `(batch_size, n_docs)`: A tensor of indices of retrieved documents. `np.ndarray` of shape `(batch_size, vector_size)`: A tensor of vector representations of retrieved documents. """ raise NotImplementedError def is_initialized(self): """ Returns `True` if index is already initialized. """ raise NotImplementedError def init_index(self): """ A function responsible for loading the index into memory. Should be called only once per training run of a RAG model. E.g. if the model is trained on multiple GPUs in a distributed setup, only one of the workers will load the index. """ raise NotImplementedError
Index
python
ray-project__ray
python/ray/tests/test_autoscaling_policy.py
{ "start": 1484, "end": 1514 }
class ____(Task): pass
Actor
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/properties/snippets.py
{ "start": 3406, "end": 3615 }
class ____(ndb.Model): name = ndb.StringProperty() color = msgprop.EnumProperty(Color, required=True) def print_part(): p1 = Part(name="foo", color=Color.RED) print(p1.color) # prints "RED"
Part
python
MongoEngine__mongoengine
tests/fields/test_reference_field.py
{ "start": 111, "end": 7032 }
class ____(MongoDBTestCase): def test_reference_field_fails_init_wrong_document_type(self): class User(Document): name = StringField() ERROR_MSG = "Argument to ReferenceField constructor must be a document class or a string" # fails if given an instance with pytest.raises(ValidationError, match=ERROR_MSG): class Test(Document): author = ReferenceField(User()) class NonDocumentSubClass: pass # fails if given a non Document subclass with pytest.raises(ValidationError, match=ERROR_MSG): class Test(Document): # noqa: F811 author = ReferenceField(NonDocumentSubClass) def test_reference_validation(self): """Ensure that invalid document objects cannot be assigned to reference fields. """ class User(Document): name = StringField() class BlogPost(Document): content = StringField() author = ReferenceField(User) User.drop_collection() BlogPost.drop_collection() # Make sure ReferenceField only accepts a document class or a string # with a document class name. with pytest.raises(ValidationError): ReferenceField(EmbeddedDocument) unsaved_user = User(name="Test User") # Ensure that the referenced object must have been saved post1 = BlogPost(content="Chips and gravy taste good.") post1.author = unsaved_user expected_error = ( "The instance of the document 'User' you are " "trying to reference has an empty 'id'. You can only reference " "documents once they have been saved to the database" ) with pytest.raises(ValidationError, match=expected_error): post1.save() # Check that an invalid object type cannot be used post2 = BlogPost(content="Chips and chilli taste good.") post1.author = post2 with pytest.raises(ValidationError): post1.validate() # Ensure ObjectID's are accepted as references user = User(name="Test User") user_object_id = user.pk post3 = BlogPost(content="Chips and curry sauce taste good.") post3.author = user_object_id post3.save() # Make sure referencing a saved document of the right type works user.save() post1.author = user post1.save() # Make sure referencing a saved document of the *wrong* type fails post2.save() post1.author = post2 with pytest.raises(ValidationError): post1.validate() def test_dbref_reference_fields(self): """Make sure storing references as bson.dbref.DBRef works.""" class Person(Document): name = StringField() parent = ReferenceField("self", dbref=True) Person.drop_collection() p1 = Person(name="John").save() Person(name="Ross", parent=p1).save() assert Person._get_collection().find_one({"name": "Ross"})["parent"] == DBRef( "person", p1.pk ) p = Person.objects.get(name="Ross") assert p.parent == p1 def test_dbref_to_mongo(self): """Make sure that calling to_mongo on a ReferenceField which has dbref=False, but actually actually contains a DBRef returns an ID of that DBRef. """ class Person(Document): name = StringField() parent = ReferenceField("self", dbref=False) p = Person(name="Steve", parent=DBRef("person", "abcdefghijklmnop")) assert p.to_mongo() == SON([("name", "Steve"), ("parent", "abcdefghijklmnop")]) def test_objectid_reference_fields(self): class Person(Document): name = StringField() parent = ReferenceField("self", dbref=False) Person.drop_collection() p1 = Person(name="John").save() Person(name="Ross", parent=p1).save() col = Person._get_collection() data = col.find_one({"name": "Ross"}) assert data["parent"] == p1.pk p = Person.objects.get(name="Ross") assert p.parent == p1 def test_undefined_reference(self): """Ensure that ReferenceFields may reference undefined Documents.""" class Product(Document): name = StringField() company = ReferenceField("Company") class Company(Document): name = StringField() Product.drop_collection() Company.drop_collection() ten_gen = Company(name="10gen") ten_gen.save() mongodb = Product(name="MongoDB", company=ten_gen) mongodb.save() me = Product(name="MongoEngine") me.save() obj = Product.objects(company=ten_gen).first() assert obj == mongodb assert obj.company == ten_gen obj = Product.objects(company=None).first() assert obj == me obj = Product.objects.get(company=None) assert obj == me def test_reference_query_conversion(self): """Ensure that ReferenceFields can be queried using objects and values of the type of the primary key of the referenced object. """ class Member(Document): user_num = IntField(primary_key=True) class BlogPost(Document): title = StringField() author = ReferenceField(Member, dbref=False) Member.drop_collection() BlogPost.drop_collection() m1 = Member(user_num=1) m1.save() m2 = Member(user_num=2) m2.save() post1 = BlogPost(title="post 1", author=m1) post1.save() post2 = BlogPost(title="post 2", author=m2) post2.save() post = BlogPost.objects(author=m1).first() assert post.id == post1.id post = BlogPost.objects(author=m2).first() assert post.id == post2.id def test_reference_query_conversion_dbref(self): """Ensure that ReferenceFields can be queried using objects and values of the type of the primary key of the referenced object. """ class Member(Document): user_num = IntField(primary_key=True) class BlogPost(Document): title = StringField() author = ReferenceField(Member, dbref=True) Member.drop_collection() BlogPost.drop_collection() m1 = Member(user_num=1) m1.save() m2 = Member(user_num=2) m2.save() post1 = BlogPost(title="post 1", author=m1) post1.save() post2 = BlogPost(title="post 2", author=m2) post2.save() post = BlogPost.objects(author=m1).first() assert post.id == post1.id post = BlogPost.objects(author=m2).first() assert post.id == post2.id
TestReferenceField
python
scipy__scipy
benchmarks/benchmarks/tests/test_go_benchmark_functions.py
{ "start": 148, "end": 2683 }
class ____: def setup_method(self): bench_members = inspect.getmembers(gbf, inspect.isclass) self.benchmark_functions = {it[0]:it[1] for it in bench_members if issubclass(it[1], gbf.Benchmark)} def teardown_method(self): pass def test_optimum_solution(self): # Check that the function returns the global minimum if given # the optimal solution for name, klass in self.benchmark_functions.items(): # LennardJones is filtered here because there are many global # optimima that give the same minimum energy if (name in ['Benchmark', 'LennardJones'] or name.startswith('Problem')): continue f = klass() if name in ['Damavandi', 'Csendes']: with np.errstate(divide='ignore', invalid='ignore'): print(name, f.fun(np.asarray(f.global_optimum[0])), f.fglob) assert np.isnan(f.fun(np.asarray(f.global_optimum[0]))) continue print(name, f.fun(np.asarray(f.global_optimum[0])), f.fglob) assert f.success(f.global_optimum[0]) def test_solution_exists(self): # Every benchmark function should have a minimum energy for name, klass in self.benchmark_functions.items(): if name == 'Benchmark': continue f = klass() # should result in an attribute error if it doesn't exist _ = f.fglob def test_bounds_access_subscriptable(self): # In Python 2 zip returns a list which is subscriptable # In Python 3 zip returns a zip object, which is not subscriptable for name, klass in self.benchmark_functions.items(): if (name == 'Benchmark' or name.startswith('Problem')): continue f = klass() _ = f.bounds[0] def test_redimension(self): # check that problems can be redimensioned, use LJ for this. LJ = self.benchmark_functions['LennardJones'] assert LJ.change_dimensionality L = LJ() L.change_dimensions(10) # if we change the size of the problem then the initial vector has to # resize x0 = L.initial_vector() assert len(x0) == 10 # the bounds should be the correct length now. bounds = L.bounds assert len(bounds) == 10 assert L.N == 10
TestGoBenchmarkFunctions
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 48789, "end": 49785 }
class ____(AssetSelection): selected_key_wildcard: str def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: regex = re.compile("^" + re.escape(self.selected_key_wildcard).replace("\\*", ".*") + "$") return { key for key in asset_graph.get_all_asset_keys() if regex.match(key.to_user_string()) } def to_selection_str(self) -> str: return f'key:"{self.selected_key_wildcard}"' def _fetch_all_upstream( selection: AbstractSet[AssetKey], asset_graph: BaseAssetGraph, depth: Optional[int] = None, include_self: bool = True, ) -> AbstractSet[AssetKey]: return operator.sub( ( selection | fetch_connected( selection, asset_graph.asset_dep_graph, direction="upstream", depth=depth ) ), selection if not include_self else set(), ) @whitelist_for_serdes @record
KeyWildCardAssetSelection
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/steps.py
{ "start": 3008, "end": 3422 }
class ____(Result): """A dataclass to capture the result of a command.""" command: click.Command def __repr__(self) -> str: # noqa D105 return f"{self.command.name}: {self.status.value}" def __str__(self) -> str: # noqa D105 return f"{self.command.name}: {self.status.value}\n\nSTDOUT:\n{self.stdout}\n\nSTDERR:\n{self.stderr}" @dataclass(kw_only=True, frozen=True)
CommandResult