问:
Adding a button to scroll to top
I am trying to detect when the user scroll down...and show a button to scroll to top when clicked
I didn't create a directive, I found it very difficult to understand so I am using Content

I have managed to scroll to top when the button is clicked

.ts

```<code>scrollToTop(){
var distance = this.content.scrollTop;

if (distance > 0){
 this.content.scrollToTop();
 }
}
</code>```

but I dont know how to show and hide the button.... currently it is shown in the constructor this.showButton = true;
I want to show the button when scrollTop changes

答:
const scrollTop = function (){
        const scroll_btn = document.querySelector('#scrollbtn');

            const rootElement = document.documentElement;
            const TOGGLE_RATIO = 0.80;

            function handleScroll() {
            // do something on scroll
            const scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

                if ((rootElement.scrollTop / scrollTotal) > TOGGLE_RATIO) {
                //show button
                scroll_btn.classList.add("showBtn")

            } else {
                //hide button
                scroll_btn.classList.remove("showBtn")

        }
    }
    scroll_btn.addEventListener("click", scrollToTop)

            function scrollToTop() {
            //scroll to top logic
            rootElement.scrollTo({
                top: 0,
                behavior: "smooth"
                })
            }

    document.addEventListener("scroll", handleScroll)

};

scrollTop();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html{
    background: yellow;
    block-size: 200vh;
    }
.scrollbtn{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 5rem;
    height: 4rem;
    color: var(--important);
    background-color: var(--main-color);
    font-weight: 600;
    position: fixed;
    bottom: 2rem;
    right: 2rem;
    border-radius: 50%;
    font-size: 1.5rem;
    z-index: 1000;
    opacity: 0;

}

.scrollbtn:hover{
    background-color: rgb(3, 141, 139);
    /*hanges the color of the button on hover*/
}

#scrollbtn.showBtn{
  /*toogles the button on js condition being true*/
    opacity: 1;
    transition: opacity 1s, transform 1s;
}</code>```

This is an H1 tag

  <button class="scrollbtn" id="scrollbtn" title="Scroll to top">Top</button>
```

I hope this answers your question.

Thanks

Title: Adding a button to scroll to top

Body:
I am trying to detect when the user scroll down...and show a button to scroll to top when clicked
I didn't create a directive, I found it very difficult to understand so I am using Content

I have managed to scroll to top when the button is clicked

.ts

scrollToTop(){
var distance = this.content.scrollTop;

if (distance > 0){
 this.content.scrollToTop();
 }
}

but I dont know how to show and hide the button.... currently it is shown in the constructor this.showButton = true;
I want to show the button when scrollTop changes

Body:
const scrollTop = function (){
        const scroll_btn = document.querySelector('#scrollbtn');

            const rootElement = document.documentElement;
            const TOGGLE_RATIO = 0.80;

            function handleScroll() {
            // do something on scroll
            const scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

                if ((rootElement.scrollTop / scrollTotal) > TOGGLE_RATIO) {
                //show button
                scroll_btn.classList.add("showBtn")

            } else {
                //hide button
                scroll_btn.classList.remove("showBtn")

        }
    }
    scroll_btn.addEventListener("click", scrollToTop)

            function scrollToTop() {
            //scroll to top logic
            rootElement.scrollTo({
                top: 0,
                behavior: "smooth"
                })
            }

    document.addEventListener("scroll", handleScroll)

};

scrollTop();

html{
    background: yellow;
    block-size: 200vh;
    }
.scrollbtn{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 5rem;
    height: 4rem;
    color: var(--important);
    background-color: var(--main-color);
    font-weight: 600;
    position: fixed;
    bottom: 2rem;
    right: 2rem;
    border-radius: 50%;
    font-size: 1.5rem;
    z-index: 1000;
    opacity: 0;

}

.scrollbtn:hover{
    background-color: rgb(3, 141, 139);
    /*hanges the color of the button on hover*/
}

#scrollbtn.showBtn{
  /*toogles the button on js condition being true*/
    opacity: 1;
    transition: opacity 1s, transform 1s;
}

<html>
  <h1>This is an H1 tag </h1>
  <button class="scrollbtn" id="scrollbtn" title="Scroll to top">Top</button>
</html>

I hope this answers your question.

Thanks


来源: stackexchange

问:
Deploy Mongodb and NodeJS with Kubernetes
I am learning Kubernetes and finding some suggestions about deploying my application.

My application background:

Backend: NodeJS

Frontend: ReactJS

Database: MongoDB (Just run mongod to start instead of using MongoDB cloud services)

I already know how to use Docker compose to deploy the application in single node.

And now I want to deploy the application with Kubernetes (3 nodes).

So how to deploy MongoDB and make sure the MongoDB data is synchronize in 3 nodes?

I have researched some information about this and I am confused on some keywords.

E.g. Deploy a Standalone MongoDB Instance,
StatefulSet, ...

Are this information / articles suitable for my situation? or do you know any information about this? Thanks!

答:
You can create helm charts for your apps for deployment -

Create Dockerfile for your app, make sure you copy the build that was created using npm build

Push to dockerhub or any other registry like ACR or ECR

Add the image tags in helm deployments & pass values from values.yaml

For MongoDb deployment, use this chart https://github.com/bitnami/charts/tree/master/bitnami/mongodb

ContentLicense: CC BY-SA 4.0


问:
Getting java.lang.NoClassDefFoundError: scala/Product$class error when I am trying to use Spark lens in Pyspark Shell
The command which I am using to start my pyspark shell is:
bin/pyspark --packages qubole:sparklens:0.3.2-s_2.11 --conf spark.extraListeners=com.qubole.sparklens.QuboleJobListener --executor-cores 1 --num-executor 1

I am using Python 3.8.10,Spark 3.2.1, JDK 1.8 in my environment.

I am trying to test the spark lens in my pyspark shell then I am getting this error.

py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: scala/Product$class
    at com.qubole.sparklens.common.ApplicationInfo.<init>(ApplicationInfo.scala:22)
    at com.qubole.sparklens.QuboleJobListener.<init>(QuboleJobListener.scala:42)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.spark.util.Utils$.$anonfun$loadExtensions$1(Utils.scala:2876)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:293)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:293)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:290)
    at scala.collection.AbstractTraversable.flatMap(Traversable.scala:108)
    at org.apache.spark.util.Utils$.loadExtensions(Utils.scala:2868)
    at org.apache.spark.SparkContext.$anonfun$setupAndStartListenerBus$1(SparkContext.scala:2538)
    at org.apache.spark.SparkContext.$anonfun$setupAndStartListenerBus$1$adapted(SparkContext.scala:2537)
    at scala.Option.foreach(Option.scala:407)
    at org.apache.spark.SparkContext.setupAndStartListenerBus(SparkContext.scala:2537)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:641)
    at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:238)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:748)```

答: You can't use this connector with Spark 3.2.1 as it's compiled for Scala 2.11, while Spark 3.2.1 uses Scala 2.12.  As I see, there is no connector version for Scala 2.12, so you need to switch to Spark 2.4.x that supports Scala 2.11</p>


问:
Postgresql query on xml data that ignores single quotes
I have an xml snippet:

```<code><message to='8ffc29107a21e3639@dev.xyz.com' id='faddf6f2-a973-4b0e-a00a-d6f9b886047a' type='abc'>
    <body>body_text</body>
    <datetime
        xmlns='dev:datetime' time='2022-01-25T11:08:57.974Z'>
    </datetime>
    <type
        xmlns='dev:xtype' type='x_type'>
    </type>
    <imageurl
        xmlns='dev:imageurl' url='https://dev.xyz.com/media/fa5a8b6272cf44f282a02599aa62e0c5.jpg' ratio='1.2091648189209165'>
    </imageurl>
</message>
</code>```

...on which i want to run an postgresql query which returns the url attribute inside the imageurl node.

In order to achieve that, I first tried to query a simple xml string and hit the following error:

```<code>SELECT unnest(xpath('//*/text()','<foo lang='en'><bar>test</bar><zar>test1</zar></foo>'));

