问:
ASP.NET MVC - is it okay to have sideline presentation logic?
In most documentation you read about ASP.NET MVC, the entire 'Separation of Concerns' is very heavily pushed. Dependency Injection/Inversion of Control, Unit Testing, keeping 'logic' out of the Views, etc.

But how far is this intended to be pushed? Is it bad practice if a specific task requires extra logic beyond the 'three layer' approach of View/Model/Persistence?

For example, I have a solution set up with four individual projects.

```<code>Project.Web (ASP.NET MVC) [ References Data.dll, Models.dll ]
Project.Data (Fluent nHibernate Mapping) [ References Models.dll ]
Project.Models (POCO, Helpers, Factories, etc)
Project.Tests (Unit Testing)
</code>```

Up until now, this has served me pretty well. But I require some very abstract logic for some of my MVC Views, such that I need to take part of the Models and arrange a View Model that is persisted in the database.

This cannot happen in my Data section, as that would dispose the re-usability of it, and there is business logic included in the process. It cannot entirely happen in my Models section, because that would require it to have knowledge of the Data section, which it does not. And I do not want to put it in the Web section because I don't want data access code there.

Question

Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to? Moreover project concerns aside, is this a bad approach in general or is this something a lot of you find yourselves having to do at times? Part of me feels that if I am having to resort to this, then I've just built my software wrong - but at the same time I am very confident I have done a fairly good job, it is just too abstract to make a raw HTML interpretation of without middle-man arrangement.

答:
I use the following structure, which more or less solves all problems we've had regarding MVC structures.

Models: contains all ViewModels. Just clean, only getters and setters.

Business logic implementation: Set of projects that contains database logic, DAL entities etc. But only has one interface (in our case this is a WCF API).

ServiceLayer: the bridge between Business Logic and ViewModels. Doesn't know anything about web.

Mapping layer: translation between business entities and ViewModels.

Web project: holds very thin Controllers and Views, and everything web related.

A web page flow will follow this flow:

URL maps to a certain Action

Actions are really clean, they only reference a method in the ServiceLayer

The ServiceLayer executes one or more actions in the Business Logic Implementation (get data, store data, etc.)

The ServiceLayer passes the business entities to the Mapping Layer.

The Mapping Layer translates business entities into ViewModels

In code this would look like:

```<code>// action
public ActionResult ListOfObjects () {
    var model = new ServiceLayer.ObjectsClient().GetListOfObjects();
    return View(model);
}

// Service Layer
public ListOfObjectsModel GetListOfObjects () {
    var businessEntities = BusinessDao.GetThingysFromDb();

    var model = Mapper.TranslateToViewModel(businessEntities);

    return model;
}

// Mapping Layer
public ListOfObjectsModel TranslateToViewModel(List<BusinessEntity> entities) {
    // do mapping
}
</code>```

When handling POSTs you will follow the same flow, but the mapping layer should translate your ViewModel into Data Entities that are given to the Business Logic.

Body:
In most documentation you read about ASP.NET MVC, the entire 'Separation of Concerns' is very heavily pushed. Dependency Injection/Inversion of Control, Unit Testing, keeping 'logic' out of the Views, etc.

But how far is this intended to be pushed? Is it bad practice if a specific task requires extra logic beyond the 'three layer' approach of View/Model/Persistence?

For example, I have a solution set up with four individual projects.

Project.Web (ASP.NET MVC) [ References Data.dll, Models.dll ]
Project.Data (Fluent nHibernate Mapping) [ References Models.dll ]
Project.Models (POCO, Helpers, Factories, etc)
Project.Tests (Unit Testing)

Up until now, this has served me pretty well. But I require some very abstract logic for some of my MVC Views, such that I need to take part of the Models and arrange a View Model that is persisted in the database.

This cannot happen in my Data section, as that would dispose the re-usability of it, and there is business logic included in the process. It cannot entirely happen in my Models section, because that would require it to have knowledge of the Data section, which it does not. And I do not want to put it in the Web section because I don't want data access code there.

Question

Is it in massive violation for me to add, say, a Project.Presentation project that references Data.dll and Models.dll to construct what I need to? Moreover project concerns aside, is this a bad approach in general or is this something a lot of you find yourselves having to do at times? Part of me feels that if I am having to resort to this, then I've just built my software wrong - but at the same time I am very confident I have done a fairly good job, it is just too abstract to make a raw HTML interpretation of without middle-man arrangement.

Body:
I use the following structure, which more or less solves all problems we've had regarding MVC structures.

Models: contains all ViewModels. Just clean, only getters and setters.

Business logic implementation: Set of projects that contains database logic, DAL entities etc. But only has one interface (in our case this is a WCF API).

ServiceLayer: the bridge between Business Logic and ViewModels. Doesn't know anything about web.

Mapping layer: translation between business entities and ViewModels.

Web project: holds very thin Controllers and Views, and everything web related.

A web page flow will follow this flow:

URL maps to a certain Action

Actions are really clean, they only reference a method in the ServiceLayer

The ServiceLayer executes one or more actions in the Business Logic Implementation (get data, store data, etc.)

The ServiceLayer passes the business entities to the Mapping Layer.

The Mapping Layer translates business entities into ViewModels

In code this would look like:

// action
public ActionResult ListOfObjects () {
    var model = new ServiceLayer.ObjectsClient().GetListOfObjects();
    return View(model);
}

// Service Layer
public ListOfObjectsModel GetListOfObjects () {
    var businessEntities = BusinessDao.GetThingysFromDb();

    var model = Mapper.TranslateToViewModel(businessEntities);

    return model;
}

// Mapping Layer
public ListOfObjectsModel TranslateToViewModel(List<BusinessEntity> entities) {
    // do mapping
}

When handling POSTs you will follow the same flow, but the mapping layer should translate your ViewModel into Data Entities that are given to the Business Logic.


来源: stackexchange

问:
Managing classes in tensorflow object detection API
I'm working on a project that requires the recognition of just people in a video or a live stream from a camera. I'm currently using the tensorflow object recognition API with python, and i've tried different pre-trained models and frozen inference graphs. I want to recognize only people and maybe cars so i don't need my neural network to recognize all 90 classes that come with the frozen inference graphs, based on mobilenet or rcnn, as it seems this slows the process, and 89 of this 90 classes are not needed in my project. Do i have to train my own model or is there a way to modify the inference graphs and the existing models? This is probably a noob question for some of you, but mind that i've worked with tensorflow and machine learning for just one month.
Thanks in advance</p>

答:
Yes, you have to train own model. Let's see in short words some ways how to do.

OPTION 1. When you want to apply transfer knowledge as maximum as possible, you can froze the CNN layers. After, you change a quantity of detected classes with dimension of classifier (dense layers). The classifier is the latest part in CNN architecture. Now, you should retrain only classifier.

OPTION 2. Assuming, you want to apply transfer knowledge for first layers of CNN (for example, froze first 2-3 CNN layers) and retrain rest of CNN with classifier. After, you change a quantity of detected classes with dimension of classifier. Now, you should retrain rest of CNN layers and classifier.

OPTION 3. Assuming, you want to retrain whole CNN with classifier. After, you change a quantity of detected classes with dimension of classifier. Now, you should retrain whole CNN with classifier.

Generally, the Tensorflow Object Detection API is a good start for beginners! How to proceed with your problem you can see here more detail about whole process and extra explanation here.

ContentLicense: CC BY-SA 4.0


问:
Using Curl with Kubernetes nginx Ingress #5116
I configured authentication through nginx to a specific service in k8s.

It works fine with WUI.

I saw some examples

This works fine too:

curl -v http://10.2.29.4/ -H 'Host: foo.bar.com' -u 'foo:bar'

But i need to close other part my url same.

For example /api/v1/upload

I deployd 2nd ingress with path:

```<code>spec:
  rules:
  - host: foo.bar.com
    http:
      paths:
      - backend:
          serviceName: service
          servicePort: 8000
        path: /api/v1/upload
</code>```

Without nginx i got to type:

curl -XPOST 'file=@/file' http://10.2.29.4:8000/api/v1/upload -H "Authorization:key"

How do i need to try use curl for hide real ip or port and get a good result?

I would really appreciate if you could help me figure it out.

ingress1:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf
  namespace: default
  labels:
    app: mobsf
#    env: dev
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: mobsf-basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - path: /
      - backend:
          serviceName: mobsf
          servicePort: 8000
</code>```

Ingress 2:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf2
  namespace: default
  labels:
    app: mobsf2
#    env: dev
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: mobsf-basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - backend:
          serviceName: mobsf2
          servicePort: 8000
        path: /api/v1/
</code>```

DNS check (correct):

```<code> nslookup worker1.mydomain.local
Server:         10.2.67.10
Address:        10.2.67.10#53

Name:   worker1.mydomain.local
Address: 10.2.67.203
</code>```

Services:

```<code>kubectl get svc
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes      ClusterIP      10.233.0.1      <none>        443/TCP          159d
minio-service   LoadBalancer   10.233.32.19    <pending>     9001:30809/TCP   104d
mobsf           NodePort       10.233.18.34    <none>        8000:30426/TCP   8d
vault           NodePort       10.233.43.134   <none>        8200:30820/TCP   69
</code>```

Ing:

