问:
Not able to reach an internal endpoint when using tcp-services
I have an issue on which am blocked since few days . Tried lot of things but none worked .

I have a k8s cluster in which I have a pod running corda (https://docs.corda.net/docker-image.html) . This pod expose a RPC endpoint (10201), endpoint that I want to be able to reach from outside the cluster (my laptop) using the corda-shell tool .

So I created an ingress (using ingress-nginx) and added a config-map that looks like that :

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-tcp-services
  namespace: {{ .Release.Namespace }}
data:
  10201: {{ .Release.Namespace }}/{{ .Release.Name }}-corda-node:10201
</code>```

The service.yaml for the corda pod looks like this :

```<code>apiVersion: v1
kind: Service
metadata:
  name: {{ include "corda-node.fullname" . }}
  labels:
{{ include "corda-node.labels" . | indent 4 }}
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      protocol: TCP
      name: http
    - port: 10200
      targetPort: p2p
      protocol: TCP
      name: p2p
    - port: 10201
      targetPort: rpc
      protocol: TCP
      name: rpc
    - port: 10202
      targetPort: rpcadmin
      protocol: TCP
      name: rpcadmin
  selector:
    app.kubernetes.io/name: {{ include "corda-node.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
</code>```

But so far, no matter what I tried I was not able to connect to it from the outside .
From another pod / container in the cluster it is working fine, same as when I'm port-forwarding to my local .

Note : I can connect to other services in my cluster from the outside . In fact this corda pod has a sidecar which expose an API on 8080 and I can access it .

I can see the port '10201' being exposed by the ingress, so I guess it took my tcp-services into account, but does not seem to be able to forward the request to the corda pod .

If I try to do telnet public-ip-of-the-cluter 10201 , I just have a timeout .
Same when running the corda-shell tool ...

I see no relevant logs in the ingress-controller pod as far as I can tell .

I created a small github repo with various 'kubectl describe xxx' commands in order to give you an overview of what I did .

If you need more info just ask me . Am really struggling with that, most likely I'm doing something stupid somewhere ...

Thanks !

EDIT :

I put the logs of the ingress on - --v=3 , I can see this when it starts :

I0215 09:30:32.081819       6 controller.go:333] Searching Endpoints
  with TCP port number 10201 for Service
  "salmon-locust/salmon-locust-corda-node-corda-node"

  │ │ I0215 09:30:32.081836       6 endpoints.go:74] Getting Endpoints
  for Service "salmon-locust/salmon-locust-corda-node-corda-node" and
  port &ServicePort{Name:rpc,Protocol:TCP,Port:10201,TargetPort:{1 0
  rpc},NodePort:0,}                  │ │ I0215 09:30:32.081849       6
  endpoints.go:117] Endpoints found for Service
  "salmon-locust/salmon-locust-corda-node-corda-node": [{10.96.1.13
  10201
  &ObjectReference{Kind:Pod,Namespace:salmon-locust,Name:salmon-locust-corda-node-corda-
  │

But no activity when I’m trying to connect to it via the corda-tools-shell.

EDIT 2 :

We found what was the issue, the ingress -> dns resolved to the cloudflare proxy, which was not handling the 1xxxx port ...

答: We found what was the issue, the ingress -> dns resolved to the cloudflare proxy, which was not handling the 1xxxx port ...</p>

Body:
I have an issue on which am blocked since few days . Tried lot of things but none worked .

I have a k8s cluster in which I have a pod running corda (https://docs.corda.net/docker-image.html) . This pod expose a RPC endpoint (10201), endpoint that I want to be able to reach from outside the cluster (my laptop) using the corda-shell tool .

So I created an ingress (using ingress-nginx) and added a config-map that looks like that :

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-tcp-services
  namespace: {{ .Release.Namespace }}
data:
  10201: {{ .Release.Namespace }}/{{ .Release.Name }}-corda-node:10201

The service.yaml for the corda pod looks like this :

apiVersion: v1
kind: Service
metadata:
  name: {{ include "corda-node.fullname" . }}
  labels:
{{ include "corda-node.labels" . | indent 4 }}
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      protocol: TCP
      name: http
    - port: 10200
      targetPort: p2p
      protocol: TCP
      name: p2p
    - port: 10201
      targetPort: rpc
      protocol: TCP
      name: rpc
    - port: 10202
      targetPort: rpcadmin
      protocol: TCP
      name: rpcadmin
  selector:
    app.kubernetes.io/name: {{ include "corda-node.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}

But so far, no matter what I tried I was not able to connect to it from the outside .
From another pod / container in the cluster it is working fine, same as when I'm port-forwarding to my local .

Note : I can connect to other services in my cluster from the outside . In fact this corda pod has a sidecar which expose an API on 8080 and I can access it .

I can see the port '10201' being exposed by the ingress, so I guess it took my tcp-services into account, but does not seem to be able to forward the request to the corda pod .

If I try to do telnet public-ip-of-the-cluter 10201 , I just have a timeout .
Same when running the corda-shell tool ...

I see no relevant logs in the ingress-controller pod as far as I can tell .

I created a small github repo with various 'kubectl describe xxx' commands in order to give you an overview of what I did .

If you need more info just ask me . Am really struggling with that, most likely I'm doing something stupid somewhere ...

Thanks !

EDIT :

I put the logs of the ingress on - --v=3 , I can see this when it starts :

I0215 09:30:32.081819       6 controller.go:333] Searching Endpoints
  with TCP port number 10201 for Service
  "salmon-locust/salmon-locust-corda-node-corda-node"

  │ │ I0215 09:30:32.081836       6 endpoints.go:74] Getting Endpoints
  for Service "salmon-locust/salmon-locust-corda-node-corda-node" and
  port &ServicePort{Name:rpc,Protocol:TCP,Port:10201,TargetPort:{1 0
  rpc},NodePort:0,}                  │ │ I0215 09:30:32.081849       6
  endpoints.go:117] Endpoints found for Service
  "salmon-locust/salmon-locust-corda-node-corda-node": [{10.96.1.13
  10201
  &ObjectReference{Kind:Pod,Namespace:salmon-locust,Name:salmon-locust-corda-node-corda-
  │

But no activity when I’m trying to connect to it via the corda-tools-shell.

EDIT 2 :

We found what was the issue, the ingress -> dns resolved to the cloudflare proxy, which was not handling the 1xxxx port ...


来源: stackexchange

问:
Does the select element have the required attribute?
Does the select element have the required attribute?</p>

答:
You can do this way to make it look better</p>

```<code>    <select required>
    <option hidden="" disabled="disabled" selected="selected" value="">Select subject</option>
    <option value="first Option">First Option</option>
    <option value="Second Option">Second Option</option>
    </select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do this way to make it look better

    <select required>
    <option hidden="" disabled="disabled" selected="selected" value="">Select subject</option>
    <option value="first Option">First Option</option>
    <option value="Second Option">Second Option</option>
    </select>

ContentLicense: CC BY-SA 4.0


问:
Getting weird markup from Google translate like ~~POS=TRUNC
I'm suddenly getting same strange markup when translating phrases in Google Translate API via the Java library. Examples for English → Swedish include:

```<code>Vector graphics → vektor~~POS=TRUNC grafikk~~POS=HEADCOMP

Javascript → Javascript script~~POS=HEADCOMP
</code>```

It looks like it's related to compound noun handling. Is this a feature of the API that I can deactivate somehow or is this a new bug on the server side?

答:
This looks like a bug in the server-side translator. I also get it on the web site,  https://translate.google.com/#view=home&op=translate&sl=ru&tl=no&text=%D0%9E%D0%B1%D1%89%D0%B5%D0%B6%D0%B8%D1%82%D0%B8%D0%B5 gives me vandrer~~POS=TRUNC.

In NLP, "POS" means Part-Of-Speech, "HEADCOMP" sounds like it could be the head of a noun-compound, I'm guessing they TRUNCate the non-head parts of compounds (practically never inflected). So Google Translate is spilling some of its internals. What's surprising is that such tags are the staple of rule-based/knowledge-based systems, whereas Google typically only does pure machine learning methods, shunning hard-coded knowledge. (One possibility is that they used a noun-compound analyser to expand their training set (which they then ran ML on, similar to how Systran & Koehn trained statistical MT on a parallel corpus translated with a rule-based MT system), but had a bug in the script to clean up the tags before training.)

It'd be fun to find out which system they used, in case it was an open source one, but unfortunately the tags are practically ungoogleable, since the web is now littered with spammy machine translated (and non-post-edited) pages full of those tags.

Body:
I'm suddenly getting same strange markup when translating phrases in Google Translate API via the Java library. Examples for English → Swedish include:

Vector graphics → vektor~~POS=TRUNC grafikk~~POS=HEADCOMP

Javascript → Javascript script~~POS=HEADCOMP

It looks like it's related to compound noun handling. Is this a feature of the API that I can deactivate somehow or is this a new bug on the server side?


问:
Iterate through objects in objects in Firebase using FirebaseRecyclerAdapter
I did some reading on my problem & while a lot of people pointed to using DataSnapshot.forEach() to solve my issue, I would like to know if it's possible to modify my query inside FirebaseRecyclerAdapter to fit my needs.

This is the structure I currently have where a Request may have 1 or many Orders. Each Order comes with its set of values such as restaurantID.
I want to basically iterate through all those requests & only display the ones that have an order with a certain restaurantID.

In my application, the user logs in & has a value for restaurantID. I want to show inside my RecyclerView only the orders that are related to that account, based on that value.

Below is the code. I tried to do some funny stuff in populateViewHolder() to fix this with ordersForThisRestaurant but it did not quite work out. I would love any help on this, I have been stuck & wasn't able to make any progress for some time. Would be awesome to advance!

THANK YOU!

OrderStatus.java

```<code>public class OrderStatus extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;

    FirebaseDatabase database;
    DatabaseReference requests;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_status);

        //Initialize the Firebase database.
        database = FirebaseDatabase.getInstance();
        requests = database.getReference("Requests");

        recyclerView = (RecyclerView) findViewById(R.id.recyclerOrder);
        recyclerView.setHasFixedSize(true);
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadOrders();
    }

    private void loadOrders() {
        adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
                Request.class,
                R.layout.order_layout,
                OrderViewHolder.class,
                requests
        ) {
            @Override
            protected void populateViewHolder(OrderViewHolder orderViewHolder, Request request, int i) {
                List<Order> activeOrders = request.getOrder();
                List<Order> ordersForThisRestaurant = new ArrayList<>();
                for(int pos=0; pos<activeOrders.size(); pos++) {
                    Order currentOrder = activeOrders.get(pos);
                    String restaurantID = currentOrder.getRestaurantID();
                    if(restaurantID.equals(Common.currentUser.getRestaurantID())) {
                        ordersForThisRestaurant.add(activeOrders.get(pos));
                    }
                }
                if(ordersForThisRestaurant.size() == 0) return;     //This means the request was not for this restaurant.

                orderViewHolder.orderID.setText(adapter.getRef(i).getKey());
                orderViewHolder.orderStatus.setText(Common.convertCodeToStatus(request.getStatus()));
                String orderMenu = "";

                for(int pos=0; pos<ordersForThisRestaurant.size(); pos++) {
                    String currentMenu = ordersForThisRestaurant.get(pos).getMenuName();
                    String currentQuantity = ordersForThisRestaurant.get(pos).getQuantity();
                    //orderMenu += currentMenu + " x" + currentQuantity + " | ";
                    if(pos != 0) {
                        orderMenu += "\n";
                    }
                    orderMenu += currentQuantity + " " + currentMenu;
                }

                orderViewHolder.orderMenu.setText(orderMenu);
                orderViewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        //Empty -> just to fix crash because of context menu
                    }
                });
            }
        };

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);

    }
</code>```

OrderViewHolder.java

```<code>public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener{

    public TextView orderID;
    public TextView orderStatus;
    public TextView orderMenu;

    private ItemClickListener itemClickListener;

    public OrderViewHolder(@NonNull View itemView) {
        super(itemView);
        orderID = (TextView) itemView.findViewById(R.id.orderID);
        orderStatus = (TextView) itemView.findViewById(R.id.orderStatus);
        orderMenu = (TextView) itemView.findViewById(R.id.orderMenu);
        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select an action");
        menu.add(0, 0, getAdapterPosition(), "Update");
        menu.add(0, 1, getAdapterPosition(), "Delete");

    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        //No onClick => otherwise it throws an error.
        //itemClickListener.onClick(v, getAdapterPosition(), false);
    }

}
</code>```

Request.java

```<code>public class Request {
    private String email;
    private String name;
    private List<Order> order;
    private String restriction;
    private String status;

    public Request() { }

    public Request(String email, String name, String restriction, List<Order> order) {
        this.email = email;
        this.name = name;
        this.restriction = restriction;
        this.order = order;
        this.status = "0";          //0: Placed. 1: Ready. 2: Picked up.
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    public String getRestriction() {
        return restriction;
    }
    public void setRestriction(String restriction) {
        this.restriction = restriction;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Order> getOrder() {
        return order;
    }
    public void setOrder(List<Order> order) {
        this.order = order;
    }
}
</code>```

答:
If you want to retrieve the data according to the resturantID, then you need to do the following:

```<code> requests = database.getReference("Requests").child("1582094998206").child("order");
 Query resturantQuery = requests.orderByChild("restaurantID").equalTo("01");
</code>```

Then use resturantQuery inside the FirebaseRecyclerAdapter.

Body:
I did some reading on my problem & while a lot of people pointed to using DataSnapshot.forEach() to solve my issue, I would like to know if it's possible to modify my query inside FirebaseRecyclerAdapter to fit my needs.

This is the structure I currently have where a Request may have 1 or many Orders. Each Order comes with its set of values such as restaurantID.
I want to basically iterate through all those requests & only display the ones that have an order with a certain restaurantID.

In my application, the user logs in & has a value for restaurantID. I want to show inside my RecyclerView only the orders that are related to that account, based on that value.

Below is the code. I tried to do some funny stuff in populateViewHolder() to fix this with ordersForThisRestaurant but it did not quite work out. I would love any help on this, I have been stuck & wasn't able to make any progress for some time. Would be awesome to advance!

THANK YOU!

OrderStatus.java

public class OrderStatus extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;

    FirebaseDatabase database;
    DatabaseReference requests;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_status);

        //Initialize the Firebase database.
        database = FirebaseDatabase.getInstance();
        requests = database.getReference("Requests");

        recyclerView = (RecyclerView) findViewById(R.id.recyclerOrder);
        recyclerView.setHasFixedSize(true);
        layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        loadOrders();
    }

    private void loadOrders() {
        adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
                Request.class,
                R.layout.order_layout,
                OrderViewHolder.class,
                requests
        ) {
            @Override
            protected void populateViewHolder(OrderViewHolder orderViewHolder, Request request, int i) {
                List<Order> activeOrders = request.getOrder();
                List<Order> ordersForThisRestaurant = new ArrayList<>();
                for(int pos=0; pos<activeOrders.size(); pos++) {
                    Order currentOrder = activeOrders.get(pos);
                    String restaurantID = currentOrder.getRestaurantID();
                    if(restaurantID.equals(Common.currentUser.getRestaurantID())) {
                        ordersForThisRestaurant.add(activeOrders.get(pos));
                    }
                }
                if(ordersForThisRestaurant.size() == 0) return;     //This means the request was not for this restaurant.

                orderViewHolder.orderID.setText(adapter.getRef(i).getKey());
                orderViewHolder.orderStatus.setText(Common.convertCodeToStatus(request.getStatus()));
                String orderMenu = "";

                for(int pos=0; pos<ordersForThisRestaurant.size(); pos++) {
                    String currentMenu = ordersForThisRestaurant.get(pos).getMenuName();
                    String currentQuantity = ordersForThisRestaurant.get(pos).getQuantity();
                    //orderMenu += currentMenu + " x" + currentQuantity + " | ";
                    if(pos != 0) {
                        orderMenu += "\n";
                    }
                    orderMenu += currentQuantity + " " + currentMenu;
                }

                orderViewHolder.orderMenu.setText(orderMenu);
                orderViewHolder.setItemClickListener(new ItemClickListener() {
                    @Override
                    public void onClick(View view, int position, boolean isLongClick) {
                        //Empty -> just to fix crash because of context menu
                    }
                });
            }
        };

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);

    }