ERROR:  syntax error at or near "en"
LINE 1: SELECT unnest(xpath('//:/text()','<foo lang='en'><bar>test</...
</code>```

It seems like the sql query is not able to handle single quotation strings. Since my original snippet above has multiple such single quote strings, I am stuck here.

What is the best way to ignore the single quotes in the psql query?

答:
The standard way to escape single quotes inside a SQL string is  to double them:

```<code>'<foo lang=''en''><bar>test</bar><zar>test1</zar></foo>'
</code>```

However in such a case, using Postgres' proprietary "dollar quoted strings is more convenient:

```<code>SELECT unnest(xpath('//*/text()',
                    $$<foo lang='en'><bar>test</bar><zar>test1</zar></foo>$$)
             );
</code>```

Body:
I have an xml snippet:

<message to='8ffc29107a21e3639@dev.xyz.com' id='faddf6f2-a973-4b0e-a00a-d6f9b886047a' type='abc'>
    body_text
    <datetime
        xmlns='dev:datetime' time='2022-01-25T11:08:57.974Z'>
    </datetime>
    <type
        xmlns='dev:xtype' type='x_type'>
    </type>
    <imageurl
        xmlns='dev:imageurl' url='https://dev.xyz.com/media/fa5a8b6272cf44f282a02599aa62e0c5.jpg' ratio='1.2091648189209165'>
    </imageurl>
</message>

...on which i want to run an postgresql query which returns the url attribute inside the imageurl node.

In order to achieve that, I first tried to query a simple xml string and hit the following error:

SELECT unnest(xpath('//*/text()','<foo lang='en'><bar>test</bar><zar>test1</zar></foo>'));

ERROR:  syntax error at or near "en"
LINE 1: SELECT unnest(xpath('//:/text()','<foo lang='en'><bar>test</...

It seems like the sql query is not able to handle single quotation strings. Since my original snippet above has multiple such single quote strings, I am stuck here.

What is the best way to ignore the single quotes in the psql query?

Body:
The standard way to escape single quotes inside a SQL string is  to double them:

'<foo lang=''en''><bar>test</bar><zar>test1</zar></foo>'

However in such a case, using Postgres' proprietary "dollar quoted strings is more convenient:

SELECT unnest(xpath('//*/text()',
                    $$<foo lang='en'><bar>test</bar><zar>test1</zar></foo>$$)
             );


问:
Running scripts inside C#
I want to run javascript/Python/Ruby inside my application. </p>

<p>I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process.
For example, the created process will have some activities and in the middle the script should be run and then the process continues as before.
Is there a mechanism to run those scripts from C#? </p>

答:
One of Microsoft's solutions to JavaScript in C# is ClearScript,
which uses V8, Chrom browser's JavaScript engine.  Check its short FAQtorial for code samples.

It has excellent two-way integration - iterator/enumerator, output parameters, optional parameters, parameter arrays, delegate, task/promise/async/await, bigint, and more.

Apart from that, I think the most distinguishing feature is that it does not depend on Rosyln or Dynamic Language Runtime.  This can be good or bad - good because there may be a lot less dependencies (depending on your project's target), bad because you need to bundle the native, platform-dependent V8 dll.

If that is ok, you get to enjoy cutting edge JavaScript / ECMAScript.  Everything you get on Chrome, or 98% ES6 as of 2022 Feb, plus several extensions.  Speed is as fast as Chrome, obviously, so you get the best of both Google and Microsoft.

ContentLicense: CC BY-SA 2.5

Title: Running scripts inside C#

Body:
I want to run javascript/Python/Ruby inside my application.

I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process.
For example, the created process will have some activities and in the middle the script should be run and then the process continues as before.
Is there a mechanism to run those scripts from C#?


问:
Mutiny - combine Uni and Multi based on business logic
I am new to reactive programming. Kindly assist in achieving the below in Mutiny.

I have a DTO class

```<code>public class UserAppSessionDto{
    private UserDto user;
    private List<OrgDto>  userOrgs;
    private List<AppDto> userApps;
}
</code>```

and 3 service methods, one returning Uni and others returning Multi.

```<code>Uni<UserDto> getUserByOrgUserId(Integer orgUserId);
Multi<AppDto> getUserApps(Integer orgUserId);
Multi<RoleDto> getUserRoles(Integer orgUserId);
</code>```

I need to write a service method which calls the above 3 methods, apply some business validations , set the return values to an instance of UserAppSessionDto and return a Uni<UserAppSessionDto>. I have mentioned the basic business logic (null check) to be applied below.

```<code>public Uni<UserAppSessionDto> getUserAppSessionDetails(Integer orgUserId)
         {
             UserAppSessionDto user=new UserAppSessionDto();

             //1. call the method Uni<UserDto> getUserByOrgUserId(Integer orgUserId)
             //2. If UserDto (in the returned Uni) is not null, call Multi<AppDto> getUserApps(Integer orgUserId) and Multi<RoleDto> getUserRoles(Integer orgUserId) methods in parallel.
             //3. Set the return values from the above three methods into user variable
             //4. Return Uni<UserAppSessionDto>

             return Uni.createFrom().item(user);
         }
</code>```

答:
Any reason why getUserApps and getUserRoles are returning Multis? I don't believe they will stream the results, but instead, return the list in one batch. If that's the case, using Uni<List<X> is better.

With this change, you logic becomes a lot easier:

public Uni<UserAppSessionDto> getUserAppSessionDetails(Integer orgUserId) {
  UserAppSessionDto user=new UserAppSessionDto();

 Uni<UserDto> uni = getUserByOrgUserId(orgUserId)
       .invoke(userDTO -> user.user = userDTO);

return uni
   onItem().ifNotNull().transformToUni(userdto ->
       Uni.combine().all()
         .unis(getUserApps(orgUserId),getUserRoles(orgUserId))
         .asTuple()
         .invoke((apps, roles) -> user....)
     )
     .map(x -> user);
}
```

Body:
I am new to reactive programming. Kindly assist in achieving the below in Mutiny.

I have a DTO class

public class UserAppSessionDto{
    private UserDto user;
    private List<OrgDto>  userOrgs;
    private List<AppDto> userApps;
}

and 3 service methods, one returning Uni and others returning Multi.

Uni<UserDto> getUserByOrgUserId(Integer orgUserId);
Multi<AppDto> getUserApps(Integer orgUserId);
Multi<RoleDto> getUserRoles(Integer orgUserId);

I need to write a service method which calls the above 3 methods, apply some business validations , set the return values to an instance of UserAppSessionDto and return a Uni<UserAppSessionDto>. I have mentioned the basic business logic (null check) to be applied below.

public Uni<UserAppSessionDto> getUserAppSessionDetails(Integer orgUserId)
         {
             UserAppSessionDto user=new UserAppSessionDto();

             //1. call the method Uni<UserDto> getUserByOrgUserId(Integer orgUserId)
             //2. If UserDto (in the returned Uni) is not null, call Multi<AppDto> getUserApps(Integer orgUserId) and Multi<RoleDto> getUserRoles(Integer orgUserId) methods in parallel.
             //3. Set the return values from the above three methods into user variable
             //4. Return Uni<UserAppSessionDto>

             return Uni.createFrom().item(user);
         }


问:
Android - How to supply an argument to a method in my ViewModel from my fragment
I'm fairly new to android kotlin, so in my ViewModel I have a method that accepts an integer as an argument. Currently the app is working because I am passing the integer argument from a global variable, now I want to be able to either call the ViewModel method in my fragment or call it in an init block in the ViewModel.

Here's my current View Model code:

```<code>class PostCommentViewModel: ViewModel() {

    private val TAG = "MainActivity"
    val mPostsComment = MutableLiveData<List<Comment>>()
    var postId: Int = 0

    init {
        postId = temp
        Log.e("Init on PostCommentViewModel", "Message: $postId")
        getDataComment(postId)

    }

     fun getDataComment(postId: Int) {
        PostRepository().getDataComment(postId).enqueue(object : Callback<List<Comment>>{
            override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
                val comments = response.body()
                comments?.let {
                    mPostsComment.value = comments!!
                }
            }

            override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
                Log.e(TAG, "On Failure: ${t.message}")
                t.printStackTrace()
            }
        })
    }

    fun getComments():MutableLiveData<List<Comment>>{
        return mPostsComment
    }

}
</code>```

And here's my fragment where I get the value for the argument:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        checkArguments()
    }

    private fun checkArguments() {
        arguments?.let { bundle ->
            if (bundle.containsKey("POST")) {
                val postString = bundle.getString("POST", "")
                val post: Post = gson.fromJson(postString, Post::class.java)

                binding.postDetailstvTitle.text = post.title
                binding.postDetailstvBody.text = post.body
                param2 = post.id

                //val model: PostCommentViewModel by viewModels()
                //model.getDataComment(param2)
                temp = param2
            }
        }
    }
</code>```

temp is the global variable. You can also see my attempt there to call the method haha. Big thanks to whoever answers <3

答:
You can use another MutableLiveData and observe it in Fragment.

In your ViewModal class

```<code>val postIdData= MutableLiveData<Int>(0) // here default set as 0
</code>```

Now in your Fragment use this as observable as below in viewCreated(). Assuming you know how to initialized viewModel in your Fragment class.

```<code>viewModel.postIdData.observe(requiredActivity, { postId->{
  // now here you will get postId whenever data change
})
</code>```

your code to get postId just post your value whenever you get it

```<code>private fun checkArguments() {
    arguments?.let { bundle ->
        if (bundle.containsKey("POST")) {
            val postString = bundle.getString("POST", "")
            val post: Post = gson.fromJson(postString, Post::class.java)

            binding.postDetailstvTitle.text = post.title
            binding.postDetailstvBody.text = post.body
            param2 = post.id

            //val model: PostCommentViewModel by viewModels()
            //model.getDataComment(param2)
            temp = param2
            // here postvalue
            viewModel.postIdData.postValue(post.id)
        }
    }
}
</code>```

Body:
I'm fairly new to android kotlin, so in my ViewModel I have a method that accepts an integer as an argument. Currently the app is working because I am passing the integer argument from a global variable, now I want to be able to either call the ViewModel method in my fragment or call it in an init block in the ViewModel.

Here's my current View Model code:

class PostCommentViewModel: ViewModel() {

    private val TAG = "MainActivity"
    val mPostsComment = MutableLiveData<List<Comment>>()
    var postId: Int = 0

    init {
        postId = temp
        Log.e("Init on PostCommentViewModel", "Message: $postId")
        getDataComment(postId)

    }

     fun getDataComment(postId: Int) {
        PostRepository().getDataComment(postId).enqueue(object : Callback<List<Comment>>{
            override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) {
                val comments = response.body()
                comments?.let {
                    mPostsComment.value = comments!!
                }
            }

            override fun onFailure(call: Call<List<Comment>>, t: Throwable) {
                Log.e(TAG, "On Failure: ${t.message}")
                t.printStackTrace()
            }
        })
    }

    fun getComments():MutableLiveData<List<Comment>>{
        return mPostsComment
    }

}

And here's my fragment where I get the value for the argument:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        checkArguments()
    }

    private fun checkArguments() {
        arguments?.let { bundle ->
            if (bundle.containsKey("POST")) {
                val postString = bundle.getString("POST", "")
                val post: Post = gson.fromJson(postString, Post::class.java)

                binding.postDetailstvTitle.text = post.title
                binding.postDetailstvBody.text = post.body
                param2 = post.id

                //val model: PostCommentViewModel by viewModels()
                //model.getDataComment(param2)
                temp = param2
            }
        }
    }

temp is the global variable. You can also see my attempt there to call the method haha. Big thanks to whoever answers <3

Body:
You can use another MutableLiveData and observe it in Fragment.

In your ViewModal class

val postIdData= MutableLiveData<Int>(0) // here default set as 0

Now in your Fragment use this as observable as below in viewCreated(). Assuming you know how to initialized viewModel in your Fragment class.

viewModel.postIdData.observe(requiredActivity, { postId->{
  // now here you will get postId whenever data change
})

your code to get postId just post your value whenever you get it

private fun checkArguments() {
    arguments?.let { bundle ->
        if (bundle.containsKey("POST")) {
            val postString = bundle.getString("POST", "")
            val post: Post = gson.fromJson(postString, Post::class.java)

            binding.postDetailstvTitle.text = post.title
            binding.postDetailstvBody.text = post.body
            param2 = post.id

            //val model: PostCommentViewModel by viewModels()
            //model.getDataComment(param2)
            temp = param2
            // here postvalue
            viewModel.postIdData.postValue(post.id)
        }
    }
}


问:
Form validation in Clean Architecture
Input validation is a business logic so we should hide this process in the domain layer.
as discussed here

I do it like this

Login validator

```<code>class LoginValidator extends Validator {
  String email;
  String password;

  LoginValidator(this.email, this.password);

  @override
  void validate(Function() success, Function(List<Failure>) errors) {
    List<Failure> failures = [];
    if (email.trim().isEmpty) {
      failures.add(const EmailValidationFailure('Email is required'));
    } else if (!validator.isEmail(email)) {
      failures.add(const EmailValidationFailure());
    }
    if (password.trim().isEmpty) {
      failures.add(const PasswordValidationFailure('Password is required'));
    }
    if (failures.isNotEmpty) {
      errors(failures);
    } else {
      success();
    }
  }
}
</code>```

And I created a failure class for each input field

```<code>class EmailValidationFailure extends Failure {
  const EmailValidationFailure([String message = 'Email is invalid'])
      : super(message);
}

class PasswordValidationFailure extends Failure {
  const PasswordValidationFailure([String message = 'Incorrect password'])
      : super(message);
}
</code>```

And I use the validator in the use case

```<code>class LoginUseCaseInteractor implements LoginUseCaseInputPort {
  final AccountRepository _repository;
  final LoginUseCaseOutputPort outputPort;

  LoginUseCaseInteractor(this._repository, this.outputPort);

  @override
  void login(LoginParams params) {
    LoginValidator(params.email, params.password).validate(() async {
      outputPort.loading();
      Result<bool> result = await _repository.login(params);
      result.when(
        success: (data) {
          outputPort.success();
        },
        error: (error) {
          outputPort.requestError(error);
        },
      );
    }, (errors) {
      outputPort.formValidationErrors(errors);
    });
  }
}
</code>```

and finally I handle the presentation logic in the presenter which it implements the output port of the login use case

```<code>class LoginPresenter implements LoginUseCaseOutputPort {
  Reader read;

  LoginPresenter(this.read) : super(LoginState.initial());

  @override
  void formValidationErrors(List<Failure> errors) =>
      state = LoginState.formValidationErrors(errors);

  @override
  void success() => read(setRootPresenterProvider.notifier).setMainPageAsRoot();

  @override
  void loading() => state = LoginState.loading();

  @override
  void requestError(Failure error) => state = LoginState.requestError(error);
}
</code>```

What I do
I create a failure class for each input field and return failures of all fields in a list and in the presentation logic I check the input failures by type

My Question:
What if I have a large form (eg:15 fields), Should I create a failure class for each of them?
Is there a better way to handle the validation?

答:
My Question: What if I have a large form (eg:15 fields), Should I create a failure class for each of them? Is there a better way to handle the validation?

Every error that can occur must be identifiable. Either through dedicated classes, failure codes or constants. Which one you choose depends on the error context information that you want to provide to clients.

I also wouldn't put messages in the failure object, because it is up to a presenter to choose a presentation for a error type. The way an error is presented to the user highly depends on the user interface. Maybe an error doesn't need a string, it is just presented as an icon or a colored marker and so on. The interactor should not create language specific strings. This is part of the user interface.

In simple cases you might only need an error code or constant like 401 and the presenter converts it to Login failed. Of course you can use a common error object for this cases too.

class Failure {
int code;
}

In other cases you might want to display a more detailed error message like E-mails under the domain '@somedomain.com' are not allowed to login.. In this cases you should use an error object instead of only a simple code to provide details. E.g.

class LoginDomainFailure {
String localPart;
String domainName
}

A presenter can then use this information to generate a failure string or present the error in some other way, e.g. highlighting the domain name in the input field or whatever you can imagine.

Title: Form validation in Clean Architecture

Body:
Input validation is a business logic so we should hide this process in the domain layer.
as discussed here

I do it like this

Login validator

class LoginValidator extends Validator {
  String email;
  String password;

  LoginValidator(this.email, this.password);

  @override
  void validate(Function() success, Function(List<Failure>) errors) {
    List<Failure> failures = [];
    if (email.trim().isEmpty) {
      failures.add(const EmailValidationFailure('Email is required'));
    } else if (!validator.isEmail(email)) {
      failures.add(const EmailValidationFailure());
    }
    if (password.trim().isEmpty) {
      failures.add(const PasswordValidationFailure('Password is required'));
    }
    if (failures.isNotEmpty) {
      errors(failures);
    } else {
      success();
    }
  }
}

And I created a failure class for each input field

class EmailValidationFailure extends Failure {
  const EmailValidationFailure([String message = 'Email is invalid'])
      : super(message);
}

class PasswordValidationFailure extends Failure {
  const PasswordValidationFailure([String message = 'Incorrect password'])
      : super(message);
}

And I use the validator in the use case

class LoginUseCaseInteractor implements LoginUseCaseInputPort {
  final AccountRepository _repository;
  final LoginUseCaseOutputPort outputPort;

  LoginUseCaseInteractor(this._repository, this.outputPort);

  @override
  void login(LoginParams params) {
    LoginValidator(params.email, params.password).validate(() async {
      outputPort.loading();
      Result<bool> result = await _repository.login(params);
      result.when(
        success: (data) {
          outputPort.success();
        },
        error: (error) {
          outputPort.requestError(error);
        },
      );
    }, (errors) {
      outputPort.formValidationErrors(errors);
    });
  }
}

and finally I handle the presentation logic in the presenter which it implements the output port of the login use case

class LoginPresenter implements LoginUseCaseOutputPort {
  Reader read;

  LoginPresenter(this.read) : super(LoginState.initial());

  @override
  void formValidationErrors(List<Failure> errors) =>
      state = LoginState.formValidationErrors(errors);

  @override
  void success() => read(setRootPresenterProvider.notifier).setMainPageAsRoot();

  @override
  void loading() => state = LoginState.loading();

  @override
  void requestError(Failure error) => state = LoginState.requestError(error);
}

What I do
I create a failure class for each input field and return failures of all fields in a list and in the presentation logic I check the input failures by type

My Question:
What if I have a large form (eg:15 fields), Should I create a failure class for each of them?
Is there a better way to handle the validation?


问:
ApexCharts.js Line Chart - Display percent from total in tooltip
I want to display percent instead of an integer.
Now it simply shows the value as integer when hovering on the data point of the chart (the tooltip).

I think I need to set in the formatter formula like this:

```<code>let test = value / SUM(all_values)
return test.toFixed(0) + '%'
</code>```

But, I could not find it in their documentation, the best I found is this one which always gives me 100%, per every data point:

```<code>    tooltip: {
      y: {
        formatter: function(value, opts) {
                let percent = opts.w.globals.seriesPercent[opts.seriesIndex][opts.dataPointIndex];
                return percent.toFixed(0) + '%'

        }
      }
    }
</code>```

答:
```<code><!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <!-- Bootstrap CSS -->

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"

    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <script src="app/app.js"></script>

  <script>

    let apiLabels = [];

    let apiData = [];

    let currentTimestamp = (Math.floor(Date.now() / 1000)).toString();

    //use this URL for daily fetch

    //let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from="+currentTimestamp;

    let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from=1639813032";

    // months list

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    // fetch from api

    var xhr = new XMLHttpRequest();

    xhr.addEventListener("readystatechange", function () {

      if (this.readyState === 4) {

        let myData = JSON.parse(this.responseText);

        console.log(myData);

        for (let i = 0; i < myData.length; i++) {

          //let formedDate = (myData[i]['x']['year']+'-'+myData[i]['x']['month']+'-'+myData[i]['x']['date']).toString();

          let formedDate = monthNames[myData[i]['x']['month']] + ' ' + myData[i]['x']['date'];

          console.log(formedDate);

          let formedLiquidData = (myData[i]['liquidityRate_avg'] * 100).toFixed(2);

          console.log(formedLiquidData+"%");

          apiLabels.push(formedDate);

          apiData.push(formedLiquidData);

        }

            const data = {

            labels: apiLabels,

            datasets: [

            {

              label: "USDC",

              borderColor: "rgb(180,11,107)",

              data: apiData

            }

          ]

        };

             const config = {

              type: "line",

              data: data,

              options:{

             scales: {

              y: {

                ticks: {

                 callback: function (value, index, values) {

                    return value + '%';

                    }

                   }

                },

              },

              },

          };

    const myChart = new Chart(document.getElementById("myChart"), config);

        }

      });

    xhr.open(

      "GET",

      url

    );

    xhr.send();

  </script>

  </div>

  <div id="app"></div>

  <title>brew</title>

  <style>

    body {

      background-color: white;

    }

    .center-form {

      width: 80%;

      margin: auto;

    }

    #title {

      color: teal;

      text-align: center;

    }

    .waitlist {

      position: relative;

      z-index: 3;

      width: 146px;

      height: 30px;

      margin-top: 60px;

      border-style: solid;

      border-width: 1px;

      border-color: #081852;

      background-color: transparent;

      box-shadow: -10px 10px 0 0 #081852;

      color: #081852;

      font-size: 12px;

      line-height: 30px;

      font-weight: 400;

      text-align: center;

      letter-spacing: 0.21px;

      position: fixed;

      right: 3%;

      top: -5%;

    }

    .waitlist-button {

      display: inline-block;

      padding: 9px 15px;

      background-color: #3898EC;

      color: white;

      border: 0;

      line-height: inherit;

      text-decoration: none;

      cursor: pointer;

      border-radius: 0;

    }

    .box-prices {

      padding: 20px;

      width: 200px;

      height: auto;

      color: #000;

      /* background-color: #fff; */

      border: 4px solid #1c1c53;

      border-radius: 2px;

    }

    .dropbtn {

      background-color: navy;

      color: white;

      padding: 16px;

      font-size: 16px;

      border: none;

    }

    .dropdown-content {

      display: none;

      position: absolute;

      background-color: #f1f1f1;

      min-width: 160px;

      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

      z-index: 1;

    }

    .dropdown-content a {

      color: black;

      padding: 12px 16px;

      text-decoration: none;

      display: block;

    }

    .dropdown-content a:hover {

      background-color: #ddd;

    }

    .dropdown:hover .dropdown-content {

      display: block;

    }

    .dropdown:hover .dropbtn {

      background-color: #0b95f1;

    }

    footer {

      display: flex;

      justify-content: space-between;

    }

    .myChart {

      width: 50%;

      height: 40px;

    }

    /* Decorative */

    a {

      text-decoration: none;

      color: #555;

    }

    footer {

      background-color: #82cdf8;

      padding: 20px 40px;

    }

    .right {

      float: left;

      text-align: center;

    }

    .article {

      color: white;

    }

  </style>

</head>

<body>

  <img src="https://uploads-ssl.webflow.com/61768faf04d20bf3487b5a2a/6176a6363e64b8d84e32d0b7_brew-icon-256px-v2.png"

    loading="eager" width="55" height="55" alt="Brew" class="img-logo" position="absolute" top="-3%" left="7;">

  <!-------------- title------------------------>

  <div class="container">

    <div class="row">

      <div class="col-md-12 mt-2">

        <h1 style="color: #1c98">

          Stablecoin Deposits on Aave

        </h1>

        <a data-w-id="14f1dfb2-926f-581f-7faa-3f62171b1db3" href="" class="waitlist waitlist-button">Join the

          waitlist</a>

      </div>

    </div>

  </div>

  <!------------------------AAVE PRICE ------------>

  <div class="container">

    <div class="row mt-5">

      <div class="col-md-6">

        <div class="aave-prices">

          <p>AAVE PRICE</p>

          <p>$172.8</p>

          <p>16%</p>

        </div>

      </div>

      <!------------------------AAVE DESCRIPTION ------------>

      <div class="col-md-6">

        <h1>What is AAVE ?</h1>

        <p>Aave is an open source and non-custodial liquidity protocol for earning

          interest on deposits and borrowing assets.</p>

      </div>

    </div>

    <!------------------------AAVe CHAIN ------------>

    <div class="row">

      <div class="col-md-12 mt-3">

        <button class="dropbtn">CHAIN</button>

        <div class="dropdown-content">

          <a href="#">Polygon</a>

          <a href="#">Ethereum</a>

          <a href="#">Avalance</a>

        </div>

      </div>

    </div>

  </div>

  <!------graph----->

  <div>

    <canvas id="myChart" height="50" weidth="50"></canvas>

  </div>

  <!-- calculator -->

  <div class="container mt-5" style="border: 1px solid black; border-radius: 5px;">

    <div class="row">

      <div class="col-md-12">

        <h1 id="title">How Much You Can Earn ?</h1>

      </div>

    </div>

    <br>

    <div class="row">

      <div class="col-md-6">

        <form>

          <div class="form-group mt-2">

            <label class="form-group">Amount</label>

            <input class="form-control mt-2" type="text" id="principal" placeholder="$">

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Interest rate:   4%</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Compound Freequency:   Daily</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Payout Freequency:   Monthly</label>

          </div>

          <button class="btn btn-block btn-info mt-3" type="button" onclick="calculate()">Calculate</button>

        </form>

      </div>

      <div class="col-md-6">

        <form style="padding-top: 70px;">

          <div class="form-group mt-2">

            <label class="form-group">Interest rate:   5%</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Compound Freequency:   Daily</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Payout Freequency:   Monthly</label>

          </div>

        </form>

      </div>

    </div>

    <br>

    <div class="row">

      <div class="col-md-6">

        <h5 class="total">Result USD</h5>

        <h1 id="USD"></h1>

      </div>

      <div class="col-md-6">

        <h5 class="total">Result USDT</h5>

        <h1 id="USDC"></h1>

      </div>

    </div>

  </div>

  <!-- calculator end -->

  <div>

    <canvas id="myChart_subbagain" height="50" weidth="50" top="80%"></canvas>

  </div>

  <!----footer-->

  <div class="col-md-12 mt-5">

    <footer>

      <div class="col-md-6">

        <img src="/dawnload.png" alt="" width="150">

      </div>

      <div class="col-md-6">

        <section class="right">

          <a href="https://www.brew.money/">Join Brew Today</a>

          <article>USDC is not a legal tender recognised by US or any other government. Unlike a bank account, your

            deposit is not insured. While Brew will make every effort to ensure that your deposit earn the best interest

            rates in the most secure way possible, please note that any investment entails risk. Interest Rates are

            subject to change anytime as per the market conditions.</article>

        </section>

      </div>

    </footer>

  </div>

</body>

<script type="text/javascript">

  function calculate() {

    var principle = 0;

    var interest = 5 / 100;

    var numberOfPeriod = 12;

    var time = 10;

    var CI = 0;

    principle = document.getElementById("principal").value;

    // CI = ((p * (1 + i) ^ n) - p);

    CI = principle * (1 + interest / numberOfPeriod) ^ (numberOfPeriod * time);

    document.getElementById("USD").innerHTML = CI;

    document.getElementById("USDC").innerHTML = CI;

  }

</script>

<!------cal graph-->

</html>
</code>```

Body:
I want to display percent instead of an integer.
Now it simply shows the value as integer when hovering on the data point of the chart (the tooltip).

I think I need to set in the formatter formula like this:

let test = value / SUM(all_values)
return test.toFixed(0) + '%'

But, I could not find it in their documentation, the best I found is this one which always gives me 100%, per every data point:

    tooltip: {
      y: {
        formatter: function(value, opts) {
                let percent = opts.w.globals.seriesPercent[opts.seriesIndex][opts.dataPointIndex];
                return percent.toFixed(0) + '%'

        }
      }
    }

Body:
<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <!-- Bootstrap CSS -->

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"

    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <script src="app/app.js"></script>

  <script>

    let apiLabels = [];

    let apiData = [];

    let currentTimestamp = (Math.floor(Date.now() / 1000)).toString();

    //use this URL for daily fetch

    //let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from="+currentTimestamp;

    let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from=1639813032";

    // months list

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    // fetch from api

    var xhr = new XMLHttpRequest();

    xhr.addEventListener("readystatechange", function () {

      if (this.readyState === 4) {

        let myData = JSON.parse(this.responseText);

        console.log(myData);

        for (let i = 0; i < myData.length; i++) {

          //let formedDate = (myData[i]['x']['year']+'-'+myData[i]['x']['month']+'-'+myData[i]['x']['date']).toString();

          let formedDate = monthNames[myData[i]['x']['month']] + ' ' + myData[i]['x']['date'];

          console.log(formedDate);

          let formedLiquidData = (myData[i]['liquidityRate_avg'] * 100).toFixed(2);

          console.log(formedLiquidData+"%");

          apiLabels.push(formedDate);

          apiData.push(formedLiquidData);

        }

            const data = {

            labels: apiLabels,

            datasets: [

            {

              label: "USDC",

              borderColor: "rgb(180,11,107)",

              data: apiData

            }

          ]

        };

             const config = {

              type: "line",

              data: data,

              options:{

             scales: {

              y: {

                ticks: {

                 callback: function (value, index, values) {

                    return value + '%';

                    }

                   }

                },

              },

              },

          };

    const myChart = new Chart(document.getElementById("myChart"), config);

        }

      });

    xhr.open(

      "GET",

      url

    );

    xhr.send();

  </script>

  </div>

  <div id="app"></div>

  <title>brew</title>

  <style>

    body {

      background-color: white;

    }

    .center-form {

      width: 80%;

      margin: auto;

    }

    #title {

      color: teal;

      text-align: center;

    }

    .waitlist {

      position: relative;

      z-index: 3;

      width: 146px;

      height: 30px;

      margin-top: 60px;

      border-style: solid;

      border-width: 1px;

      border-color: #081852;

      background-color: transparent;

      box-shadow: -10px 10px 0 0 #081852;

      color: #081852;

      font-size: 12px;

      line-height: 30px;

      font-weight: 400;

      text-align: center;

      letter-spacing: 0.21px;

      position: fixed;

      right: 3%;

      top: -5%;

    }

    .waitlist-button {

      display: inline-block;

      padding: 9px 15px;

      background-color: #3898EC;

      color: white;

      border: 0;

      line-height: inherit;

      text-decoration: none;

      cursor: pointer;

      border-radius: 0;

    }

    .box-prices {

      padding: 20px;

      width: 200px;

      height: auto;

      color: #000;

      /* background-color: #fff; */

      border: 4px solid #1c1c53;

      border-radius: 2px;

    }

    .dropbtn {

      background-color: navy;

      color: white;

      padding: 16px;

      font-size: 16px;

      border: none;

    }

    .dropdown-content {

      display: none;

      position: absolute;

      background-color: #f1f1f1;

      min-width: 160px;

      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);

      z-index: 1;

    }

    .dropdown-content a {

      color: black;

      padding: 12px 16px;

      text-decoration: none;

      display: block;

    }

    .dropdown-content a:hover {

      background-color: #ddd;

    }

    .dropdown:hover .dropdown-content {

      display: block;

    }

    .dropdown:hover .dropbtn {

      background-color: #0b95f1;

    }

    footer {

      display: flex;

      justify-content: space-between;

    }

    .myChart {

      width: 50%;

      height: 40px;

    }

    /* Decorative */

    a {

      text-decoration: none;

      color: #555;

    }

    footer {

      background-color: #82cdf8;

      padding: 20px 40px;

    }

    .right {

      float: left;

      text-align: center;

    }

    .article {

      color: white;

    }

  </style>

</head>

<body>

  <img src="https://uploads-ssl.webflow.com/61768faf04d20bf3487b5a2a/6176a6363e64b8d84e32d0b7_brew-icon-256px-v2.png"

    loading="eager" width="55" height="55" alt="Brew" class="img-logo" position="absolute" top="-3%" left="7;">

  <!-------------- title------------------------>

  <div class="container">

    <div class="row">

      <div class="col-md-12 mt-2">

        <h1 style="color: #1c98">

          Stablecoin Deposits on Aave

        </h1>

        <a data-w-id="14f1dfb2-926f-581f-7faa-3f62171b1db3" href="" class="waitlist waitlist-button">Join the

          waitlist</a>

      </div>

    </div>

  </div>

  <!------------------------AAVE PRICE ------------>

  <div class="container">

    <div class="row mt-5">

      <div class="col-md-6">

        <div class="aave-prices">

          <p>AAVE PRICE</p>

          <p>$172.8</p>

          <p>16%</p>

        </div>

      </div>

      <!------------------------AAVE DESCRIPTION ------------>

      <div class="col-md-6">

        <h1>What is AAVE ?</h1>

        <p>Aave is an open source and non-custodial liquidity protocol for earning

          interest on deposits and borrowing assets.</p>

      </div>

    </div>

    <!------------------------AAVe CHAIN ------------>

    <div class="row">

      <div class="col-md-12 mt-3">

        <button class="dropbtn">CHAIN</button>

        <div class="dropdown-content">

          <a href="#">Polygon</a>

          <a href="#">Ethereum</a>

          <a href="#">Avalance</a>

        </div>

      </div>

    </div>

  </div>

  <!------graph----->

  <div>

    <canvas id="myChart" height="50" weidth="50"></canvas>

  </div>

  <!-- calculator -->

  <div class="container mt-5" style="border: 1px solid black; border-radius: 5px;">

    <div class="row">

      <div class="col-md-12">

        <h1 id="title">How Much You Can Earn ?</h1>

      </div>

    </div>

    <br>

    <div class="row">

      <div class="col-md-6">

        <form>

          <div class="form-group mt-2">

            <label class="form-group">Amount</label>

            <input class="form-control mt-2" type="text" id="principal" placeholder="&#36;">

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Interest rate:&nbsp;&nbsp;&nbsp;4%</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Compound Freequency:&nbsp;&nbsp;&nbsp;Daily</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Payout Freequency:&nbsp;&nbsp;&nbsp;Monthly</label>

          </div>

          <button class="btn btn-block btn-info mt-3" type="button" onclick="calculate()">Calculate</button>

        </form>

      </div>

      <div class="col-md-6">

        <form style="padding-top: 70px;">

          <div class="form-group mt-2">

            <label class="form-group">Interest rate:&nbsp;&nbsp;&nbsp;5%</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Compound Freequency:&nbsp;&nbsp;&nbsp;Daily</label>

          </div>

          <div class="form-group mt-2">

            <label class="form-group">Payout Freequency:&nbsp;&nbsp;&nbsp;Monthly</label>

          </div>

        </form>

      </div>

    </div>

    <br>

    <div class="row">

      <div class="col-md-6">

        <h5 class="total">Result USD</h5>

        <h1 id="USD"></h1>

      </div>

      <div class="col-md-6">

        <h5 class="total">Result USDT</h5>

        <h1 id="USDC"></h1>

      </div>

    </div>

  </div>

  <!-- calculator end -->

  <div>

    <canvas id="myChart_subbagain" height="50" weidth="50" top="80%"></canvas>

  </div>

  <!----footer-->

  <div class="col-md-12 mt-5">

    <footer>

      <div class="col-md-6">

        <img src="/dawnload.png" alt="" width="150">

      </div>

      <div class="col-md-6">

        <section class="right">

          <a href="https://www.brew.money/">Join Brew Today</a>

          <article>USDC is not a legal tender recognised by US or any other government. Unlike a bank account, your

            deposit is not insured. While Brew will make every effort to ensure that your deposit earn the best interest

            rates in the most secure way possible, please note that any investment entails risk. Interest Rates are

            subject to change anytime as per the market conditions.</article>

        </section>

      </div>

    </footer>

  </div>

</body>

<script type="text/javascript">

  function calculate() {

    var principle = 0;

    var interest = 5 / 100;

    var numberOfPeriod = 12;

    var time = 10;

    var CI = 0;

    principle = document.getElementById("principal").value;

    // CI = ((p * (1 + i) ^ n) - p);

    CI = principle * (1 + interest / numberOfPeriod) ^ (numberOfPeriod * time);

    document.getElementById("USD").innerHTML = CI;

    document.getElementById("USDC").innerHTML = CI;

  }

</script>

<!------cal graph-->

</html>


问:
servicestack and ormlite database auto generation
In servicestack and ormlite
How do you auto generate database and seed it the first time it is accessed when using code first approach and you have a valid connection to the database server.</p>

答:
You'd use ServiceStack's AutoQuery AutoGen feature if you're asking about auto generating APIs and POCO data models for your existing RDBMS tables.

If you want to generate Tables from POCO Data Models you would use OrmLite Create Table APIs, e.g:

using var db = appHost.Resolve<IDbConnectionFactory>().Open();

if (db.CreateTableIfNotExists<Person>())
{
    db.Insert(new Person { Id = 1, Name = "John Doe" });
}
```


问:
Inherit configurations from a basic-language in monaco-editor
Is it possible to create a new language:

```<code>monaco.languages.register({ id: 'sql2' });
</code>```

Inheriting all the configs from an already existing language ('sql' in this case)?

Basically, I want to create a new language to add some completionProviders, but I want to inherit all the default configs (syntax highlighting mostly) from the base 'sql' lang.

答:
That's possible, yes. Check the language definition files in Monaco (e.g. monaco-editor/esm/vs/basic-languages/mysql/mysql) and how they define keywords and syntax highlighting. You can create your own definition file and import existing files to re-use those. Here's a part of a language definition I wrote, which combines 4 languages into one:

import { languages } from "monaco-editor/esm/vs/editor/editor.api";

import { language as js } from "monaco-editor/esm/vs/basic-languages/javascript/javascript";
import { conf as tsConfig, language as ts } from "monaco-editor/esm/vs/basic-languages/typescript/typescript";
import { language as mysql } from "monaco-editor/esm/vs/basic-languages/mysql/mysql";
import { language as py } from "monaco-editor/esm/vs/basic-languages/python/python";

type IRichLanguageConfiguration = languages.LanguageConfiguration;
type ILanguage = languages.IMonarchLanguage;

export const languageConfiguration: IRichLanguageConfiguration = {
    ...tsConfig,
};

export const language: ILanguage = {
    defaultToken: "invalid",
    ignoreCase: false,

    typeKeywords: [], // We have no TS types.
    keywords: ts.keywords,

    operators: ts.operators,
    symbols: ts.symbols,
    escapes: ts.escapes,
    digits: ts.digits,
    octaldigits: ts.octaldigits,
    binarydigits: ts.binarydigits,
    hexdigits: ts.hexdigits,
    regexpctl: ts.regexpctl,
    regexpesc: ts.regexpesc,

    // Since we use also JS as sub language and we can only specify case sensitivity on a global level, we make
    // SQL case-insensitive by duplicating some symbols with lower case style.
    mysqlBrackets: mysql.brackets,
    mysqlKeywords: [
        ...mysql.keywords,
        ...(mysql.keywords as string[]).map((keyword) => { return keyword.toLowerCase(); }),
    ],
    mysqlOperators: [
        ...mysql.operators,
        ...(mysql.operators as string[]).map((operator: string) => { return operator.toLowerCase(); }),
    ],
...
```

Body:
Is it possible to create a new language:

monaco.languages.register({ id: 'sql2' });

Inheriting all the configs from an already existing language ('sql' in this case)?

Basically, I want to create a new language to add some completionProviders, but I want to inherit all the default configs (syntax highlighting mostly) from the base 'sql' lang.


问:
Azure speech-to-text - Continuos Recognition
I would like to see the accuracy of the speech services from Azure, specifically speech-to-text using an audio file.

I have been reading the documentation https://learn.microsoft.com/en-us/python/api/azure-cognitiveservices-speech/?view=azure-python and playing around with a suggested code from the MS quickstar page. The code workds fine and I can get some transcription, but it just transcribes the beginning of the audio (first utterance):

```<code>import azure.cognitiveservices.speech as speechsdk

speechKey = 'xxx'
service_region = 'westus'

speech_config = speechsdk.SpeechConfig(subscription=speechKey, region=service_region, speech_recognition_language="es-MX")
audio_config = speechsdk.audio.AudioConfig(use_default_microphone=False, filename='lala.wav')

sr = speechsdk.SpeechRecognizer(speech_config, audio_config)

es = speechsdk.EventSignal(sr.recognized, sr.recognized)

result = sr.recognize_once()

if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print("Recognized: {}".format(result.text))
elif result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized: {}".format(result.no_match_details))
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print("Speech Recognition canceled: {}".format(cancellation_details.reason))
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("Error details: {}".format(cancellation_details.error_details))
</code>```

Based on the documentation, looks like I have to use signals and events to capture the full audio using method start_continuous_recognition (which is not documented for python, but looks like the method and related classes are implemented).
I tried to follow other examples from c# and Java but was not able to implement this in Python.

Has anyone been able to do this and provie some pointers?
Thank you very much!

答:
and to further assist with @David Beauchemin's solution, the following code block worked for me to get the final result in a neat list:</p>
```<code>speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING:{}'.format(evt)))
speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED:{}'.format(evt)))
all_results = []
def handle_final_result(evt):
    all_results.append(evt.result.text)
speech_recognizer.recognized.connect(handle_final_result)
speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED:{}'.format(evt)))
speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))

speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)
</code>```

Body:
I would like to see the accuracy of the speech services from Azure, specifically speech-to-text using an audio file.

I have been reading the documentation https://learn.microsoft.com/en-us/python/api/azure-cognitiveservices-speech/?view=azure-python and playing around with a suggested code from the MS quickstar page. The code workds fine and I can get some transcription, but it just transcribes the beginning of the audio (first utterance):

import azure.cognitiveservices.speech as speechsdk

speechKey = 'xxx'
service_region = 'westus'

speech_config = speechsdk.SpeechConfig(subscription=speechKey, region=service_region, speech_recognition_language="es-MX")
audio_config = speechsdk.audio.AudioConfig(use_default_microphone=False, filename='lala.wav')

sr = speechsdk.SpeechRecognizer(speech_config, audio_config)

es = speechsdk.EventSignal(sr.recognized, sr.recognized)

result = sr.recognize_once()

if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print("Recognized: {}".format(result.text))
elif result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized: {}".format(result.no_match_details))
elif result.reason == speechsdk.ResultReason.Canceled:
    cancellation_details = result.cancellation_details
    print("Speech Recognition canceled: {}".format(cancellation_details.reason))
    if cancellation_details.reason == speechsdk.CancellationReason.Error:
        print("Error details: {}".format(cancellation_details.error_details))

Based on the documentation, looks like I have to use signals and events to capture the full audio using method start_continuous_recognition (which is not documented for python, but looks like the method and related classes are implemented).
I tried to follow other examples from c# and Java but was not able to implement this in Python.

Has anyone been able to do this and provie some pointers?
Thank you very much!

Body:
and to further assist with @David Beauchemin's solution, the following code block worked for me to get the final result in a neat list:

speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING:{}'.format(evt)))
speech_recognizer.recognized.connect(lambda evt: print('RECOGNIZED:{}'.format(evt)))
all_results = []
def handle_final_result(evt):
    all_results.append(evt.result.text)
speech_recognizer.recognized.connect(handle_final_result)
speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED:{}'.format(evt)))
speech_recognizer.session_stopped.connect(lambda evt: print('SESSION STOPPED {}'.format(evt)))
speech_recognizer.canceled.connect(lambda evt: print('CANCELED {}'.format(evt)))

speech_recognizer.session_stopped.connect(stop_cb)
speech_recognizer.canceled.connect(stop_cb)


问:
Using PowerShell to get the Vnet name by resource ID in Azure
Assuming I have an Azure resource ID
Such as:

"/subscriptions/XXXXXXXX/resourceGroups/YYYYYY/providers/Microsoft.ZZZZ/WWWWW/my-resource-name"

How can I find out to which Vnets its connected/sits in using PowerShell commands?

答:
It will be possible ,but you have to write lengthy code for it.(e.g If you have Network interface you need to use if block for it, so that it gets you the network interface subnetid and then again elseiffor any other resource ).

Azure portal provides a feature called connected device from their we can simply check the devices are connected to the V-net.
As shown here:

Using Powershell CMD if you get the virtual network you can determine the associated resources in the subnet :-


问:
Cannot run debug Go using VSCode on Mac M1
I found a topic that encounter the same problem (Can't debug Golang in vscode apple m1) but I'm not sure it's an old solution or not because I'm using the Go version

```<code>go1.17.1 darwin/arm64
</code>```

with

```<code>dlv version 1.7.2
</code>```

and

```<code>VSCode version 1.60.2 (arm64)
</code>```

on

```<code>Mac M1 BigSur (11.6)
</code>```

when I run debug (fn+f5) a Debug console shows:

```<code>Starting: /Users/username/go/bin/dlv-dap dap --check-go-version=false --listen=127.0.0.1:53115 --log-dest=3 from /Users/username/go/src/project-name
DAP server listening at: 127.0.0.1:53115
</code>```

and there is a Pop-up error:

```<code>Failed to launch: could not launch process: can not run under Rosetta, check that the installed build of Go is right for your CPU architecture
</code>```

I have tried downgrade go version to 1.16.8 arm64 with dlv 1.6.1 but still got the same error.

I can use go build successfully on both versions.

答:
What worked for me:

Check for "chip" your mac is using, you can check that from "About This Mac" > "Overview" > "Chip"

If Apple chip is used, then download "arm64" type of files, such as "go-darwin-arm64.pkg", "vscode-arm64" etc. You get my point.

If Intel chip is used, then download with "amd" type.

Download and install "DELVE" from https://github.com/go-delve/delve/tree/master/Documentation/installation

Run your debugger.

Let me know, if you want the "launch.json" file config too, to debug.

EDIT 11-04-22

Sharing the launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}/main.go",
            "args": [],
        }
    ]
}
</code>```