```<code> kubectl get ing
NAME     HOSTS                  ADDRESS   PORTS   AGE
mobsf    worker1.dev002.local             80      2d1h
mobsf2   worker1.dev002.local             80      23h
</code>```

答:
In bare metal installations is not possible to use Ingress and LoadBalancer services by default. You can't get EXTERNAL-IP, as displayed in the outputs that you provided.

The first curl command you provided show that you are using your service mobsf as NodePort, it means you are able to reach your application typing IP of your node + port like this http://<NODE_IP>:8080, but without authentication since you are not accessing the server through the ingress.

Here is all service types and how that works:

ClusterIP: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default  ServiceType.

NodePort: Exposes the Service on each Node’s IP at a static port (the  NodePort). A  ClusterIP  Service, to which the  NodePort  Service routes, is automatically created. You’ll be able to contact the  NodePort  Service, from outside the cluster, by requesting  <NodeIP>:<NodePort>.

LoadBalancer: Exposes the Service externally using a cloud provider’s load balancer.  NodePort  and  ClusterIP  Services, to which the external load balancer routes, are automatically created.

How to use LoadBalancer and Ingress in bare metal installations?

The Nginx docs shows how to setup MetalLB to allow your bare metal cluster the usage of LoadBalancer Services.

MetalLB provides a network load-balancer implementation for Kubernetes clusters that do not run on a supported cloud provider, effectively allowing the usage of LoadBalancer Services within any cluster.

Basically, the setup is easy:

```<code>kubectl apply -f https://raw.githubusercontent.com/google/metallb/v0.8.3/manifests/metallb.yaml
</code>```

And then create a ConfigMap to configure:
- Edit the ip range according yout network

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 192.168.1.240-192.168.1.250 <= EDIT IP RANGE
</code>```

Check the installation typing kubectl get pods -n metallb-system, this is an expected output:

```<code>$ kubectl get pods -n metallb-system
NAME                          READY   STATUS    RESTARTS   AGE
controller-65895b47d4-6wzfr   1/1     Running   0          9d
speaker-v52xj                 1/1     Running   0          9d
</code>```

After MetalLB installed and configured you should be able to use your ingress and Loadbalancer services.

Here there's an example of how setup a Service (ClusterIP) and Ingress:

```<code>apiVersion: v1
kind: Service
metadata:
  name: mobsf
spec:
  selector:
    app: mobsf
  ports:
    - protocol: TCP
      port: 8000
      targetPort: 8000
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf-ing
  namespace: default
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - foo'
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - path: "/"
        backend:
          serviceName: mobsf
          servicePort: 8000
      - path: "/api/v1"
        backend:
          serviceName: mobsf
          servicePort: 8080
</code>```

Check your ingress with the command kubectl get ing and look for in EXTERNAL-IP column.

After that make sure you configure in your local DNS an entry for worker1.mydomain.local pointing to the ip above.

Please let me know if that helped

Body:
I configured authentication through nginx to a specific service in k8s.

It works fine with WUI.

I saw some examples

This works fine too:

curl -v http://10.2.29.4/ -H 'Host: foo.bar.com' -u 'foo:bar'

But i need to close other part my url same.

For example /api/v1/upload

I deployd 2nd ingress with path:

spec:
  rules:
  - host: foo.bar.com
    http:
      paths:
      - backend:
          serviceName: service
          servicePort: 8000
        path: /api/v1/upload

Without nginx i got to type:

curl -XPOST 'file=@/file' http://10.2.29.4:8000/api/v1/upload -H "Authorization:key"

How do i need to try use curl for hide real ip or port and get a good result?

I would really appreciate if you could help me figure it out.

ingress1:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf
  namespace: default
  labels:
    app: mobsf
#    env: dev
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: mobsf-basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - path: /
      - backend:
          serviceName: mobsf
          servicePort: 8000

Ingress 2:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf2
  namespace: default
  labels:
    app: mobsf2
#    env: dev
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: mobsf-basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - backend:
          serviceName: mobsf2
          servicePort: 8000
        path: /api/v1/

DNS check (correct):

 nslookup worker1.mydomain.local
Server:         10.2.67.10
Address:        10.2.67.10#53

Name:   worker1.mydomain.local
Address: 10.2.67.203

Services:

kubectl get svc
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
kubernetes      ClusterIP      10.233.0.1      <none>        443/TCP          159d
minio-service   LoadBalancer   10.233.32.19    <pending>     9001:30809/TCP   104d
mobsf           NodePort       10.233.18.34    <none>        8000:30426/TCP   8d
vault           NodePort       10.233.43.134   <none>        8200:30820/TCP   69

Ing:

 kubectl get ing
NAME     HOSTS                  ADDRESS   PORTS   AGE
mobsf    worker1.dev002.local             80      2d1h
mobsf2   worker1.dev002.local             80      23h

Body:
In bare metal installations is not possible to use Ingress and LoadBalancer services by default. You can't get EXTERNAL-IP, as displayed in the outputs that you provided.

The first curl command you provided show that you are using your service mobsf as NodePort, it means you are able to reach your application typing IP of your node + port like this http://<NODE_IP>:8080, but without authentication since you are not accessing the server through the ingress.

Here is all service types and how that works:

ClusterIP: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default  ServiceType.

NodePort: Exposes the Service on each Node’s IP at a static port (the  NodePort). A  ClusterIP  Service, to which the  NodePort  Service routes, is automatically created. You’ll be able to contact the  NodePort  Service, from outside the cluster, by requesting  <NodeIP>:<NodePort>.

LoadBalancer: Exposes the Service externally using a cloud provider’s load balancer.  NodePort  and  ClusterIP  Services, to which the external load balancer routes, are automatically created.

How to use LoadBalancer and Ingress in bare metal installations?

The Nginx docs shows how to setup MetalLB to allow your bare metal cluster the usage of LoadBalancer Services.

MetalLB provides a network load-balancer implementation for Kubernetes clusters that do not run on a supported cloud provider, effectively allowing the usage of LoadBalancer Services within any cluster.

Basically, the setup is easy:

kubectl apply -f https://raw.githubusercontent.com/google/metallb/v0.8.3/manifests/metallb.yaml

And then create a ConfigMap to configure:
- Edit the ip range according yout network

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 192.168.1.240-192.168.1.250 <= EDIT IP RANGE

Check the installation typing kubectl get pods -n metallb-system, this is an expected output:

$ kubectl get pods -n metallb-system
NAME                          READY   STATUS    RESTARTS   AGE
controller-65895b47d4-6wzfr   1/1     Running   0          9d
speaker-v52xj                 1/1     Running   0          9d

After MetalLB installed and configured you should be able to use your ingress and Loadbalancer services.

Here there's an example of how setup a Service (ClusterIP) and Ingress:

apiVersion: v1
kind: Service
metadata:
  name: mobsf
spec:
  selector:
    app: mobsf
  ports:
    - protocol: TCP
      port: 8000
      targetPort: 8000
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: mobsf-ing
  namespace: default
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - foo'
spec:
  rules:
  - host: worker1.mydomain.local
    http:
      paths:
      - path: "/"
        backend:
          serviceName: mobsf
          servicePort: 8000
      - path: "/api/v1"
        backend:
          serviceName: mobsf
          servicePort: 8080

Check your ingress with the command kubectl get ing and look for in EXTERNAL-IP column.

After that make sure you configure in your local DNS an entry for worker1.mydomain.local pointing to the ip above.

Please let me know if that helped


问:
Logical exception vs technical exception
There is a restriction on the database level in the user table for the unique field - email. That is, if we try to save the user with an existing email address, then an SQLServerException will occur. In this case, we can catch this technical exception, create and then throw our own technical exception.

But we can also make a request to the database and check if the user exists and then throw our own a logical exception.

The question is which of the options is more preferable?

答:
It depend on your requirement

In case of 1 option you need to had to have constrains on email field. Then while catching the exception you need to be careful that thats indeed constrains violation on email field. Only advantage i can see here that you have to do only one query to db.

In 2nd case you have all the control, you can explicitly check if email already exist in separate db query and if not throw exception, otherwise make additional query to insert the data.
Here you have to make 2 db call, but you have better control over behaviour.


问:
What's the difference between tf.placeholder and tf.Variable?
I'm a newbie to TensorFlow. I'm confused about the difference between tf.placeholder and tf.Variable. In my view, tf.placeholder is used for input data, and tf.Variable is used to store the state of data. This is all what I know.

Could someone explain to me more in detail about their differences? In particular, when to use tf.Variable and when to use tf.placeholder?

答:
Tensorflow 2.0 Compatible Answer: The concept of Placeholders, tf.placeholder will not be available in Tensorflow 2.x (>= 2.0) by default, as the Default Execution Mode is Eager Execution.

However, we can use them if used in Graph Mode (Disable Eager Execution).

Equivalent command for TF Placeholder in version 2.x is tf.compat.v1.placeholder.

Equivalent Command for TF Variable in version 2.x is tf.Variable and if you want to migrate the code from 1.x to 2.x, the equivalent command is

tf.compat.v2.Variable.

Please refer this Tensorflow Page for more information about Tensorflow Version 2.0.

Please refer the Migration Guide for more information about migration from versions 1.x to 2.x.

ContentLicense: CC BY-SA 3.0


问:
how can i get validation error in controller?
im posting some textfields data to controller using ajax method without using form ,
now i want to get validation error msgs if any field is kept empty in controller through modelstate , so how can I??                             </p>

```<code> public JsonResult Check(Employee emp)
    {
        string msg = null;
        bool success = false;
        if(ModelState.IsValid)
        {
            success = true;
        }
        else {
            return Json(new { msg = ModelState });
        }

        return Json(emp);
</code>```

答:
You need to add attributes to the properties in the Employee viewmodel that are required as follows:

```<code>[Required]
public string Name {get; set;}
</code>```

This post provides some more details as to different types of validation you can add.

Body:
im posting some textfields data to controller using ajax method without using form ,
now i want to get validation error msgs if any field is kept empty in controller through modelstate , so how can I??

 public JsonResult Check(Employee emp)
    {
        string msg = null;
        bool success = false;
        if(ModelState.IsValid)
        {
            success = true;
        }
        else {
            return Json(new { msg = ModelState });
        }

        return Json(emp);

Body:
You need to add attributes to the properties in the Employee viewmodel that are required as follows:

[Required]
public string Name {get; set;}

This post provides some more details as to different types of validation you can add.


问:
Issue encountered while retrieving observable states from a given account in corda?
I'm trying to broadcast a given state to some observer accounts (everything is on accounts level). The problem that I'm facing is that for the observer, I'm unable to retrieve the flows that I'd broadcasted to it. The broadcast has been done successfully which I confirmed with the presence of entries in the account_to_state_refs table as well as on the node itself (I broadcasted the state from account on one node to another account on another node).

The query which I'm using to retrieve accounts is as below:

```<code>public List<StateAndRef<TradeState>> getTradeStatesByAccount(){
    AccountInfo myAccount = UtilitiesKt.getAccountService(this).accountInfo(accountName).get(0).getState().getData();
    QueryCriteria.VaultQueryCriteria criteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.ALL).withExternalIds(Collections.singletonList(myAccount.getIdentifier().getId()));

    List<StateAndRef<TradeState>> myOrders = getServiceHub().getVaultService().queryBy(TradeState.class,criteria).getStates();
    return myOrders;
}
</code>```

And the code which is used to broadcast a state to other accounts is

```<code>UtilitiesKt.getAccountService(this).shareStateWithAccount(accountInfo.getIdentifier().getId(), stateToBroadcast);
</code>```

In this case, how do I get around with retrieving the states for which I'm the observer along with the states of which I'm a participant party? Let me know if you need any other info. Thanks in advance!

Edit: Found a workaround, added in the answer.

答:
Solved the issue by executing a JDBC query on the table itself in order to retrieve the transaction ids of the states which had the account as an observer. Below is the code written inside a corda flow:

```<code>AccountInfo myAccount = UtilitiesKt.getAccountService(this).accountInfo(accountName).get(0).getState().getData();
String accId = myAccount.getLinearId().getId().toString();
String nativeQuery = "SELECT transaction_id FROM account_to_state_refs WHERE external_id=\'" + accId + "\'";
java.sql.Connection connection = getServiceHub().jdbcSession();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(nativeQuery);