OrderViewHolder.java

public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener{

    public TextView orderID;
    public TextView orderStatus;
    public TextView orderMenu;

    private ItemClickListener itemClickListener;

    public OrderViewHolder(@NonNull View itemView) {
        super(itemView);
        orderID = (TextView) itemView.findViewById(R.id.orderID);
        orderStatus = (TextView) itemView.findViewById(R.id.orderStatus);
        orderMenu = (TextView) itemView.findViewById(R.id.orderMenu);
        itemView.setOnClickListener(this);
        itemView.setOnCreateContextMenuListener(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Select an action");
        menu.add(0, 0, getAdapterPosition(), "Update");
        menu.add(0, 1, getAdapterPosition(), "Delete");

    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        //No onClick => otherwise it throws an error.
        //itemClickListener.onClick(v, getAdapterPosition(), false);
    }

}

Request.java

public class Request {
    private String email;
    private String name;
    private List<Order> order;
    private String restriction;
    private String status;

    public Request() { }

    public Request(String email, String name, String restriction, List<Order> order) {
        this.email = email;
        this.name = name;
        this.restriction = restriction;
        this.order = order;
        this.status = "0";          //0: Placed. 1: Ready. 2: Picked up.
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    public String getRestriction() {
        return restriction;
    }
    public void setRestriction(String restriction) {
        this.restriction = restriction;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Order> getOrder() {
        return order;
    }
    public void setOrder(List<Order> order) {
        this.order = order;
    }
}

Body:
If you want to retrieve the data according to the resturantID, then you need to do the following:

 requests = database.getReference("Requests").child("1582094998206").child("order");
 Query resturantQuery = requests.orderByChild("restaurantID").equalTo("01");

Then use resturantQuery inside the FirebaseRecyclerAdapter.


问:
Defining Eq instance for Haskell GADTs
I have a GADT that's a lot like this:

```<code>data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (a -> b) -> In a -> In b
</code>```

It wraps various input primitives, but the last constructor also allows for a Functor instance:

```<code>instance Functor In where
  fmap f (F g v) = F (f . g) v
  fmap f x = F f x
</code>```

The point of this type, BTW, is to support:

```<code>read :: In a -> IO a
read (M v) = takeMVar v
read (T v) = atomically (readTVar v)
read (F f v) = f <$> read v
</code>```

What I want to be able to do is define the obvious Eq instance on this type, something like:

```<code>instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = x == y
  _ == _ = False
</code>```

The problem is the third case, which fails because x and y don't necessarily have the same type at that point.  I understand that.  In my own code I can make a long work-around, but it feels like there should be a way to define Eq directly.  In my mind the solution is something like "keep drilling through the F constructors until you hit M or T, then if they're the same constructor (i.e. both M or both T) and same type, do the equality comparison", but I'm not sure how I could write that.

答:
I'm highly suspicious about your equality since it only really tests half of the F, but if that's what you really want, here's how you can do it.  Note that the cast serves as a test for type equality, since you can only compare the two Fs if the types of the existentially quantified a inside are the same.

```<code>data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (Typeable a) => (a -> b) -> In a -> In b
  deriving (Typeable)

instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = Just x == cast y
  _ == _ = False
</code>```

Or maybe this isn't what you want either?  Reading your motivation again it seems like you want a function where an In Int can be equal to an In Double.

How would you like these two to compare F floor r and F id r (if r is M x :: In Double)?

Title: Defining Eq instance for Haskell GADTs

Body:
I have a GADT that's a lot like this:

data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (a -> b) -> In a -> In b

It wraps various input primitives, but the last constructor also allows for a Functor instance:

instance Functor In where
  fmap f (F g v) = F (f . g) v
  fmap f x = F f x

The point of this type, BTW, is to support:

read :: In a -> IO a
read (M v) = takeMVar v
read (T v) = atomically (readTVar v)
read (F f v) = f <$> read v

What I want to be able to do is define the obvious Eq instance on this type, something like:

instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = x == y
  _ == _ = False

The problem is the third case, which fails because x and y don't necessarily have the same type at that point.  I understand that.  In my own code I can make a long work-around, but it feels like there should be a way to define Eq directly.  In my mind the solution is something like "keep drilling through the F constructors until you hit M or T, then if they're the same constructor (i.e. both M or both T) and same type, do the equality comparison", but I'm not sure how I could write that.

Body:
I'm highly suspicious about your equality since it only really tests half of the F, but if that's what you really want, here's how you can do it.  Note that the cast serves as a test for type equality, since you can only compare the two Fs if the types of the existentially quantified a inside are the same.

data In a where
  M :: MVar a -> In a
  T :: TVar a -> In a
  F :: (Typeable a) => (a -> b) -> In a -> In b
  deriving (Typeable)

instance Eq (In a) where
  (M x) == (M y) = x == y
  (T x) == (T y) = x == y
  (F _ x) == (F _ y) = Just x == cast y
  _ == _ = False

Or maybe this isn't what you want either?  Reading your motivation again it seems like you want a function where an In Int can be equal to an In Double.

How would you like these two to compare F floor r and F id r (if r is M x :: In Double)?


问:
How to remove the default Navigation Bar space in SwiftUI NavigationView
I am new to SwiftUI (like most people) and trying to figure out how to remove some whitespace above a List that I embedded in a NavigationView.

In this image, you can see that there is some white space above the List.

What I want to accomplish is this:

I've tried using:

```<code>.navigationBarHidden(true)
</code>```

but this did not make any noticeable changes.

I'm currently setting up my navigiationView like this:

```<code>NavigationView {
    FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL))
        .navigationBarHidden(true)
}
</code>```

where FileBrowserView is a view with a List and FileCells defined like this:

```<code>List {
   Section(header: Text("Root")) {
       FileCell(name: "Test", fileType: "JPG",fileDesc: "Test number 1")
       FileCell(name: "Test 2", fileType: "txt",fileDesc: "Test number 2")
       FileCell(name: "test3", fileType: "fasta", fileDesc: "")
    }
}
</code>```

I do want to note that the ultimate goal here is that you will be able to click on these cells to navigate deeper into a file tree and thus should display a Back button on the bar on deeper navigation, but I do not want anything at the top as such during my initial view.

答: For me it was because I was pushing my NavigationView from an existing. In effect having one inside the other. If you are coming from a NavigationView you do not need to create one inside the next as you already inside a NavigatonView. </p>

Body:
I am new to SwiftUI (like most people) and trying to figure out how to remove some whitespace above a List that I embedded in a NavigationView.

In this image, you can see that there is some white space above the List.

What I want to accomplish is this:

I've tried using:

.navigationBarHidden(true)

but this did not make any noticeable changes.

I'm currently setting up my navigiationView like this:

NavigationView {
    FileBrowserView(jsonFromCall: URLRetrieve(URLtoFetch: applicationDelegate.apiURL))
        .navigationBarHidden(true)
}

where FileBrowserView is a view with a List and FileCells defined like this:

List {
   Section(header: Text("Root")) {
       FileCell(name: "Test", fileType: "JPG",fileDesc: "Test number 1")
       FileCell(name: "Test 2", fileType: "txt",fileDesc: "Test number 2")
       FileCell(name: "test3", fileType: "fasta", fileDesc: "")
    }
}

I do want to note that the ultimate goal here is that you will be able to click on these cells to navigate deeper into a file tree and thus should display a Back button on the bar on deeper navigation, but I do not want anything at the top as such during my initial view.


问:
This for loop loops through the same values more then once?
Why does this for loop loop through the same Values more then once? I added the categories Class to the code so that you can see what I mean with that they are actual lists. These lists withholds values that are scrambled and that should be unscrambled depending on if they have the same three first numbers

```<code>     for(int i = 0; i < categories2.parentCategoryId.Count; i++)
     {
        for (int j = 0; j < categories2.NewCategoryId.Count; j++)
        {
            if(categories2.parentCategoryId[i].Substring(0, 3) == categories2.NewCategoryId[j].Substring(0, 3)){

                Console.Write(categories2.parentCategoryId[i] + " ");
                Console.Write(categories2.parentCategoryName[i] + "´          ");
                Console.Write(categories2.NewCategoryId[j] + " ");
                Console.Write(categories2.NewCategoryName[j] + "\n");

            }
        }
     }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrestaConverter
{
    public class Categories
    {
        public List<string> CategoryName = new List<string>();
        public List<string> CategoryId = new List<string>();

        public List<string> NewCategoryId = new List<string>();
        public List<string> NewCategoryName = new List<string>();

        public List<string> oldCategoryName = new List<string>();
        public List<string> oldCategoryId = new List<string>();

        public List<string> parentCategoryId = new List<string>();
        public List<string> parentCategoryName = new List<string>();

        public List<string> childCategoryID = new List<string>();
        public List<string> childCategoryName = new List<string>();

        public Categories()
        {

        }
        public bool checkFirstNumbers(string categoryid,string correctNumber)
        {
            for(int i = 0; i < 2; i++){
                if(categoryid.Substring(i) == correctNumber.Substring(i))
                {
                    return true;
                }
            }

            return false;

        }

    }
}
</code>```

I have 3 categories in full which is 3 objects that withhold 6 different lists. Categories2 is a list of a bunch of subcategories that should exist beneath categories1. So these categories have two different identification ways either by id or name so we have NewCategoryId and NewCategoryName. These lists does not have two of the same values in them. But then we have the parencategoryName and parentCategoryId lists and these withholds the parentcategoryNames in the number of times that they need to show up to be able to place the subcategories beneath them. and now we need to compare NewCategoryID with parentCategoryId to see where to place NewCategoryName in our exceldocument.

答:
To explain a bit, as mentioned in my comment, if both categories2.parentCategoryId.Count and categories2.NewCategoryId.Count are the same, your sample code could look like this:

```<code> for(int i = 0; i < categories2.parentCategoryId.Count; i++)
 {
        if(categories2.parentCategoryId[i].Substring(0, 3) == categories2.NewCategoryId[i].Substring(0, 3)){

            Console.Write(categories2.parentCategoryId[i] + " ");
            Console.Write(categories2.parentCategoryName[i] + "´          ");
            Console.Write(categories2.NewCategoryId[i] + " ");
            Console.Write(categories2.NewCategoryName[i] + "\n");
    }
 }
</code>```

Your code uses nested loops, which work like this:

```<code>for(int i = 0; i < 10; i++)
{
    // this is run 10 times
    for(int j = 0; j < 10; j++)
    {
       // this runs 10 times for each iteration of i, so all in all 100 times
    }
}
</code>```

If I understand your needed functionality correctly and you use List<T> You can use something like:

```<code> for(int i = 0; i < categories2.parentCategoryId.Count; i++)
 {
     var match = categories2.NewCategoryId.FirstOrDefault(stringToCheck => stringToCheck.Substring(0, 3) == categories2.parentCategoryId[i].Substring(0, 3)));
    if(match != null)
    {
            Console.Write(categories2.parentCategoryId[i] + " ");
            Console.Write(categories2.parentCategoryName[i] + "´          ");
            Console.Write(match  + " ");
            Console.Write(match  + "\n");
    }
 }
</code>```

What should happen here is that the loop runs through the first list and in each iteration checks, if there exist an item with the same substring in the second list (FirstOrDefault either returns the first item that fits the result, or null if it doesn't find any).
If a correct item is found, the same code as in OP is run.

Hope I didn't make any mistakes, doesn't have a code editor in front of me ;)

Body:
Why does this for loop loop through the same Values more then once? I added the categories Class to the code so that you can see what I mean with that they are actual lists. These lists withholds values that are scrambled and that should be unscrambled depending on if they have the same three first numbers

     for(int i = 0; i < categories2.parentCategoryId.Count; i++)
     {
        for (int j = 0; j < categories2.NewCategoryId.Count; j++)
        {
            if(categories2.parentCategoryId[i].Substring(0, 3) == categories2.NewCategoryId[j].Substring(0, 3)){

                Console.Write(categories2.parentCategoryId[i] + " ");
                Console.Write(categories2.parentCategoryName[i] + "´          ");
                Console.Write(categories2.NewCategoryId[j] + " ");
                Console.Write(categories2.NewCategoryName[j] + "\n");

            }
        }
     }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrestaConverter
{
    public class Categories
    {
        public List<string> CategoryName = new List<string>();
        public List<string> CategoryId = new List<string>();

        public List<string> NewCategoryId = new List<string>();
        public List<string> NewCategoryName = new List<string>();

        public List<string> oldCategoryName = new List<string>();
        public List<string> oldCategoryId = new List<string>();

        public List<string> parentCategoryId = new List<string>();
        public List<string> parentCategoryName = new List<string>();

        public List<string> childCategoryID = new List<string>();
        public List<string> childCategoryName = new List<string>();

        public Categories()
        {

        }
        public bool checkFirstNumbers(string categoryid,string correctNumber)
        {
            for(int i = 0; i < 2; i++){
                if(categoryid.Substring(i) == correctNumber.Substring(i))
                {
                    return true;
                }
            }

            return false;

        }

    }
}

I have 3 categories in full which is 3 objects that withhold 6 different lists. Categories2 is a list of a bunch of subcategories that should exist beneath categories1. So these categories have two different identification ways either by id or name so we have NewCategoryId and NewCategoryName. These lists does not have two of the same values in them. But then we have the parencategoryName and parentCategoryId lists and these withholds the parentcategoryNames in the number of times that they need to show up to be able to place the subcategories beneath them. and now we need to compare NewCategoryID with parentCategoryId to see where to place NewCategoryName in our exceldocument.

Body:
To explain a bit, as mentioned in my comment, if both categories2.parentCategoryId.Count and categories2.NewCategoryId.Count are the same, your sample code could look like this:

 for(int i = 0; i < categories2.parentCategoryId.Count; i++)
 {
        if(categories2.parentCategoryId[i].Substring(0, 3) == categories2.NewCategoryId[i].Substring(0, 3)){

            Console.Write(categories2.parentCategoryId[i] + " ");
            Console.Write(categories2.parentCategoryName[i] + "´          ");
            Console.Write(categories2.NewCategoryId[i] + " ");
            Console.Write(categories2.NewCategoryName[i] + "\n");
    }
 }

Your code uses nested loops, which work like this:

for(int i = 0; i < 10; i++)
{
    // this is run 10 times
    for(int j = 0; j < 10; j++)
    {
       // this runs 10 times for each iteration of i, so all in all 100 times
    }
}

If I understand your needed functionality correctly and you use List<T> You can use something like:

 for(int i = 0; i < categories2.parentCategoryId.Count; i++)
 {
     var match = categories2.NewCategoryId.FirstOrDefault(stringToCheck => stringToCheck.Substring(0, 3) == categories2.parentCategoryId[i].Substring(0, 3)));
    if(match != null)
    {
            Console.Write(categories2.parentCategoryId[i] + " ");
            Console.Write(categories2.parentCategoryName[i] + "´          ");
            Console.Write(match  + " ");
            Console.Write(match  + "\n");
    }
 }

What should happen here is that the loop runs through the first list and in each iteration checks, if there exist an item with the same substring in the second list (FirstOrDefault either returns the first item that fits the result, or null if it doesn't find any).
If a correct item is found, the same code as in OP is run.

Hope I didn't make any mistakes, doesn't have a code editor in front of me ;)


问:
When to override dark mode in Activity lifecycle?
I'm trying to adopt best practice for managing light and dark mode in my app, based on guidance here and here.

Based on this, I am using a theme inherited from DayNight:

In Manifest:

```<code><application
    android:theme="@style/Theme.MyApp"
</application>
</code>```

In themes.xml:

```<code><style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorButtonNormal">@color/colorButtonNormal</item>
</style>
</code>```

This has the desired effect of opening up an Activity in a light or dark theme, based on the device's system setting.

But I want to give the user the option of overriding the mode, e.g. to be always dark (even if the system is in light mode).

But when the system is in light mode, I'm finding that that my Activity initially opens up with a light theme (flash of white), before I get the chance to switch over to the dark theme.  I'm switching as soon as I possibly can in the Activity lifecycle:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    super.onCreate(savedInstanceState);
    // ...
</code>```

But even then, I'm getting an annoying "flash of light" before the Activity switches over to dark.

How do I avoid the flash of light?

答:
I took some teaching from this project about how to do things properly.

What they do in the sample app above is to specify a single theme in the Manifest, but cunningly that theme is overridden in the night variant of the theme:

In src/main/res/values/themes.xml:

```<code><style name="Base.MaterialGallery" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    ... some base styling ...
</style>

<style name="Theme.MaterialGallery" parent="Base.MaterialGallery">
    ... styling specific to LIGHT theme ...
</style>

<style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery" />
</code>```

The last one above is what is set in the Manifest:

```<code><application
    android:name=".MaterialGalleryApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/Theme.MaterialGallery.DayNight"
    tools:ignore="GoogleAppIndexingWarning">
</code>```

Cunningly, the DayNight theme is overridden for dark mode in src/main/res/values-night/themes.xml:

```<code><style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery">
    ... styling specific to DARK theme (since we're in the NIGHT values-night/themes.xml ...
</style>
</code>```

By specifying the DayNight theme in the Manifest, you get the right theme straight away when the Activity starts, with no messing around.

Body:
I'm trying to adopt best practice for managing light and dark mode in my app, based on guidance here and here.

Based on this, I am using a theme inherited from DayNight:

In Manifest:

<application
    android:theme="@style/Theme.MyApp"
</application>

In themes.xml:

This has the desired effect of opening up an Activity in a light or dark theme, based on the device's system setting.

But I want to give the user the option of overriding the mode, e.g. to be always dark (even if the system is in light mode).

But when the system is in light mode, I'm finding that that my Activity initially opens up with a light theme (flash of white), before I get the chance to switch over to the dark theme.  I'm switching as soon as I possibly can in the Activity lifecycle:

@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    super.onCreate(savedInstanceState);
    // ...

But even then, I'm getting an annoying "flash of light" before the Activity switches over to dark.

How do I avoid the flash of light?

Body:
I took some teaching from this project about how to do things properly.

What they do in the sample app above is to specify a single theme in the Manifest, but cunningly that theme is overridden in the night variant of the theme:

In src/main/res/values/themes.xml:

<style name="Base.MaterialGallery" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    ... some base styling ...
</style>

<style name="Theme.MaterialGallery" parent="Base.MaterialGallery">
    ... styling specific to LIGHT theme ...
</style>

<style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery" />

The last one above is what is set in the Manifest:

<application
    android:name=".MaterialGalleryApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/Theme.MaterialGallery.DayNight"
    tools:ignore="GoogleAppIndexingWarning">

Cunningly, the DayNight theme is overridden for dark mode in src/main/res/values-night/themes.xml:

<style name="Theme.MaterialGallery.DayNight" parent="Theme.MaterialGallery">
    ... styling specific to DARK theme (since we're in the NIGHT values-night/themes.xml ...
</style>

By specifying the DayNight theme in the Manifest, you get the right theme straight away when the Activity starts, with no messing around.


问:
When does surfaceDestroyed() occur
I'm having trouble figuring out when surfaceDestroyed() occurs. I am trying to make my threads stop running in the surfaceDestroyed() method (of a SurfaceView) but it appears that my surface is never actually destroyed...can someone tell me when this happens? Or how to trigger it?

答: surfaceDestroyed() is not called when the view is managed by a TabHost.

Title: When does surfaceDestroyed() occur


问:
This is a code that I followed in a YouTube video and it doesn't work
I followed this YouTube tutorial code up to 11:55 in it and did exactly everything but I'm getting two errors:

The name 'Move' does not exist in the current context and method must have a return type.

This is the code for blend tree to move the character with animation:

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Animator _animator;

    // Start is called before the first frame update
    void Start()
    {
        _animator = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        if (_animator == null) return;

        var x = Input.GetAxis("Horizontal");
        var y = Input.GetAxis("Vertical");

        Move(x, y);
    }
    private Move(float x, float y)
    {
        _animator.SetFloat("VelX", x);
        _animator.SetFloat("VelY", y);
    }

}
</code>```

答:
Change this line

```<code>private Move(float x, float y)
</code>```

to look like

```<code>private void Move(float x, float y)
</code>```

The problem is that you haven't specified a return type for the method.

Body:
I followed this YouTube tutorial code up to 11:55 in it and did exactly everything but I'm getting two errors:

The name 'Move' does not exist in the current context and method must have a return type.

This is the code for blend tree to move the character with animation:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Animator _animator;

    // Start is called before the first frame update
    void Start()
    {
        _animator = GetComponent<Animator>();

    }

    // Update is called once per frame
    void Update()
    {
        if (_animator == null) return;

        var x = Input.GetAxis("Horizontal");
        var y = Input.GetAxis("Vertical");

        Move(x, y);
    }
    private Move(float x, float y)
    {
        _animator.SetFloat("VelX", x);
        _animator.SetFloat("VelY", y);
    }

}

Body:
Change this line

private Move(float x, float y)

to look like

private void Move(float x, float y)

The problem is that you haven't specified a return type for the method.


问:
How to specify the outer product of certain axis in python?
may I ask how to calculate the outer product for certain axes of 2 matrices in numpy?
For instance:

```<code>A = np.arange(24).reshape(3,4,2,1)
B = np.arange(24).reshape(3,4,1,2)
</code>```

And I wish to get a matrix C:

```<code>C = some_function(A,B)
</code>```

such that

```<code>C.shape: (3,4,2,2)
</code>```

which means that I just do the outer product for the last 2 axes.

Thanks!

Body:
may I ask how to calculate the outer product for certain axes of 2 matrices in numpy?
For instance:

A = np.arange(24).reshape(3,4,2,1)
B = np.arange(24).reshape(3,4,1,2)

And I wish to get a matrix C:

C = some_function(A,B)

such that

C.shape: (3,4,2,2)

which means that I just do the outer product for the last 2 axes.

Thanks!

Body:
does

C = np.einsum('...ij,...ik->...ik',A,B)

do the trick? C is

  [[[[  0,   0],
     [  0,   1]],

    [[  4,   6],
     [  6,   9]],

    [[ 16,  20],
     [ 20,  25]],

    [[ 36,  42],
     [ 42,  49]]],

   [[[ 64,  72],
     [ 72,  81]],

    [[100, 110],
     [110, 121]],

    [[144, 156],
     [156, 169]],

    [[196, 210],
     [210, 225]]],

   [[[256, 272],
     [272, 289]],

    [[324, 342],
     [342, 361]],

    [[400, 420],
     [420, 441]],

    [[484, 506],
     [506, 529]]]])

This is a good blog post for understanding einsum: http://ajcr.net/Basic-guide-to-einsum/

PS in your question you already had the extra dimensions added to A and B which would make * give an outer product (in 2D version). However einsum can give outer product without the extra dimension:

A = np.arange(24).reshape(3,4,2)
B = np.arange(24).reshape(3,4,2)
C = np.einsum('...i,...j->...ij', A, B)


问:
Large number values shows in exponential format Kendo jquery Tree List
I am using kendo JQuery Tree List. When very large number is coming from response then its displaying in Exponential format. I believe this is java script limitation for numbers having more than 15 digits.

Is there any workaround for the same. I would like to display the number as it is and should respect format

Dojo for the same: https://dojo.telerik.com/@amitdwivedi/uzecuDep

Kendo version for jquery :
 "@progress/kendo-ui": "^2018.2.530",

答:
JavaScript Number supports integers till 2^53 - 1.
If you want a bigger number than that please try  BigInt .
You can write  a very big number like this.

```<code>const theBiggestInt = BigInt(9007199254740991324324324324324);
</code>```

More more you can refer this.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Body:
JavaScript Number supports integers till 2^53 - 1.
If you want a bigger number than that please try  BigInt .
You can write  a very big number like this.

const theBiggestInt = BigInt(9007199254740991324324324324324);

More more you can refer this.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt


问:
How to add Gson extras to an Android project?
I am using gson parser (latest version -> 2.8.2).

I would like to use RuntimeTypeAdapterFactory which is part of the gson extras.

In my build.gradle there is currently a single compile directive:

```<code>compile 'com.google.code.gson:gson:2.8.2'
</code>```

However this gives me only the gson lib without the extras (RuntimeTypeAdapterFactory is not recognized in the project...).

I have looked at gson extras' pom file (https://github.com/google/gson/blob/master/extras/pom.xml) and
tried to add below line to my build gradle:

```<code>compile 'com.google.code.gson:gson-extras:2.8.2'
</code>```

But gradle just won't compile the gson extras:

```<code>"Error:Failed to resolve: com.google.code.gson:gson-extras:2.8.2"
</code>```

Any Idea how to make this work?

Thank you very much for your time and assistance in this matter.

答:
As mention in the maven page
https://mvnrepository.com/artifact/com.google.code.gson/gson-extras/2.8.5!

you need to use the specified maven repo

Note: this artifact it located at CronApp repository
  (https://artifactory.cronapp.io/public-release/)

in gradle you can add custom repositories that way:

```<code>repositories {
    maven { url "https://artifactory.cronapp.io/public-release/" }
    mavenCentral()
}
</code>```

Body:
I am using gson parser (latest version -> 2.8.2).

I would like to use RuntimeTypeAdapterFactory which is part of the gson extras.

In my build.gradle there is currently a single compile directive:

compile 'com.google.code.gson:gson:2.8.2'

However this gives me only the gson lib without the extras (RuntimeTypeAdapterFactory is not recognized in the project...).

I have looked at gson extras' pom file (https://github.com/google/gson/blob/master/extras/pom.xml) and
tried to add below line to my build gradle:

compile 'com.google.code.gson:gson-extras:2.8.2'

But gradle just won't compile the gson extras:

"Error:Failed to resolve: com.google.code.gson:gson-extras:2.8.2"

Any Idea how to make this work?

Thank you very much for your time and assistance in this matter.

Body:
As mention in the maven page
https://mvnrepository.com/artifact/com.google.code.gson/gson-extras/2.8.5!

you need to use the specified maven repo

Note: this artifact it located at CronApp repository
  (https://artifactory.cronapp.io/public-release/)

in gradle you can add custom repositories that way:

repositories {
    maven { url "https://artifactory.cronapp.io/public-release/" }
    mavenCentral()
}


问:
capture all user interactions in a react application centrally
I need to capture user interactions in React ex:- click, scroll etc. I am searching for a way where I can capture these events centrally so that I will not have to write code in each of the components inside the application. Is there any listener or something which can capture all these events centrally ?</p>

答:
You could use e.g. react-idle-timer for this.

Import the component with:

```<code>import IdleTimer from 'react-idle-timer';
</code>```

and then in your render method add something like this:

```<code><><IdleTimer onAction={(e) => console.log('event happened: ', e)} /><YourLayoutComponent /></>
</code>```

you should end up with a similar result when moving and clicking through the page:

Body:
You could use e.g. react-idle-timer for this.

Import the component with:

import IdleTimer from 'react-idle-timer';

and then in your render method add something like this:

<><IdleTimer onAction={(e) => console.log('event happened: ', e)} /><YourLayoutComponent /></>

you should end up with a similar result when moving and clicking through the page:


问:
immediate consistency on projection with event sourcing and cqrs
When using a SQL journal in an event sourced system, is it ok to update the journal and one or more projections in the same transaction ? Is it an anti pattern ?

The pros I can think of is this the consistency of the view is immediate, but what are the cons ? Performance ?

答:
Scalability is the biggest price.

But interestingly you say it's 'immediate' but that isn't strictly true.

There is still a delay while the transaction completes and depending on how long that takes or how many transactions per second are being made, you run the risk of unnecessary concurrency conflicts.

You still have to pay the "eventual consistency" price, you just pay it in a blocking way (nothing wrong with that if it's a conscious choice).

Hope that helps.


问:
Update CurrentRecord column depending on EmployeeVersion column
I have the following table containing the versions for each employee:

```<code>EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         0             3
</code>```

I want to update CurrentRecord and set it to 1 for the record having the maximum EmployeeVersion (as it is the latest version) like below:

```<code>EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         1             3
</code>```

This is my query:

```<code>UPDATE DimEmployeeSharedV1
  SET CurrentRecord = 1
WHERE EmployeeVersion = (
  SELECT MAX(e.EmployeeVersion)
  FROM DimEmployeeSharedV1 e
  WHERE e.EmployeeId = EmployeeId
  GROUP BY e.EmployeeId
)
</code>```

I have the following error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

答:
You can use updatable cte :

```<code>with ucte as (
     select v.*, row_number() over (partition by EmployeeId order by EmployeeVersion) as seq
     from DimEmployeeSharedV1 v
)
update ucte
     set CurrentRecord = 1
where seq = 1;
</code>```

Correlated sub-query will also work :

```<code>UPDATE v1
      SET v1.CurrentRecord = 1
FROM DimEmployeeSharedV1 v1
WHERE v1.EmployeeVersion = (SELECT MAX(e.EmployeeVersion)
                            FROM DimEmployeeSharedV1 e
                            WHERE e.EmployeeId = v1.EmployeeId
                           );
</code>```

Body:
I have the following table containing the versions for each employee:

EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         0             3

I want to update CurrentRecord and set it to 1 for the record having the maximum EmployeeVersion (as it is the latest version) like below:

EmployeeId Status Department CurrentRecord EmployeeVersion
45         1      33         0             1
45         1      45         0             2
45         2      45         1             3

This is my query:

UPDATE DimEmployeeSharedV1
  SET CurrentRecord = 1
WHERE EmployeeVersion = (
  SELECT MAX(e.EmployeeVersion)
  FROM DimEmployeeSharedV1 e
  WHERE e.EmployeeId = EmployeeId
  GROUP BY e.EmployeeId
)

I have the following error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

Body:
You can use updatable cte :

with ucte as (
     select v.*, row_number() over (partition by EmployeeId order by EmployeeVersion) as seq
     from DimEmployeeSharedV1 v
)
update ucte
     set CurrentRecord = 1
where seq = 1;

Correlated sub-query will also work :

UPDATE v1
      SET v1.CurrentRecord = 1
FROM DimEmployeeSharedV1 v1
WHERE v1.EmployeeVersion = (SELECT MAX(e.EmployeeVersion)
                            FROM DimEmployeeSharedV1 e
                            WHERE e.EmployeeId = v1.EmployeeId
                           );


问:
need assistance with pop and push operations
I'm studying for a Microsoft Exam, one of the preparation questions is as follows:

You have a stack that contains integer values. The values are pushed onto the stack in the following order: 2,4,6,8.
The following sequence of operations is executed:

Pop,
Push 3,
Pop,
Push 4,
Push 6,
Push 7,
Pop,
Pop,
Pop,

What is the value of the top element after these operations are executed?

A. 2

B. 3

C. 6

D. 7

Correct Answer: B

Why is B the correct answer?

答:
Agree with the answer also... checking with code</p>

```<code>namespace StackTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();
            // Starting
            st.Push(2);
            st.Push(4);
            st.Push(6);
            st.Push(8);
            // Showing state
            ShowStack(st,"Contenido inicial");
            //Pop, Push 3, Pop, Push 4, Push 6, Push 7, Pop, Pop, Pop,
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(3);
            ShowStack(st, "Agregado 3");
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(4);
            ShowStack(st, "Agregado 4");
            st.Push(6);
            ShowStack(st, "Agregado 6");
            st.Push(7);
            ShowStack(st, "Agregado 7");
            st.Pop();
            st.Pop();
            st.Pop();
            ShowStack(st, "Quitar tres");
            ShowStack(st,"Situacion Final");
            Console.ReadKey();
            // 2, 4 , 6 , 8
        }
        private static void ShowStack(Stack st,string message)
        {
            Console.WriteLine(message);
            foreach (var item in st)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("-------------------");
        }
    }
}
</code>```

Body:
Agree with the answer also... checking with code

namespace StackTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();
            // Starting
            st.Push(2);
            st.Push(4);
            st.Push(6);
            st.Push(8);
            // Showing state
            ShowStack(st,"Contenido inicial");
            //Pop, Push 3, Pop, Push 4, Push 6, Push 7, Pop, Pop, Pop,
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(3);
            ShowStack(st, "Agregado 3");
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(4);
            ShowStack(st, "Agregado 4");
            st.Push(6);
            ShowStack(st, "Agregado 6");
            st.Push(7);
            ShowStack(st, "Agregado 7");
            st.Pop();
            st.Pop();
            st.Pop();
            ShowStack(st, "Quitar tres");
            ShowStack(st,"Situacion Final");
            Console.ReadKey();
            // 2, 4 , 6 , 8
        }
        private static void ShowStack(Stack st,string message)
        {
            Console.WriteLine(message);
            foreach (var item in st)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("-------------------");
        }
    }
}


问:
Replace after specific text
I would like to remove after specific text in rows whatever exist.

I use this:

```<code>dframe$col1 <- gsub("Stock Amazon|Or Another|Google","",dframe$col1)
</code>```

but it removes the whole row and not whatever after the string. What can I do to fix it?

答:
It's not easy to answer without an example, but here is a pointer using the stringr library:

library(tidyverse)
dframe <- dframe %>%
  mutate(col1 = str_extract(col1, "Your text"))
```

Hope it helps.

Title: Replace after specific text

Body:
I would like to remove after specific text in rows whatever exist.

I use this:

dframe$col1 <- gsub("Stock Amazon|Or Another|Google","",dframe$col1)

but it removes the whole row and not whatever after the string. What can I do to fix it?

Body:
It's not easy to answer without an example, but here is a pointer using the stringr library:

library(tidyverse)
dframe <- dframe %>%
  mutate(col1 = str_extract(col1, "Your text"))

Hope it helps.


问:
url hash tag to stop scrolling / focusing
Working on a project which uses Jquery(1.6) Tabs, works all good but wondering if there's a way to stop the page focusing on the content div when using the hash tag in the url, its the browsers bookmarking feature i suspect but asking if i can override this, stop it or alternative solutions?

I already have alternative javascript referencing solutions ie make the ids obtuse and re-reference them in an array so when you use a certain hash its translated to "tab1" for example, that bit is easy its questioning whether this is possible via means of simply stopping the auto id focusing.

Example scenario:

Go to www.domain.com/about-us#company-info

www.domain.com/about-us loads and tab "company-info" activates, browser focuses on the div with the same id as the tab which has the content of the tab hiding the whole heading section.

Code is as follows:

```<code><ul>
  <li><a href="#company-info">Company Info</a></li>
  <li><a href="#meet-the-team">Meet the team</a></li>
</ul>

<div id="company-info">
 content here
</div>
<div id="meet-the-team">
content here
</div>

<script>
   var tabs = $("#tabs").tabs({
    select: function(event, ui) {
     window.location.hash = ui.tab.hash;
    }
   });

 if(window.location.hash!=''){
   var param = window.location.hash;
   param = param.replace('#','');
   tabs.tabs('select',param);
 }
</script>
</code>```

答:
```<code>var tabs = $("#tabs").tabs({
    select: function(event, ui) {
      event.preventDefault();
      window.location.hash = ui.tab.hash;
      return;
   }
});
</code>```

I think this should do it .

Body:
Working on a project which uses Jquery(1.6) Tabs, works all good but wondering if there's a way to stop the page focusing on the content div when using the hash tag in the url, its the browsers bookmarking feature i suspect but asking if i can override this, stop it or alternative solutions?

I already have alternative javascript referencing solutions ie make the ids obtuse and re-reference them in an array so when you use a certain hash its translated to "tab1" for example, that bit is easy its questioning whether this is possible via means of simply stopping the auto id focusing.

Example scenario:

Go to www.domain.com/about-us#company-info

www.domain.com/about-us loads and tab "company-info" activates, browser focuses on the div with the same id as the tab which has the content of the tab hiding the whole heading section.

Code is as follows:

Company Info

Meet the team

 content here

content here

Body:
var tabs = $("#tabs").tabs({
    select: function(event, ui) {
      event.preventDefault();
      window.location.hash = ui.tab.hash;
      return;
   }
});

I think this should do it .


问:
getting hostname of remote computers on the local network not setup in /etc/hosts
I have a new learning, I was trying to get hostname using python's socket.

so from my macbook I ran the below code:

```<code>socket.gethostbyaddr("192.168.1.111")
</code>```

and I get the ('rock64', [], ['192.168.1.111']) then I tried IP address of a computer that is not on the network anymore but used to be:

```<code>socket.gethostbyaddr("192.168.1.189")
</code>```

and it returned: ('mint', [], ['192.168.1.189']) then I realised its coming from the /etc/hosts file.

now in that host file I also have this entry:

/etc/hosts

172.217.25.3 google.com.hk

but if I try to get host from ip of wan address i get different results than expected!

socket.gethostbyaddr("172.217.25.3")

that returns ('hkg07s24-in-f3.1e100.net', ['3.25.217.172.in-addr.arpa'], ['172.217.25.3'])

so I am not wondering where in the later case of WAN ip address I am getting the hostname and why in case of local computer IP's I am getting hostname from the configured /etc/hosts file ?

How can we get hostname of host computers on the local network without socket.gethostbyaddr having to look into /etc/hosts file or by other means ?

答:
This is opinion based answer to the question "how to build registry of network devices on your local network?"

The best way to build registry of devices on your local network is to setup ntopng on your gateway. It uses DPI (Deep Packet Inspection) Technics to collect information about hosts.
NTOPNG has nice user interface and displays host names (when possible).
You can assign aliases for specific hosts which do not leak host names via any protocol.

For some reasons ntopng developers did not include alias into json response for request http://YOUR-SERVER:3000/lua/host_get_json.lua?ifid=2&host=IP-OF-DEVICE .

You can add it manually by adding lines require "mac_utils" and hj["alias"]=getDeviceName(hj["mac_address"]) into file /usr/share/ntopng/scripts/lua/host_get_json.lua

You can use REST API to interrogate ntopng and use provided information for building any script you need.

Body:
I have a new learning, I was trying to get hostname using python's socket.

so from my macbook I ran the below code:

socket.gethostbyaddr("192.168.1.111")

and I get the ('rock64', [], ['192.168.1.111']) then I tried IP address of a computer that is not on the network anymore but used to be:

socket.gethostbyaddr("192.168.1.189")

and it returned: ('mint', [], ['192.168.1.189']) then I realised its coming from the /etc/hosts file.

now in that host file I also have this entry:

/etc/hosts

172.217.25.3 google.com.hk

but if I try to get host from ip of wan address i get different results than expected!

socket.gethostbyaddr("172.217.25.3")

that returns ('hkg07s24-in-f3.1e100.net', ['3.25.217.172.in-addr.arpa'], ['172.217.25.3'])

so I am not wondering where in the later case of WAN ip address I am getting the hostname and why in case of local computer IP's I am getting hostname from the configured /etc/hosts file ?

How can we get hostname of host computers on the local network without socket.gethostbyaddr having to look into /etc/hosts file or by other means ?


问:
How to query between two x amount of days using Laravel and Carbon?
I'm trying to retrieve data from the past 30 to 60 days. Which means I'm leaving out days 0 to 30 and everything past day 60.

My current progress is as such:

```<code>$previousMonth = DB::table('table')
->select('table.*')
->whereBetween('date', [Carbon::now()->subDays(30), Carbon::now()->subDays(60)])
->get();

return $previousMonth;
</code>```

"date" has the datatype of DATETIME in mysql database.

答:
Try this startOfDay()

```<code>use Carbon\Carbon;

$previousMonth = DB::table('table')
->select('table.*')->whereBetween('date', [Carbon::now()->subDays(60)->startOfDay(), Carbon::now()->subDays(30)->startOfDay()])->get();

return $previousMonth;
</code>```

Refer This Link

http://carbon.nesbot.com/docs/

Body:
I'm trying to retrieve data from the past 30 to 60 days. Which means I'm leaving out days 0 to 30 and everything past day 60.

My current progress is as such:

$previousMonth = DB::table('table')
->select('table.*')
->whereBetween('date', [Carbon::now()->subDays(30), Carbon::now()->subDays(60)])
->get();

return $previousMonth;

"date" has the datatype of DATETIME in mysql database.

Body:
Try this startOfDay()

use Carbon\Carbon;

$previousMonth = DB::table('table')
->select('table.*')->whereBetween('date', [Carbon::now()->subDays(60)->startOfDay(), Carbon::now()->subDays(30)->startOfDay()])->get();

return $previousMonth;

Refer This Link

http://carbon.nesbot.com/docs/


问:
Programmatically change the height and width of a UIImageView Xcode Swift
Hey for some reason I am struggling with trying to set the height and width of one of my image views. I want to set it so the height only goes for 20% of my screen. I know to regularly set it you can do things like:
image = (0,0,50,50)

But I need the height to not be a static number.
Something like image = (0,0, frame.height * 0.2, 50)

Any suggestions?

答:
A faster / alternative way to change the height and/or width of a UIView is by setting its width/height through frame.size:

```<code>let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight
</code>```

Body:
A faster / alternative way to change the height and/or width of a UIView is by setting its width/height through frame.size:

let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight


问:
Howto use external plugins via config file (runtime configuration) with Autofac 5
I'm trying to setup a simple .NET Core 3.1 project that uses Autofac 5 IoC Container.

I've added a reference to latest Autofac.Configuration 5.0.0 package.

I've created interface, implementation and test app with a simple JSON config (following this guide):

```<code>{
  "components": [
    {
      "type": "Implementations.ImplementationN, Implementations",
      "services": [
        {
          "type": "Interfaces.InterfaceN, Interfaces"
        }
      ]
    }
  ]
}
</code>```

I use the following code (according to the same guide):

```<code>using Interfaces;
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;
using System;

------------------------
var config = new ConfigurationBuilder();
config.AddJsonFile("config.json");

var module = new ConfigurationModule(config.Build());

var builder = new ContainerBuilder();
builder.RegisterModule(module);

var container = builder.Build();
------------------------
</code>```

But I'm getting System.InvalidOperationException:

The type 'Implementations.ImplementationN, Implementations'
  could not be found. It may require assembly qualification,
  e.g. "MyType, MyAssembly"

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.5 Enterprise, Windows 10 1909 x64 Professional

UPDATE: To clarify more - my final goal is to have Interfaces.dll with no special references, Implementations.dll with reference to ONLY Interfaces.dll and Test.exe with reference to ONLY Interfaces.dll (and Autofac package of course). I expect Autofac to load specific class from a specific assembly (that are specified in config.json) via Reflection. That was possible with Unity Container and I expected to achieve the same with Autofac IoC.

Once again: I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

答:
The problem is the main project is looking for the type you entered to the config.json file but it doesn't have reference to the implementations project so it will not found the module. My solution is, first add a reference to the implementations project then create an autofac module in the implementations project (you need autofac lib in the implementations project so it is better to have a shared kernel or simply shared project for all projects):

```<code>public class ImplementationModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ImplementationN>().As<InterfaceN>();
        }
    }