Body:
I found a topic that encounter the same problem (Can't debug Golang in vscode apple m1) but I'm not sure it's an old solution or not because I'm using the Go version

go1.17.1 darwin/arm64

with

dlv version 1.7.2

and

VSCode version 1.60.2 (arm64)

on

Mac M1 BigSur (11.6)

when I run debug (fn+f5) a Debug console shows:

Starting: /Users/username/go/bin/dlv-dap dap --check-go-version=false --listen=127.0.0.1:53115 --log-dest=3 from /Users/username/go/src/project-name
DAP server listening at: 127.0.0.1:53115

and there is a Pop-up error:

Failed to launch: could not launch process: can not run under Rosetta, check that the installed build of Go is right for your CPU architecture

I have tried downgrade go version to 1.16.8 arm64 with dlv 1.6.1 but still got the same error.

I can use go build successfully on both versions.

Body:
What worked for me:

Check for "chip" your mac is using, you can check that from "About This Mac" > "Overview" > "Chip"

If Apple chip is used, then download "arm64" type of files, such as "go-darwin-arm64.pkg", "vscode-arm64" etc. You get my point.

If Intel chip is used, then download with "amd" type.

Download and install "DELVE" from https://github.com/go-delve/delve/tree/master/Documentation/installation

Run your debugger.

Let me know, if you want the "launch.json" file config too, to debug.

EDIT 11-04-22

Sharing the launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}/main.go",
            "args": [],
        }
    ]
}