List<StateAndRef<TradeState>> result = new ArrayList<StateAndRef<TradeState>>();

// All the states related to the node
    List<StateAndRef<TradeState>> myOrders = getServiceHub().getVaultService().queryBy(TradeState.class).getStates();

// To filter out the observed states from all the states above
while ( rs.next() ) {
    String txnId = rs.getString("transaction_id");
    for (StateAndRef<TradeState> order: myOrders) {
        if(order.getRef().getTxhash().toString().equalsIgnoreCase(txnId)) {
                result.add(order);
        }
    }
}

return result;
</code>```

This might not the best/optimal way of performing the desired action, but this works for me as of now until I find the right way.

Body:
I'm trying to broadcast a given state to some observer accounts (everything is on accounts level). The problem that I'm facing is that for the observer, I'm unable to retrieve the flows that I'd broadcasted to it. The broadcast has been done successfully which I confirmed with the presence of entries in the account_to_state_refs table as well as on the node itself (I broadcasted the state from account on one node to another account on another node).

The query which I'm using to retrieve accounts is as below:

public List<StateAndRef<TradeState>> getTradeStatesByAccount(){
    AccountInfo myAccount = UtilitiesKt.getAccountService(this).accountInfo(accountName).get(0).getState().getData();
    QueryCriteria.VaultQueryCriteria criteria = new QueryCriteria.VaultQueryCriteria(Vault.StateStatus.ALL).withExternalIds(Collections.singletonList(myAccount.getIdentifier().getId()));

    List<StateAndRef<TradeState>> myOrders = getServiceHub().getVaultService().queryBy(TradeState.class,criteria).getStates();
    return myOrders;
}

And the code which is used to broadcast a state to other accounts is

UtilitiesKt.getAccountService(this).shareStateWithAccount(accountInfo.getIdentifier().getId(), stateToBroadcast);

In this case, how do I get around with retrieving the states for which I'm the observer along with the states of which I'm a participant party? Let me know if you need any other info. Thanks in advance!

Edit: Found a workaround, added in the answer.

Body:
Solved the issue by executing a JDBC query on the table itself in order to retrieve the transaction ids of the states which had the account as an observer. Below is the code written inside a corda flow:

AccountInfo myAccount = UtilitiesKt.getAccountService(this).accountInfo(accountName).get(0).getState().getData();
String accId = myAccount.getLinearId().getId().toString();
String nativeQuery = "SELECT transaction_id FROM account_to_state_refs WHERE external_id=\'" + accId + "\'";
java.sql.Connection connection = getServiceHub().jdbcSession();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(nativeQuery);

List<StateAndRef<TradeState>> result = new ArrayList<StateAndRef<TradeState>>();

// All the states related to the node
    List<StateAndRef<TradeState>> myOrders = getServiceHub().getVaultService().queryBy(TradeState.class).getStates();

// To filter out the observed states from all the states above
while ( rs.next() ) {
    String txnId = rs.getString("transaction_id");
    for (StateAndRef<TradeState> order: myOrders) {
        if(order.getRef().getTxhash().toString().equalsIgnoreCase(txnId)) {
                result.add(order);
        }
    }
}

return result;

This might not the best/optimal way of performing the desired action, but this works for me as of now until I find the right way.


问:
How to get previous/next row when ordering by date/time then ID in MySQL?
I have table like

```<code>SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...
</code>```

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

答:
If you are using 8.0, you can try this:</p>

```<code>SELECT LEAD(id) OVER (ORDER BY id DESC) AS 'Next',id,LAG(id) OVER (ORDER BY id DESC) AS 'Previous'
FROM table
WHERE id = 8
ORDER BY `date` DESC, id DESC
</code>```

Body:
I have table like

SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

Body:
If you are using 8.0, you can try this:

SELECT LEAD(id) OVER (ORDER BY id DESC) AS 'Next',id,LAG(id) OVER (ORDER BY id DESC) AS 'Previous'
FROM table
WHERE id = 8
ORDER BY `date` DESC, id DESC


问:
Passing an image in axios request in react-native
I am trying to pass an image along with this request, other parameters get sent, but not the image. What way would be better. appApi is an axios instance which I imported.

```<code>const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info

      // const picture = new FormData()
      // picture.append("picture", {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // });

      // const picture = {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // }
      // console.log(picture)
      const picture = {
        type: 'image/jpg',
        uri: photo,
        name: 'profilepic.jpg'
      }

      const response = await appApi.put(`/userregister/${id}`, { name, email, phone, picture, Age, Blood, Gender, Height, Weight })
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };
</code>```

答:
you need to make a FormData like so :

```<code>const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info
      let data = { name, email, phone, photo, Age, Blood, Gender, Height, Weight };
       //notice that your photo must be a file
      let fd = new FormData();
      Object.keys(data).map(item => {
         fd.append(item , data[item]);
      });

      const response = await appApi.put(`/userregister/${id}`,fd )
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };

</code>```

Body:
I am trying to pass an image along with this request, other parameters get sent, but not the image. What way would be better. appApi is an axios instance which I imported.

const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info

      // const picture = new FormData()
      // picture.append("picture", {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // });

      // const picture = {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // }
      // console.log(picture)
      const picture = {
        type: 'image/jpg',
        uri: photo,
        name: 'profilepic.jpg'
      }

      const response = await appApi.put(`/userregister/${id}`, { name, email, phone, picture, Age, Blood, Gender, Height, Weight })
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };

Body:
you need to make a FormData like so :

const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info
      let data = { name, email, phone, photo, Age, Blood, Gender, Height, Weight };
       //notice that your photo must be a file
      let fd = new FormData();
      Object.keys(data).map(item => {
         fd.append(item , data[item]);
      });

      const response = await appApi.put(`/userregister/${id}`,fd )
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };


问:
How the RISC-V HW can determine the privilege level?
The RISC-V current SW privilege level is not set in any CSR. Nevertheless the spec states that "Attempts to access a CSR without appropriate privilege level ... raise illegal instruction". How can it be implemented then (in the HW)?</p>

答:
Well, on interrupts - "xPP holds the previous privilege mode (x=M,S or U). The xPP fields can only hold privilege modes up to x, so MPP is two bits wide, SPP is one bit wide, and UPP is implicitly zero."

Actually, what I have found now is that the xRET instruction enables the processor to store (internally) the current mode - "The MRET, SRET, or URET instructions are used to return from traps in M-mode, S-mode, or U-mode respectively. When executing an xRET instruction, supposing xPP holds the value y, x IE is set to x PIE; the privilege mode is changed to y; x PIE is set to 1; and xPP is set to U (or M if user-mode is not supported)."


问:
What kind of Ad that appears in the middle of screen
I need to know Type of Ad shown in the picture, thanks

答:
You can use Native Ad format. Firstly, include native ad library in your app. And then you should redesing layout like this.</p>

```<code><RelativeLayout ...>

  <com.google.android.ads.nativetemplates.TemplateView
        android:id="@+id/my_template"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        app:gnt_template_type="@layout/your_layout" />