</code>```

All your registration of the implimentation project goes here.
Then change the config.json file like this:

```<code>{
  "modules": [
    {
      "type": "Implementations.ImplementationModule, Implementations"
    }
  ]
}
</code>```

Then everything should be fine.

If you want don't want your main project to have reference to the implementations project you need to add some new project that to the registration of all the modules of your application. And it should have references to all the projects as well.

Body:
I'm trying to setup a simple .NET Core 3.1 project that uses Autofac 5 IoC Container.

I've added a reference to latest Autofac.Configuration 5.0.0 package.

I've created interface, implementation and test app with a simple JSON config (following this guide):

{
  "components": [
    {
      "type": "Implementations.ImplementationN, Implementations",
      "services": [
        {
          "type": "Interfaces.InterfaceN, Interfaces"
        }
      ]
    }
  ]
}

I use the following code (according to the same guide):

using Interfaces;
using Autofac;
using Autofac.Configuration;
using Microsoft.Extensions.Configuration;
using System;

------------------------
var config = new ConfigurationBuilder();
config.AddJsonFile("config.json");

var module = new ConfigurationModule(config.Build());

var builder = new ContainerBuilder();
builder.RegisterModule(module);

var container = builder.Build();
------------------------

But I'm getting System.InvalidOperationException:

The type 'Implementations.ImplementationN, Implementations'
  could not be found. It may require assembly qualification,
  e.g. "MyType, MyAssembly"

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.5 Enterprise, Windows 10 1909 x64 Professional

UPDATE: To clarify more - my final goal is to have Interfaces.dll with no special references, Implementations.dll with reference to ONLY Interfaces.dll and Test.exe with reference to ONLY Interfaces.dll (and Autofac package of course). I expect Autofac to load specific class from a specific assembly (that are specified in config.json) via Reflection. That was possible with Unity Container and I expected to achieve the same with Autofac IoC.

Once again: I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

Body:
The problem is the main project is looking for the type you entered to the config.json file but it doesn't have reference to the implementations project so it will not found the module. My solution is, first add a reference to the implementations project then create an autofac module in the implementations project (you need autofac lib in the implementations project so it is better to have a shared kernel or simply shared project for all projects):

public class ImplementationModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ImplementationN>().As<InterfaceN>();
        }
    }

All your registration of the implimentation project goes here.
Then change the config.json file like this:

{
  "modules": [
    {
      "type": "Implementations.ImplementationModule, Implementations"
    }
  ]
}

Then everything should be fine.

If you want don't want your main project to have reference to the implementations project you need to add some new project that to the registration of all the modules of your application. And it should have references to all the projects as well.


问:
Why are Rust documentation tests not executed in Docker when cross-compiling to musl?
My documentation tests are silently not executed in my Docker environment while everything works on both Windows and Ubuntu/Debian hosts.

I created a minimal Github Repository to demonstrate the issue. I tried two different versions of Rust nightly and Rust stable, debug/release, all without success. See my Dockerfile and complete build output.

Example code:

```<code>/// Fixes string arrays which can also be objects into string arrays
/// # Examples
///
/// ```
/// assert_eq!(cargo_test_doc_docker::add(1, 2), 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
</code>```

Result when executing on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 2.39s
     Running target/debug/deps/cargo_test_doc_docker-9d5ae146cd4c3628

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/cargo_test_doc_docker-2a696d2579128ce1

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests cargo-test-doc-docker

running 1 test
test src/lib.rs - add (line 4) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
```