问:
Flex compiler metadata "DefaultProperty"
Given the following:

```<code><?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2009/mxml">
    <mx:Panel title="blah">
       <mx:Button />
    </mx:Panel>
</mx:Application>
</code>```

Can you tell me where child elements (ex. mx:Button) are assigned in parent elements (ex. mx:Panel) by default by mxmlc. You can set the "DefaultProperty" compiler metadata tag to specify where they are assigned but what does flex do when it is not specified.

For example I've traversed the source of all the flex classes mx:Panel inherits from and DefaultProperty is never mentioned, leading me to wonder what the default value of DefaultProperty.

sorry for any noobishness but i've read the docs inside out.

答: The compiler actually treats child components of containers as a special case. Take a look at the childDescriptors property of mx.core.Container for some explanation. When you create a Flex component instance in MXML, it isn't instantiated immediately. Instead, a "descriptor" is created, and that is used to instantiate the component at some future time, as determined by the container's creationPolicy property. If you add the -keep-generated-actionscript argument (or the shortened version, -keep) to your compiler arguments, you'll be able to see the AS3 code that the compiler generates from MXML.

OwnerDisplayName: max

Body:
Given the following:

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2009/mxml">
    <mx:Panel title="blah">
       <mx:Button />
    </mx:Panel>
</mx:Application>