</RelativeLayout>
</code>```

Body:
You can use Native Ad format. Firstly, include native ad library in your app. And then you should redesing layout like this.

<RelativeLayout ...>

  <com.google.android.ads.nativetemplates.TemplateView
        android:id="@+id/my_template"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        app:gnt_template_type="@layout/your_layout" />

</RelativeLayout>


问:
Git submodules and ssh access
I have some trouble with a git repository that contains several submodules.

The super git repository was constructed with the commands

```<code>mkdir projectname
cd projectname
git init
git submodule add ssh://myusername@server/pathtorepos
</code>```

When a different user ("otheruser") then clones the super repository everything seems to work out. But when it is time to get access to the submodule

```<code>git submodule init
git submodule update
</code>```

git tries to clone the submodule using "myusername" instead of "otheruser".

How to solve this problem?

答:
If possible, it's best to make sure that the .gitmodules file contains a URL for the repository that can be cloned by anyone, typically either a git:// or http:// URL.  Then users that have SSH access themselves can change into the submodule after cloning and change the URL in remote.origin.url to point to an SSH URL with their username, e.g.:

```<code> cd my-submodule
 git remote set-url origin otheruser@server:/pathtorepos
</code>```

The other user should be able to do that even in the current situation.   Update: Chris Johnsen points out below that it's also reasonable to use an SSH URL in .gitmodules if you omit the username and all the users of the repository will have SSH access - they'll need to add their username similarly to the above if it differs locally and remotely.

Note that the URLs in .gitmodules are only used when initializing the submodule.  Initializing the submodule sets the config value submodule.<SUBMODULE-NAME>.url in the main project to whatever's committed in .gitmodules - this is the value that will be used on the first submodule update.  Between initializing and updating the submodule, you can also change this URL that will be used for that first update with a command like:

```<code>git config submodule.my-submodule.url otheruser@server:/pathtorepos
</code>```

Indeed, you may need to do this if the first update fails.  Once the submodule has been updated for the first time, the URL you need to change is that defined for origin within the submodule - at that point it's only useful to set the submodule.my-submodule.url config value in the main project if you're likely to be deleting and re-updating the submodule.

Title: Git submodules and ssh access

Body:
I have some trouble with a git repository that contains several submodules.

The super git repository was constructed with the commands

mkdir projectname
cd projectname
git init
git submodule add ssh://myusername@server/pathtorepos

When a different user ("otheruser") then clones the super repository everything seems to work out. But when it is time to get access to the submodule

git submodule init
git submodule update

git tries to clone the submodule using "myusername" instead of "otheruser".

How to solve this problem?

Body:
If possible, it's best to make sure that the .gitmodules file contains a URL for the repository that can be cloned by anyone, typically either a git:// or http:// URL.  Then users that have SSH access themselves can change into the submodule after cloning and change the URL in remote.origin.url to point to an SSH URL with their username, e.g.:

 cd my-submodule
 git remote set-url origin otheruser@server:/pathtorepos

The other user should be able to do that even in the current situation.   Update: Chris Johnsen points out below that it's also reasonable to use an SSH URL in .gitmodules if you omit the username and all the users of the repository will have SSH access - they'll need to add their username similarly to the above if it differs locally and remotely.

Note that the URLs in .gitmodules are only used when initializing the submodule.  Initializing the submodule sets the config value submodule.<SUBMODULE-NAME>.url in the main project to whatever's committed in .gitmodules - this is the value that will be used on the first submodule update.  Between initializing and updating the submodule, you can also change this URL that will be used for that first update with a command like:

git config submodule.my-submodule.url otheruser@server:/pathtorepos

Indeed, you may need to do this if the first update fails.  Once the submodule has been updated for the first time, the URL you need to change is that defined for origin within the submodule - at that point it's only useful to set the submodule.my-submodule.url config value in the main project if you're likely to be deleting and re-updating the submodule.


问:
C# Switch If condition to expand the switch cases
I have some data which need to converted, for that I need a switch condition with more than 50 cases, I need the same cases 3 times but in the third time I need the 50 cases and some more and I don't want to write the same code twice. Maybe there is a possibility to do something like this.</p>

```<code>switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    if (condition == true)
    {
        case "1":
            //do something else than above at case "1", and so on
            //now its i little bit illogical, but i neet to do the first 50 cases and then
            //use the cases 1 to 50 again but with other actions
    }
}
</code>```

答:
Starting from C# 7 you can combine the case statement with when clause and use it to simplify your code a little bit

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    case "51" when condition == true:
        //do something, and so on
    default:
        break;
}
```

Starting with C# 7.0, because case statements need not be mutually
  exclusive, you can add a when clause to specify an additional
  condition that must be satisfied for the case statement to evaluate to
  true. The when clause can be any expression that returns a Boolean
  value.

Body:
I have some data which need to converted, for that I need a switch condition with more than 50 cases, I need the same cases 3 times but in the third time I need the 50 cases and some more and I don't want to write the same code twice. Maybe there is a possibility to do something like this.

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    if (condition == true)
    {
        case "1":
            //do something else than above at case "1", and so on
            //now its i little bit illogical, but i neet to do the first 50 cases and then
            //use the cases 1 to 50 again but with other actions
    }
}

Body:
Starting from C# 7 you can combine the case statement with when clause and use it to simplify your code a little bit

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    case "51" when condition == true:
        //do something, and so on
    default:
        break;
}

Starting with C# 7.0, because case statements need not be mutually
  exclusive, you can add a when clause to specify an additional
  condition that must be satisfied for the case statement to evaluate to
  true. The when clause can be any expression that returns a Boolean
  value.


问:
Can I custom condition min/max a number field in Contact Form 7
First, I have more than 100 products and different price. I want my contact form validation a price. So I declare a variable like this in PHP file.

```<code>$discount = 70/100;
$disc_price = $price * $discount;
</code>```

It's possible to get a variable $price replace in min:$price

[number number-111 min: max:]

or have any solution?

答:
Try Dom events https://contactform7.com/dom-events/
or </p>

```<code>function action_wpcf7_before_send_mail( $contact_form ) {
 // var_dump($contact_form);
};

add_action( 'wpcf7_before_send_mail', 'action_wpcf7_before_send_mail', 10, 1 );
</code>```

Body:
First, I have more than 100 products and different price. I want my contact form validation a price. So I declare a variable like this in PHP file.

$discount = 70/100;
$disc_price = $price * $discount;

It's possible to get a variable $price replace in min:$price

[number number-111 min: max:]

or have any solution?

Body:
Try Dom events https://contactform7.com/dom-events/
or

function action_wpcf7_before_send_mail( $contact_form ) {
 // var_dump($contact_form);
};

add_action( 'wpcf7_before_send_mail', 'action_wpcf7_before_send_mail', 10, 1 );


问:
How to de-serialize the spark data frame into another data frame
I am trying to de-serialize the the spark data frame into another data frame as expected below.

Existing Dataframe Data:

Existing Dataframe schema:

Expected Dataframe:

Can anyone help me on this?

答:
You can use the explode function for that.

```<code>from pyspark.sql.functions import explode
df.withColumn("ns2:fileName", explode(df.ns2:fileName))
</code>```

EDIT

```<code>df.withColumn("result", explode(zip($"ns2:fileName", $"ns2:alias"))).select(
   $"result._1".alias("ns2:fileName"), $"result._2".alias("ns2:alias"))
</code>```

Possible duplicate.

Body:
You can use the explode function for that.

from pyspark.sql.functions import explode
df.withColumn("ns2:fileName", explode(df.ns2:fileName))

EDIT

df.withColumn("result", explode(zip($"ns2:fileName", $"ns2:alias"))).select(
   $"result._1".alias("ns2:fileName"), $"result._2".alias("ns2:alias"))

Possible duplicate.


问:
Puppeteer - simulate scroll down
I have seen that there are functions like page.mouse.down() but it does nothing.
Do you know any way to scroll?

答:
The page.mouse.down() is used to simulate a mouse click, not the scroll. That's why it doesn't do what you want to.

You may have to take a look at the window.scrollTo or window.scrollBy function to be used inside the page.evaluate(...) scope (in which the window variable is available). You'll then be able to scroll the page by some given distance. Please see the following topic in which the answer has already been given : Puppeteer - scroll down until you can't anymore

Title: Puppeteer - simulate scroll down


问:
How to do nested custom validation in Angular 8
I want to check the validation between two different fields  OR condition. Supposed I have two fields age and birth_date. I want to check only one field required either age or birth_date.

I am using Angular 8. My form is nested with Add more features.

答:
Hope this helps...on form submission result will be dispalyed

app.component.ts

