问:
Ingress on GKE. Run specify service healthcheck
I try to use ingress for loadbalancer of 2 services on Google Kubernetes engine:

here is ingress config for this:

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress

spec:
  rules:
  - http:
      paths:
      - path: /*
        backend:
          serviceName: web
          servicePort: 8080
      - path: /v2/keys
        backend:
          serviceName: etcd-np
          servicePort: 2379
</code>```

where web is some example service from google samples:

```<code>apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: default
spec:
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    run: web
  type: NodePort

----
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
spec:
  selector:
    matchLabels:
      run: web
  template:
    metadata:
      labels:
        run: web
    spec:
      containers:
      - image: gcr.io/google-samples/hello-app:1.0
        imagePullPolicy: IfNotPresent
        name: web
        ports:
        - containerPort: 8080
          protocol: TCP
</code>```

But the second service is ETCD cluster with NodePort service:

```<code>---
apiVersion: v1
kind: Service
metadata:
  name: etcd-np
spec:
  ports:
  - port: 2379
    targetPort: 2379
  selector:
    app: etcd
  type: NodePort
</code>```

But only first ingress rule works properly i see in logs:

```<code>ingress.kubernetes.io/backends: {"k8s-be-30195--ebfd7339a961462d":"UNHEALTHY","k8s-be-30553--ebfd7339a961462d":"HEALTHY","k8s-be-31529--ebfd7339a961462d":"HEALTHY"}
</code>```

I etcd-np works properly it is not a problem of etcd , i think that the problem is that etcd server answers with 404 on GET / request and some healthcheck on ingress level does not allow to use it .

Thats why i have 2 questions :

1 ) How can I provide healthcheck urls for each backend path on ingress

2 ) How can I debug such issues . What I see now is

```<code>kubectl describe ingress basic-ingress
Name:             basic-ingress
Namespace:        default
Address:          4.4.4.4
Default backend:  default-http-backend:80 (10.52.6.2:8080)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /*         web:8080 (10.52.8.10:8080)
              /v2/keys   etcd-np:2379 (10.52.0.2:2379,10.52.2.4:2379,10.52.8.4:2379)
Annotations:  ingress.kubernetes.io/backends:
                {"k8s-be-30195--ebfd7339a961462d":"UNHEALTHY","k8s-be-30553--ebfd7339a961462d":"HEALTHY","k8s-be-31529--ebfd7339a961462d":"HEALTHY"}
              ingress.kubernetes.io/forwarding-rule: k8s-fw-default-basic-ingress--ebfd7339a961462d
              ingress.kubernetes.io/target-proxy: k8s-tp-default-basic-ingress--ebfd7339a961462d
              ingress.kubernetes.io/url-map: k8s-um-default-basic-ingress--ebfd7339a961462d
Events:       <none>
</code>```

But it does not provide me any info about this incident

UP

```<code>kubectl describe svc etcd-np

Name:                     etcd-np
Namespace:                default
Labels:                   <none>
Annotations:              Selector:  app=etcd
Type:                     NodePort
IP:                       10.4.7.20
Port:                     <unset>  2379/TCP
TargetPort:               2379/TCP
NodePort:                 <unset>  30195/TCP
Endpoints:                10.52.0.2:2379,10.52.2.4:2379,10.52.8.4:2379
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

答:
According to the doc.

A Service exposed through an Ingress must respond to health checks
  from the load balancer. Any container that is the final destination of
  load-balanced traffic must do one of the following to indicate that it
  is healthy:

Serve a response with an HTTP 200 status to GET requests on the / path.

Configure an HTTP readiness probe. Serve a response with an HTTP 200 status to GET requests on the path specified by the readiness
  probe. The Service exposed through an Ingress must point to the same
  container port on which the readiness probe is enabled.

For example, suppose a container specifies this readiness probe:

```<code>...
readinessProbe:
  httpGet:
    path: /healthy
</code>```

Then if the handler for the container's /healthy path returns an
  HTTP 200 status, the load balancer considers the container to be
  alive and healthy.

Now since ETCD has a health endpoint at /health the readiness probe will look like

```<code>...
readinessProbe:
  httpGet:
    path: /health
</code>```

This becomes a bit tricky if mTLS is enabled in ETCD. To avoid that check the docs.

Body:
I try to use ingress for loadbalancer of 2 services on Google Kubernetes engine:

here is ingress config for this:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress

spec:
  rules:
  - http:
      paths:
      - path: /*
        backend:
          serviceName: web
          servicePort: 8080
      - path: /v2/keys
        backend:
          serviceName: etcd-np
          servicePort: 2379

where web is some example service from google samples:

apiVersion: v1
kind: Service
metadata:
  name: web
  namespace: default
spec:
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    run: web
  type: NodePort

----
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: default
spec:
  selector:
    matchLabels:
      run: web
  template:
    metadata:
      labels:
        run: web
    spec:
      containers:
      - image: gcr.io/google-samples/hello-app:1.0
        imagePullPolicy: IfNotPresent
        name: web
        ports:
        - containerPort: 8080
          protocol: TCP

But the second service is ETCD cluster with NodePort service:

---
apiVersion: v1
kind: Service
metadata:
  name: etcd-np
spec:
  ports:
  - port: 2379
    targetPort: 2379
  selector:
    app: etcd
  type: NodePort

But only first ingress rule works properly i see in logs:

ingress.kubernetes.io/backends: {"k8s-be-30195--ebfd7339a961462d":"UNHEALTHY","k8s-be-30553--ebfd7339a961462d":"HEALTHY","k8s-be-31529--ebfd7339a961462d":"HEALTHY"}

I etcd-np works properly it is not a problem of etcd , i think that the problem is that etcd server answers with 404 on GET / request and some healthcheck on ingress level does not allow to use it .

Thats why i have 2 questions :

1 ) How can I provide healthcheck urls for each backend path on ingress

2 ) How can I debug such issues . What I see now is

kubectl describe ingress basic-ingress
Name:             basic-ingress
Namespace:        default
Address:          4.4.4.4
Default backend:  default-http-backend:80 (10.52.6.2:8080)
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /*         web:8080 (10.52.8.10:8080)
              /v2/keys   etcd-np:2379 (10.52.0.2:2379,10.52.2.4:2379,10.52.8.4:2379)
Annotations:  ingress.kubernetes.io/backends:
                {"k8s-be-30195--ebfd7339a961462d":"UNHEALTHY","k8s-be-30553--ebfd7339a961462d":"HEALTHY","k8s-be-31529--ebfd7339a961462d":"HEALTHY"}
              ingress.kubernetes.io/forwarding-rule: k8s-fw-default-basic-ingress--ebfd7339a961462d
              ingress.kubernetes.io/target-proxy: k8s-tp-default-basic-ingress--ebfd7339a961462d
              ingress.kubernetes.io/url-map: k8s-um-default-basic-ingress--ebfd7339a961462d
Events:       <none>

But it does not provide me any info about this incident

UP

kubectl describe svc etcd-np

Name:                     etcd-np
Namespace:                default
Labels:                   <none>
Annotations:              Selector:  app=etcd
Type:                     NodePort
IP:                       10.4.7.20
Port:                     <unset>  2379/TCP
TargetPort:               2379/TCP
NodePort:                 <unset>  30195/TCP
Endpoints:                10.52.0.2:2379,10.52.2.4:2379,10.52.8.4:2379
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

Body:
According to the doc.

A Service exposed through an Ingress must respond to health checks
  from the load balancer. Any container that is the final destination of
  load-balanced traffic must do one of the following to indicate that it
  is healthy:

Serve a response with an HTTP 200 status to GET requests on the / path.

Configure an HTTP readiness probe. Serve a response with an HTTP 200 status to GET requests on the path specified by the readiness
  probe. The Service exposed through an Ingress must point to the same
  container port on which the readiness probe is enabled.

For example, suppose a container specifies this readiness probe:

...
readinessProbe:
  httpGet:
    path: /healthy

Then if the handler for the container's /healthy path returns an
  HTTP 200 status, the load balancer considers the container to be
  alive and healthy.

Now since ETCD has a health endpoint at /health the readiness probe will look like

...
readinessProbe:
  httpGet:
    path: /health

This becomes a bit tricky if mTLS is enabled in ETCD. To avoid that check the docs.


来源: stackexchange

问:
Required String parameter 'token' is not present
I'm using spring boot and thymeleaf in my application, I'm trying implement 'token CSRF' in Controller and thymeleaf file to reset password and protect by CSRF:

my controller:

```<code>@Controller
@RequestMapping("/sdsc0004")
public class SdsPasswordRegController {

private static final Logger LOGGER = LoggerFactory.getLogger(SdsPasswordRegController.class);

@Autowired
private CustomerService customerService;

@ModelAttribute("customer")
public SdsPasswordRegForm passwordReset() {
  return new SdsPasswordRegForm();
}

@GetMapping
public String getUpdatePassword(HttpServletRequest request, HttpServletResponse response,
@RequestParam("token") String token, Model model) {

   Customer checkTokenUser = customerService.findByConfirmationTokenCSRF(token);
   // No token found in DB
    if(checkTokenUser == null) {
      // modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
      LOGGER.info("invalid Token");
      model.addAttribute("invalidToken", "can not verify token !!");
    }
    else {
       model.addAttribute("confirmationToken", checkTokenUser.getConfirmationToken());
      LOGGER.info("invalid Token", checkTokenUser.getConfirmationToken());
    }

    LOGGER.info("Loading submit form successfully");
    model.addAttribute("customer", customer);

    return "sdsc0004";
  }

  @PostMapping
  public String setUpdatePassword(@ModelAttribute("customer") @Validated SdsPasswordRegForm customer,
BindingResult result, Model model, @RequestParam Map requestParams) {

 Customer customerDTO = new Customer();
 // boolean resetOrUpdatePassword = customerService.save(customer.getNewPassword());

 if (result.hasErrors()) {
  LOGGER.info("Submit form: confirm submit password success !!");
    return "sdsc0004";
  }
  else {
    // customer.setSdsUserMgmtDto(customerDTO.setIsLocked(false));
    customerDTO.setIsLocked(true);
    customerDTO.setConfirmationToken(UUID.randomUUID().toString());

    System.out.println();
    System.out.println("token generate automatic: " + customerDTO.getConfirmationToken());

    // customerService.save(customer.getNewPassword());

    return "redirect:/sdsc0005";
   }
  }
 }
</code>```

my HTML:

```<code><div th:if="${invalidToken}" class="alert alert-danger" role="alert" th:text=${invalidToken}></div>

    <form th:if="!${invalidToken}" th:action="@{/sdsc0004}" th:object="${customer}" method="post">
      <input type="hidden" name="token" th:value=${confirmationToken}  >

        <div style="margin-top: 2em">
            <div class="row">
                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                </div>
                <div class="row">
                    <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                        <div class="row">
                            <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                                <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                                <p>
                                <input type="password" style="width: 100%;" name="newPassword" th:value="*{newPassword}" placeholder="New password" />
                                <div class="text-danger" th:if="${#fields.hasErrors('newPassword')}" th:errors="*{newPassword}"></div>
                                </p>
                                </div>
                            <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                            </div>
                            <div class="row">
                                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                                <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                                <p>
                                    <input type="password" style="width: 100%;" name="confirmNewPassword" th:value="*{confirmNewPassword}" placeholder="Confirm new password" />
                                    <div class="text-danger" th:if="${#fields.hasErrors('confirmNewPassword')}" th:errors="*{confirmNewPassword}"></div>
                                </p>
                            </div>
                                <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                            </div>

                <div class="row">
                    <div class="col-xs-2 col-sm-2 col-lg-3"></div>
                        <div class="col-xs-8 col-sm-8 col-lg-5" style="background: #f2f2f2;">
                            <button type="submit" class="logoff-btn" style="width: 100%; padding: 3%; margin: 0">Reset</button>
                        </div>
                    </div>
                </div>
    </form>
</code>```

When I build and it happen an error following as:

```<code>There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'token' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'token' is not present
        at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
        at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
</code>```

How to fix the problem

答:
It doesn't look like you actually add the token as a request parameter, but, like all other values, it is part of the Form Model. You might want to check the contents of your Model first.

EDIT: For further development it's a good idea to debug and explore your ServletRequest. It shows the called URL, the request headers and body. IF you actually send data from your client, you'll find it there.

ContentLicense: CC BY-SA 4.0

Body:
I'm using spring boot and thymeleaf in my application, I'm trying implement 'token CSRF' in Controller and thymeleaf file to reset password and protect by CSRF:

my controller:

@Controller
@RequestMapping("/sdsc0004")
public class SdsPasswordRegController {

private static final Logger LOGGER = LoggerFactory.getLogger(SdsPasswordRegController.class);

@Autowired
private CustomerService customerService;

@ModelAttribute("customer")
public SdsPasswordRegForm passwordReset() {
  return new SdsPasswordRegForm();
}

@GetMapping
public String getUpdatePassword(HttpServletRequest request, HttpServletResponse response,
@RequestParam("token") String token, Model model) {

   Customer checkTokenUser = customerService.findByConfirmationTokenCSRF(token);
   // No token found in DB
    if(checkTokenUser == null) {
      // modelAndView.addObject("invalidToken", "Oops!  This is an invalid confirmation link.");
      LOGGER.info("invalid Token");
      model.addAttribute("invalidToken", "can not verify token !!");
    }
    else {
       model.addAttribute("confirmationToken", checkTokenUser.getConfirmationToken());
      LOGGER.info("invalid Token", checkTokenUser.getConfirmationToken());
    }

    LOGGER.info("Loading submit form successfully");
    model.addAttribute("customer", customer);

    return "sdsc0004";
  }

  @PostMapping
  public String setUpdatePassword(@ModelAttribute("customer") @Validated SdsPasswordRegForm customer,
BindingResult result, Model model, @RequestParam Map requestParams) {

 Customer customerDTO = new Customer();
 // boolean resetOrUpdatePassword = customerService.save(customer.getNewPassword());

 if (result.hasErrors()) {
  LOGGER.info("Submit form: confirm submit password success !!");
    return "sdsc0004";
  }
  else {
    // customer.setSdsUserMgmtDto(customerDTO.setIsLocked(false));
    customerDTO.setIsLocked(true);
    customerDTO.setConfirmationToken(UUID.randomUUID().toString());

    System.out.println();
    System.out.println("token generate automatic: " + customerDTO.getConfirmationToken());

    // customerService.save(customer.getNewPassword());

    return "redirect:/sdsc0005";
   }
  }
 }

my HTML:

    <form th:if="!${invalidToken}" th:action="@{/sdsc0004}" th:object="${customer}" method="post">
      <input type="hidden" name="token" th:value=${confirmationToken}  >

                                <input type="password" style="width: 100%;" name="newPassword" th:value="*{newPassword}" placeholder="New password" />

                                    <input type="password" style="width: 100%;" name="confirmNewPassword" th:value="*{confirmNewPassword}" placeholder="Confirm new password" />

                            <button type="submit" class="logoff-btn" style="width: 100%; padding: 3%; margin: 0">Reset</button>

    </form>

When I build and it happen an error following as:

There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'token' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'token' is not present
        at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
        at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
        at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
        at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)

How to fix the problem


问:
Can I access Companion Object properties in the Companion Class using Scala
I have the following very simple code...

```<code>import org.apache.logging.log4j.{LogManager, Logger}

class TestSingle {
  def doSomething(): Unit = logger.debug("My Log Statement")
}
object TestSingle {
  private val logger: Logger = LogManager.getLogger(classOf[TestSingle])
}
</code>```

But it won't let me access logger from the companion class. Do I need to move the logger to the class and add the final keyword or is there something else I am missing about how to do this?

答:
Yes you can. Either qualify the name when you use it:

```<code>def doSomething(): Unit = TestSingle.logger.debug("My Log Statement")
</code>```

or import everything from the companion object to bring logger in scope:

```<code>class TestSingle {
  import TestSingle._

  def doSomething(): Unit = logger.debug("My Log Statement")
}
</code>```

Body:
I have the following very simple code...

import org.apache.logging.log4j.{LogManager, Logger}

class TestSingle {
  def doSomething(): Unit = logger.debug("My Log Statement")
}
object TestSingle {
  private val logger: Logger = LogManager.getLogger(classOf[TestSingle])
}

But it won't let me access logger from the companion class. Do I need to move the logger to the class and add the final keyword or is there something else I am missing about how to do this?

Body:
Yes you can. Either qualify the name when you use it:

def doSomething(): Unit = TestSingle.logger.debug("My Log Statement")

or import everything from the companion object to bring logger in scope:

class TestSingle {
  import TestSingle._

  def doSomething(): Unit = logger.debug("My Log Statement")
}


问:
How to pass input configuration to camera 2 android
I am developing an android camera application, and I wanted to pass in the capture size to configure the camera before taking a picture.

This is my code:

```<code>try {
    mCaptureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    mCaptureRequestBuilder.addTarget(previewSurface);

    InputConfiguration inputConfiguration = new InputConfiguration(1920, 1080, ImageFormat.JPEG); //error here.

    cameraDevice.createReprocessableCaptureSession(inputConfiguration, Arrays.asList(previewSurface), new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                try {
                    cameraCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, handler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                Toast.makeText(getApplicationContext(), "Camera Preview Failed!!", Toast.LENGTH_SHORT).show();
            }
    }, null);
}
</code>```

So, I am trying to pass an input configuration to the camera here.
My problem is I'm getting an error on the InputConfiguration line.
This is my error:

java.lang.IllegalArgumentException: input format 256 is not valid

I tried this with a lot of different ImageFormats like JPEG, UNKNOWN, NV21 and others. It's not working.
Help me resolve this error and also if my approach is wrong in interacting with the camera do tell me.

答:
Another sad case is described here: https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.html#REPROCESS_MAX_CAPTURE_STALL

Check that your camera supports reprocessing or you would not pass through "input format is not valid" at all as no input would be allowed for reprocessing.

Also the absence of this key value can signal that Yuv reprocessing is not available: https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING

Body:
I am developing an android camera application, and I wanted to pass in the capture size to configure the camera before taking a picture.

This is my code:

try {
    mCaptureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    mCaptureRequestBuilder.addTarget(previewSurface);

    InputConfiguration inputConfiguration = new InputConfiguration(1920, 1080, ImageFormat.JPEG); //error here.

    cameraDevice.createReprocessableCaptureSession(inputConfiguration, Arrays.asList(previewSurface), new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                try {
                    cameraCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, handler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                Toast.makeText(getApplicationContext(), "Camera Preview Failed!!", Toast.LENGTH_SHORT).show();
            }
    }, null);
}

So, I am trying to pass an input configuration to the camera here.
My problem is I'm getting an error on the InputConfiguration line.
This is my error:

java.lang.IllegalArgumentException: input format 256 is not valid

I tried this with a lot of different ImageFormats like JPEG, UNKNOWN, NV21 and others. It's not working.
Help me resolve this error and also if my approach is wrong in interacting with the camera do tell me.


问:
Self inner join, aggregate and sum of set
I've got the following schema:

```<code>CREATE TABLE aTable
    ("id" int, "idOfOperation" varchar(10), "uniqueName" varchar(6), "randomNumber" int)
;

INSERT INTO aTable
    ("id", "idOfOperation", "uniqueName", "randomNumber")
VALUES
    (1, 'operation1', 'model1', 3),
    (2, 'operation1', 'model2', 5),
    (3, 'operation2', 'model2', 43),
    (4, 'operation2', 'model3', 57),
    (5, 'operation2', 'model4', 65)
;
</code>```

Constraints:

(idOfOperation, uniqueName) are unique.

Table contains results of different operations (operation1, operation2) and which operation has multiple sub models (model1, model2, model3, model4) with some unique values (randomNumber).

What I need to achieve:

Create a query which will find a sum of set of two operations (operation1, operation2) withe following output:
'model2', 5.18, 'model2', 43.2

I already tried the following inner join:

```<code>select r1.*, r2.*
from aTable r1
         inner join aTable r2
         on (r1."uniqueName" = r2."uniqueName" and r1."idOfOperation" != r2."idOfOperation")
where (r1."idOfOperation" = 'operation1' or r1."idOfOperation" = 'operation2')
</code>```

But the result contains two rows instead of one (with swapped values):

```<code>id  idOfOperation   uniqueName  randomNumber    id  idOfOperation   uniqueName  randomNumber
3   operation2  model2  43  2   operation1  model2  5
2   operation1  model2  5   3   operation2  model2  43
</code>```

Expected result is:

```<code>operation2, operation1, model2, 43, 5
</code>```

I'd really appreciate any help.

答:
I understand that you are looking for transitions from operation1 to operation2. One option uses window functions: lead() and lag() let you access the next and previous operation, that you can then then use for filtering:

```<code>select "id", "idOfOperation", "uniqueName", "randomNumber"
from (
    select
        t.*,
        lag("idOfOperation") over(order by id) lagIdOfOperation,
        lead("idOfOperation") over(order by id) leadIdOfOperation
    from aTable t
) t
where ('operation1', 'operation2') in (
    (t."idOfOperation",  leadIdOfOperation) ,
    (lagIdOfOperation, t."idOfOperation")
)
</code>```

Demo on DB Fiddle:

```
id | idOfOperation | uniqueName | randomNumber
-: | :------------ | :--------- | -----------:
 2 | operation1    | model2     |            5
 3 | operation2    | model2     |           43
```

Side notes:

avoid using double-quoted (case sensitive) identifiers: they just make things more complicated, for no obvious benefit

column randomNumber should probably be numeric rather than int

Body:
I've got the following schema:

CREATE TABLE aTable
    ("id" int, "idOfOperation" varchar(10), "uniqueName" varchar(6), "randomNumber" int)
;

INSERT INTO aTable
    ("id", "idOfOperation", "uniqueName", "randomNumber")
VALUES
    (1, 'operation1', 'model1', 3),
    (2, 'operation1', 'model2', 5),
    (3, 'operation2', 'model2', 43),
    (4, 'operation2', 'model3', 57),
    (5, 'operation2', 'model4', 65)
;

Constraints:

(idOfOperation, uniqueName) are unique.

Table contains results of different operations (operation1, operation2) and which operation has multiple sub models (model1, model2, model3, model4) with some unique values (randomNumber).

What I need to achieve:

Create a query which will find a sum of set of two operations (operation1, operation2) withe following output:
'model2', 5.18, 'model2', 43.2

I already tried the following inner join:

select r1.*, r2.*
from aTable r1
         inner join aTable r2
         on (r1."uniqueName" = r2."uniqueName" and r1."idOfOperation" != r2."idOfOperation")
where (r1."idOfOperation" = 'operation1' or r1."idOfOperation" = 'operation2')

But the result contains two rows instead of one (with swapped values):

id  idOfOperation   uniqueName  randomNumber    id  idOfOperation   uniqueName  randomNumber
3   operation2  model2  43  2   operation1  model2  5
2   operation1  model2  5   3   operation2  model2  43

Expected result is:

operation2, operation1, model2, 43, 5

I'd really appreciate any help.

Body:
I understand that you are looking for transitions from operation1 to operation2. One option uses window functions: lead() and lag() let you access the next and previous operation, that you can then then use for filtering:

select "id", "idOfOperation", "uniqueName", "randomNumber"
from (
    select
        t.*,
        lag("idOfOperation") over(order by id) lagIdOfOperation,
        lead("idOfOperation") over(order by id) leadIdOfOperation
    from aTable t
) t
where ('operation1', 'operation2') in (
    (t."idOfOperation",  leadIdOfOperation) ,
    (lagIdOfOperation, t."idOfOperation")
)

Demo on DB Fiddle:

id | idOfOperation | uniqueName | randomNumber
-: | :------------ | :--------- | -----------:
 2 | operation1    | model2     |            5
 3 | operation2    | model2     |           43

Side notes:

avoid using double-quoted (case sensitive) identifiers: they just make things more complicated, for no obvious benefit

column randomNumber should probably be numeric rather than int


问:
FBRequestDelegate only works on AppDelegate?
I want to encapsulate all my Facebook interactions within a FacebookFacade class to keep things clean and tidy. I have an instance of the iOS SDK Facebook class within my FacebookFacade.

My problem is that when I make a Graph API call within the facade, such as:

```<code>    [self.facebook requestWithGraphPath:@"me" andDelegate:self];
</code>```

The only method of FBRequestDelegate that gets called is requestLoading: and nothing else.  I have tried putting similar code in other places, like in controllers and other models, and there too not all of the FBRequestDelegate methods get called, only requestLoading:.

In fact the only way I can get the other FBRequestDelegate methods to be called is to put all my Facebook logic in the AppDelegate and make my AppDelegate the FBRequestDelegate.

Why is this the case? Am I missing something here? I definitely do not want to use the AppDelegate as my FBRequestDelegate as I don't want to confuse the purpose of the AppDelegate.

Thanks.

答:
You can share your appDelegate with the other controllers in your application.

I solved this problem by importing my AppDelgate (which instantiates and allocates the facebook object in it) into my interface, i.e

```<code>#import "MyAppDelegate.h"

interface MyViewController: UIViewController <FBRequestDelegate, FBDialogDelegate, FBSessionDelegate>
</code>```

This way, i can create a pointer to point to the delegate object and use the facebook methods in where i need to.

```<code>-(void) someFunction{
      MyAppDelgate *sharedAppDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]
      [sharedAppDelegate.facebook dialog:@"feed" andDelegate:self];
}
</code>```

Let me know if this doesn't work

ContentLicense: CC BY-SA 3.0

Body:
I want to encapsulate all my Facebook interactions within a FacebookFacade class to keep things clean and tidy. I have an instance of the iOS SDK Facebook class within my FacebookFacade.

My problem is that when I make a Graph API call within the facade, such as:

    [self.facebook requestWithGraphPath:@"me" andDelegate:self];

The only method of FBRequestDelegate that gets called is requestLoading: and nothing else.  I have tried putting similar code in other places, like in controllers and other models, and there too not all of the FBRequestDelegate methods get called, only requestLoading:.

In fact the only way I can get the other FBRequestDelegate methods to be called is to put all my Facebook logic in the AppDelegate and make my AppDelegate the FBRequestDelegate.

Why is this the case? Am I missing something here? I definitely do not want to use the AppDelegate as my FBRequestDelegate as I don't want to confuse the purpose of the AppDelegate.

Thanks.

Body:
You can share your appDelegate with the other controllers in your application.

I solved this problem by importing my AppDelgate (which instantiates and allocates the facebook object in it) into my interface, i.e

#import "MyAppDelegate.h"

interface MyViewController: UIViewController <FBRequestDelegate, FBDialogDelegate, FBSessionDelegate>

This way, i can create a pointer to point to the delegate object and use the facebook methods in where i need to.

-(void) someFunction{
      MyAppDelgate *sharedAppDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]
      [sharedAppDelegate.facebook dialog:@"feed" andDelegate:self];
}

Let me know if this doesn't work


问:
Network File share access on GKE cluster - Windows node pool
We are Containerizing dotnet application on GKE cluster(Windows node-pool). We have a requirement, where multiple pods can access same shared space(persistent volume). Also it should support "ReadWriteMany" AccessMode. We have explored below option:

GCE Persistent disk accessed by Persistent volume.(It doesn't support ReadWriteMany. Only one pod can access the disk).

Network File Share(NFS). Currently not supported for windows node pools.

Filestore fits the solutions but expensive and managed by google.

We are looking other options to fit our requirement. Please help.

答:
You are right by saying that NFS isn't yet supported on Windows, at least, not for the built-in client v4. So as long as there is no support for NFS v4, Kubernetes team could not start up this work in k8s. source

With this constraint, the only solution I can see remains the Filestore.


问:
Azure Function v1 as SOAP endpoint
I have an azure function app (v1, with no possibility for upgrading, unfortunately) with an endpoint receiving JSON via POST requests, doing some computation and returning JSON in the response. This endpoint needs to be made SOAP-compatible, meaning that it should receive SOAP requests and return SOAP responses and also be able to provide a WSDL file.

Using the SOAP mapper in API Management is not an option, due to its limitations.

The methods I have tried are:

Create a WCF service and try to delegate the HTTP request to it from the Azure function endpoint. This didn't seem to work because the corresponding handler in WCF can only receive a request via its own HTTP endpoint (which does not seem to be exposable via the azure function endpoint), but cannot be called from within the code.

Use an ASP.net web application with SoapCore as a starting point and try to migrate it to an azure function. This doesn't seem possible because of a completely different structure. SoapCore is attached to the ASP.net app instance as a middleware, whereas azure function does not provide the means to use middleware.

Parse the SOAP request manually, convert it to JSON, do the computation, convert the result back to a SOAP message and return it. The seems very hacky and also the WSDL must be created and served manually. Despite these drawbacks, I'm leaning towards this solution because of the unfeasibility of the first two.

Is there any other possible solution that I have might missed?

答:
If you are using Azure API Management , then below option works;

You can write transformation policies at the service or endpoint level - JSON to SOAP refer: https://learn.microsoft.com/en-us/azure/api-management/api-management-transformation-policies#convert-json-to-soap-using-a-liquid-template

Also refer this link Expose REST API as SOAP via Azure API Management would help.

Title: Azure Function v1 as SOAP endpoint


问:
Rails: accept first search result
I'm using MetaSearch in a Rails 3 project although I imagine the search method doesn't really matter that much.

My controller looks like this:

```<code>  def index
    @search = Household.search(params[:search])
    @households = @search.all
  end
</code>```

If there is only a single search result, I want to go directly to the "show" action for that item, otherwise go to the "index" action. (Right now everything goes to the "index" action, which adds another step for the user).

Any ideas how to accomplish this?

答:
you could add something like</p>

```<code>if @households.count == 1
redirect_to household_path(@households.first)
end
</code>```

Title: Rails: accept first search result

Body:
I'm using MetaSearch in a Rails 3 project although I imagine the search method doesn't really matter that much.

My controller looks like this:

  def index
    @search = Household.search(params[:search])
    @households = @search.all
  end

If there is only a single search result, I want to go directly to the "show" action for that item, otherwise go to the "index" action. (Right now everything goes to the "index" action, which adds another step for the user).

Any ideas how to accomplish this?

Body:
you could add something like

if @households.count == 1
redirect_to household_path(@households.first)
end


问:
JSON Data producing key error for nested data
I'm getting a key error when trying to access some nested JSON data, this is because i am struggling to print the SECOND set of data under ["updates"] , see code below:

```<code>for url in URLs:
    JSONdata = requests.get(url, cookies=cookies, verify=False) .json()
    notifications = JSONdata["notifications"]
    for JSONkey in notifications:
        outDiscards = JSONkey["updates"]["outDiscards"]["value"]["avg"]["float"]
        inDiscards = JSONkey["updates"]["inDiscards"]["value"]["avg"]["float"]
        name = JSONkey["path_elements"][1]
        interface = JSONkey["path_elements"][5]
        print(name, interface, outDiscards, inDiscards, sep=',')
</code>```

The JSON data looks like this and i am trying to access the AVG float for the key ["outDiscards]" (Scroll all the way to the bottom to find it):

```<code>{
 "notifications": [
  {
   "timestamp": "1590228300000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "alignmentErrors": {
     "key": "alignmentErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "fcsErrors": {
     "key": "fcsErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooLongs": {
     "key": "frameTooLongs",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooShorts": {
     "key": "frameTooShorts",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inDiscards": {
     "key": "inDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inErrors": {
     "key": "inErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "outErrors": {
     "key": "outErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "symbolErrors": {
     "key": "symbolErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
  {
   "timestamp": "1590672660000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "inOctets": {
     "key": "inOctets",
     "value": {
      "avg": {
       "float": 2252589.403482577
      },
      "max": {
       "float": 3062029.5123118195
      },
      "min": {
       "float": 1716651.1165519762
      },
      "stddev": {
       "float": 486507.3457503787
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "inUcastPkts": {
     "key": "inUcastPkts",
     "value": {
      "avg": {
       "float": 4924.985636262933
      },
      "max": {
       "float": 6405.247375228221
      },
      "min": {
       "float": 4027.16222744576
      },
      "stddev": {
       "float": 856.3274693923914
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outMulticastPkts": {
     "key": "outMulticastPkts",
     "value": {
      "avg": {
       "float": 0.03331537922781352
      },
      "max": {
       "float": 0.09996021185548479
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0.047115061840280935
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outOctets": {
     "key": "outOctets",
     "value": {
      "avg": {
       "float": 532952.2820988153
      },
      "max": {
       "float": 686277.7896707873
      },
      "min": {
       "float": 453320.58138715214
      },
      "stddev": {
       "float": 80364.91411229585
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outUcastPkts": {
     "key": "outUcastPkts",
     "value": {
      "avg": {
       "float": 4409.95750691497
      },
      "max": {
       "float": 5605.478585933741
      },
      "min": {
       "float": 3652.11719308749
      },
      "stddev": {
       "float": 677.6427171449172
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    }
   }
  },
  {
   "timestamp": "1590444480000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "outDiscards": {
     "key": "outDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
</code>```

I keep getting a KeyError, this is because if i print out just ["updates"] it only goes up to "SymbolErrors" in the JSON data, because it closes out with ))), i don't know how to access the second part of the data

答:
inDiscards and outDiscards is not in every updates you have and .get("inDiscards" or "outDiscards") doesn't do what you think it can.

Just check out updates dict you will find that both inDiscards and outDiscards are not in a single updates dict.

Body:
I'm getting a key error when trying to access some nested JSON data, this is because i am struggling to print the SECOND set of data under ["updates"] , see code below:

for url in URLs:
    JSONdata = requests.get(url, cookies=cookies, verify=False) .json()
    notifications = JSONdata["notifications"]
    for JSONkey in notifications:
        outDiscards = JSONkey["updates"]["outDiscards"]["value"]["avg"]["float"]
        inDiscards = JSONkey["updates"]["inDiscards"]["value"]["avg"]["float"]
        name = JSONkey["path_elements"][1]
        interface = JSONkey["path_elements"][5]
        print(name, interface, outDiscards, inDiscards, sep=',')

The JSON data looks like this and i am trying to access the AVG float for the key ["outDiscards]" (Scroll all the way to the bottom to find it):

{
 "notifications": [
  {
   "timestamp": "1590228300000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "alignmentErrors": {
     "key": "alignmentErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "fcsErrors": {
     "key": "fcsErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooLongs": {
     "key": "frameTooLongs",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "frameTooShorts": {
     "key": "frameTooShorts",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inDiscards": {
     "key": "inDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "inErrors": {
     "key": "inErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "outErrors": {
     "key": "outErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    },
    "symbolErrors": {
     "key": "symbolErrors",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },
  {
   "timestamp": "1590672660000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "inOctets": {
     "key": "inOctets",
     "value": {
      "avg": {
       "float": 2252589.403482577
      },
      "max": {
       "float": 3062029.5123118195
      },
      "min": {
       "float": 1716651.1165519762
      },
      "stddev": {
       "float": 486507.3457503787
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "inUcastPkts": {
     "key": "inUcastPkts",
     "value": {
      "avg": {
       "float": 4924.985636262933
      },
      "max": {
       "float": 6405.247375228221
      },
      "min": {
       "float": 4027.16222744576
      },
      "stddev": {
       "float": 856.3274693923914
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outMulticastPkts": {
     "key": "outMulticastPkts",
     "value": {
      "avg": {
       "float": 0.03331537922781352
      },
      "max": {
       "float": 0.09996021185548479
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0.047115061840280935
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outOctets": {
     "key": "outOctets",
     "value": {
      "avg": {
       "float": 532952.2820988153
      },
      "max": {
       "float": 686277.7896707873
      },
      "min": {
       "float": 453320.58138715214
      },
      "stddev": {
       "float": 80364.91411229585
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    },
    "outUcastPkts": {
     "key": "outUcastPkts",
     "value": {
      "avg": {
       "float": 4409.95750691497
      },
      "max": {
       "float": 5605.478585933741
      },
      "min": {
       "float": 3652.11719308749
      },
      "stddev": {
       "float": 677.6427171449172
      },
      "weight": {
       "float": 0.9999999999999999
      }
     }
    }
   }
  },
  {
   "timestamp": "1590444480000000000",
   "path_elements": [
    "Devices",
    "ASDASDA23",
    "versioned-data",
    "interfaces",
    "data",
    "Ethernet6",
    "aggregate",
    "rates",
    "1m"
   ],
   "updates": {
    "outDiscards": {
     "key": "outDiscards",
     "value": {
      "avg": {
       "float": 0
      },
      "max": {
       "float": 0
      },
      "min": {
       "float": 0
      },
      "stddev": {
       "float": 0
      },
      "weight": {
       "float": 1
      }
     }
    }
   }
  },

I keep getting a KeyError, this is because if i print out just ["updates"] it only goes up to "SymbolErrors" in the JSON data, because it closes out with ))), i don't know how to access the second part of the data


问:
plot bar graph with column names on x axis
Dataframe how to plot a bar graph using python with column names on x axis and the total of the first column on y axis. I have a dataframe similar to this

```<code>     Name  1990 1991 1992 1993 1994
  0   A      10    2   15   20   18
  1   B      13   14   18   11   17
  2   C      12   17    8   10   13
  3   D       9   15   16    6    9
  4   E      19   18   13   17   19
  5   Total  63   66   70   64   76
</code>```

I want to plot a bar graph with x-axis = 1990,1991,1992,1993,1994 and y-axis = Total values. Any help with python code would be much appreciated.

could anyone help me with the dynamic scatter plot using plotly express taking years 1990, 1991,1992,1993,1994 on x-axis and corresponding yearly data on y-axis. The Name column values to be taken as animation. as the play button is clicked, the data corresponding to the year and name value should move from 1990 to 1994

答:
Ok. This is the full solution</p>
```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
namesofxaxis= ['C', 'C++', 'Java', 'Python', 'PHP']
df = pd.DataFrame({'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'Total'},
     '1990': {0: 10, 1: 13, 2: 12, 3: 9, 4: 19, 5: 63},
     '1991': {0: 2, 1: 14, 2: 17, 3: 15, 4: 18, 5: 66},
     '1992': {0: 15, 1: 18, 2: 8, 3: 16, 4: 13, 5: 70},
     '1993': {0: 20, 1: 11, 2: 10, 3: 6, 4: 17, 5: 64},
     '1994': {0: 18, 1: 17, 2: 13, 3: 9, 4: 19, 5: 76}})

print(df)
print('\n')
res_df  = df.iloc[5:,1:]

print('\n')
res_df1  = df.iloc[3:3,:]
namesofxaxis=list(df.columns[1:])
print((res_df.values.tolist()))
flat_ls = [item for sublist in res_df.values.tolist() for item in sublist]
print('\n')

print('\n')
print((namesofxaxis))

Mine_std = [2, 3, 4, 1,5]

width = 0.3

fig, ax = plt.subplots()

ax.bar(namesofxaxis,flat_ls, width,
       yerr = Mine_std,
       label ='Mine')

ax.set_ylabel('Articles')
ax.legend()

ax.set_title('matplotlib.axes.Axes.bar Example')

plt.show()
</code>```

Body:
Dataframe how to plot a bar graph using python with column names on x axis and the total of the first column on y axis. I have a dataframe similar to this

     Name  1990 1991 1992 1993 1994
  0   A      10    2   15   20   18
  1   B      13   14   18   11   17
  2   C      12   17    8   10   13
  3   D       9   15   16    6    9
  4   E      19   18   13   17   19
  5   Total  63   66   70   64   76

I want to plot a bar graph with x-axis = 1990,1991,1992,1993,1994 and y-axis = Total values. Any help with python code would be much appreciated.

could anyone help me with the dynamic scatter plot using plotly express taking years 1990, 1991,1992,1993,1994 on x-axis and corresponding yearly data on y-axis. The Name column values to be taken as animation. as the play button is clicked, the data corresponding to the year and name value should move from 1990 to 1994

Body:
Ok. This is the full solution

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
namesofxaxis= ['C', 'C++', 'Java', 'Python', 'PHP']
df = pd.DataFrame({'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'Total'},
     '1990': {0: 10, 1: 13, 2: 12, 3: 9, 4: 19, 5: 63},
     '1991': {0: 2, 1: 14, 2: 17, 3: 15, 4: 18, 5: 66},
     '1992': {0: 15, 1: 18, 2: 8, 3: 16, 4: 13, 5: 70},
     '1993': {0: 20, 1: 11, 2: 10, 3: 6, 4: 17, 5: 64},
     '1994': {0: 18, 1: 17, 2: 13, 3: 9, 4: 19, 5: 76}})

print(df)
print('\n')
res_df  = df.iloc[5:,1:]

print('\n')
res_df1  = df.iloc[3:3,:]
namesofxaxis=list(df.columns[1:])
print((res_df.values.tolist()))
flat_ls = [item for sublist in res_df.values.tolist() for item in sublist]
print('\n')

print('\n')
print((namesofxaxis))

Mine_std = [2, 3, 4, 1,5]

width = 0.3

fig, ax = plt.subplots()

ax.bar(namesofxaxis,flat_ls, width,
       yerr = Mine_std,
       label ='Mine')

ax.set_ylabel('Articles')
ax.legend()

ax.set_title('matplotlib.axes.Axes.bar Example')

plt.show()


问:
Cypress upload file gives error Failed to execute 'atob' on 'Window'
```<code>    cy.fixture('invitati100.xls').as('logo')
        cy.get('[name="fileLista"]').then(function($input) {
          // convert the logo base64 string to a blob
          return Cypress.Blob.base64StringToBlob(this.logo, 'application/vnd.ms-excel')
            .then((blob) => {
              // pass the blob to the fileupload jQuery plugin
              // used in your application's code
              // which initiates a programmatic upload
              $input.fileupload('add', { files: blob })
            })
    })
</code>```

Gives error:

```<code>cypress_runner. : 159529 InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.
at http://platform/__cypress/runner/cypress_runner.js:1531:44
From previous event:
at Context.thenFn (http://platform/__cypress/runner/cypress_runner.js:69293:23)
</code>```

We are using dojo as framework.
Why this error?

Thanks!

答:
Just use this plug-in:

https://www.npmjs.com/package/cypress-file-upload

it's super easy and it works!

Body:
    cy.fixture('invitati100.xls').as('logo')
        cy.get('[name="fileLista"]').then(function($input) {
          // convert the logo base64 string to a blob
          return Cypress.Blob.base64StringToBlob(this.logo, 'application/vnd.ms-excel')
            .then((blob) => {
              // pass the blob to the fileupload jQuery plugin
              // used in your application's code
              // which initiates a programmatic upload
              $input.fileupload('add', { files: blob })
            })
    })

Gives error:

cypress_runner. : 159529 InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.
at http://platform/__cypress/runner/cypress_runner.js:1531:44
From previous event:
at Context.thenFn (http://platform/__cypress/runner/cypress_runner.js:69293:23)

We are using dojo as framework.
Why this error?

Thanks!


问:
Open CV 2.2 Include Directory Missing
I have several Windows 7 64bit systems with OpenCV 2.2 installed on them using CMake and Visual Studio 2008 Standard. CMake generates everything in C:\libs\OpenCV-2.2.0\build just fine and Visual Studio 2008 compiles everything without complaint.

However, every time I do this process on various machines I find that the include directory (C:\libs\OpenCV-2.2.0\build\include\opencv2) is either empty or nearly so. I usually end up thrashing around compiling different versions and poking on random project files until it appears and every time I think I have it figured out. However, with each new install I'm back to the begining.

Is this a known issue for 64bit build of OpenCV 2.2 on Windows 7 64bit using Visual Studio 2008 and is there a known workaround?

Various questions here seem to be hinting at the same thing and guides online are either old or don't reference the problem at all.

答:
To solve this problem compile everything in release and debug then right click the INSTALL project in Visual Studio 2008 and choose Build. This will "install" numerous files and move all the include files into the proper location.

Now /include will contain subfolders

opencv

opencv2

and /include/opencv2 will contain numerous subfolders:

calib3d

contrib

core

feature2d

flann

gpu

highgui

imgproc

legacy

ml

objdetect

video

Title: Open CV 2.2 Include Directory Missing


问:
Gitlab console frozen when entering password
I am trying to create a project on GitLab. I have up to the point of committing a new project with git cli but it freezes (no input goes in). The command I used was git push -u origin master, it asks me a question and does not commit.
enter image description here

答: Alternatively ,I used gitkraken (a software solution) to setup my accounts.I configured each git user and it worked with no collsions.</p>


问:
How Do I Remove The Border Of An Input
enter image description here

I have been trying to create a very simple login page. Around these inputs, as you can see, there are black borders. My question is, how do I remove that border?

答:
Try to use the following stylization:

```<code>button {
   border: none;
}

button:checked {
   border: none;
}
</code>```

otherwise, the problem may be a feature of the browser you are using.

I hope to help and, if possible, add the code snippet used.

Title: How Do I Remove The Border Of An Input

Body:
Try to use the following stylization:

button {
   border: none;
}

button:checked {
   border: none;
}

otherwise, the problem may be a feature of the browser you are using.

I hope to help and, if possible, add the code snippet used.


问:
Azure durable function call activtity function in foreach loop. Is it OK?
Is it ok to call activity function in a loop, like this: ?

```<code>foreach(var item in items)
{
    await context.CallActivityWithRetryAsync(....,item,...);
}
</code>```

expanding on the problem I need to execute 2 activities sequentially inside the loop

```<code>var tasks = new List<Task<TypeA>>();

foreach(var item in items)
{
    var task = context.CallActivityWithRetryAsync(Activity2Name,item,...);

    tasks.Add(task);

    task.ContinueWith(t => {
        var innerTask =  context.CallActivityWithRetryAsync(Activity3Name,t.Result,...);
        return innerTask;
    },TaskContinuationOptions.ExecuteSynchronously );
}
await Task.WhenAll(tasks);
</code>```

I should maybe add inner tasks to task collection somehow, so await will wait on all tasks. And then get rid of the TaskContinuationOptions.ExecuteSynchronously ?

Above thing works. But I'm not sure if its the right way to go about it.

答:
This is a good question. I'm not a 100% sure if there's a problem but here's my guess: Your durable context will be executed multiple times, so you'd better await for all the activities outside the loop.

```<code>var tasks = new Task<long>[files.Length];
for (int i = 0; i < files.Length; i++)
{
        tasks[i] = context.CallActivityWithRetryAsync("FunctionName", files[i]);
}

await Task.WhenAll(tasks);
</code>```

At least this is the way I've been using successfully in my projects

Body:
Is it ok to call activity function in a loop, like this: ?

foreach(var item in items)
{
    await context.CallActivityWithRetryAsync(....,item,...);
}

expanding on the problem I need to execute 2 activities sequentially inside the loop

var tasks = new List<Task<TypeA>>();

foreach(var item in items)
{
    var task = context.CallActivityWithRetryAsync(Activity2Name,item,...);

    tasks.Add(task);

    task.ContinueWith(t => {
        var innerTask =  context.CallActivityWithRetryAsync(Activity3Name,t.Result,...);
        return innerTask;
    },TaskContinuationOptions.ExecuteSynchronously );
}
await Task.WhenAll(tasks);

I should maybe add inner tasks to task collection somehow, so await will wait on all tasks. And then get rid of the TaskContinuationOptions.ExecuteSynchronously ?

Above thing works. But I'm not sure if its the right way to go about it.

Body:
This is a good question. I'm not a 100% sure if there's a problem but here's my guess: Your durable context will be executed multiple times, so you'd better await for all the activities outside the loop.

var tasks = new Task<long>[files.Length];
for (int i = 0; i < files.Length; i++)
{
        tasks[i] = context.CallActivityWithRetryAsync("FunctionName", files[i]);
}

await Task.WhenAll(tasks);

At least this is the way I've been using successfully in my projects


问:
Defining context for Core Data with AppDelegate as a singleton
I’m trying to get my head around NSManagedObjectContext for Core Data. Xcode 10.1 provides a fair amount of boilerplate if the Core Data checkbox is selected when creating a new project. But I find it a bit confusing wrt how the current context is set for each view controller. I think I have a better way and am looking for advice to confirm, or to put me back on the right track.

For example, in the boilerplate AppDelegate code,  didFinishLaunchingWithOptions provides the context to the MasterViewController like this:

```<code>let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.persistentContainer.viewContex
</code>```

In the MasterViewContoller, the first use of context picks it up from the fetchedResultsController AND there is code to save the context provided, even though the AppDelegate already has a saveContext() function available to do the same thing:

```<code>@objc
func insertNewObject(_ sender: Any) {
    let context = self.fetchedResultsController.managedObjectContext
    let newEvent = Event(context: context)

    // If appropriate, configure the new managed object.
    newEvent.timestamp = Date()

    // Save the context.
    do {
        try context.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
}
</code>```

In my app with multiple view controllers  I have made mistakes trying to re-declare or hand off the context in each one where it’s needed, so had to contend with errors that were caused by inadvertently having more than one context flying around.

So my question is this: Am I making a mistake, or is there some downside to the following approach:

1) Make the AppDelegate a singleton:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

var window: UIWindow?

static let shared = AppDelegate()
…
</code>```

2) In each class where it’s needed, always define the context (I’m assuming I only need one) like this:

```<code>let context = AppDelegate.shared.persistentContainer.viewContext
</code>```

3) Whenever the context needs to be saved, do it like this:

```<code>AppDelegate.shared.saveContext()
</code>```

That seems much simpler, clearer and less prone to errors, and seems to work in my implementation. Are there problems with this that I'm not seeing?

答: An interesting experiment is to utilise the responder chain and move the insertNewObject method to the app delegate and change it to call [self saveContext]. Then have the add button send the action to nil instead of self. Or in the storyboard drag on a bar button item and drag from its action to the first responder icon (it’s at the top of the view controller and also in the left side bar) and select insertNewObject and try it out!</p>

Body:
I’m trying to get my head around NSManagedObjectContext for Core Data. Xcode 10.1 provides a fair amount of boilerplate if the Core Data checkbox is selected when creating a new project. But I find it a bit confusing wrt how the current context is set for each view controller. I think I have a better way and am looking for advice to confirm, or to put me back on the right track.

For example, in the boilerplate AppDelegate code,  didFinishLaunchingWithOptions provides the context to the MasterViewController like this:

let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.persistentContainer.viewContex

In the MasterViewContoller, the first use of context picks it up from the fetchedResultsController AND there is code to save the context provided, even though the AppDelegate already has a saveContext() function available to do the same thing:

@objc
func insertNewObject(_ sender: Any) {
    let context = self.fetchedResultsController.managedObjectContext
    let newEvent = Event(context: context)

    // If appropriate, configure the new managed object.
    newEvent.timestamp = Date()

    // Save the context.
    do {
        try context.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
}

In my app with multiple view controllers  I have made mistakes trying to re-declare or hand off the context in each one where it’s needed, so had to contend with errors that were caused by inadvertently having more than one context flying around.

So my question is this: Am I making a mistake, or is there some downside to the following approach:

1) Make the AppDelegate a singleton:

class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

var window: UIWindow?

static let shared = AppDelegate()
…

2) In each class where it’s needed, always define the context (I’m assuming I only need one) like this:

let context = AppDelegate.shared.persistentContainer.viewContext

3) Whenever the context needs to be saved, do it like this:

AppDelegate.shared.saveContext()

That seems much simpler, clearer and less prone to errors, and seems to work in my implementation. Are there problems with this that I'm not seeing?


问:
React JS - SVG file href not displaying in my app
I have this svg and includes xlink:href that contains the path of the images

```<code><image style="overflow:visible;" width="190" height="76" id="logo" xlink:href="./logos/pic1.png">
</code>```

And in my css file

```<code>.item {
    background-image: url(./pic.svg);
}
</code>```

When I click the svg it shows the logo which pic1.png but in my react app it doesn't show. Is there something wrong here, thanks

答:
you can do something like this in react

make sure your path is correct

```<code><svg>
+
+
<image style="overflow:visible;" width="190" height="76" id="logo" xlinkHref="./logos/pic1.png">
</svg>
</code>```

Body:
I have this svg and includes xlink:href that contains the path of the images

<image style="overflow:visible;" width="190" height="76" id="logo" xlink:href="./logos/pic1.png">

And in my css file

.item {
    background-image: url(./pic.svg);
}

When I click the svg it shows the logo which pic1.png but in my react app it doesn't show. Is there something wrong here, thanks

Body:
you can do something like this in react

make sure your path is correct

<svg>
+
+
<image style="overflow:visible;" width="190" height="76" id="logo" xlinkHref="./logos/pic1.png">
</svg>


问:
how add click event and get the dom in the iframe with react-frame-component?
i use the react-frame-component create a iframe,i want to bind a click event on the iframe and get the dom that id is abc in the iframe. how do that?

above is my code,it's will output null, get the element is not working.what wrong with my code.Help will be appreciated.Thanks.

```<code>...
componentDidMount() {

    var iframe = document.getElementById("ccc");
    console.log(iframe);

    var iwindow = iframe.contentWindow;

    console.log(iwindow);

    var idoc = iwindow.document;

    console.log(idoc);

    console.log(idoc.getElementById('abc'));

  }
return (
      <div>
        <Frame id="ccc">
          <div id="abc">
            <div>this.state.show is true and now I'm visible</div>
          </div>
        </Frame>
      </div>
    );
</code>```

答:
Something like this might work...</p>

```<code>import { FrameContextConsumer } from 'react-frame-component';

const MyComponent = (props) => {
    const frameWindow = useRef(null);

    const getInnerHTML = () => {
        const iframeWindow = frameWindow.current;
        if(!iframeWindow) return;

        // here you got the iframe window object
        // work with it as you like
    };

    return (
        <Iframe onClick={getInnerHTML}>
            <FrameContextConsumer>
                {(frameContext) => {
                    const { document, window } = frameContext;
                    frameWindow.current = window;

                    return <div>Your content goes in this return statement</div>
                }}
            </FrameContextConsumer>
        </Iframe>
    )
};
</code>```

Body:
i use the react-frame-component create a iframe,i want to bind a click event on the iframe and get the dom that id is abc in the iframe. how do that?

above is my code,it's will output null, get the element is not working.what wrong with my code.Help will be appreciated.Thanks.

...
componentDidMount() {

    var iframe = document.getElementById("ccc");
    console.log(iframe);

    var iwindow = iframe.contentWindow;

    console.log(iwindow);

    var idoc = iwindow.document;

    console.log(idoc);

    console.log(idoc.getElementById('abc'));

  }
return (

        <Frame id="ccc">

this.state.show is true and now I'm visible

        </Frame>

    );

Body:
Something like this might work...

import { FrameContextConsumer } from 'react-frame-component';

const MyComponent = (props) => {
    const frameWindow = useRef(null);

    const getInnerHTML = () => {
        const iframeWindow = frameWindow.current;
        if(!iframeWindow) return;

        // here you got the iframe window object
        // work with it as you like
    };

    return (
        <Iframe onClick={getInnerHTML}>
            <FrameContextConsumer>
                {(frameContext) => {
                    const { document, window } = frameContext;
                    frameWindow.current = window;

                    return <div>Your content goes in this return statement</div>
                }}
            </FrameContextConsumer>
        </Iframe>
    )
};


答:
Here is another solution relying on a sequence which would catch gaps in which no date/agent combination exists or even allow an arbitrary range. Not sure if this is what the OP is after.  </p>

```<code>cbind.data.frame(Date = seq(min(df$Date), max(df$Date),1), stringsAsFactors=F) %>%
  crossing(cbind.data.frame(Agent = c("A", "B", "C"), stringsAsFactors=F)) %>%
  left_join(df %>% mutate(actual = 1), by = c("Date", "Agent")) %>%
  filter(is.na(actual)) %>%
  select(-actual)
</code>```

Title: Extract rows from dataframe which were absent on certain days

Body:
I have a dataframe:

Date          Agent
2020-02-10    A
2020-02-11    A
2020-02-12    A
2020-02-13    A
2020-02-14    A
2020-02-10    B
2020-02-12    B
2020-02-10    C
2020-02-11    C
2020-02-14    C

I want to get a data frame with those row which were absent at certain days from 2020-02-10 to 2020-02-14. So desired output is:

Agent  Days_absent
B      2020-02-11; 2020-02-13; 2020-02-14
C      2020-02-12; 2020-02-13

or

Date          Agent
2020-02-11    B
2020-02-13    B
2020-02-14    B
2020-02-12    C
2020-02-13    C

How could i do that?

Body:
Here is another solution relying on a sequence which would catch gaps in which no date/agent combination exists or even allow an arbitrary range. Not sure if this is what the OP is after.

cbind.data.frame(Date = seq(min(df$Date), max(df$Date),1), stringsAsFactors=F) %>%
  crossing(cbind.data.frame(Agent = c("A", "B", "C"), stringsAsFactors=F)) %>%
  left_join(df %>% mutate(actual = 1), by = c("Date", "Agent")) %>%
  filter(is.na(actual)) %>%
  select(-actual)


问:
Unity timer count down not working when app killed android
I'm new to unity and c#, I have a code to increase energy after 10m, I have used PlayerPrefs to do so it is working in unity but not working on mobile please help.
I'm unable to understand what exactly is causing problem in phone. Also the timer pauses when the app is not killed but just minimized on mobile. I want the timer countdown to keep going game minimized and also if killed.

using System;
using UnityEngine;
using UnityEngine.UI;

public class EnergyAdder : MonoBehaviour
{
    // Start is called before the first frame update
    public float waitTime = 600;
    Timer timer;
    public GameRoot gameRoot;
    public int count;
    DateTime currentDate;
    DateTime oldDate;

    void Start()
    {
        //timer = new Timer(waitTime);
        float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
        timer = new Timer(remainingTime);
        if (PlayerPrefs.HasKey("sysString"))
        {
            currentDate = DateTime.Now;
            long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
            oldDate = DateTime.FromBinary(temp);
            TimeSpan difference = currentDate.Subtract(oldDate);
            count = (int)(difference.TotalSeconds / waitTime);
            Debug.Log("time remaining " + count);
            gameRoot.AddEnergy(count);
            timer = new Timer(remainingTime - (float)difference.TotalSeconds);
            //PlayerPrefs.DeleteKey("TimeOnExit");
            //PlayerPrefs.DeleteKey("sysString");
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Gameroot.isFull)
        {
            GetComponent<Text>().text = "Full";
            count = 0;
            timer.refresh();
        }
        else
        {
            //Debug.Log("deltatime ************************"+ secondstime);
            timer.countDown();
            if (timer.isFinished())
            {
                timer = new Timer(waitTime);
                timer.refresh();
                gameRoot.AddEnergy(1);
            }
            UpdateClock();
        }
    }

    void UpdateClock()
    {
        int seconds = ((int)timer.timeLeft) % 60;
        int minutes = (int)(timer.timeLeft / 60);
        GetComponent<Text>().text = minutes.ToString() + ":" + seconds.ToString("00");
    }

    void OnApplicationQuit()
    {
        PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
        var today = DateTime.Now;
        PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
        PlayerPrefs.Save();
    }
}
```

Please help what is wrong in above code or what is missing.

答:
From OnApplicationQuit

Note: iOS applications are usually suspended and do not quit. You should tick "Exit on Suspend" in Player settings for iOS builds to cause the game to quit and not suspend, otherwise you may not see this call. If "Exit on Suspend" is not ticked then you will see calls to OnApplicationPause instead.

I suspect it is just the same with modern Android where your app is also not really closed but hibernate.

So I think you could use OnApplicationPause and OnApplicationFocus

On Android, when the on-screen keyboard is enabled, it causes a OnApplicationFocus(false) event. Additionally, if you press "Home" at the moment the keyboard is enabled, the OnApplicationFocus() event is not called, but OnApplicationPause() is called instead.

and just do the same as you do in OnApplicationQuit also for OnApplicationPause(true) and OnApplicationFocus(false)

and do the same as you do in Start also in OnApplicationPause(false) and OnApplictionFocus(true) like

public class EnergyAdder : MonoBehaviour
{
    public float waitTime = 600;
    public GameRoot gameRoot;
    public int count;

    // already reference this in the Inspector
    [SerializeField] private Text timerText;

    private Timer timer;
    private DateTime currentDate;
    private DateTime oldDate;

    private void Awake()
    {
        // store this reference ONCE
        if(!timerText) timerText = GetComponent<Text>();
    }

    private void Start()
    {
        GetTime();
    }

    private void Update()
    {
        // Note: probably a typo? shouldn't it be "gameRoot" ?
        if (Gameroot.isFull)
        {
            timerText.text = "Full";
            count = 0;
            timer.refresh();
        }
        else
        {
            //Debug.Log("deltatime ************************"+ secondstime);
            timer.countDown();
            if (timer.isFinished())
            {
                timer = new Timer(waitTime);
                timer.refresh();
                gameRoot.AddEnergy(1);
            }
            UpdateClock();
        }
    }

    private void UpdateClock()
    {
        int seconds = ((int)timer.timeLeft) % 60;
        int minutes = (int)(timer.timeLeft / 60);
        timerText.text = $"{minutes}:{seconds:00}";
    }

    private void OnApplicationQuit()
    {
        StoreTime();
    }

    // pauseStatus is True if the application is paused, else False.
    private void OnApplicationPause(bool pauseStatus)
    {
        if(pauseStatus)
        {
            StoreTime();
        }
        else
        {
            GetTime();
        }
    }

    // hasFocus is True if the GameObjects have focus, else False.
    private void OnApplicationFocus(bool hasFocus)
    {
        if(hasFocus)
        {
            GetTime();
        }
        else
        {
            StoreTime();
        }
    }

    private void StoreTime()
    {
        PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
        var today = DateTime.Now;
        PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
        PlayerPrefs.Save();
    }

    private void GetTime()
    {
        // NOTE: You should consider to pass a default value like
        //float remainingTime = PlayerPrefs.GetFloat("TimeOnExit", 15);
        float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
        timer = new Timer(remainingTime);
        if (PlayerPrefs.HasKey("sysString"))
        {
            currentDate = DateTime.Now;
            long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
            oldDate = DateTime.FromBinary(temp);
            TimeSpan difference = currentDate.Subtract(oldDate);
            count = (int)(difference.TotalSeconds / waitTime);
            Debug.Log("time remaining " + count);
            gameRoot.AddEnergy(count);
            timer = new Timer(remainingTime - (float)difference.TotalSeconds);
        }
    }
}
```

Note: Typed on smartphone so I can't test it but I hope it goes into the right direction

Body:
I'm new to unity and c#, I have a code to increase energy after 10m, I have used PlayerPrefs to do so it is working in unity but not working on mobile please help.
I'm unable to understand what exactly is causing problem in phone. Also the timer pauses when the app is not killed but just minimized on mobile. I want the timer countdown to keep going game minimized and also if killed.

using System;
using UnityEngine;
using UnityEngine.UI;

public class EnergyAdder : MonoBehaviour
{
    // Start is called before the first frame update
    public float waitTime = 600;
    Timer timer;
    public GameRoot gameRoot;
    public int count;
    DateTime currentDate;
    DateTime oldDate;

    void Start()
    {
        //timer = new Timer(waitTime);
        float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
        timer = new Timer(remainingTime);
        if (PlayerPrefs.HasKey("sysString"))
        {
            currentDate = DateTime.Now;
            long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
            oldDate = DateTime.FromBinary(temp);
            TimeSpan difference = currentDate.Subtract(oldDate);
            count = (int)(difference.TotalSeconds / waitTime);
            Debug.Log("time remaining " + count);
            gameRoot.AddEnergy(count);
            timer = new Timer(remainingTime - (float)difference.TotalSeconds);
            //PlayerPrefs.DeleteKey("TimeOnExit");
            //PlayerPrefs.DeleteKey("sysString");
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Gameroot.isFull)
        {
            GetComponent<Text>().text = "Full";
            count = 0;
            timer.refresh();
        }
        else
        {
            //Debug.Log("deltatime ************************"+ secondstime);
            timer.countDown();
            if (timer.isFinished())
            {
                timer = new Timer(waitTime);
                timer.refresh();
                gameRoot.AddEnergy(1);
            }
            UpdateClock();
        }
    }

    void UpdateClock()
    {
        int seconds = ((int)timer.timeLeft) % 60;
        int minutes = (int)(timer.timeLeft / 60);
        GetComponent<Text>().text = minutes.ToString() + ":" + seconds.ToString("00");
    }

    void OnApplicationQuit()
    {
        PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
        var today = DateTime.Now;
        PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
        PlayerPrefs.Save();
    }
}

Please help what is wrong in above code or what is missing.

Body:
From OnApplicationQuit

Note: iOS applications are usually suspended and do not quit. You should tick "Exit on Suspend" in Player settings for iOS builds to cause the game to quit and not suspend, otherwise you may not see this call. If "Exit on Suspend" is not ticked then you will see calls to OnApplicationPause instead.

I suspect it is just the same with modern Android where your app is also not really closed but hibernate.

So I think you could use OnApplicationPause and OnApplicationFocus

On Android, when the on-screen keyboard is enabled, it causes a OnApplicationFocus(false) event. Additionally, if you press "Home" at the moment the keyboard is enabled, the OnApplicationFocus() event is not called, but OnApplicationPause() is called instead.

and just do the same as you do in OnApplicationQuit also for OnApplicationPause(true) and OnApplicationFocus(false)

and do the same as you do in Start also in OnApplicationPause(false) and OnApplictionFocus(true) like

public class EnergyAdder : MonoBehaviour
{
    public float waitTime = 600;
    public GameRoot gameRoot;
    public int count;

    // already reference this in the Inspector
    [SerializeField] private Text timerText;

    private Timer timer;
    private DateTime currentDate;
    private DateTime oldDate;

    private void Awake()
    {
        // store this reference ONCE
        if(!timerText) timerText = GetComponent<Text>();
    }

    private void Start()
    {
        GetTime();
    }

    private void Update()
    {
        // Note: probably a typo? shouldn't it be "gameRoot" ?
        if (Gameroot.isFull)
        {
            timerText.text = "Full";
            count = 0;
            timer.refresh();
        }
        else
        {
            //Debug.Log("deltatime ************************"+ secondstime);
            timer.countDown();
            if (timer.isFinished())
            {
                timer = new Timer(waitTime);
                timer.refresh();
                gameRoot.AddEnergy(1);
            }
            UpdateClock();
        }
    }

    private void UpdateClock()
    {
        int seconds = ((int)timer.timeLeft) % 60;
        int minutes = (int)(timer.timeLeft / 60);
        timerText.text = $"{minutes}:{seconds:00}";
    }

    private void OnApplicationQuit()
    {
        StoreTime();
    }

    // pauseStatus is True if the application is paused, else False.
    private void OnApplicationPause(bool pauseStatus)
    {
        if(pauseStatus)
        {
            StoreTime();
        }
        else
        {
            GetTime();
        }
    }

    // hasFocus is True if the GameObjects have focus, else False.
    private void OnApplicationFocus(bool hasFocus)
    {
        if(hasFocus)
        {
            GetTime();
        }
        else
        {
            StoreTime();
        }
    }

    private void StoreTime()
    {
        PlayerPrefs.SetFloat("TimeOnExit", timer.timeLeft);
        var today = DateTime.Now;
        PlayerPrefs.SetString("sysString", today.ToBinary().ToString());
        PlayerPrefs.Save();
    }

    private void GetTime()
    {
        // NOTE: You should consider to pass a default value like
        //float remainingTime = PlayerPrefs.GetFloat("TimeOnExit", 15);
        float remainingTime = PlayerPrefs.GetFloat("TimeOnExit");
        timer = new Timer(remainingTime);
        if (PlayerPrefs.HasKey("sysString"))
        {
            currentDate = DateTime.Now;
            long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));
            oldDate = DateTime.FromBinary(temp);
            TimeSpan difference = currentDate.Subtract(oldDate);
            count = (int)(difference.TotalSeconds / waitTime);
            Debug.Log("time remaining " + count);
            gameRoot.AddEnergy(count);
            timer = new Timer(remainingTime - (float)difference.TotalSeconds);
        }
    }
}

Note: Typed on smartphone so I can't test it but I hope it goes into the right direction


问:
Serilog multiple files appsettings.json
Im trying to configure serilog to write to multiple files, with no luck whatsoever.
With this configuration it just writes to the second file?

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\audit-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\error-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  }
}
```

<p>Or is there any way to load many loggers to the software with different configurations from appsettings.json. Something like this?</p>

<pre class="lang-cs prettyprint-override"><code>var errorLogConfiguration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();

_log = new LoggerConfiguration()
    .ReadFrom
    .Configuration(errorLogConfiguration)
    .CreateLogger();
</code>```

答:
My findings after a while of errors, retry and nearly giving up based on lack of documentation about Serilog. They have a tread on GitHub: https://github.com/serilog/serilog-filters-expressions/issues/27. Nearly every thread goes to the same conclusion that you have to create a SUBLOGGER. This is my implementation. For this implementation you need the following plugins:

Serilog Filter

Serilog Sink

Serilog Async

```<code>"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
  }
},
"WriteTo:Information": { //this name here can be changed
  "Name": "Logger", //this name here is essential
  "Args": {
    "configureLogger": {
      "Filter": [
        {
          "Name": "ByIncludingOnly",
          "Args": {
            "expression": "@Level = 'Information'"
          }
        }
      ],
      "WriteTo": [
        {
          "Name": "Async", //i use async plugin from serilog
          "Args": {
            "configure": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/Log_.txt",
                  "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      ]
    }
  }
},
</code>```

Title: Serilog multiple files appsettings.json

Body:
Im trying to configure serilog to write to multiple files, with no luck whatsoever.
With this configuration it just writes to the second file?

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\audit-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "c:\\temp\\error-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      }
    ]
  }
}

Or is there any way to load many loggers to the software with different configurations from appsettings.json. Something like this?

var errorLogConfiguration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();

_log = new LoggerConfiguration()
    .ReadFrom
    .Configuration(errorLogConfiguration)
    .CreateLogger();

Body:
My findings after a while of errors, retry and nearly giving up based on lack of documentation about Serilog. They have a tread on GitHub: https://github.com/serilog/serilog-filters-expressions/issues/27. Nearly every thread goes to the same conclusion that you have to create a SUBLOGGER. This is my implementation. For this implementation you need the following plugins:

Serilog Filter

Serilog Sink

Serilog Async

"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
  }
},
"WriteTo:Information": { //this name here can be changed
  "Name": "Logger", //this name here is essential
  "Args": {
    "configureLogger": {
      "Filter": [
        {
          "Name": "ByIncludingOnly",
          "Args": {
            "expression": "@Level = 'Information'"
          }
        }
      ],
      "WriteTo": [
        {
          "Name": "Async", //i use async plugin from serilog
          "Args": {
            "configure": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/Log_.txt",
                  "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      ]
    }
  }
},


问:
How to create a composite primary key in my document in elasticsearch
I want to create primary keys using name and ssn.

```<code>"hits" : [
  {
    "_index" : "students",
    "_type" : "_doc",
    "_id" : "_prfVnIB9H5oRoSoC",
    "_score" : 1.0,
    "_source" : {
      "name" : Sam,
      "age" : "23",
      "SSN" : "2365PK",
      "Class" : "10",
      "School" : "St jose School "
     }
 ]
</code>```

I am trying something like this, I don't think this is correct :

```<code>  PUT students/_doc/_create
   {
     "name" : "ssn"
    }
</code>```

Here is the code where I'm sending the data to elasticsearch :

```<code> String newESURL = esUrl + "/students/_doc";
        int diplayCount = 0;
        for (; rec < Records.size(); rec++) {
            String StudRecord = Obj.writeValueAsString(Records.get(rec));
            String Resp = given().trustStore("keystore/cacerts", "xyz").baseUri(newESURL).contentType("application/json").accept("application/json")
                    .body(StudRecord)
                    .auth().basic(User, Password)
                    .post().then().extract().body().asString();
</code>```

答:
There we go. Here is the modified code that would achieve what you need:

```<code>String newESURL = esUrl + "/students/_doc/";
    int diplayCount = 0;
    for (; rec < Records.size(); rec++) {
        Record = record = Records.get(rec);
        String StudRecord = Obj.writeValueAsString(record);
        String StudentKey = "TODO";
        String Resp = given().trustStore("keystore/cacerts", "xyz")
                .baseUri(newESURL + StudentKey)
                .contentType("application/json")
                .accept("application/json")
                .body(StudRecord)
                .auth().basic(User, Password)
                .put().then().extract().body().asString();
</code>```

Where you see "TODO", you need to create a compound key using the name and SSN fields of the record and join them together, e.g. john-123-456-6789
So the URL is actually different for each record because it contains the ID (i.e. primary key) of your record. This will prevent duplication on subsequent loads.

Also make sure to use put() instead of post()

Body:
I want to create primary keys using name and ssn.

"hits" : [
  {
    "_index" : "students",
    "_type" : "_doc",
    "_id" : "_prfVnIB9H5oRoSoC",
    "_score" : 1.0,
    "_source" : {
      "name" : Sam,
      "age" : "23",
      "SSN" : "2365PK",
      "Class" : "10",
      "School" : "St jose School "
     }
 ]

I am trying something like this, I don't think this is correct :

  PUT students/_doc/_create
   {
     "name" : "ssn"
    }

Here is the code where I'm sending the data to elasticsearch :

 String newESURL = esUrl + "/students/_doc";
        int diplayCount = 0;
        for (; rec < Records.size(); rec++) {
            String StudRecord = Obj.writeValueAsString(Records.get(rec));
            String Resp = given().trustStore("keystore/cacerts", "xyz").baseUri(newESURL).contentType("application/json").accept("application/json")
                    .body(StudRecord)
                    .auth().basic(User, Password)
                    .post().then().extract().body().asString();

Body:
There we go. Here is the modified code that would achieve what you need:

String newESURL = esUrl + "/students/_doc/";
    int diplayCount = 0;
    for (; rec < Records.size(); rec++) {
        Record = record = Records.get(rec);
        String StudRecord = Obj.writeValueAsString(record);
        String StudentKey = "TODO";
        String Resp = given().trustStore("keystore/cacerts", "xyz")
                .baseUri(newESURL + StudentKey)
                .contentType("application/json")
                .accept("application/json")
                .body(StudRecord)
                .auth().basic(User, Password)
                .put().then().extract().body().asString();

Where you see "TODO", you need to create a compound key using the name and SSN fields of the record and join them together, e.g. john-123-456-6789
So the URL is actually different for each record because it contains the ID (i.e. primary key) of your record. This will prevent duplication on subsequent loads.

Also make sure to use put() instead of post()


答:
IIUC, you want to just plot the 'Total' row by year. You can use pandas plot, first filter the dataframe down to just the total line then set_index and transpose, T, the dataframe rows and columns, then use pd.DataFrame.plot:

```<code>df.query('Name == "Total"').set_index('Name').T.plot()
</code>```

Output:

For bar chart:

```<code>df.query('Name == "Total"').set_index('Name').T.plot.bar()
</code>```

Output:

A minimum complete example:

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'Total'},
 '1990': {0: 10, 1: 13, 2: 12, 3: 9, 4: 19, 5: 63},
 '1991': {0: 2, 1: 14, 2: 17, 3: 15, 4: 18, 5: 66},
 '1992': {0: 15, 1: 18, 2: 8, 3: 16, 4: 13, 5: 70},
 '1993': {0: 20, 1: 11, 2: 10, 3: 6, 4: 17, 5: 64},
 '1994': {0: 18, 1: 17, 2: 13, 3: 9, 4: 19, 5: 76}})

df.query('Name == "Total"').set_index('Name').T.plot.bar()
plt.show()
</code>```

Title: plot bar graph with column names on x axis

Body:
Dataframe how to plot a bar graph using python with column names on x axis and the total of the first column on y axis. I have a dataframe similar to this

     Name  1990 1991 1992 1993 1994
  0   A      10    2   15   20   18
  1   B      13   14   18   11   17
  2   C      12   17    8   10   13
  3   D       9   15   16    6    9
  4   E      19   18   13   17   19
  5   Total  63   66   70   64   76

I want to plot a bar graph with x-axis = 1990,1991,1992,1993,1994 and y-axis = Total values. Any help with python code would be much appreciated.

could anyone help me with the dynamic scatter plot using plotly express taking years 1990, 1991,1992,1993,1994 on x-axis and corresponding yearly data on y-axis. The Name column values to be taken as animation. as the play button is clicked, the data corresponding to the year and name value should move from 1990 to 1994

Body:
IIUC, you want to just plot the 'Total' row by year. You can use pandas plot, first filter the dataframe down to just the total line then set_index and transpose, T, the dataframe rows and columns, then use pd.DataFrame.plot:

df.query('Name == "Total"').set_index('Name').T.plot()

Output:

For bar chart:

df.query('Name == "Total"').set_index('Name').T.plot.bar()

Output:

A minimum complete example:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'Total'},
 '1990': {0: 10, 1: 13, 2: 12, 3: 9, 4: 19, 5: 63},
 '1991': {0: 2, 1: 14, 2: 17, 3: 15, 4: 18, 5: 66},
 '1992': {0: 15, 1: 18, 2: 8, 3: 16, 4: 13, 5: 70},
 '1993': {0: 20, 1: 11, 2: 10, 3: 6, 4: 17, 5: 64},
 '1994': {0: 18, 1: 17, 2: 13, 3: 9, 4: 19, 5: 76}})

df.query('Name == "Total"').set_index('Name').T.plot.bar()
plt.show()