Can you tell me where child elements (ex. mx:Button) are assigned in parent elements (ex. mx:Panel) by default by mxmlc. You can set the "DefaultProperty" compiler metadata tag to specify where they are assigned but what does flex do when it is not specified.

For example I've traversed the source of all the flex classes mx:Panel inherits from and DefaultProperty is never mentioned, leading me to wonder what the default value of DefaultProperty.

sorry for any noobishness but i've read the docs inside out.

OwnerDisplayName: joshtynjala


问:
How to make the corresponding text bold depending on the URL visited/link clicked in ASP.NET Core?
I have this rather primitive issue, but I have no idea how to solve this:

I have a side hierarchy menu in one of many Razor pages and for now I just manually make the current page bold in the HTML.

Is there a possibility to automate this?

What's the best approach for giving the state of the current page?

Does ASP.NET Core have an integrated function/etc for this?

Here's how my side menu looks like:

```<code><div class="col-sm-2 side-menu" style="">
      <ul id="menu-map" class="menu" style="">
          <li class=""><a href="/test1" aria-current="page">
            <span>TEST1</span>
          </a></li>
          <li class=""><a href="/test2" aria-current="page">
            <span>test2</span>
          </a></li>
          <li class=""><a href="/test3" aria-current="page">
            <span>test3</span>
          </a></li>
          <li class=""><a href="/test4" aria-current="page">
            <span>test4</span>
          </a></li>
          <li class=""><a href="/test5" aria-current="page">
            <span><strong>test5</strong></span>
          </a></li>
      </ul>
</div>
</code>```