```<code>export class AppComponent implements OnInit {
   form: FormGroup;

   constructor(private formBuilder: FormBuilder){}

   ngOnInit() {
     this.form = this.formBuilder.group({
       nestedForm: this.formBuilder.array([
          this.formBuilder.group({
          age: [null, Validators.required],
          dob: [null, Validators.required],
          validObject: [false]
     }),
     this.formBuilder.group({
        age: [null, Validators.required],
        dob: [null, Validators.required],
        validObject: [false]
     })
   ])
   });
  }

  checkFormValidation() {
    this.form.get('nestedForm')['controls'].filter(item => {
      if(item.get('age').valid || item.get('dob').valid) {
        item.get('validObject').setValue(true);
      } else {
         item.get('validObject').setValue(false);
      }
   });
</code>```

}
    }

app.component.html

```<code><div class="container">
   <form [formGroup]="form" (submit)="checkFormValidation()">
<div formArrayName="nestedForm" *ngFor="let item of form.get('nestedForm')['controls']; let i = index">
  <ng-container [formGroupName]="i">
    <div class="form-group">
      <label for="email">Age:</label>
      <input type="number" class="form-control" id="email" formControlName="age" placeholder="Enter Age" name="email">
    </div>
    <div class="form-group">
      <label for="pwd">DOB:</label>
      <input type="text" class="form-control" id="pwd" formControlName="dob" placeholder="Enter DOB" name="pwd">
    </div>
    <span [ngClass]="item.get('validObject').value ? 'success'  : 'error'">Valid: {{item.get('validObject').value}}</span>
  </ng-container>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</code>```

app.component.css

```<code>.success {
   color: green;
}

.error {
   color: red;
 }
</code>```

Body:
Hope this helps...on form submission result will be dispalyed

app.component.ts

export class AppComponent implements OnInit {
   form: FormGroup;

   constructor(private formBuilder: FormBuilder){}

   ngOnInit() {
     this.form = this.formBuilder.group({
       nestedForm: this.formBuilder.array([
          this.formBuilder.group({
          age: [null, Validators.required],
          dob: [null, Validators.required],
          validObject: [false]
     }),
     this.formBuilder.group({
        age: [null, Validators.required],
        dob: [null, Validators.required],
        validObject: [false]
     })
   ])
   });
  }

  checkFormValidation() {
    this.form.get('nestedForm')['controls'].filter(item => {
      if(item.get('age').valid || item.get('dob').valid) {
        item.get('validObject').setValue(true);
      } else {
         item.get('validObject').setValue(false);
      }
   });

}
    }

app.component.html

<div class="container">
   <form [formGroup]="form" (submit)="checkFormValidation()">
<div formArrayName="nestedForm" *ngFor="let item of form.get('nestedForm')['controls']; let i = index">
  <ng-container [formGroupName]="i">
    <div class="form-group">
      <label for="email">Age:</label>
      <input type="number" class="form-control" id="email" formControlName="age" placeholder="Enter Age" name="email">
    </div>
    <div class="form-group">
      <label for="pwd">DOB:</label>
      <input type="text" class="form-control" id="pwd" formControlName="dob" placeholder="Enter DOB" name="pwd">
    </div>
    <span [ngClass]="item.get('validObject').value ? 'success'  : 'error'">Valid: {{item.get('validObject').value}}</span>
  </ng-container>
</div>
<button type="submit" class="btn btn-primary">Submit</button>

app.component.css

.success {
   color: green;
}

.error {
   color: red;
 }


问:
How to fetch data in getInitialProps with redux-saga.Then get the response from redux store while in the getInitialProps method?
I finished coding a React app created using the create-react-app (CSR) but I'm now rewriting this entire app using the Next.js framework for better SEO performance.

While rewriting it I had some hard times figuring out how to properly deal with redux and redux-saga to do the fetching and storing data process.
The main reason to use Next.js in this project is to make use of the getInitialProps method, to fetch the data on the server-side before the first page load happens. But for some reason, I'm not able to "await" for the Redux dispatch to complete and get the fetched data on time.

So what ends up happening is that I dispatch the action to fetch the data, but it doesn't get stored in the redux store on time during the initial server-side page load. But when I change routes using next/link the data comes in, but only on client-side, after the server-side rendering happened.

So it kinda defeats the purpose of using the Next.js.

This new code is very similar to the create-react-app project, with some minor changes to fit the Next.js project requirements.

Here is my code.

./pages/_app.js

```<code>import App from 'next/app';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import makeStore from '../store/index';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    const pageProps = Component.getInitialProps
      ? await Component.getInitialProps(ctx)
      : {};
    return { pageProps };
  }

  render() {
    const { Component, pageProps, store } = this.props;
    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    );
  }
}

export default withRedux(makeStore)(MyApp);
</code>```

./pages/index.jsx:

import React from 'react';
import { useRouter } from 'next/router';

import Layout from '../components/Layout';
import SubNavBarCategories from '../components/Pages/Home/SubNavBarCategory';

import * as BlogActions from '../store/actions/blog/categories';

const Blog = (props) => {
  const router = useRouter();
  const {
    blogCategories,
  } = props;

  return (
    <Layout>
      <SubNavBarCategories blogCategories={blogCategories} />
    </Layout>
  );
};

Blog.getInitialProps = async ({ isServer, store }) => {
  await store.execSagaTasks(isServer, (dispatch) => {
    dispatch(BlogActions.getRecentCategories(5));
  });

  console.log('await store:', await store.getState().blog.blogCategories);
  //output: await store: { data: [], loading: true, fetched: false, error: false }
  //expected something like this:
  // await store: { data: ['test1', 'category', 'crypto', 'test4', 'Day trade'] loading: false, fetched: true, error: false }

  return {
    blogCategories: await store.getState().blog.blogCategories,
  };
};

export default Blog;
```

<p>./store/index.js</p>

```import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';

import rootReducer from './reducers';
import rootSaga from './sagas';

const sagaMiddleware = createSagaMiddleware();
const makeStore = (initialState) => {
  const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;

  const store = createStore(
    rootReducer,
    initialState,
    compose(
      composeEnhancers(applyMiddleware(sagaMiddleware)),
    ),
  );

  store.runSaga = () => {
    if (store.saga) {
      return;
    }
    store.sagaTask = sagaMiddleware.run(rootSaga);
  };

  store.stopSaga = async () => {
    if (!store.saga) {
      return;
    }
    store.dispatch(END);
    await store.saga.done;
    store.saga = null;
  };

  store.execSagaTasks = async (isServer, tasks) => {
    store.runSaga();
    tasks(store.dispatch);

    await store.stopSaga();

    if (!isServer) {
      store.runSaga();
    }
  };

  store.runSaga();
  return store;
};

export default makeStore;
```

<p>./store/actions/blog/blog.js</p>

```export function getRecentCategories(number) {
  return {
    type: 'REQUEST_RECENT_CATEGORIES',
    payload: {
      number,
    },
  };
}
```

<p>./store/reducers/blog/blog.js</p>

```import update from 'immutability-helper';

const initialState = {
  blogCategories: {
    data: [],
    loading: false,
    fetched: false,
    error: false,
  },
};

export default function blog(state = initialState, action) {
  switch (action.type) {
    case 'REQUEST_RECENT_CATEGORIES':
      return update(state, {
        blogCategories: {
          loading: { $set: true },
        },
      });
    case 'SUCCESS_RECENT_CATEGORIES':
      console.log('actions:', action.payload.data);
      //output: actions: blogCategories [ 'test1', 'category', 'crypto', 'test4', 'Day trade' ]
      return update(state, {
        blogCategories: {
          data: { $set: action.payload.data },
          loading: { $set: false },
          fetched: { $set: true },
          error: { $set: false },
        },
      });
    case 'FAILURE_RECENT_CATEGORIES':
      return update(state, {
        blogCategories: {
          fetched: { $set: true },
          error: { $set: true },
        },
      });
    default:
      return state;
  }
}
```

<p>./store/sagas/blog/getRecentCategories.js</p>

```import {
  put,
  call,
} from 'redux-saga/effects';

import 'isomorphic-fetch';