<p>The problem occurs when executing the build on Docker. This is a minimal Dockerfile that reproduces the problem:</p>

```FROM ekidd/rust-musl-builder:nightly-2020-01-26-openssl11 as build
COPY --chown=rust:rust . .
RUN cargo test; echo $?
```

<p>Result for every Rust toolchain I tried:</p>

<pre class="lang-none prettyprint-override"><code>Step 6/17 : RUN cargo test; echo $?
 ---> Running in b266fc72f3c1
   Compiling cargo-test-doc-docker v0.1.0 (/home/rust/src)
    Finished test [unoptimized + debuginfo] target(s) in 0.32s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-7b40e7e5b47f49eb

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-0bfec9752a7bec14

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0
</code>```

It does not even try to execute any doc tests and exits with zero so it's not easily noticed. I guess it must be something the Docker base image does, but what could that be?

答:
Cross Compilation

This is a logical, if surprising, outcome of cross-compilation.

To understand why, imagine that you:

Compile on a Linux x64 machine (Host).

Target a Windows ARM machine.

The generated code cannot be executed on the current host (Linux x64): it is prepared for a different CPU (instruction set) and OS (system calls).

Since the tests -- unit tests, integration tests, and documentation tests -- are also generated for the target architecture, they cannot be executed on the host either.

What to do with the tests?

If your code has no specific dependency on a specific platform, then you can content yourself with compiling for the host and running those.

Otherwise, you will need access to a machine that can actually run the cross-compiled binaries. You can still use cross-compilation to speed up building those binaries, and then upload them to either a physical or virtual machine to run them.

AFAIK Cargo does not help with the latter, so you'll need your own scripts.

Body:
My documentation tests are silently not executed in my Docker environment while everything works on both Windows and Ubuntu/Debian hosts.

I created a minimal Github Repository to demonstrate the issue. I tried two different versions of Rust nightly and Rust stable, debug/release, all without success. See my Dockerfile and complete build output.

Example code:

/// Fixes string arrays which can also be objects into string arrays
/// # Examples
///
/// ```
/// assert_eq!(cargo_test_doc_docker::add(1, 2), 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