col-sm-2 is a Bootstrap 4 class, yes.

Another ELI5 example:

In the side menu above if I click on TEST1 the TEST1 gets bold text, if I click on test2, test2 gets bold text on that page. (/test1 and /test2 correspondently)

A CSS solution might kind of work, but what if the user gets a link to one of the pages? Hence a pure CSS solution is not viable in my opinion.

答:
Does ASP.NET Core have an integrated function/etc for this?

It seems no such build-in function to achive this client side requirement.

Once you click the link, it will redirect to another page and lose the state of the anchor tag. So you can use localStorage to store the selected anchor tag's index. And add the font-weight: bold class to selected link:

```<code><head>
    <style>
          .active{
                font-weight: bold;
            }
    </style>
</head>
<script>
    $(function(){
        var data = localStorage.getItem("index");
        if(data!=null)
        {
            $('ul li').eq(data).addClass('active');
        }
    })
    $("#menu-map").find('a').click(function () {
        var str = $(this).parents("li").index();
        localStorage.setItem("index",str);
    });
</script>
</code>```

Body:
I have this rather primitive issue, but I have no idea how to solve this:

I have a side hierarchy menu in one of many Razor pages and for now I just manually make the current page bold in the HTML.

Is there a possibility to automate this?

What's the best approach for giving the state of the current page?