async function getRecentCategoriesApi(number) {
  const res = await fetch(`http://localhost:5000/blog/get/categories/newest/${number}`, {
    method: 'GET',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const data = await res.json();
  return data;
}

export default function* asyncGetRecentCategoriesApi(action) {
  try {
    const response = yield call(getRecentCategoriesApi, action.payload.number);

    yield put({ type: 'SUCCESS_RECENT_CATEGORIES', payload: { data: response } });
  } catch (err) {
    yield put({ type: 'FAILURE_RECENT_CATEGORIES' });
  }
}
```

As you can see this app is a pretty ordinary react redux-saga app. Everything else is working as it should besides this getting data from the backend using redux-saga thing.

Is there any way to make getInitialProps method work with redux and redux-saga as intended?

答:
Have a look at the official Next.js example with redux-saga example.

https://github.com/zeit/next.js/tree/canary/examples/with-redux-saga

Body:
I finished coding a React app created using the create-react-app (CSR) but I'm now rewriting this entire app using the Next.js framework for better SEO performance.

While rewriting it I had some hard times figuring out how to properly deal with redux and redux-saga to do the fetching and storing data process.
The main reason to use Next.js in this project is to make use of the getInitialProps method, to fetch the data on the server-side before the first page load happens. But for some reason, I'm not able to "await" for the Redux dispatch to complete and get the fetched data on time.

So what ends up happening is that I dispatch the action to fetch the data, but it doesn't get stored in the redux store on time during the initial server-side page load. But when I change routes using next/link the data comes in, but only on client-side, after the server-side rendering happened.

So it kinda defeats the purpose of using the Next.js.

This new code is very similar to the create-react-app project, with some minor changes to fit the Next.js project requirements.

Here is my code.

./pages/_app.js

import App from 'next/app';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import makeStore from '../store/index';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    const pageProps = Component.getInitialProps
      ? await Component.getInitialProps(ctx)
      : {};
    return { pageProps };
  }

  render() {
    const { Component, pageProps, store } = this.props;
    return (
      <Provider store={store}>
        <Component {...pageProps} />
      </Provider>
    );
  }
}

export default withRedux(makeStore)(MyApp);

./pages/index.jsx:

import React from 'react';
import { useRouter } from 'next/router';

import Layout from '../components/Layout';
import SubNavBarCategories from '../components/Pages/Home/SubNavBarCategory';

import * as BlogActions from '../store/actions/blog/categories';

const Blog = (props) => {
  const router = useRouter();
  const {
    blogCategories,
  } = props;

  return (
    <Layout>
      <SubNavBarCategories blogCategories={blogCategories} />
    </Layout>
  );
};

Blog.getInitialProps = async ({ isServer, store }) => {
  await store.execSagaTasks(isServer, (dispatch) => {
    dispatch(BlogActions.getRecentCategories(5));
  });

  console.log('await store:', await store.getState().blog.blogCategories);
  //output: await store: { data: [], loading: true, fetched: false, error: false }
  //expected something like this:
  // await store: { data: ['test1', 'category', 'crypto', 'test4', 'Day trade'] loading: false, fetched: true, error: false }

  return {
    blogCategories: await store.getState().blog.blogCategories,
  };
};

export default Blog;

./store/index.js

import {
  createStore,
  applyMiddleware,
  compose,
} from 'redux';
import createSagaMiddleware, { END } from 'redux-saga';

import rootReducer from './reducers';
import rootSaga from './sagas';

const sagaMiddleware = createSagaMiddleware();
const makeStore = (initialState) => {
  const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;

  const store = createStore(
    rootReducer,
    initialState,
    compose(
      composeEnhancers(applyMiddleware(sagaMiddleware)),
    ),
  );

  store.runSaga = () => {
    if (store.saga) {
      return;
    }
    store.sagaTask = sagaMiddleware.run(rootSaga);
  };

  store.stopSaga = async () => {
    if (!store.saga) {
      return;
    }
    store.dispatch(END);
    await store.saga.done;
    store.saga = null;
  };

  store.execSagaTasks = async (isServer, tasks) => {
    store.runSaga();
    tasks(store.dispatch);

    await store.stopSaga();

    if (!isServer) {
      store.runSaga();
    }
  };

  store.runSaga();
  return store;
};

export default makeStore;

./store/actions/blog/blog.js

export function getRecentCategories(number) {
  return {
    type: 'REQUEST_RECENT_CATEGORIES',
    payload: {
      number,
    },
  };
}

./store/reducers/blog/blog.js

import update from 'immutability-helper';

const initialState = {
  blogCategories: {
    data: [],
    loading: false,
    fetched: false,
    error: false,
  },
};

export default function blog(state = initialState, action) {
  switch (action.type) {
    case 'REQUEST_RECENT_CATEGORIES':
      return update(state, {
        blogCategories: {
          loading: { $set: true },
        },
      });
    case 'SUCCESS_RECENT_CATEGORIES':
      console.log('actions:', action.payload.data);
      //output: actions: blogCategories [ 'test1', 'category', 'crypto', 'test4', 'Day trade' ]
      return update(state, {
        blogCategories: {
          data: { $set: action.payload.data },
          loading: { $set: false },
          fetched: { $set: true },
          error: { $set: false },
        },
      });
    case 'FAILURE_RECENT_CATEGORIES':
      return update(state, {
        blogCategories: {
          fetched: { $set: true },
          error: { $set: true },
        },
      });
    default:
      return state;
  }
}

./store/sagas/blog/getRecentCategories.js

import {
  put,
  call,
} from 'redux-saga/effects';

import 'isomorphic-fetch';

async function getRecentCategoriesApi(number) {
  const res = await fetch(`http://localhost:5000/blog/get/categories/newest/${number}`, {
    method: 'GET',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
  });
  const data = await res.json();
  return data;
}

export default function* asyncGetRecentCategoriesApi(action) {
  try {
    const response = yield call(getRecentCategoriesApi, action.payload.number);

    yield put({ type: 'SUCCESS_RECENT_CATEGORIES', payload: { data: response } });
  } catch (err) {
    yield put({ type: 'FAILURE_RECENT_CATEGORIES' });
  }
}

As you can see this app is a pretty ordinary react redux-saga app. Everything else is working as it should besides this getting data from the backend using redux-saga thing.

Is there any way to make getInitialProps method work with redux and redux-saga as intended?


问:
Jms component transacted and camel route transacted

After going through Camel In Action book, I encountered following doubts.

I have below 2 routes

A.

     from("file:/home/src")                            //(A.1)
     .transacted("required")                       //(A.2)
     .bean("dbReader", "readFromDB()")             //(A.3) only read from DB
     .bean("dbReader", "readFromDB()")             //(A.4) only read from DB
     .to("jms:queue:DEST_QUEUE")                   //(A.5)

Questions:

     A.a. Is transacted in (A.2) really required here ?

A.b. If answer to #a is yes, then what should be the associated transaction manager of the "required" policy ? Should it be JmsTransactionManager or JpaTransactionManager ?

A.c. As DEST_QUEUE is at the producer end, so does JMS component in (A.5) need to be transacted ?

B.
     from("jms:queue:SRC_QUEUE")                   //(B.1) transactional jms endpoint
     .transacted("required")                     //(B.2)
     .bean("someBean", "someMethod()")           //(B.3) simple arithmetic computation
     .to("jms1:queue:DEST_QUEUE")                //(B.4)

SRC_QUEUE and DEST_QUEUE are queues of different jms broker

Questions:

B.a. The JMS component in (B.1) is marked as transacted, so in this case does route need to be transacted as mentioned in (B.2) ?

B.b. As DEST_QUEUE is at the producer end, so does JMS component in (B.4) need to be transacted ?

答:
Very good questions to talk about Camel transaction handling.

General remark: when talking about Camel transactions it means to consume transacted from a transaction capable system like a database or JMS broker. The transacted statement in a route must immediately follow the from statement because it is always related to the consumption.

A.a. Is transacted in (A.2) really required here ?

No, it is not. Since the filesystem is not transaction capable, it can't be of any help in this route.

A.b. If answer to #a is yes, then ... ?

There is no "filesystem transaction manager"

A.c. As DEST_QUEUE is at the producer end, so does JMS component in (A.5) need to be transacted ?

Not sure, but I don't think so. The producer tries to hand over a message to the broker. Transactions are used to enable a rollback, but if the broker has not received the data, what could a rollback do?

B.a. The JMS component in (B.1) is marked as transacted, so in this case does route need to be transacted as mentioned in (B.2) ?

It depends because SRC and DEST are on different brokers.

If you want an end-to-end-transaction between the brokers, you need to use an XA-transaction manager and then you have to mark the route as transacted.

If you are OK with consumer transaction, you can configure the JMS component for it and omit the Spring Tx manager and the Camel transacted statement.

To clarify the last point: if you consume with local broker transaction, Camel does not commit the message until the route is successfully processed. So if any error occurs, a rollback would happen and the message would be redelivered.

In most cases this is totally OK, however, what still could happen with two different brokers is that the route is successfully processed, the message is delivered to DEST broker but Camel is no more able to commit against SRC broker. Then a redelivery occurs, the route is processed one more time and the message is delivered multiple times to DEST broker.

In my opinion the complexity of XA transactions is harder to handle than the very rare edge cases with local broker transactions. But this is a very subjective opinion and perhaps also depends on the context or data you are working with.

And important to note: if SRC and DEST broker are the same, local broker transactions are 100% sufficient! Absolutely no need for Spring Tx manager and Camel transacted.

B.b. As DEST_QUEUE is at the producer end, so does JMS component in (B.4) need to be transacted ?

Same as answer to B.a.


问:
How to find closest vectors to a certain point
I have thousands of multidimensional sentence-embedding vectors and want to calculate the closest (euclidean distance) 4 to certain predefined clusteroids. Same would appear multiple times if they are right between two points, some would not appear at all if they are way off.

example, lets say I have 6 vector:

```<code>[1 0 3 1]
[2 1 2 1]
[3 4 1 1]
[1 0 3 1]
[2 1 2 1]
[3 4 1 1]
</code>```

And now I want to know what are the closest 4 vectors to the points [1 1 1 1] and [2 2 2 2].

How would I calculate that and what would be the easiest way in terms of computingpower? - I am happy to use already existing librarys.

Edit: I added another dimension to the points to point out the fact that I am operating in the n-dimensional space

答:
use numpy.linalg.norm to calculate the (Euclidean) distances, then numpy.argsort for sorting the point indices according to their distance.