Result when executing on Debian:

arturh@host:~/projects/cargo-test-doc-docker$ cargo test
   Compiling cargo-test-doc-docker v0.1.0 (/home/arturh/projects/cargo-test-doc-docker)
    Finished test [unoptimized + debuginfo] target(s) in 2.39s
     Running target/debug/deps/cargo_test_doc_docker-9d5ae146cd4c3628

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/cargo_test_doc_docker-2a696d2579128ce1

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests cargo-test-doc-docker

running 1 test
test src/lib.rs - add (line 4) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The problem occurs when executing the build on Docker. This is a minimal Dockerfile that reproduces the problem:

FROM ekidd/rust-musl-builder:nightly-2020-01-26-openssl11 as build
COPY --chown=rust:rust . .
RUN cargo test; echo $?

Result for every Rust toolchain I tried:

Step 6/17 : RUN cargo test; echo $?
 ---> Running in b266fc72f3c1
   Compiling cargo-test-doc-docker v0.1.0 (/home/rust/src)
    Finished test [unoptimized + debuginfo] target(s) in 0.32s
     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-7b40e7e5b47f49eb

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/x86_64-unknown-linux-musl/debug/deps/cargo_test_doc_docker-0bfec9752a7bec14

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

0

It does not even try to execute any doc tests and exits with zero so it's not easily noticed. I guess it must be something the Docker base image does, but what could that be?