Does ASP.NET Core have an integrated function/etc for this?

Here's how my side menu looks like:

            TEST1

            test2

            test3

            test4

            test5

col-sm-2 is a Bootstrap 4 class, yes.

Another ELI5 example:

In the side menu above if I click on TEST1 the TEST1 gets bold text, if I click on test2, test2 gets bold text on that page. (/test1 and /test2 correspondently)

A CSS solution might kind of work, but what if the user gets a link to one of the pages? Hence a pure CSS solution is not viable in my opinion.

Body:
Does ASP.NET Core have an integrated function/etc for this?

It seems no such build-in function to achive this client side requirement.

Once you click the link, it will redirect to another page and lose the state of the anchor tag. So you can use localStorage to store the selected anchor tag's index. And add the font-weight: bold class to selected link:

<head>
    <style>
          .active{
                font-weight: bold;
            }
    </style>
</head>
<script>
    $(function(){
        var data = localStorage.getItem("index");
        if(data!=null)
        {
            $('ul li').eq(data).addClass('active');
        }
    })
    $("#menu-map").find('a').click(function () {
        var str = $(this).parents("li").index();
        localStorage.setItem("index",str);
    });
</script>


问:
Hover on anchor link and show icon
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

答:
You could add another element like span after a and use the sibling selector +.

a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
}

span {
  display: inline-block;
  width: 15px;
  height: 15px;
}

/* mouse hover link */

a:hover+span {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<span></span><br>
Some Random Header Text but Longer<span></span></code>```

Title: Hover on anchor link and show icon

Body:
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}

Some Random Header Text

Some Random Header Text but Longer

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

Body:
You could add another element like span after a and use the sibling selector +.

a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
}

span {
  display: inline-block;
  width: 15px;
  height: 15px;
}

/* mouse hover link */

a:hover+span {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: cover;
}

<a href="#">Some Random Header Text</a><span></span><br>
<a href="#">Some Random Header Text but Longer</a><span></span>


问:
How to get the json representation of the ElasticSearch query/request that was built with Java API Client (7.16)?
A new Java API Client was released in the 7.16 version of ES and the Java Rest Client was deprecated. There was the ability to convert a query to JSON in the deprecated client. It was convenient for debugging/tuning/profiling of the query in Kibana.

Unfortunately, I don't see any mention of this in the new client documentation. So my question is:

Is it possible to get a JSON representation of the query that was constructed via the Java API Client? It can be either some utility class or log config of the client that prints outgoing requests.

答:
The only way I found so far is to put a conditional breakpoint in
co/elastic/clients/transport/rest_client/RestClientTransport.java:215 from elasticsearch-java-7.16.2.jar and check the value of baos variable.</p>


问:
Countif only if it exists for one particular criteria for only the first instance
I am stuck with something that I feel like should be relatively simple.

I am trying to create a count column that only counts the IDs that are only classified with DC, and only counts it for the first instance.

Expected outcome:

So far what I thought of was to create an unique ID in order to only count the first instance:

I tried the following formula but it's not correct as it cannot correctly identify only the cells that fit my criteria.

=IF(A2=A1,0,COUNTIF($A$2:$A$7,C2:C7="DC"))

Any help is much appreciated.

答:
Your question is unclear on several aspects, for example the first and last rows match the criteria you mentioned (classified as DC and first instance).  In addition the count is showing "1", where there are 2 x "DC" instances in the ID? Would assume this is sorted in Key order.   So with that...

The trick is to work out the cell in which the first instance that the criteria occurs within, and then execute the count.

```<code>=IF(AND(COUNTIF(A$2:A$7,A2)>1,COUNTIF(A$2:A2,A2)=1),COUNTIF(A$2:A$7,A2)-1,0)
</code>```

This IF statement checks if the key appears more than once, AND if it is the first occurrence of the key. If these are both true, then execute the count.  I have assumed you don't want to count the first instance (hence the -1), so keep or remove that if it makes sense.  Please take careful note of the absolute references, particularly in the second COUNTIF which only counts down to the current row (A2).

Update.

With the comments below, if you are only looking to mark the row, then the following will show a true/false that takes into account your updated criteria. If you need more, use this as the basis for an "IF" statement.

```<code>=AND(COUNTIF(B$2:B$7,B2)=COUNTIF(A$2:A$7,A2),COUNTIF(A$2:A2,A2)=1)
</code>```

Body:
Your question is unclear on several aspects, for example the first and last rows match the criteria you mentioned (classified as DC and first instance).  In addition the count is showing "1", where there are 2 x "DC" instances in the ID? Would assume this is sorted in Key order.   So with that...

The trick is to work out the cell in which the first instance that the criteria occurs within, and then execute the count.

=IF(AND(COUNTIF(A$2:A$7,A2)>1,COUNTIF(A$2:A2,A2)=1),COUNTIF(A$2:A$7,A2)-1,0)

This IF statement checks if the key appears more than once, AND if it is the first occurrence of the key. If these are both true, then execute the count.  I have assumed you don't want to count the first instance (hence the -1), so keep or remove that if it makes sense.  Please take careful note of the absolute references, particularly in the second COUNTIF which only counts down to the current row (A2).

Update.

With the comments below, if you are only looking to mark the row, then the following will show a true/false that takes into account your updated criteria. If you need more, use this as the basis for an "IF" statement.

=AND(COUNTIF(B$2:B$7,B2)=COUNTIF(A$2:A$7,A2),COUNTIF(A$2:A2,A2)=1)


问:
php - mysql avoid sql injections
I have many functions like

```<code>updateUser($id,$username,$email)
updateMusic($id, $music)
</code>```

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

```<code>$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);
</code>```

答: No there isn't, but you can parse all your inputs ( eg. GET and POST ) at beggining of the script</p>

ContentLicense: CC BY-SA 3.0

Title: php - mysql avoid sql injections

Body:
I have many functions like

updateUser($id,$username,$email)
updateMusic($id, $music)

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);


问:
How to change default Anaconda python environment
I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from the terminal it gives me version 2.7. In order to work with Python 3.4, I need to issue the commands (in the shell)

```<code>source activate py34
ipython
</code>```

which change the default environment to Python 3.4. This works fine, but it's annoying since most of the time I work on Python 3.4, instead of Python 2.7 (which I hold for teaching purposes, it's a rather long story). Anyway, I'll like to know how to change the default environment to Python 3.4, bearing in mind that I don't want to reinstall everything from scratch.

答:
Tried both source activate default_3_9 and source conda activate default_3_9

but worked conda activate default_3_9

Body:
I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from the terminal it gives me version 2.7. In order to work with Python 3.4, I need to issue the commands (in the shell)

source activate py34
ipython

which change the default environment to Python 3.4. This works fine, but it's annoying since most of the time I work on Python 3.4, instead of Python 2.7 (which I hold for teaching purposes, it's a rather long story). Anyway, I'll like to know how to change the default environment to Python 3.4, bearing in mind that I don't want to reinstall everything from scratch.