```<code>import numpy
points = numpy.array([
    [1, 0, 3],
    [2, 1, 2],
    [3, 4, 1],
    [1, 0, 3],
    [2, 1, 2],
    [3, 4, 1]
])

distances = numpy.linalg.norm(points - numpy.array([[1, 1, 1]]), axis=1)
print(distances)
print(numpy.argsort(distances))
</code>```

The output is

```<code>[2.23606798 1.41421356 3.60555128 2.23606798 1.41421356 3.60555128]
[1 4 0 3 2 5]
</code>```

The first line lists the Euclidean distances of each point in the list to the reference point. The second line gives the point indices sorted according to their distance: The closest point is 1, second-closest is point 4, third-closest is point 0, ...

Body:
I have thousands of multidimensional sentence-embedding vectors and want to calculate the closest (euclidean distance) 4 to certain predefined clusteroids. Same would appear multiple times if they are right between two points, some would not appear at all if they are way off.

example, lets say I have 6 vector:

[1 0 3 1]
[2 1 2 1]
[3 4 1 1]
[1 0 3 1]
[2 1 2 1]
[3 4 1 1]

And now I want to know what are the closest 4 vectors to the points [1 1 1 1] and [2 2 2 2].

How would I calculate that and what would be the easiest way in terms of computingpower? - I am happy to use already existing librarys.

Edit: I added another dimension to the points to point out the fact that I am operating in the n-dimensional space

Body:
use numpy.linalg.norm to calculate the (Euclidean) distances, then numpy.argsort for sorting the point indices according to their distance.

import numpy
points = numpy.array([
    [1, 0, 3],
    [2, 1, 2],
    [3, 4, 1],
    [1, 0, 3],
    [2, 1, 2],
    [3, 4, 1]
])

distances = numpy.linalg.norm(points - numpy.array([[1, 1, 1]]), axis=1)
print(distances)
print(numpy.argsort(distances))

The output is

[2.23606798 1.41421356 3.60555128 2.23606798 1.41421356 3.60555128]
[1 4 0 3 2 5]

The first line lists the Euclidean distances of each point in the list to the reference point. The second line gives the point indices sorted according to their distance: The closest point is 1, second-closest is point 4, third-closest is point 0, ...


问:
How to load Google fonts asynchronously with Font Face Observer
After having read this article about the best ways to serve web fonts, I wanted to make use of the recent javascript library Font Face Observer to load Google fonts asynchronously on my website.

The documentation reads that "fonts can be supplied by [...] a font service such as Google Fonts", but it doesn't show any examples on how to actually implement this. I've read the recommended articles about the Font Face Observer listed on the official website, but all of them showed how to use it with self-hosted fonts.

Did anyone use the Font Face Observer to load Google fonts? Or, could you point me to some documentation that shows how to approach this?

答:
I've used such an approach in order to achieve fonts lazy-loading.
You have to make sure your Google font is added to the stylesheet link. After that use FontFaceObserver as usual - just pass Google font name as an argument to create a new FontFaceObserver instance.
To manage my Google fonts I've used a tiny helper google-fonts.

Code sample will look like this:

```<code>import googleFonts from 'google-fonts';
import FontFaceObserver from 'fontfaceobserver';

loadGoogleFont(fontName) {
    googleFonts.add({[fontName]: true}); // or some other options if you need
    const fontObserver = new FontFaceObserver(fontName);
    return fontObserver.load()
        .catch(err => console.log(fontName, err));
}
</code>```

Body:
I've used such an approach in order to achieve fonts lazy-loading.
You have to make sure your Google font is added to the stylesheet link. After that use FontFaceObserver as usual - just pass Google font name as an argument to create a new FontFaceObserver instance.
To manage my Google fonts I've used a tiny helper google-fonts.

Code sample will look like this:

import googleFonts from 'google-fonts';
import FontFaceObserver from 'fontfaceobserver';

loadGoogleFont(fontName) {
    googleFonts.add({[fontName]: true}); // or some other options if you need
    const fontObserver = new FontFaceObserver(fontName);
    return fontObserver.load()
        .catch(err => console.log(fontName, err));
}


问:
How to pass variable to later in program / Inputting double to dialog box
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

```<code>void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
</code>```

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

答: You can use global variables for that, as @Cédric Julien suggested. The second problem should be resolved if you change your sprintf( buf, "%d", variable); to sprintf(buf, "%d", (int)variable);, because %d parameter relates to integer types: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Body:
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.


问:
Encode UTF8 text to Unicode C#
How to encode UTF8 text to Unicode?

```<code>string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);
</code>```

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

答:
Well, you probably mean this:

```<code>// Forward: given in UTF-8 represented in WIN-1252

  byte[] data = Encoding.UTF8.GetBytes("привет");
  string text = Encoding.GetEncoding(1252).GetString(data);

// Reverse: given in WIN-1252 represented in UTF-8

  byte[] reversedData = Encoding.GetEncoding(1252).GetBytes("Ð¿Ñ€Ð¸Ð²ÐµÑ‚");
  string reversedText = Encoding.UTF8.GetString(reversedData);

  Console.WriteLine($"{string.Join(" ", data)} <=> {text}");
  Console.WriteLine(reversedText);
</code>```

Outcome:

```<code>208 191 209 128 208 184 208 178 208 181 209 130 <=> Ð¿Ñ€Ð¸Ð²ÐµÑ‚
привет
</code>```

Please, note that you've omitted € and , characters:

```<code> Ð¿Ñ Ð¸Ð²ÐµÑ  - actual string
 Ð¿Ñ€Ð¸Ð²ÐµÑ‚ - should be
</code>```

Title: Encode UTF8 text to Unicode C#

Body:
How to encode UTF8 text to Unicode?

string text_txt = "Ð¿ÑÐ¸Ð²ÐµÑ";
byte[] bytesUtf8 = Encoding.Default.GetBytes(text_txt);
text_txt = Encoding.UTF8.GetString(bytesUtf8);

The problem is output: п�?иве�

I need output: привет

Using that site: https://www.branah.com/unicode-converter enter text in "UTF-8 text (Example: a ä¸ Ð¯)" to "Ð¿ÑÐ¸Ð²ÐµÑ" it will show you "привет" on Unicode text

Please give some advice thanks

Body:
Well, you probably mean this:

// Forward: given in UTF-8 represented in WIN-1252

  byte[] data = Encoding.UTF8.GetBytes("привет");
  string text = Encoding.GetEncoding(1252).GetString(data);

// Reverse: given in WIN-1252 represented in UTF-8

  byte[] reversedData = Encoding.GetEncoding(1252).GetBytes("Ð¿Ñ€Ð¸Ð²ÐµÑ‚");
  string reversedText = Encoding.UTF8.GetString(reversedData);

  Console.WriteLine($"{string.Join(" ", data)} <=> {text}");
  Console.WriteLine(reversedText);

Outcome:

208 191 209 128 208 184 208 178 208 181 209 130 <=> Ð¿Ñ€Ð¸Ð²ÐµÑ‚
привет

Please, note that you've omitted € and , characters:

 Ð¿Ñ Ð¸Ð²ÐµÑ  - actual string
 Ð¿Ñ€Ð¸Ð²ÐµÑ‚ - should be


问:
How to Iterate List (e.g. ArrayList) in XSLT
I have a List of String named as myList and
  I want to set all the values in XSLT in a tag using iteration:-

```<code><alpha>
...
</alpha>
</code>```

How is it possible to do it?

答:
XSLT 1.0 has no data structure in its data model to represent a sequence of strings; the only "collection" structure it supports is a node-set. If you're absolutely tied to XSLT 1.0, then you're going to have to wrap the strings as XML elements and pass in a document containing these elements.

But you're using Java, so you have access to XSLT 2.0 and XSLT 3.0 by installing Saxon, so it makes no sense to try and live with these restrictions. XSLT 2.0 greatly extends the set of data types supported (to include "sequence of strings" as one of the many possibilities), and XSLT 3.0 extends it further to include maps. Saxon's mappings from Java data types to XSLT/XPath data types include the possibility of converting a Java List<String> to an XPath xs:string*.

With Saxon, you can declare a parameter as expecting a list of strings:

```<code><xsl:param name="in" as="xs:string*"/>
</code>```

and you can then supply as the actual value a List<String>, which is converted as described here:

http://www.saxonica.com/documentation/index.html#!extensibility/functions/function-result