问:
How can I schedule updates (f/e, to update a clock) in tkinter?
I'm writing a program with Python's tkinter library.

My major problem is that I don't know how to create a timer or a clock like hh:mm:ss.

I need it to update itself (that's what I don't know how to do); when I use time.sleep() in a loop the whole GUI freezes.

答:
You should call .after_idle(callback) before the mainloop and .after(ms, callback) at the end of the callback function.

Example:

```<code>import tkinter as tk
import time

def refresh_clock():
    clock_label.config(
        text=time.strftime("%H:%M:%S", time.localtime())
    )
    root.after(1000, refresh_clock)  # <--

root = tk.Tk()

clock_label = tk.Label(root, font="Times 25", justify="center")
clock_label.pack()

root.after_idle(refresh_clock)  # <--
root.mainloop()
</code>```

Body:
You should call .after_idle(callback) before the mainloop and .after(ms, callback) at the end of the callback function.

Example:

import tkinter as tk
import time

def refresh_clock():
    clock_label.config(
        text=time.strftime("%H:%M:%S", time.localtime())
    )
    root.after(1000, refresh_clock)  # <--

root = tk.Tk()

clock_label = tk.Label(root, font="Times 25", justify="center")
clock_label.pack()

root.after_idle(refresh_clock)  # <--
root.mainloop()


问:
Authorization Failed in Twitter
I am implementing Twitter api in android, I have generated new api and consumer key but this returns the error "This happend only is consumer key is wrong or signature is different".

Code:
OAUTHREquestTokenTask.java

```<code>package com.ex.softZilla;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

/**
 * An asynchronous task that communicates with Twitter to
 * retrieve a request token.
 * (OAuthGetRequestToken)
 *
 * After receiving the request token from Twitter,
 * pop a browser to the user to authorize the Request Token.
 * (OAuthAuthorizeToken)
 *
 */
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

    final String TAG = getClass().getName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    /**
     *
     * We pass the OAuth consumer and provider.
     *
     * @param   context
     *          Required to be able to start the intent to launch the browser.
     * @param   provider
     *          The OAuthProvider object
     * @param   consumer
     *          The OAuthConsumer object
     */
    public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
    }

    /**
     *
     * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
     *
     */
    @Override
    protected Void doInBackground(Void... params) {

        try {
            Log.i(TAG, "Retrieving request token from Google servers");
            final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
            Log.i(TAG, "Popping a browser with the authorize URL : " + url);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error during OAUth retrieve request token", e);
        }

        return null;
    }

}
</code>```

答:
I too got the same problem. I think this is because of request token url as twitter changed their  Request token URL from http://api.twitter.com/oauth/request_token to http://twitter.com/oauth/request_token.