In XSLT you can then wrap these strings as elements (I've used XSLT 3.0 syntax here):

```<code><xsl:for-each select="$in">
  <alpha>{.}</alpha>
</xsl:for-each>
</code>```

[Disclaimer: I am the lead developer of Saxon]

Body:
I have a List of String named as myList and
  I want to set all the values in XSLT in a tag using iteration:-

<alpha>
...
</alpha>

How is it possible to do it?

Body:
XSLT 1.0 has no data structure in its data model to represent a sequence of strings; the only "collection" structure it supports is a node-set. If you're absolutely tied to XSLT 1.0, then you're going to have to wrap the strings as XML elements and pass in a document containing these elements.

But you're using Java, so you have access to XSLT 2.0 and XSLT 3.0 by installing Saxon, so it makes no sense to try and live with these restrictions. XSLT 2.0 greatly extends the set of data types supported (to include "sequence of strings" as one of the many possibilities), and XSLT 3.0 extends it further to include maps. Saxon's mappings from Java data types to XSLT/XPath data types include the possibility of converting a Java List<String> to an XPath xs:string*.

With Saxon, you can declare a parameter as expecting a list of strings:

<xsl:param name="in" as="xs:string*"/>

and you can then supply as the actual value a List<String>, which is converted as described here:

http://www.saxonica.com/documentation/index.html#!extensibility/functions/function-result

In XSLT you can then wrap these strings as elements (I've used XSLT 3.0 syntax here):

<xsl:for-each select="$in">
  <alpha>{.}</alpha>
</xsl:for-each>

[Disclaimer: I am the lead developer of Saxon]


问:
S3 Cross region replication using Terraform
I was using Terraform to setup S3 buckets (different region) and set up replication between them.

It was working properly until I added KMS in it.

I created 2 KMS keys one for source and one for destination.

Now while applying replication configuration, there is an option to pass destination key for destination bucket but I am not sure how to apply key at the source.

Any help would be appreciated.

provider "aws" {
  alias  = "east"
  region = "us-east-1"
}

resource "aws_s3_bucket" "destination-bucket" {
  bucket = ""destination-bucket"
  provider = "aws.east"
  acl    = "private"
  region   = "us-east-1"
  versioning {
    enabled = true
  }
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = "${var.kms_cmk_dest_arn}"
        sse_algorithm     = "aws:kms"
      }
    }
  }
}

resource "aws_s3_bucket" "source-bucket" {
  bucket = "source-bucket"
  acl    = "private"
  versioning {
    enabled = true
  }
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        kms_master_key_id = "${var.kms_cmk_arn}"
        sse_algorithm     = "aws:kms"
      }
    }
  }
  replication_configuration {
    role = "${aws_iam_role.replication.arn}"

    rules {
      status = "Enabled"
   destination {
        bucket        = "${aws_s3_bucket.source-bucket.arn}"
        storage_class = "STANDARD"
  replica_kms_key_id = "${var.kms_cmk_dest_arn}"
      }
   source_selection_criteria {
      sse_kms_encrypted_objects {
      enabled = true
   }
    }
    }
  }
}

resource "aws_iam_role" "replication" {
  name = "cdd-iam-role-replication"
  permissions_boundary    = "arn:aws:iam::${var.account_id}:policy/ServiceRoleBoundary"
  assume_role_policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy" "replication" {
  name = "cdd-iam-role-policy-replication"
  role = "${aws_iam_role.replication.id}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:GetReplicationConfiguration",
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Resource": [
        "${aws_s3_bucket.source-bucket.arn}"
      ]
    },
    {
      "Action": [
        "s3:GetObjectVersion",
        "s3:GetObjectVersionAcl"
      ],
      "Effect": "Allow",
      "Resource": [
        "${aws_s3_bucket.source-bucket.arn}/*"
      ]
    },
    {
      "Action": [
        "s3:ReplicateObject",
        "s3:ReplicateDelete"
      ],
      "Effect": "Allow",
      "Resource": "${aws_s3_bucket.destination-bucket.arn}/*"
    }
  ]
}
POLICY
}```

答:
In case you're using a Customer Managed Key(CMK) for S3 encryption, you need extra configuration.
AWS S3 Documentation mentions that the CMK owner must grant the source bucket owner permission to use the CMK.

https://docs.aws.amazon.com/AmazonS3/latest/dev/replication-config-for-kms-objects.html#replication-kms-cross-acct-scenario

Also, a good article to summarize the S3 cross region replication configuration:

https://medium.com/@devopslearning/100-days-of-devops-day-44-s3-cross-region-replication-crr-8c58ae8c68d4


问:
marklogic xdmp:http-post options parameter issue
Trying to build options parameter from another config XML to pass in the xdmp:http-post function.

```<code>let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/user-name/text()}</username>
                <password>{$db-config/password/text()}</password>
            </authentication>
        </options>
return $options
</code>```

output of the above code is:

```<code><options xmlns="xdmp:http">
  <authentication method="digest">
    <username>
    </username>
    <password>
    </password>
 </authentication>
</options>
</code>```

No able to understand why the xpath is returning blank.
On removing the xmlns="xdmp:http" namespace getting the correct output.

答:
Correct. It is a very subtle side-effect of using literal elements in default namespace inside your XQuery. Simplest is to use *: prefix wildcarding:

```<code>let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/*:user-name/text()}</username>
                <password>{$db-config/*:password/text()}</password>
            </authentication>
        </options>
return $options
</code>```

You can also pre-calc the values before the literal elements:

```<code>let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $user as xs:string := $db-config/user-name
let $pass as xs:string := $db-config/password
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$user}</username>
                <password>{$pass}</password>
            </authentication>
        </options>
return $options
</code>```

Or use element constuctors:

```<code>let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        element {fn:QName("xdmp:http", "options")} {
            element {fn:QName("xdmp:http", "authentication")} {
                attribute method { "digest" },

                element {fn:QName("xdmp:http", "username")} {
                    $db-config/user-name/text()
                },
                element {fn:QName("xdmp:http", "password")} {
                    $db-config/password/text()
                }
            }
        }
return $options
</code>```

HTH!

Body:
Trying to build options parameter from another config XML to pass in the xdmp:http-post function.

let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/user-name/text()}</username>
                <password>{$db-config/password/text()}</password>
            </authentication>
        </options>
return $options

output of the above code is:

<options xmlns="xdmp:http">
  <authentication method="digest">
    <username>
    </username>
    <password>
    </password>
 </authentication>
</options>

No able to understand why the xpath is returning blank.
On removing the xmlns="xdmp:http" namespace getting the correct output.

Body:
Correct. It is a very subtle side-effect of using literal elements in default namespace inside your XQuery. Simplest is to use *: prefix wildcarding:

let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$db-config/*:user-name/text()}</username>
                <password>{$db-config/*:password/text()}</password>
            </authentication>
        </options>
return $options

You can also pre-calc the values before the literal elements:

let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $user as xs:string := $db-config/user-name
let $pass as xs:string := $db-config/password
let $options :=
        <options xmlns="xdmp:http">
            <authentication method="digest">
                <username>{$user}</username>
                <password>{$pass}</password>
            </authentication>
        </options>
return $options

Or use element constuctors:

let $db-config :=
  <config>
      <user-name>admin</user-name>
      <password>admin</password>
  </config>
let $options :=
        element {fn:QName("xdmp:http", "options")} {
            element {fn:QName("xdmp:http", "authentication")} {
                attribute method { "digest" },

                element {fn:QName("xdmp:http", "username")} {
                    $db-config/user-name/text()
                },
                element {fn:QName("xdmp:http", "password")} {
                    $db-config/password/text()
                }
            }
        }
return $options

HTH!


问:
Trying to send a json encoded array from php to a js file, "Unexpected end of input"
So im trying to send an object array to a js function anytime I push a button.

```<code><button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>
</code>```

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

```<code>   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}
</code>```

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

```<code>$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });
</code>```

This is the full json I'm trying to send

```<code>[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]
</code>```

答:
I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

Strings in JSON are delimited with " characters.

```<code><button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>
</code>```

Your HTML attribute value is delimited with " characters.

The " in the data will cut off the attribute value.

You need to encode your data (using htmlspecialchars) for embedding in HTML:

```<code><?php echo htmlspecialchars(json_encode($p_array)); ?>
</code>```

Body:
So im trying to send an object array to a js function anytime I push a button.

<button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>

I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

That function is in a different js file:

   function actualizarProcesos(p_array){
    var p = JSON.parse(p_array);
}

At the moment I'm trying to send make sure the function is receiving the data but it keeps throwing the error Uncaught SyntaxError: Unexpected end of inputSo I'm stuck trying to find out how to fix the error.

I plan afterwards on sending that array to another php file using ajax, something like this:

$.ajax({
            type: "POST",
            url: "post.php",
            data: JSON.stringify(values),
            success: function(data){
                alert(data)
            }
    });

This is the full json I'm trying to send

[{"name":"A","t_arrival":7,"t_est":25,"state":1,"pages":5,"mem_data":[[1,8,13,5,0,1],[0,0,0,0,0,0],[1,11,17,3,1,1],[1,12,16,4,0,1],[0,0,0,0,0,0]],"t_rem":25,"t_wait":0,"rem_quantum":0},{"name":"B","t_arrival":6,"t_est":13,"state":2,"pages":4,"mem_data":[[0,0,0,0,0,0],[1,9,16,5,0,1],[1,7,14,6,1,0],[0,0,0,0,0,0]],"t_rem":13,"t_wait":0,"rem_quantum":0},{"name":"C","t_arrival":8,"t_est":37,"state":3,"pages":3,"mem_data":[[1,9,12,2,0,0],[0,0,0,0,0,0],[1,13,21,7,0,1]],"t_rem":37,"t_wait":0,"rem_quantum":0}]

Body:
I've made sure my json isnt sending any weird characters as it is mostly int except for the object attribute "name" which is string.

Strings in JSON are delimited with " characters.

<button onclick="actualizarProcesos(<?php echo json_encode($p_array)?>);">X</button>

Your HTML attribute value is delimited with " characters.

The " in the data will cut off the attribute value.

You need to encode your data (using htmlspecialchars) for embedding in HTML:

<?php echo htmlspecialchars(json_encode($p_array)); ?>