But official doc says Request token URL is http://api.twitter.com/oauth/request_token. But the sample app is failed. I think it is it is he reason.

Title: Authorization Failed in Twitter

Body:
I am implementing Twitter api in android, I have generated new api and consumer key but this returns the error "This happend only is consumer key is wrong or signature is different".

Code:
OAUTHREquestTokenTask.java

package com.ex.softZilla;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

/**
 * An asynchronous task that communicates with Twitter to
 * retrieve a request token.
 * (OAuthGetRequestToken)
 *
 * After receiving the request token from Twitter,
 * pop a browser to the user to authorize the Request Token.
 * (OAuthAuthorizeToken)
 *
 */
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {

    final String TAG = getClass().getName();
    private Context context;
    private OAuthProvider provider;
    private OAuthConsumer consumer;

    /**
     *
     * We pass the OAuth consumer and provider.
     *
     * @param   context
     *          Required to be able to start the intent to launch the browser.
     * @param   provider
     *          The OAuthProvider object
     * @param   consumer
     *          The OAuthConsumer object
     */
    public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
        this.context = context;
        this.consumer = consumer;
        this.provider = provider;
    }

    /**
     *
     * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
     *
     */
    @Override
    protected Void doInBackground(Void... params) {

        try {
            Log.i(TAG, "Retrieving request token from Google servers");
            final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
            Log.i(TAG, "Popping a browser with the authorize URL : " + url);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Error during OAUth retrieve request token", e);
        }

        return null;
    }

}


问:
Webhook is created, but callback is never hit
I'm trying to remove the pooling and integrate webhooks in the process of file conversion. The problem is that the webhook is created but the callback is never called back.

I'm following the instructions from here: https://forge.autodesk.com/en/docs/webhooks/v1/tutorials/create-a-hook-model-derivative/

The web server is started by the following command : ngrok http host-header=rewrite https://localhost:44366

The callback is http://f36a47b8.ngrok.io/derivative and is up and running. Post requests from postman(internal network) and Post requests from external networks (cellular data) are reaching the endpoint and are successfully redirected.

A hook is created:

```<code>  "hookId": "51897b50-522a-11ea-b885-f34f23e3435e",
  "tenant": "c0761189-32dd-4ca3-9e52-3ae400f91651",
  "callbackUrl": "http://f36a47b8.ngrok.io/derivative",
  "createdBy": "HUpqLPysSUmbFGlhQo0uG8XMqimfQnRG",
  "event": "extraction.updated",
  "createdDate": "2020-02-18T08:40:29.829+0000",
  "system": "derivative",
  "creatorType": "Application",
  "status": "active",
  "scope": {
    "workflow": "c0761189-32dd-4ca3-9e52-3ae400f91651"
  },
  "urn": "urn:adsk.webhooks:events.hook:51897b50-522a-11ea-b885-f34f23e3435e",
  "__self__": "/systems/derivative/events/extraction.updated/hooks/51897b50-522a-11ea-b885-f34f23e3435e"
}
</code>```

Than a call to modelderivative/v2/designdata/job is issued with the following content:

```<code> var job = new JobRequest
            {
                Input = new Input
                {
                    Urn = urnBase64,
                },
                Output = new Output
                {
                    Formats = new List<Format>
                    {
                        new Format
                        {
                            Type = "svf",
                            Views = new List<string> { "2d", "3d" }
                        }
                    },
                    Destination = new Destination { Region = "EMEA" }
                },
                Misc = new Misc
                {
                    Workflow = workflowId
                }
            };
</code>```

The response is success with an urn (like before);

And from that point nothing follows from the webhook. The callback is never reached, even though that within some time the file is converted and it can be loaded in the viewer as before.

I've viewed those topics:

Unable to receive Forge webhooks, or unable to get them to fire

Why is webhook workflow not taken into consideration when creating modelderivative job?

but they didn't helped.

What am i missing ?

答:
It turns out that there is a problem with jobs for derivative API in 'EMEA' region where no callbacks are called when a job finishes. Changing the region to 'us' fixes the issue and callback is hit when a job event occurs.

From the documentation example change the region parameter:

```<code>curl -X 'POST' \
     -H 'Content-Type: application/json; charset=utf-8' \
     -H 'Authorization: Bearer PtnrvrtSRpWwUi3407QhgvqdUVKL' \
     -H 'x-ads-force: false' -v 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job' \
     -d
'{
   "input": {
     "urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LnppcA",
     "compressedUrn": true,
     "rootFilename": "A5.iam"
   },
   "output": {
     "destination": {
       "region": "us" <- Change the region form 'EMEA' to 'us'
     },
     "formats": [
       {
         "type": "svf",
         "views": [
           "2d",
           "3d"
         ]
       }
     ]
   }
 }'

</code>```

Body:
I'm trying to remove the pooling and integrate webhooks in the process of file conversion. The problem is that the webhook is created but the callback is never called back.

I'm following the instructions from here: https://forge.autodesk.com/en/docs/webhooks/v1/tutorials/create-a-hook-model-derivative/

The web server is started by the following command : ngrok http host-header=rewrite https://localhost:44366

The callback is http://f36a47b8.ngrok.io/derivative and is up and running. Post requests from postman(internal network) and Post requests from external networks (cellular data) are reaching the endpoint and are successfully redirected.

A hook is created:

  "hookId": "51897b50-522a-11ea-b885-f34f23e3435e",
  "tenant": "c0761189-32dd-4ca3-9e52-3ae400f91651",
  "callbackUrl": "http://f36a47b8.ngrok.io/derivative",
  "createdBy": "HUpqLPysSUmbFGlhQo0uG8XMqimfQnRG",
  "event": "extraction.updated",
  "createdDate": "2020-02-18T08:40:29.829+0000",
  "system": "derivative",
  "creatorType": "Application",
  "status": "active",
  "scope": {
    "workflow": "c0761189-32dd-4ca3-9e52-3ae400f91651"
  },
  "urn": "urn:adsk.webhooks:events.hook:51897b50-522a-11ea-b885-f34f23e3435e",
  "__self__": "/systems/derivative/events/extraction.updated/hooks/51897b50-522a-11ea-b885-f34f23e3435e"
}

Than a call to modelderivative/v2/designdata/job is issued with the following content:

 var job = new JobRequest
            {
                Input = new Input
                {
                    Urn = urnBase64,
                },
                Output = new Output
                {
                    Formats = new List<Format>
                    {
                        new Format
                        {
                            Type = "svf",
                            Views = new List<string> { "2d", "3d" }
                        }
                    },
                    Destination = new Destination { Region = "EMEA" }
                },
                Misc = new Misc
                {
                    Workflow = workflowId
                }
            };

The response is success with an urn (like before);

And from that point nothing follows from the webhook. The callback is never reached, even though that within some time the file is converted and it can be loaded in the viewer as before.

I've viewed those topics:

Unable to receive Forge webhooks, or unable to get them to fire

Why is webhook workflow not taken into consideration when creating modelderivative job?

but they didn't helped.

What am i missing ?

Body:
It turns out that there is a problem with jobs for derivative API in 'EMEA' region where no callbacks are called when a job finishes. Changing the region to 'us' fixes the issue and callback is hit when a job event occurs.

From the documentation example change the region parameter:

curl -X 'POST' \
     -H 'Content-Type: application/json; charset=utf-8' \
     -H 'Authorization: Bearer PtnrvrtSRpWwUi3407QhgvqdUVKL' \
     -H 'x-ads-force: false' -v 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job' \
     -d
'{
   "input": {
     "urn": "dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LnppcA",
     "compressedUrn": true,
     "rootFilename": "A5.iam"
   },
   "output": {
     "destination": {
       "region": "us" <- Change the region form 'EMEA' to 'us'
     },
     "formats": [
       {
         "type": "svf",
         "views": [
           "2d",
           "3d"
         ]
       }
     ]
   }
 }'


问:
Improving the efficiency of searching a normalised logs table
For many years now I've recorded user interaction logs using PHP and MySQL in a normalised format such as this:

LogID (int)

UserID (int)

TargetUserID (optional int)

ActionID (int)

AdditionalString1 (string)

AdditionalString2 (string)

This would allow me to re-construct the logs using PHP afterwards to create logs like these:

John Smith kicked Amy Adams from the server for 'spamming messages' (stored as "1,1,2,1,'spamming messages','')

Amy Adams sent John Smith $300,000 for 'house payment' (stored as "2,2,1,2,'300000','house payment')

All whilst only storing a very small amount of data, as shown.

The problem is that in order to search this data, every log message has to be reconstructed before filtering. So if I have 500,000 log messages, I have to parse all 500,000 into the above format, in order to match a filter such as "Smith kicked" (which would match the first log) or "sent John" (which would match the second).

I know that I could store the log messages in full-text to begin with, but this worries me as then when users change name, or when log message formats change, these old messages would be stuck.

I can only assume there is a best practise for this, and I fear it might be to use an additional technology such as Logstash, but just wanted to see what people thought first.

Thanks in advance.

答:
There are several techniques how you can optimize your algorithm which needs to go through all the logs in order to systematically parse them.

One of the techniques you can use is caching partial results for expensive operations and reusing the cached results where possible. In your case caching results of database SELECT queries will mean you don't need to execute the same SELECT queries multiple times - in some cases it can be several hundreds / thousands / millions of times. This technique is also known as Memoization and is a one of the techniques used in dynamic programming.