问:
Build errors. Duplicate class android.support.v4
I have created a simple image to text app using Visual Studio following uTube guide https://www.youtube.com/watch?v=CLjzLiU_GpE

I am new to app dev and wanted to learn this but cant get to compile.

I have tried to follow similar errors in here
Duplicate class android.support.v4.app.INotificationSideChannel found in modules classes?

When I try to follow this and add to the AndroidStudioProjects\ImageToTextApp\gradle.properties
I get more errors

My errors are as show but i have included (only) first and last 2, there are 390 in total.

I think i can see it tells me (as per other issues in here) that the class is in 2 libraries.
(com.android.support:support-compat:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)

Were do i see my project importing these libraries and how do I fix these errors.

Duplicate class android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat found in modules classes.jar (com.android.support:support-compat:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
Duplicate class android.support.v4.app.ActionBarDrawerToggle found in modules classes.jar (com.android.support:support-core-ui:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
...
Duplicate class android.support.v4.widget.ViewDragHelper$2 found in modules classes.jar (com.android.support:customview:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
Duplicate class android.support.v4.widget.ViewDragHelper$Callback found in modules classes.jar (com.android.support:customview:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)

Go to the documentation to learn how to Fix dependency resolution errors.

Hi @BachVu
I added your suggested line and the build.gradle file now looks like

dependencies {
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      implementation 'com.android.support:appcompat-v7:28.0.0'      implementation
  'com.android.support.constraint:constraint-layout:2.0.0-beta1'
    testImplementation 'junit:junit:4.13-beta-3'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation
  'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services-vision:10.2.4'
    exclude module: 'support-v4'  }

But this just creates more errors

ERROR: Gradle DSL method not found: 'exclude()'

Do i need to add another import or have i added in the wrong place?

答:
Try adding this line to the library that causes this issue exclude module: 'support-v4' like this:

```<code>implementation("androidx.recyclerview:recyclerview:x.x") {
        exclude group: 'com.android.support'
        exclude module: 'appcompat-v7'
        exclude module: 'support-v4'
    }
</code>```

Body:
Try adding this line to the library that causes this issue exclude module: 'support-v4' like this:

implementation("androidx.recyclerview:recyclerview:x.x") {
        exclude group: 'com.android.support'
        exclude module: 'appcompat-v7'
        exclude module: 'support-v4'
    }


来源: stackexchange

问:
Any way that we can prevent the breakdown between reference and object when resize a vector?
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

```<code>#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}
</code>```

答:
The only way I can think of is to use std::deque instead of std::vector.

The reason for suggesting std::deque is this (from cppreference):

The storage of a deque is automatically expanded and contracted as
  needed. Expansion of a deque is cheaper than the expansion of a
  std::vector because it does not involve copying of the existing
  elements to a new memory location.

That line about not copying is really the answer to your question. It means that the objects remain where you placed them (in memory) as long as the deque is alive.

However, on the very next line it says:

On the other hand, deques typically have large minimal memory cost; a
  deque holding just one element has to allocate its full internal array
  (e.g. 8 times the object size on 64-bit libstdc++; 16 times the object
  size or 4096 bytes, whichever is larger, on 64-bit libc++).

It's now up to you to decide which is better - higher initial memory cost or changing your program's logic not to require referencing the items in the vector like that. You might also want to consider std::set or std::unordered_set for quickly finding an object within the container

ContentLicense: CC BY-SA 4.0

Body:
I was debugging an issue and realized that when a vector is resizing, the reference will not work anymore. To illustrate this point, below is the minimal code. The output is 0 instead of 1. Is there anyway that we can prevent this happen except reserving a large space for x?

#include <iostream>
#include <vector>
using namespace std;

vector<int> x{};

int main(){
  x.reserve(1);
  x.push_back(0);
  int & y = x[0];
  x.resize(10);
  y=1;
  cout << x[0] << endl;
  return 0;
}


问:
Don't know the right way to import taskrouter.js into react
I trying to import taskrouter.js into my react app, and I dont know the right way to do it.

```<code> const script = document.createElement("script");
    script.src = "../library/taskrouter.js";
    script.async = true;
    document.body.appendChild(script)
    script.onload = function() {
        axios.get(url_host + '/worker/activiti')
        .then((res) => {
            var worker = new Twilio.TaskRouter.Worker(res);
            console.log("YEET",worker)
        })
      };
</code>```

This is the error that I get.

```<code>Unhandled Rejection (TypeError): Cannot read property 'Worker' of undefined
</code>```

答:
Twilio developer evangelist here.

First of all, have you confirmed that loading the script like that does actually include the TaskRouter JS file on your page? I'd be concerned that webpack (or whatever you are using to build your application) might do something unexpected with the script src you're setting there. Or may not ultimately refer to the correct file after the project is built.

I would try one of two things to include TaskRouter.js. Either include the TaskRouter.js file from the CDN outside of React's control over the application, in the  of your index.html file.

```<code><script src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>
</code>```

Alternatively, there is an npm package now available for TaskRouter JS. Use it by installing into your project:

```<code>npm install twilio-taskrouter --save
</code>```

You can then use the worker from React by importing it like so:

```<code>import { Worker } from 'twilio-taskrouter';
</code>```

You can then instantiate a new worker using:

```<code>const worker = new Worker(token);
</code>```

Let me know if that helps at all.

Body:
I trying to import taskrouter.js into my react app, and I dont know the right way to do it.

 const script = document.createElement("script");
    script.src = "../library/taskrouter.js";
    script.async = true;
    document.body.appendChild(script)
    script.onload = function() {
        axios.get(url_host + '/worker/activiti')
        .then((res) => {
            var worker = new Twilio.TaskRouter.Worker(res);
            console.log("YEET",worker)
        })
      };

This is the error that I get.

Unhandled Rejection (TypeError): Cannot read property 'Worker' of undefined

Body:
Twilio developer evangelist here.

First of all, have you confirmed that loading the script like that does actually include the TaskRouter JS file on your page? I'd be concerned that webpack (or whatever you are using to build your application) might do something unexpected with the script src you're setting there. Or may not ultimately refer to the correct file after the project is built.

I would try one of two things to include TaskRouter.js. Either include the TaskRouter.js file from the CDN outside of React's control over the application, in the <head> of your index.html file.

<script src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>

Alternatively, there is an npm package now available for TaskRouter JS. Use it by installing into your project:

npm install twilio-taskrouter --save

You can then use the worker from React by importing it like so:

import { Worker } from 'twilio-taskrouter';

You can then instantiate a new worker using:

const worker = new Worker(token);

Let me know if that helps at all.


问:
How to get latest data inserted in mySQL?
I have this kind of table:

```<code>ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 A             2     2019-05-27
 A             0     2019-05-28
 B             0     2019-05-27
 B             1     2019-05-28
</code>```

I use GROUP BY to get group the data and the result is:

```<code> ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 B             0     2019-05-27
</code>```

The desired output is:

```<code> ID        NUMBER     DATE_INPUT
 A             0     2019-05-28
 B             1     2019-05-28
</code>```

答:
you can use a correlated subquery</p>

```<code>select * from tablename a
where date_input = (select max(date_input) from tablename b
where a.id=b.id)
</code>```

Body:
I have this kind of table:

ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 A             2     2019-05-27
 A             0     2019-05-28
 B             0     2019-05-27
 B             1     2019-05-28

I use GROUP BY to get group the data and the result is:

 ID        NUMBER     DATE_INPUT
 A             1     2019-05-26
 B             0     2019-05-27

The desired output is:

 ID        NUMBER     DATE_INPUT
 A             0     2019-05-28
 B             1     2019-05-28

Body:
you can use a correlated subquery

select * from tablename a
where date_input = (select max(date_input) from tablename b
where a.id=b.id)


问:
Overflowing a child element outside the parent element
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

答:
There are three reasons your image is not visible when lifted.

you have overflow:hidden on .menu-card

you have overflow:hidden on .menu-card__header

you have a clip-path set on .menu-card__header

You can get the angled effect using a white element positioned at the bottom of the header using a clip-path or css triangle. This would negate the need for the header clip path. Then remove the overflow css and you should get the effect you are looking for.

Body:
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}

    Lorem Ipsum

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?


问:
rpc error: code = Unknown desc = Moved Permanently: HTTP status code 301
I have GRPC service written in go and i need to deploy the service on top of AWS-EKS, we are using nginx-ingress and cloudflare to point to our cluster gateway (nginx).

but when i tried to deploy the service and test it using this command grpcurl grpc.fd-admin.com:443 list
i always get the following error:

```<code>Failed to list services: rpc error: code = Unknown desc = Moved Permanently: HTTP status code 301; transport: missing content-type field
</code>```

And this is what i did for kubernetes resources:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: grpc
  labels:
    k8s-app: grpc
spec:
  replicas: 1
  template:
    metadata:
      labels:
        k8s-app: grpc
    spec:
      containers:
      - name: grpc
        image: quay.io/kubernetes-ingress-controller/grpc-fortune-teller:0.1
        ports:
        - containerPort: 50051
          name: grpc
---
apiVersion: v1
kind: Service
metadata:
  name: grpc
  namespace: grpc
spec:
  selector:
    k8s-app: grpc
  ports:
  - port: 50051
    targetPort: 50051
    protocol: TCP
    name: grpc
  type: ClusterIP
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  name: grpc
  namespace: grpc
spec:
  rules:
  - host: grpc.fd-admin.com
    http:
      paths:
      - backend:
          serviceName: grpc
          servicePort: grpc
  tls:
  - secretName: grpc
    hosts:
      - grpc.fd-admin.com
</code>```

So can any one explain why i got this error or what is the reasons may cause this kind of error ?

答:
Try below the annotations of nginx ingress,</p>

```<code>kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
    nginx.ingress.kubernetes.io/grpc-backend-for-port: "grpc"
  name: grpc
</code>```

Body:
I have GRPC service written in go and i need to deploy the service on top of AWS-EKS, we are using nginx-ingress and cloudflare to point to our cluster gateway (nginx).

but when i tried to deploy the service and test it using this command grpcurl grpc.fd-admin.com:443 list
i always get the following error:

Failed to list services: rpc error: code = Unknown desc = Moved Permanently: HTTP status code 301; transport: missing content-type field

And this is what i did for kubernetes resources:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: grpc
  labels:
    k8s-app: grpc
spec:
  replicas: 1
  template:
    metadata:
      labels:
        k8s-app: grpc
    spec:
      containers:
      - name: grpc
        image: quay.io/kubernetes-ingress-controller/grpc-fortune-teller:0.1
        ports:
        - containerPort: 50051
          name: grpc
---
apiVersion: v1
kind: Service
metadata:
  name: grpc
  namespace: grpc
spec:
  selector:
    k8s-app: grpc
  ports:
  - port: 50051
    targetPort: 50051
    protocol: TCP
    name: grpc
  type: ClusterIP
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  name: grpc
  namespace: grpc
spec:
  rules:
  - host: grpc.fd-admin.com
    http:
      paths:
      - backend:
          serviceName: grpc
          servicePort: grpc
  tls:
  - secretName: grpc
    hosts:
      - grpc.fd-admin.com

So can any one explain why i got this error or what is the reasons may cause this kind of error ?

Body:
Try below the annotations of nginx ingress,

kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/backend-protocol: "GRPC"
    nginx.ingress.kubernetes.io/grpc-backend-for-port: "grpc"
  name: grpc


问:
Unable to Call function without being stuck in endless loop
When the following function is called and run, if the initial "if" condition is met, the program runs as intended; repetitively. If the initial "if" condition is not met, the program proceeds to run the else statement, but gets stuck in an endless loop.

Why?

```<code>#include <stdio.h>
#include <string.h>

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
            }
        }

    else {
        printf("You were told to put in a number!");
    }

    num_func();
}
</code>```

I am also interested in finding out how to make num and yn[1] global variables so that num_func() can access them w/o having to allocate memory each run. If you could explain that, I would be grateful.

答:
Following the answer here. On invalid input stdin won't be cleared so you need to clear it yourself. Otherwise, the next time that scanf is called it will see that there is still data to be read and try to read the invalid data again.

```<code>#include <stdio.h>
#include <string.h>

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num, c;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
                while ((c = getchar()) != EOF && c != '\n')
                    continue;
            }
        }

    else {
        printf("You were told to put in a number!\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
    }

    num_func();
}
</code>```

As far as the second question is concerned, making the variable global to save space is totally unnecessary here since the function has negligibly small stack frame already.

Body:
When the following function is called and run, if the initial "if" condition is met, the program runs as intended; repetitively. If the initial "if" condition is not met, the program proceeds to run the else statement, but gets stuck in an endless loop.

Why?

#include <stdio.h>
#include <string.h>

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
            }
        }

    else {
        printf("You were told to put in a number!");
    }

    num_func();
}

I am also interested in finding out how to make num and yn[1] global variables so that num_func() can access them w/o having to allocate memory each run. If you could explain that, I would be grateful.

Body:
Following the answer here. On invalid input stdin won't be cleared so you need to clear it yourself. Otherwise, the next time that scanf is called it will see that there is still data to be read and try to read the invalid data again.

#include <stdio.h>
#include <string.h>

int num_func();

int main()
{
    num_func();

   return 0;
}

int num_func()
{
    int num, c;
    char yn[1];

    printf("Please enter an integer value: ");

    if (scanf("%d", &num) == 1)

        {
            printf("The value you entered is: %d. Is this correct? ", num);
            scanf("%s", &yn);

            if (strcmp(yn, "y") == 0) {
                printf("Great! \n");
            }

            else if (strcmp(yn, "n") == 0) {
                printf(":( \n");
            }

            else {
                printf("Illegal Entry. \n");
                while ((c = getchar()) != EOF && c != '\n')
                    continue;
            }
        }

    else {
        printf("You were told to put in a number!\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
    }

    num_func();
}

As far as the second question is concerned, making the variable global to save space is totally unnecessary here since the function has negligibly small stack frame already.


问:
How to avoid nested loop in a real Javascript coding test
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

```<code>
const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

</code>```

[[1, 2]] should be returned.

答:
You can use Array.prototype.reduce() combined with Array.prototype.find() and Array.prototype.push()

const compareArrs = (arr1, arr2) => arr1.reduce((a, c) => {
  const found = arr2.find(arr => JSON.stringify(arr) === JSON.stringify(c))
  if (found.length) a.push(found)
  return a
}, [])

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2]], [[1, 2], [3, 4]]))```

Body:
Between two input arrays, find the same array or arrays and return them.

I just could come up with nested loop solution.

const compareArrs = (arr1, arr2) => {
  const rtnArr = []
  for (let ar1 of arr1){
    for (let ar2 of arr2){
      if (JSON.stringify(ar1) === JSON.stringify(ar2)){
        rtnArr.push(ar1)
      }
    }
  }
  return rtnArr
}

// compare [1, 2] [3, 4] with [1, 2]
console.log(compareArrs([[1, 2], [3, 4]], [[1, 2]]))

[[1, 2]] should be returned.


问:
C++ Create fixed size queue
In C++, how do you create a simple fixed size queue?

I have done it multiple times in Java and Python but am looking for a C++ based way of doing so.

I need a simple FIFO queue with only 2 elements in order to use the push and pop utilities: I am already aware of the fact that I could implement my own class to perform this kind of restriction but my question aims to know if there exist any already available solution to this.

Or is it maybe possible to accomplish the same task with an array? That would work as well.

答:
Using cycling custom container. Online example is here: https://ideone.com/0nEBZa

```<code>#include <array>
#include <iostream>
#include <queue>

template <typename T, size_t N = 2>
class CyclicArray {
 public:
  typedef typename std::array<T, N>::value_type value_type;
  typedef typename std::array<T, N>::reference reference;
  typedef typename std::array<T, N>::const_reference const_reference;
  typedef typename std::array<T, N>::size_type size_type;

  ~CyclicArray() {
    while (size())
      pop_front();
  }

  void push_back(const T& v) {
    if (size_ + 1 > N)
      throw;
    new (&array_[(front_ + size_) % N]) T(v);
    ++size_;
  }

  void pop_front() {
    if (size_ < 1)
      throw;
    front().~T();
    ++front_;
    --size_;
    if (front_ >= N)
      front_ = 0;
  }

  const_reference front() const {
    return *reinterpret_cast<const T*>(&array_[front_]);
  }

  reference front() {
    return *reinterpret_cast<T*>(&array_[front_]);
  }

  size_type size() const {
    return size_;
  }

 private:
  size_type front_ = 0;
  size_type size_ = 0;
  std::array<char[sizeof(T)], N> array_;
};

int main() {
    std::queue<int, CyclicArray<int, 2>> queue;
    queue.push(1);
    queue.push(2);
    queue.pop();
    queue.push(3);
    int f = queue.front();
    queue.pop();
    std::cout << f << std::endl;
    f = queue.front();
    queue.pop();
    std::cout << f << std::endl;
    return 0;
}
</code>```

Outputs

```<code>2
3
</code>```

Title: C++ Create fixed size queue

Body:
Using cycling custom container. Online example is here: https://ideone.com/0nEBZa

#include <array>
#include <iostream>
#include <queue>

template <typename T, size_t N = 2>
class CyclicArray {
 public:
  typedef typename std::array<T, N>::value_type value_type;
  typedef typename std::array<T, N>::reference reference;
  typedef typename std::array<T, N>::const_reference const_reference;
  typedef typename std::array<T, N>::size_type size_type;

  ~CyclicArray() {
    while (size())
      pop_front();
  }

  void push_back(const T& v) {
    if (size_ + 1 > N)
      throw;
    new (&array_[(front_ + size_) % N]) T(v);
    ++size_;
  }

  void pop_front() {
    if (size_ < 1)
      throw;
    front().~T();
    ++front_;
    --size_;
    if (front_ >= N)
      front_ = 0;
  }

  const_reference front() const {
    return *reinterpret_cast<const T*>(&array_[front_]);
  }

  reference front() {
    return *reinterpret_cast<T*>(&array_[front_]);
  }

  size_type size() const {
    return size_;
  }

 private:
  size_type front_ = 0;
  size_type size_ = 0;
  std::array<char[sizeof(T)], N> array_;
};

int main() {
    std::queue<int, CyclicArray<int, 2>> queue;
    queue.push(1);
    queue.push(2);
    queue.pop();
    queue.push(3);
    int f = queue.front();
    queue.pop();
    std::cout << f << std::endl;
    f = queue.front();
    queue.pop();
    std::cout << f << std::endl;
    return 0;
}

Outputs

2
3


问:
Making Synchronous api Call in javascript
I Have a method in javascript which call an GET api

```<code>var PC;
    function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
        }
    });
}
</code>```

I am setting response in a variable named PC and in another method i am calling this

```<code>function PerformTask()
{
GetDetails();
console.log(PC);
}
</code>```

In GetDetails Method console.log(response); works but in PerformTask() console.log(PC) is undefined

As per my understanding it is a async call and PC is not set yet

How can i make it sync with next statement , ?? as i need value of PC to execute next set of statement

I also tried fetch api call

```<code>fetch(Myurl)
        .then(resp => resp.json())
          .then(resp=> setting variable here) ;
</code>```

But it does not work (work but in async way )

Update 1

```<code>return new Promise(function (resolve, reject) {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);;
            resolve(response);
        },
        error: function (err) {
            reject(err);
        }
    });
});
</code>```

And in Performtask()

```<code>GetPropertyDetails()
    .then(function (data) {
        PC= data;
    });
console.log(PC);
</code>```

But still PC is undefined

答:
The better option is to call the PerformTask() function inside the ajax success and pass the result to PerformTask function.
ie, </p>

```<code>   function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PerformTask(response);
        }
    });
}
</code>```

Body:
I Have a method in javascript which call an GET api

var PC;
    function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
        }
    });
}

I am setting response in a variable named PC and in another method i am calling this

function PerformTask()
{
GetDetails();
console.log(PC);
}

In GetDetails Method console.log(response); works but in PerformTask() console.log(PC) is undefined

As per my understanding it is a async call and PC is not set yet

How can i make it sync with next statement , ?? as i need value of PC to execute next set of statement

I also tried fetch api call

fetch(Myurl)
        .then(resp => resp.json())
          .then(resp=> setting variable here) ;

But it does not work (work but in async way )

Update 1

return new Promise(function (resolve, reject) {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);;
            resolve(response);
        },
        error: function (err) {
            reject(err);
        }
    });
});

And in Performtask()

GetPropertyDetails()
    .then(function (data) {
        PC= data;
    });
console.log(PC);

But still PC is undefined

Body:
The better option is to call the PerformTask() function inside the ajax success and pass the result to PerformTask function.
ie,

   function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PerformTask(response);
        }
    });
}


问:
How to change the button color when the button is press?
I have a button that has an orange background. But on pressing the button the colour does not remain the same. It changes to its default colour. And on release of button I get back the same colour. Is it possible to change the colour of the button while the button is being pressed?

My code is:

```<code>b = Button(frame1, text='Quit', command=quit_func)
b.grid(row=6,column=4,pady=5,padx=10)
b.config( background="darkorange1", foreground="white")
</code>```

答:
Button widget takes activebackground and activeforeground as parameters.

```<code>from tkinter import *

root = Tk()

b = Button(root, text='Quit', command="")
b.grid(row=6,column=4,pady=5,padx=10)
b.config(background="darkorange1", foreground="white",
         activebackground="darkorange1", activeforeground="white")

root.mainloop()
</code>```

For a full list of button widget options, you can read it up here.

Body:
I have a button that has an orange background. But on pressing the button the colour does not remain the same. It changes to its default colour. And on release of button I get back the same colour. Is it possible to change the colour of the button while the button is being pressed?

My code is:

b = Button(frame1, text='Quit', command=quit_func)
b.grid(row=6,column=4,pady=5,padx=10)
b.config( background="darkorange1", foreground="white")

Body:
Button widget takes activebackground and activeforeground as parameters.

from tkinter import *

root = Tk()

b = Button(root, text='Quit', command="")
b.grid(row=6,column=4,pady=5,padx=10)
b.config(background="darkorange1", foreground="white",
         activebackground="darkorange1", activeforeground="white")

root.mainloop()

For a full list of button widget options, you can read it up here.


问:
Exception occurred when mock a class which having static method
I'm writing unit test (using TestNG) for a static method. When mocking the class of the static method I'm getting an exception.

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest(TempClass.class)
public class MyTestClass {

  @Test
  public void testMethodt() {
    PowerMockito.mockStatic(TempClass.class);
  }
}

public class TempClass {

  public static String getName(String name){
    return "Hi " + name;
  }
}
</code>```

When execute PowerMockito.mockStatic(TempClass.class); i'm getting following exception

```<code>org.powermock.api.mockito.ClassNotPreparedException:

[Ljava.lang.Object;@65466a6a
The class com.test.TempClass not prepared for test
</code>```

Any solution for this?

答:
Fixed the issue by adding following</p>

```<code>@PrepareForTest(TempClass.class)
public class MyTestClass extends PowerMockTestCase {
   ....
}
</code>```

Body:
I'm writing unit test (using TestNG) for a static method. When mocking the class of the static method I'm getting an exception.

@RunWith(PowerMockRunner.class)
@PrepareForTest(TempClass.class)
public class MyTestClass {

  @Test
  public void testMethodt() {
    PowerMockito.mockStatic(TempClass.class);
  }
}

public class TempClass {

  public static String getName(String name){
    return "Hi " + name;
  }
}

When execute PowerMockito.mockStatic(TempClass.class); i'm getting following exception

org.powermock.api.mockito.ClassNotPreparedException:

[Ljava.lang.Object;@65466a6a
The class com.test.TempClass not prepared for test

Any solution for this?

Body:
Fixed the issue by adding following

@PrepareForTest(TempClass.class)
public class MyTestClass extends PowerMockTestCase {
   ....
}


问:
How to copy handlebars files to dist folder
I'm using Typescript, which compiles from src/ to lib/ folder, and Babel, which compiles from lib/ to dist/.

The issue I have is that I have .handlebars files within src/email_templates/ that are not being copied over to dist/ when I compile the app. Therefore when I run the app it fails with errors as dist/email_templates/ does not exist.

I'm using nodemailer-handlebars package and have tried moving the email_templates/ folder to the project root directory and setting viewPath to the folder, however this also fails as the app is located in var/www/api.my-domain.com/. It seems that the fact that I have periods in api.my-domain.com folder name causes viewPath to fail with error:

```<code>TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.resolve (path.js:1080:7)
    at ExpressHandlebars._resolveLayoutPath (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:342:17)
    at ExpressHandlebars.<anonymous> (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:223:35)
</code>```

Here's my package.json script to build the app:

```<code>"build": "tsc && babel ./lib --out-dir ./dist ",
</code>```

How can I change this so that it delete the current contents of dist/email_templates then copies the contents of src/email_templates to dist/email_templates?

答:
delete the current contents of dist/email_templates then copies the contents of src/email_templates to dist/email_templates

Two additional npm packages

rmraf to delete old files in dist folder https://www.npmjs.com/package/rimraf

mv to move new files to dist folder https://www.npmjs.com/package/mv

Body:
I'm using Typescript, which compiles from src/ to lib/ folder, and Babel, which compiles from lib/ to dist/.

The issue I have is that I have .handlebars files within src/email_templates/ that are not being copied over to dist/ when I compile the app. Therefore when I run the app it fails with errors as dist/email_templates/ does not exist.

I'm using nodemailer-handlebars package and have tried moving the email_templates/ folder to the project root directory and setting viewPath to the folder, however this also fails as the app is located in var/www/api.my-domain.com/. It seems that the fact that I have periods in api.my-domain.com folder name causes viewPath to fail with error:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.resolve (path.js:1080:7)
    at ExpressHandlebars._resolveLayoutPath (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:342:17)
    at ExpressHandlebars.<anonymous> (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:223:35)

Here's my package.json script to build the app:

"build": "tsc && babel ./lib --out-dir ./dist ",

How can I change this so that it delete the current contents of dist/email_templates then copies the contents of src/email_templates to dist/email_templates?


问:
how to manage accelerometer value .x and .y
hello i am making game application in that game  i a moving game using accelerometer
but i want that my ball should not move in upper direction , only move my ball in right ,left and bottom side

please  help me........

答:
Please have a look at the BubbleLevel sample code available at

http://developer.apple.com/library/ios/#samplecode/BubbleLevel/Introduction/Intro.html

This will help you for sure.

ContentLicense: CC BY-SA 3.0


答:
From success you can call another method which you need a response. As the call is ASYNC so the function will not get the response.

```<code>var PC;
function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
            // Your next function
            PerformTask(PC);
        }
    });
}

function PerformTask(pc)
{
    GetDetails();
    console.log(pc);
}
</code>```

there is another way of doing this but I think that is bad way

```<code>$.ajax({
            type: "GET",
            url: Myurl,
            async:false,
            success: function (response) {
                //console.log(response);
                PC= response;
                // Your next function
                PerformTask(PC);
            }
        });
</code>```

Using promise => you can use async & await

function asyncCall() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5)
    }, 2000)
  });
}

(async function() {
  const result = await asyncCall();
  if (result) console.log(result)
})()```

Hope this helps you.

Title: Making Synchronous api Call in javascript

Body:
From success you can call another method which you need a response. As the call is ASYNC so the function will not get the response.

var PC;
function GetDetails() {
    $.ajax({
        type: "GET",
        url: Myurl,
        success: function (response) {
            //console.log(response);
            PC= response;
            // Your next function
            PerformTask(PC);
        }
    });
}

function PerformTask(pc)
{
    GetDetails();
    console.log(pc);
}

there is another way of doing this but I think that is bad way

$.ajax({
            type: "GET",
            url: Myurl,
            async:false,
            success: function (response) {
                //console.log(response);
                PC= response;
                // Your next function
                PerformTask(PC);
            }
        });

Using promise => you can use async & await

function asyncCall() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(5)
    }, 2000)
  });
}

(async function() {
  const result = await asyncCall();
  if (result) console.log(result)
})()

Hope this helps you.


问:
Renew kubernetes pki after expired
My kubernetes PKI expired (API server to be exact) and I can't find a way to renew it. The error I get is

```<code>May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922595    8751 server.go:417] Version: v1.14.2
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922784    8751 plugins.go:103] No cloud provider specified.
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922800    8751 server.go:754] Client rotation is on, will bootstrap in background
May 27 08:43:51 node1 kubelet[8751]: E0527 08:43:51.925859    8751 bootstrap.go:264] Part of the existing bootstrap client certificate is expired: 2019-05-24 13:24:42 +0000 UTC
May 27 08:43:51 node1 kubelet[8751]: F0527 08:43:51.925894    8751 server.go:265] failed to run Kubelet: unable to load bootstrap
kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such file or directory
</code>```

The documentation on https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-certs/ describes how to renew but it only works if the API server is not expired. I have tried to do a

```<code>kubeadm alpha cert renew all
</code>```

and do a reboot but that just made the entire cluster fail so I did a rollback to a snapshot (my cluster is running on VMware).

The cluster is running and all containers seem to work but I can't access it via kubectl so I can't really deploy or query.

My kubernetes version is 1.14.2.

答:
So the solution was to (first a backup)

```<code>$ cd /etc/kubernetes/pki/
$ mv {apiserver.crt,apiserver-etcd-client.key,apiserver-kubelet-client.crt,front-proxy-ca.crt,front-proxy-client.crt,front-proxy-client.key,front-proxy-ca.key,apiserver-kubelet-client.key,apiserver.key,apiserver-etcd-client.crt} ~/
$ kubeadm init phase certs all --apiserver-advertise-address <IP>
$ cd /etc/kubernetes/
$ mv {admin.conf,controller-manager.conf,kubelet.conf,scheduler.conf} ~/
$ kubeadm init phase kubeconfig all
$ reboot
</code>```

then

```<code>$ cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
</code>```

that did the job for me and thanks for your hints :)

Title: Renew kubernetes pki after expired

Body:
My kubernetes PKI expired (API server to be exact) and I can't find a way to renew it. The error I get is

May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922595    8751 server.go:417] Version: v1.14.2
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922784    8751 plugins.go:103] No cloud provider specified.
May 27 08:43:51 node1 kubelet[8751]: I0527 08:43:51.922800    8751 server.go:754] Client rotation is on, will bootstrap in background
May 27 08:43:51 node1 kubelet[8751]: E0527 08:43:51.925859    8751 bootstrap.go:264] Part of the existing bootstrap client certificate is expired: 2019-05-24 13:24:42 +0000 UTC
May 27 08:43:51 node1 kubelet[8751]: F0527 08:43:51.925894    8751 server.go:265] failed to run Kubelet: unable to load bootstrap
kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such file or directory

The documentation on https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-certs/ describes how to renew but it only works if the API server is not expired. I have tried to do a

kubeadm alpha cert renew all

and do a reboot but that just made the entire cluster fail so I did a rollback to a snapshot (my cluster is running on VMware).

The cluster is running and all containers seem to work but I can't access it via kubectl so I can't really deploy or query.

My kubernetes version is 1.14.2.

Body:
So the solution was to (first a backup)

$ cd /etc/kubernetes/pki/
$ mv {apiserver.crt,apiserver-etcd-client.key,apiserver-kubelet-client.crt,front-proxy-ca.crt,front-proxy-client.crt,front-proxy-client.key,front-proxy-ca.key,apiserver-kubelet-client.key,apiserver.key,apiserver-etcd-client.crt} ~/
$ kubeadm init phase certs all --apiserver-advertise-address <IP>
$ cd /etc/kubernetes/
$ mv {admin.conf,controller-manager.conf,kubelet.conf,scheduler.conf} ~/
$ kubeadm init phase kubeconfig all
$ reboot

then

$ cp -i /etc/kubernetes/admin.conf $HOME/.kube/config

that did the job for me and thanks for your hints :)


问:
Is it possible to use Android Studio to build a website in flutter
I have some basic knowledge of building android apps using Android Studio with Java language. Now I want to start learning flutter but not really sure about a couple of things. I read that it's possible to build cross-platform mobile apps with flutter and I can use an android studio to build those apps. Using flutter its also possible to build a website and desktop projects.

My confusions are :

1) Can I use Android Studio IDE with flutter to build mobile apps(both Android & IOS), desktop apps and websites?

2) First of all, I thought I just write a single code for both mobile apps and websites but guess I am wrong. So, if codes are different for mobile apps and website then how different are they? I mean is it something totally different or has some similarities. So, if someone can build a mobile app using flutter then they can easily build a website with flutter too?

3) Can flutter web be used instead of PHP for making websites and web services?

答:
You can absolutely use the Android Studio IDE to write apps in the Dart language for both Android and iOS. I have built for both platforms with Android Studio and loaded them on iOS and Android emulators. Like Bevan Shaw said in his answer, you can checkout the flutter tutorials on the flutter.dev website to learn how to use one language to develop for both platforms at one time.

You can build web applications using flutter, but it is in its infancy. I have been looking heavily into this lately. Go to this link for some web examples: https://flutter.github.io/samples/ ---> more info for flutter web apps is here: https://flutter.dev/web. Unfortunately, I have been unable to find any commercial applications that use Flutter for web.


问:
What is the difference between import css or link css in a React app?
In a React app I can include my CSS either using import or <link> it in the index.html file (From a CDN, for example).

What is the difference?

Is there any significant performance difference between the two methods?

To be clear, I mean this type of import from inside a *js or *.jsx file:

```<code>import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
</code>```

答:
In theory, the only difference between them is that import is the CSS mechanism to include a style sheet and  the HTML mechanism. However, browsers handle them differently, giving  a clear advantage in terms of performance.

Also, using the  tag allows you to define "preferred" and alternate stylesheets. You can't do that with import.

Overall, the  tag is processed more quickly than the import rule (which is apparently somewhat slow as far as the css processing engine is concerned).

Body:
In a React app I can include my CSS either using import or <link> it in the index.html file (From a CDN, for example).

What is the difference?

Is there any significant performance difference between the two methods?

To be clear, I mean this type of import from inside a *js or *.jsx file:

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";


问:
Using a Do-Loop, to read a column of data (numerical & string) and filter the numbers as output into another file
I have an output file, single column, where each 7th line is a string and the others numerical (something like below)

```<code>998.69733
377.29340
142.22397
53.198547
19.743515
7.5493960
timestep:  1
998.69733
377.29340
142.22047
53.188023
19.755905
7.5060229
timestep:  2
998.69733
377.29337
</code>```

I need to read this data into another file, omitting the text and keeping only the numbers and tried a loop to allocate a dummy for my string but I get an error as it does not recognize (AI).

```<code>DO 10 I = 1, 1000
 IF (MOD(I,7) == 0) THEN
  READ (8, FMT= '(AI)') dummy
 END IF
  READ (8,*) val
  WRITE (9,*) val
10 CONTINUE
</code>```

(8 - input file and 9 - output file allocation)

I am quite new to Fortran and spent a lot of time surfing for a solution or at least a similar problem but did not find anything. I would really appreciate some help.

Thank you very much in advance.

答:
If you just want to skip the seventh lines, you could do "read (8, '(A)' )  dummy" where dummy is declared as a character string (i.e., "character (len=80) :: dummy").   It won't matter than some of the characters are letters and others numbers.

P.S.   The modern was to write loops is "do", "end do" ... no need for line numbers and continue statements.

Body:
I have an output file, single column, where each 7th line is a string and the others numerical (something like below)

998.69733
377.29340
142.22397
53.198547
19.743515
7.5493960
timestep:  1
998.69733
377.29340
142.22047
53.188023
19.755905
7.5060229
timestep:  2
998.69733
377.29337

I need to read this data into another file, omitting the text and keeping only the numbers and tried a loop to allocate a dummy for my string but I get an error as it does not recognize (AI).

DO 10 I = 1, 1000
 IF (MOD(I,7) == 0) THEN
  READ (8, FMT= '(AI)') dummy
 END IF
  READ (8,*) val
  WRITE (9,*) val
10 CONTINUE

(8 - input file and 9 - output file allocation)

I am quite new to Fortran and spent a lot of time surfing for a solution or at least a similar problem but did not find anything. I would really appreciate some help.

Thank you very much in advance.


问:
How to check if record exist in sqlite, if yes, then update it.?
first of all i'm describing some explanation about my question,
i have two fragments name as "Main Fragment" and second one is " Cart Fragment"

1==> Main Fragment- Contains recyclerview in which data comes from firestore and set in recyclerview, when user click on add or remove button then data is entered and update in sqlite.

2==> Cart Fragment- Contains recyclerview in which data comes from SQLITE and set in recycelerview.

My Question is when i navigate from cart fragment to Main Fragment then First check that any item is already saved in sqlite or not, if exist then get total item quantity from cart fragment of that item(including other data like name, price etc.) and set in main fragmnet.

Here code for Main Fragment Adapter

```<code>@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.TV_OFF.setText(_mylistdata.get(position).getDiscount()+"% OFF");
   //"Rs "+
    holder.TV_CURNT_PRICE.setText(_mylistdata.get(position).getCurr_price());
    holder.TV_OLD_PRICE.setText(_mylistdata.get(position).getOld_price());
    holder.TV_NAME.setText(_mylistdata.get(position).getName());
    holder.TV_OFFER_DES.setText(_mylistdata.get(position).getOffers_des());
    holder.TV_UNIT.setText(_mylistdata.get(position).getUnit_products()+" Unit");
    Picasso.get().load(_mylistdata.get(position).getImgId()).placeholder(R.drawable.no_image_find).into(holder.imageView);

    holder.add_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Toast.makeText(context, "pos="+prd_id, Toast.LENGTH_SHORT).show();
            holder.add_btn.setVisibility(View.GONE);
            holder.TV_REMOVEITEM.setVisibility(View.VISIBLE);
            holder.TV_TOTALITEM.setVisibility(View.VISIBLE);
            holder.TV_ADDITEM.setVisibility(View.VISIBLE);
            count_value=1;

            holder.TV_TOTALITEM.setText(Integer.toString(count_value));
            // get data from views
            getDataFromViews(position);
            total_qty_pro= (String) holder.TV_TOTALITEM.getText();
            //qty_pro=_mylistdata.get(position).getUnit_products();
            qty_new=qty_pro+" Unit";
            saveData_To_SQLITE(new_name,qty_new,price_pro,price_old,total_qty_pro,image_id,context);

        }

    });
    holder.TV_REMOVEITEM.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {

            //productId= (int) getItemId(position);
            count_value--;
            if (count_value<1)
            {
                Log.d(TAG,"Remove button is pressed");
                holder.add_btn.setVisibility(View.VISIBLE);
                holder.TV_REMOVEITEM.setVisibility(View.GONE);
                holder.TV_TOTALITEM.setVisibility(View.GONE);
                holder.TV_ADDITEM.setVisibility(View.GONE);
                count_value=1;

                String prdct_name= _mylistdata.get(position).getName();

                delete_record(prdct_name,context);

            }else {
                //Data_parsing.setCountText(count_value);
                holder.TV_TOTALITEM.setText(Integer.toString(count_value));

                total_qty_pro= (String) holder.TV_TOTALITEM.getText();
                String prdct_name= _mylistdata.get(position).getName();

                UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

            }

        }
    });
    holder.TV_ADDITEM.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Add button is pressed");
            count_value++;
            //Data_parsing.setCountText(count_value);
            holder.TV_TOTALITEM.setText(Integer.toString(count_value));

            total_qty_pro= (String) holder.TV_TOTALITEM.getText();
            String prdct_name= _mylistdata.get(position).getName();
            UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
        }

    });
}
</code>```

Here is my SQLite class in which i define my static methods for saving, updating and delete my data from sqlite

public class SQLITE_RUD {

```<code>// Save data to sqlite
public static void  saveData_To_SQLITE(String name_pro, String qty_pro, String price_pro,String price_old, String total_qty_pro, String image_id, Context context) {
    DBAdapter db = new DBAdapter(context);
    db.openDB();
    long result =  db.add(name_pro, qty_pro, price_pro,price_old, total_qty_pro, image_id);
    if (result > 0) {
        Toast.makeText(context, "Data is saved succeffuly", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(context, "Unable to save", Toast.LENGTH_SHORT).show();
    }
    db.closeDB();
}

// update data in sqlite

public static void UPDATE_SQL_DATA(String p_name, String total_qty_pro, Context context)
{
    DBAdapter db=new DBAdapter(context);
    db.openDB();
    try {
        long result=db.update_DB(p_name,total_qty_pro);
        if(result>0)
        {
            Toast.makeText(context, "Updated Sucesfully", Toast.LENGTH_SHORT).show();
        }else
        {
            Toast.makeText(context, "Unable to update", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
    {
        Log.d("MyListAdapter","error_update="+e);
    }
    db.closeDB();
}
// Delete data from SQlite
public static void delete_record(String prdct_name,Context context) {
    //
    DBAdapter db=new DBAdapter(context);
    db.openDB();
    try {
        long result=db.Delete_DB(prdct_name);
        if(result>0)
        {
            Toast.makeText(context, "Deleted Sucesfully", Toast.LENGTH_SHORT).show();
        }else
        {
            Toast.makeText(context, "Unable to Delete", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
    {
        Log.d("MyListAdapter","error_delete="+e);
    }
    db.closeDB();
}
</code>```

}

Here i create class name ad DBAdapter in which i define methods for saving, updating, and retriving quires.

```<code>public class DBAdapter {
Context c;
SQLiteDatabase db;
DbHelper database_helper;   // on create and on upgrade is defined

public DBAdapter(Context c) {
    this.c = c;
    database_helper=new DbHelper(c);

}

//OPEN DB
public void openDB()
{
    try {
        db=database_helper.getWritableDatabase();
        db=database_helper.getReadableDatabase();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//CLOSE DB
public void closeDB()
{
    try {
        database_helper.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//INSERT/SAVE
public long add(String P_name,String P_qty,String P_price,String P_OldPrice,String P_Total_qty, String P_Image)
{
    try {
        ContentValues cv=new ContentValues();
        // cv.put(KEY_ItemID, P_id);
        cv.put(KEY_ProductName, P_name);
        cv.put(KEY_ProductQuantity, P_qty);
        cv.put(KEY_ProductPrice, P_price);
        cv.put(KEY_OldPrice, P_OldPrice);
        cv.put(KEY_ProductTotal, P_Total_qty);
        cv.put(KEY_ProductImage,P_Image);
        return db.insert(Table_name, KEY_RowID, cv);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
public long update_DB(String name_prdct, String prdct_TOTAL_QTY)
{
    try
    {
        ContentValues cv=new ContentValues();
        cv.put(KEY_ProductTotal,prdct_TOTAL_QTY);
        return db.update(Table_name,cv,KEY_ProductName +" =?",new String[]{String.valueOf(name_prdct)});
        //return;
    }catch (SQLException e)
    {
        e.printStackTrace();
    }

    return 0;
}

//DELETE
public long Delete_DB(String prdct_name)
{
    try
    {
        return db.delete(Table_name,KEY_ProductName+" =?",new String[]{String.valueOf(prdct_name)});

    }catch (SQLException e)
    {
        e.printStackTrace();
    }

    return 0;
}

//SELECT/RETRIEVE
public Cursor retrieve() {
    String[] columns = {KEY_RowID,KEY_ProductName,KEY_ProductQuantity, KEY_ProductPrice,KEY_OldPrice, KEY_ProductTotal, KEY_ProductImage};
    return db.query(Constants.Table_name, columns, null, null, null, null, null);
}
</code>```

}

Here is my Cart Fragment

```<code>public class CartFragment extends Fragment {
private static final String Tag ="CartFragment" ;
FragmentManager fragmentManager;
RecyclerView recyclerView;
RelativeLayout proceedBtn;
TextView finalprice_bottom, finalprice_upper;
Adapter_chart adapter;
View view;
ArrayList<Chart_getter_setter> chartGetterSetters = new ArrayList<>();

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view= inflater.inflate(R.layout.fragment_cart, container, false);
    recyclerView = view.findViewById(R.id.chart_recyclerview);
    proceedBtn=view.findViewById(R.id.bottomChart);

    finalprice_upper=view.findViewById(R.id.price);
    finalprice_bottom =view.findViewById(R.id.FinalPrice_TV);
    proceedBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(savedInstanceState==null) {
                getFragmentManager().beginTransaction().replace(R.id.fragment_container, ProceedFragment.newInstance()).addToBackStack(null).commit();
            }
        }
    });

    adapter = new Adapter_chart(getActivity(), fragmentManager, chartGetterSetters);

    recyclerView.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);

    //RETRIEVE
    retrieve_data();

    getActivity().setTitle("Final chart");

    return view;
}
private void retrieve_data() {
    DBAdapter db = new DBAdapter(getContext());
    db.openDB();
    chartGetterSetters.clear();
    //RETRIEVE
    Cursor c = db.retrieve();
    while (c.moveToNext())
    {
        int index_id=c.getColumnIndex(Constants.KEY_RowID);
        int index_name=c.getColumnIndex(Constants.KEY_ProductName);
        int index_qty=c.getColumnIndex(Constants.KEY_ProductQuantity);
        int index_price=c.getColumnIndex(Constants.KEY_ProductPrice);
        int index_oldprice=c.getColumnIndex(Constants.KEY_OldPrice);
        int index_total=c.getColumnIndex(Constants.KEY_ProductTotal);
        int index_image=c.getColumnIndex(Constants.KEY_ProductImage);

        int id=c.getInt(index_id);
        String name=c.getString(index_name);
        String qty=c.getString(index_qty);
        String price=c.getString(index_price);
        String oldPrice=c.getString(index_oldprice);
        String total=c.getString(index_total);
        String IMAGE=c.getString(index_image);

        Chart_getter_setter p=new Chart_getter_setter(name,qty,price,oldPrice,total,IMAGE);
        //ADD TO ARRAYLIS
        chartGetterSetters.add(p);

        //CHECK IF ARRAYLIST ISNT EMPTY

        if(chartGetterSetters.size()>0)
        {
            int totalPrice = 0;
            int total_qty=0;
            for(int j = 0 ; j < chartGetterSetters.size(); j++) {

                totalPrice += Integer.parseInt(chartGetterSetters.get(j).getPrice_prdct())*Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity()) ;
                total_qty += Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity());
            }
            String tProice=String.valueOf(totalPrice);
            finalprice_upper.setText("Rs "+tProice);
            finalprice_bottom.setText(String.valueOf(total_qty));//totelPriceTV.setText(tProice);
            recyclerView.setAdapter(adapter);

        }
    }
}
</code>```

}

Here is my Adapter Cart

```<code>public class Adapter_chart extends RecyclerView.Adapter<ViewHolder_chart> {
private static final String TAG ="Adapater_chart" ;
ArrayList<Chart_getter_setter> _chartdata;
Context context;
FragmentManager fragmentManager;
String total = "";

public Adapter_chart(Context context, FragmentManager fragmentManager,
    ArrayList<Chart_getter_setter> _chartdata) {
    this.context = context;
    this.fragmentManager = fragmentManager;
    this._chartdata = _chartdata;

    _chartdata = new ArrayList<>();
}

@NonNull
@Override
public ViewHolder_chart onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    View view = layoutInflater.inflate(R.layout.chart_single_item, viewGroup, false);
    ViewHolder_chart viewHolder = new ViewHolder_chart(view);
    return viewHolder;

}

@Override
public void onBindViewHolder(@NonNull final ViewHolder_chart viewHolder_chart, final int i) {

    viewHolder_chart.p_name_CHART_tv.setText(_chartdata.get(i).getName_prdct()); // set name of product
    //Replace these two methods
    viewHolder_chart.p_price_CHART_tv.setText(_chartdata.get(i).getPrice_prdct());  // set quantity
    viewHolder_chart.p_quantity_Chart_tv.setText(_chartdata.get(i).getUnit_prdct());  // set price
    ////////////////////////////////
    viewHolder_chart.p_totalITem_CHART_tv.setText(_chartdata.get(i).getTotal_quantity());

    Log.d("Adapter_chart", "bitmap=" + _chartdata.get(i).getImage_prdct());
    //viewHolder_chart.p_img_CHART.setImageBitmap(_chartdata.get(i).getImage_prdct());
    Picasso.get().load(_chartdata.get(i).getImage_prdct()).placeholder(R.drawable.no_image_find).into(viewHolder_chart.p_img_CHART);

    viewHolder_chart.p_add_CHART_tv.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Add button is pressed");
            int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());

            count_value++;
            viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));

            String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
            String prdct_name= (String) _chartdata.get(i).getName_prdct();
            UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

        }
    });
    viewHolder_chart.p_remove_CHART_tv.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());
            count_value--;
            if (count_value<1)
            {
                Log.d(TAG,"Remove button is pressed");

                String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
                delete_record(name_prdct,context);
                _chartdata.remove(i);
                notifyDataSetChanged();

            }else {
                viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));
                String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
                String prdct_name= (String) _chartdata.get(i).getName_prdct();
                UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

            }
        }

    viewHolder_chart.item_remove_imageview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
            delete_record(name_prdct,context);
            _chartdata.remove(i);
            notifyDataSetChanged();
        }

    });
}
@Override
public int getItemCount() {

    return _chartdata.size();
}
</code>```

}

https://i.stack.imgur.com/FMEcN.jpg

答:
SQLite replace statement is for you.

REPLACE INTO table_name ( col1, col2 ) VALUES ( val1, val2 );

Replace will either
-- insert into db if not exist
-- update db if already exist

Body:
first of all i'm describing some explanation about my question,
i have two fragments name as "Main Fragment" and second one is " Cart Fragment"

1==> Main Fragment- Contains recyclerview in which data comes from firestore and set in recyclerview, when user click on add or remove button then data is entered and update in sqlite.

2==> Cart Fragment- Contains recyclerview in which data comes from SQLITE and set in recycelerview.

My Question is when i navigate from cart fragment to Main Fragment then First check that any item is already saved in sqlite or not, if exist then get total item quantity from cart fragment of that item(including other data like name, price etc.) and set in main fragmnet.

Here code for Main Fragment Adapter

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.TV_OFF.setText(_mylistdata.get(position).getDiscount()+"% OFF");
   //"Rs "+
    holder.TV_CURNT_PRICE.setText(_mylistdata.get(position).getCurr_price());
    holder.TV_OLD_PRICE.setText(_mylistdata.get(position).getOld_price());
    holder.TV_NAME.setText(_mylistdata.get(position).getName());
    holder.TV_OFFER_DES.setText(_mylistdata.get(position).getOffers_des());
    holder.TV_UNIT.setText(_mylistdata.get(position).getUnit_products()+" Unit");
    Picasso.get().load(_mylistdata.get(position).getImgId()).placeholder(R.drawable.no_image_find).into(holder.imageView);

    holder.add_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Toast.makeText(context, "pos="+prd_id, Toast.LENGTH_SHORT).show();
            holder.add_btn.setVisibility(View.GONE);
            holder.TV_REMOVEITEM.setVisibility(View.VISIBLE);
            holder.TV_TOTALITEM.setVisibility(View.VISIBLE);
            holder.TV_ADDITEM.setVisibility(View.VISIBLE);
            count_value=1;

            holder.TV_TOTALITEM.setText(Integer.toString(count_value));
            // get data from views
            getDataFromViews(position);
            total_qty_pro= (String) holder.TV_TOTALITEM.getText();
            //qty_pro=_mylistdata.get(position).getUnit_products();
            qty_new=qty_pro+" Unit";
            saveData_To_SQLITE(new_name,qty_new,price_pro,price_old,total_qty_pro,image_id,context);

        }

    });
    holder.TV_REMOVEITEM.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {

            //productId= (int) getItemId(position);
            count_value--;
            if (count_value<1)
            {
                Log.d(TAG,"Remove button is pressed");
                holder.add_btn.setVisibility(View.VISIBLE);
                holder.TV_REMOVEITEM.setVisibility(View.GONE);
                holder.TV_TOTALITEM.setVisibility(View.GONE);
                holder.TV_ADDITEM.setVisibility(View.GONE);
                count_value=1;

                String prdct_name= _mylistdata.get(position).getName();

                delete_record(prdct_name,context);

            }else {
                //Data_parsing.setCountText(count_value);
                holder.TV_TOTALITEM.setText(Integer.toString(count_value));

                total_qty_pro= (String) holder.TV_TOTALITEM.getText();
                String prdct_name= _mylistdata.get(position).getName();

                UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

            }

        }
    });
    holder.TV_ADDITEM.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Add button is pressed");
            count_value++;
            //Data_parsing.setCountText(count_value);
            holder.TV_TOTALITEM.setText(Integer.toString(count_value));

            total_qty_pro= (String) holder.TV_TOTALITEM.getText();
            String prdct_name= _mylistdata.get(position).getName();
            UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);
        }

    });
}

Here is my SQLite class in which i define my static methods for saving, updating and delete my data from sqlite

public class SQLITE_RUD {

// Save data to sqlite
public static void  saveData_To_SQLITE(String name_pro, String qty_pro, String price_pro,String price_old, String total_qty_pro, String image_id, Context context) {
    DBAdapter db = new DBAdapter(context);
    db.openDB();
    long result =  db.add(name_pro, qty_pro, price_pro,price_old, total_qty_pro, image_id);
    if (result > 0) {
        Toast.makeText(context, "Data is saved succeffuly", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(context, "Unable to save", Toast.LENGTH_SHORT).show();
    }
    db.closeDB();
}

// update data in sqlite

public static void UPDATE_SQL_DATA(String p_name, String total_qty_pro, Context context)
{
    DBAdapter db=new DBAdapter(context);
    db.openDB();
    try {
        long result=db.update_DB(p_name,total_qty_pro);
        if(result>0)
        {
            Toast.makeText(context, "Updated Sucesfully", Toast.LENGTH_SHORT).show();
        }else
        {
            Toast.makeText(context, "Unable to update", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
    {
        Log.d("MyListAdapter","error_update="+e);
    }
    db.closeDB();
}
// Delete data from SQlite
public static void delete_record(String prdct_name,Context context) {
    //
    DBAdapter db=new DBAdapter(context);
    db.openDB();
    try {
        long result=db.Delete_DB(prdct_name);
        if(result>0)
        {
            Toast.makeText(context, "Deleted Sucesfully", Toast.LENGTH_SHORT).show();
        }else
        {
            Toast.makeText(context, "Unable to Delete", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e)
    {
        Log.d("MyListAdapter","error_delete="+e);
    }
    db.closeDB();
}

}

Here i create class name ad DBAdapter in which i define methods for saving, updating, and retriving quires.

public class DBAdapter {
Context c;
SQLiteDatabase db;
DbHelper database_helper;   // on create and on upgrade is defined

public DBAdapter(Context c) {
    this.c = c;
    database_helper=new DbHelper(c);

}

//OPEN DB
public void openDB()
{
    try {
        db=database_helper.getWritableDatabase();
        db=database_helper.getReadableDatabase();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//CLOSE DB
public void closeDB()
{
    try {
        database_helper.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//INSERT/SAVE
public long add(String P_name,String P_qty,String P_price,String P_OldPrice,String P_Total_qty, String P_Image)
{
    try {
        ContentValues cv=new ContentValues();
        // cv.put(KEY_ItemID, P_id);
        cv.put(KEY_ProductName, P_name);
        cv.put(KEY_ProductQuantity, P_qty);
        cv.put(KEY_ProductPrice, P_price);
        cv.put(KEY_OldPrice, P_OldPrice);
        cv.put(KEY_ProductTotal, P_Total_qty);
        cv.put(KEY_ProductImage,P_Image);
        return db.insert(Table_name, KEY_RowID, cv);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
public long update_DB(String name_prdct, String prdct_TOTAL_QTY)
{
    try
    {
        ContentValues cv=new ContentValues();
        cv.put(KEY_ProductTotal,prdct_TOTAL_QTY);
        return db.update(Table_name,cv,KEY_ProductName +" =?",new String[]{String.valueOf(name_prdct)});
        //return;
    }catch (SQLException e)
    {
        e.printStackTrace();
    }

    return 0;
}

//DELETE
public long Delete_DB(String prdct_name)
{
    try
    {
        return db.delete(Table_name,KEY_ProductName+" =?",new String[]{String.valueOf(prdct_name)});

    }catch (SQLException e)
    {
        e.printStackTrace();
    }

    return 0;
}

//SELECT/RETRIEVE
public Cursor retrieve() {
    String[] columns = {KEY_RowID,KEY_ProductName,KEY_ProductQuantity, KEY_ProductPrice,KEY_OldPrice, KEY_ProductTotal, KEY_ProductImage};
    return db.query(Constants.Table_name, columns, null, null, null, null, null);
}

}

Here is my Cart Fragment

public class CartFragment extends Fragment {
private static final String Tag ="CartFragment" ;
FragmentManager fragmentManager;
RecyclerView recyclerView;
RelativeLayout proceedBtn;
TextView finalprice_bottom, finalprice_upper;
Adapter_chart adapter;
View view;
ArrayList<Chart_getter_setter> chartGetterSetters = new ArrayList<>();

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                         final Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view= inflater.inflate(R.layout.fragment_cart, container, false);
    recyclerView = view.findViewById(R.id.chart_recyclerview);
    proceedBtn=view.findViewById(R.id.bottomChart);

    finalprice_upper=view.findViewById(R.id.price);
    finalprice_bottom =view.findViewById(R.id.FinalPrice_TV);
    proceedBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(savedInstanceState==null) {
                getFragmentManager().beginTransaction().replace(R.id.fragment_container, ProceedFragment.newInstance()).addToBackStack(null).commit();
            }
        }
    });

    adapter = new Adapter_chart(getActivity(), fragmentManager, chartGetterSetters);

    recyclerView.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false);
    recyclerView.setLayoutManager(layoutManager);

    //RETRIEVE
    retrieve_data();

    getActivity().setTitle("Final chart");

    return view;
}
private void retrieve_data() {
    DBAdapter db = new DBAdapter(getContext());
    db.openDB();
    chartGetterSetters.clear();
    //RETRIEVE
    Cursor c = db.retrieve();
    while (c.moveToNext())
    {
        int index_id=c.getColumnIndex(Constants.KEY_RowID);
        int index_name=c.getColumnIndex(Constants.KEY_ProductName);
        int index_qty=c.getColumnIndex(Constants.KEY_ProductQuantity);
        int index_price=c.getColumnIndex(Constants.KEY_ProductPrice);
        int index_oldprice=c.getColumnIndex(Constants.KEY_OldPrice);
        int index_total=c.getColumnIndex(Constants.KEY_ProductTotal);
        int index_image=c.getColumnIndex(Constants.KEY_ProductImage);

        int id=c.getInt(index_id);
        String name=c.getString(index_name);
        String qty=c.getString(index_qty);
        String price=c.getString(index_price);
        String oldPrice=c.getString(index_oldprice);
        String total=c.getString(index_total);
        String IMAGE=c.getString(index_image);

        Chart_getter_setter p=new Chart_getter_setter(name,qty,price,oldPrice,total,IMAGE);
        //ADD TO ARRAYLIS
        chartGetterSetters.add(p);

        //CHECK IF ARRAYLIST ISNT EMPTY

        if(chartGetterSetters.size()>0)
        {
            int totalPrice = 0;
            int total_qty=0;
            for(int j = 0 ; j < chartGetterSetters.size(); j++) {

                totalPrice += Integer.parseInt(chartGetterSetters.get(j).getPrice_prdct())*Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity()) ;
                total_qty += Integer.parseInt(chartGetterSetters.get(j).getTotal_quantity());
            }
            String tProice=String.valueOf(totalPrice);
            finalprice_upper.setText("Rs "+tProice);
            finalprice_bottom.setText(String.valueOf(total_qty));//totelPriceTV.setText(tProice);
            recyclerView.setAdapter(adapter);

        }
    }
}

}

Here is my Adapter Cart

public class Adapter_chart extends RecyclerView.Adapter<ViewHolder_chart> {
private static final String TAG ="Adapater_chart" ;
ArrayList<Chart_getter_setter> _chartdata;
Context context;
FragmentManager fragmentManager;
String total = "";

public Adapter_chart(Context context, FragmentManager fragmentManager,
    ArrayList<Chart_getter_setter> _chartdata) {
    this.context = context;
    this.fragmentManager = fragmentManager;
    this._chartdata = _chartdata;

    _chartdata = new ArrayList<>();
}

@NonNull
@Override
public ViewHolder_chart onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    View view = layoutInflater.inflate(R.layout.chart_single_item, viewGroup, false);
    ViewHolder_chart viewHolder = new ViewHolder_chart(view);
    return viewHolder;

}

@Override
public void onBindViewHolder(@NonNull final ViewHolder_chart viewHolder_chart, final int i) {

    viewHolder_chart.p_name_CHART_tv.setText(_chartdata.get(i).getName_prdct()); // set name of product
    //Replace these two methods
    viewHolder_chart.p_price_CHART_tv.setText(_chartdata.get(i).getPrice_prdct());  // set quantity
    viewHolder_chart.p_quantity_Chart_tv.setText(_chartdata.get(i).getUnit_prdct());  // set price
    ////////////////////////////////
    viewHolder_chart.p_totalITem_CHART_tv.setText(_chartdata.get(i).getTotal_quantity());

    Log.d("Adapter_chart", "bitmap=" + _chartdata.get(i).getImage_prdct());
    //viewHolder_chart.p_img_CHART.setImageBitmap(_chartdata.get(i).getImage_prdct());
    Picasso.get().load(_chartdata.get(i).getImage_prdct()).placeholder(R.drawable.no_image_find).into(viewHolder_chart.p_img_CHART);

    viewHolder_chart.p_add_CHART_tv.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Add button is pressed");
            int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());

            count_value++;
            viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));

            String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
            String prdct_name= (String) _chartdata.get(i).getName_prdct();
            UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

        }
    });
    viewHolder_chart.p_remove_CHART_tv.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            int count_value= Integer.parseInt((String) viewHolder_chart.p_totalITem_CHART_tv.getText());
            count_value--;
            if (count_value<1)
            {
                Log.d(TAG,"Remove button is pressed");

                String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
                delete_record(name_prdct,context);
                _chartdata.remove(i);
                notifyDataSetChanged();

            }else {
                viewHolder_chart.p_totalITem_CHART_tv.setText(Integer.toString(count_value));
                String total_qty_pro= (String) viewHolder_chart.p_totalITem_CHART_tv.getText();
                String prdct_name= (String) _chartdata.get(i).getName_prdct();
                UPDATE_SQL_DATA(prdct_name,total_qty_pro,context);

            }
        }

    viewHolder_chart.item_remove_imageview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name_prdct= (String) viewHolder_chart.p_name_CHART_tv.getText();
            delete_record(name_prdct,context);
            _chartdata.remove(i);
            notifyDataSetChanged();
        }

    });
}
@Override
public int getItemCount() {

    return _chartdata.size();
}

}

https://i.stack.imgur.com/FMEcN.jpg


问:
git clone trailing slash
I would just like to understand the significance of a trailing slash with git clone, especially as only the one without a trailing slash seems to work (for a colleague both seem fine).

```<code>$ git clone https://github.com/bazelbuild/examples/
Cloning into 'examples'...
ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

$ git clone https://github.com/bazelbuild/examples
Cloning into 'examples'...
remote: Enumerating objects: 979, done.
remote: Total 979 (delta 0), reused 0 (delta 0), pack-reused 979
Receiving objects: 100% (979/979), 326.45 KiB | 2.61 MiB/s, done.
Resolving deltas: 100% (330/330), done.

$ git --version
git version 2.21.0
</code>```

答:
Ok, figured out the issue I had added
git config --global url."git@github.com:".insteadOf "https://github.com/" to my gitconfig a while back...

Title: git clone trailing slash

Body:
I would just like to understand the significance of a trailing slash with git clone, especially as only the one without a trailing slash seems to work (for a colleague both seem fine).

$ git clone https://github.com/bazelbuild/examples/
Cloning into 'examples'...
ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

$ git clone https://github.com/bazelbuild/examples
Cloning into 'examples'...
remote: Enumerating objects: 979, done.
remote: Total 979 (delta 0), reused 0 (delta 0), pack-reused 979
Receiving objects: 100% (979/979), 326.45 KiB | 2.61 MiB/s, done.
Resolving deltas: 100% (330/330), done.

$ git --version
git version 2.21.0


问:
How To write an SQL query to return all "historical records" for TODAY'S DATE (month and day) for EVERY YEAR in the DB?
I've been using Visual Studio, C#, and SQL Server for 8 months now and have created a very functional personal project as I've been learning.  But, there one bit of functionality I want in my program that I cannot get to work--automatically, that is.

If I type THIS into the button click event, run the program, and click the History button, it works perfectly.  All seven columns of information go to the datagridview perfectly.

```<code>SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-05-27' ORDER BY DATE DESC; ", conn);
</code>```

However, what is not awesome is that I want to write the query so that I can push a button ("History") that will return information from MAY 27 (or whatever today's date actually is) of EVERY YEAR, and I just can't figure out how to do it.  It is a "Happened On This Day In History" list.

Obviously, I need to keep SELECT * FROM AllConcertList WHERE Date...  Somehow I need to include GETDATE() otherwise how would the program know  to start with 05-27?  But then I feel I need to include DATEFROMPARTS because I only really want Month and Day to be static to whatever the actual date (today) is.  It must be a subquery in there somehow.

答:
You should be able to use with simple month() and day() functions based on whatever the system's GETDATE() value is.  Is this what you are looking for?

```<code>select
      ACL.*
   from
      AllConcertList ACL
   where
          month( ACL.Date ) = month( getdate())
      and day( ACL.Date ) = day( getdate())
   order by
      ACL.Date desc
</code>```

No Parameters, no sql-injection

Body:
I've been using Visual Studio, C#, and SQL Server for 8 months now and have created a very functional personal project as I've been learning.  But, there one bit of functionality I want in my program that I cannot get to work--automatically, that is.

If I type THIS into the button click event, run the program, and click the History button, it works perfectly.  All seven columns of information go to the datagridview perfectly.

SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AllConcertList WHERE Date LIKE '%%%%-05-27' ORDER BY DATE DESC; ", conn);

However, what is not awesome is that I want to write the query so that I can push a button ("History") that will return information from MAY 27 (or whatever today's date actually is) of EVERY YEAR, and I just can't figure out how to do it.  It is a "Happened On This Day In History" list.

Obviously, I need to keep SELECT * FROM AllConcertList WHERE Date...  Somehow I need to include GETDATE() otherwise how would the program know  to start with 05-27?  But then I feel I need to include DATEFROMPARTS because I only really want Month and Day to be static to whatever the actual date (today) is.  It must be a subquery in there somehow.

Body:
You should be able to use with simple month() and day() functions based on whatever the system's GETDATE() value is.  Is this what you are looking for?

select
      ACL.*
   from
      AllConcertList ACL
   where
          month( ACL.Date ) = month( getdate())
      and day( ACL.Date ) = day( getdate())
   order by
      ACL.Date desc

No Parameters, no sql-injection


问:
How to correctly use dependency Injection with .Net Core SignalR
I'm learning .Net Core SignalR and investigating how I could use it with my app live charts. I play with some examples on the net and they all work, but I don't know how to use SignalR with database polling. I'm getting below error:

Cannot access a disposed object ...

I'm assuming it is related to my contex is being disposed after request is completed. I'm using dependency injection.

ChatController

```<code>public class ChatController : ControllerBase
{
    private IChatService _chatService;
    private IChatContext<ChatHub> _hub;

    public ChatController(IChatContext<ChatHub> hub, IChatService chatService)
    {
        _hub = hub;
        _chatService = chatService;
    }
    public IActionResult Get()
    {
        var timerManager = new TimerManager(() => _hub.Clients.All.SendAsync("transferchatdata", _chatService.ChatDataByProds()));

        return Ok(new { Message = "Request Completed" });
    }
}
</code>```

ChatService

```<code>public interface IChatService
{
    IEnumerable<ChatDataByProd> ChatDataByProds();
}

public class ChatService : IChatService
{
    private ChatContext _context;

    public ChatService(ChatContext  context)
    {
        _context = context;
    }

    public IEnumerable<ChatDataByProd> ChatDataByProds()
    {
       return _context.ChatDataByProds;
    }
}
</code>```

ChatHub

```<code>    public class ChatHub : Hub
{
}
</code>```

答:
It seems that you are using a EF Core context that is a scoped lifetime service, which means per-request lifetime in ASP.NET Core. Your ChatService must have a longer lifetime than a HTTP request, and a single instance of the database context would be disposed by the container while you are still holding the reference to it.

Thus, you need to obtain an IServiceProvider container in the ctor of ChatService, and GetService the database context each time when you need to access the database.

Body:
I'm learning .Net Core SignalR and investigating how I could use it with my app live charts. I play with some examples on the net and they all work, but I don't know how to use SignalR with database polling. I'm getting below error:

Cannot access a disposed object ...

I'm assuming it is related to my contex is being disposed after request is completed. I'm using dependency injection.

ChatController

public class ChatController : ControllerBase
{
    private IChatService _chatService;
    private IChatContext<ChatHub> _hub;

    public ChatController(IChatContext<ChatHub> hub, IChatService chatService)
    {
        _hub = hub;
        _chatService = chatService;
    }
    public IActionResult Get()
    {
        var timerManager = new TimerManager(() => _hub.Clients.All.SendAsync("transferchatdata", _chatService.ChatDataByProds()));

        return Ok(new { Message = "Request Completed" });
    }
}

ChatService

public interface IChatService
{
    IEnumerable<ChatDataByProd> ChatDataByProds();
}

public class ChatService : IChatService
{
    private ChatContext _context;

    public ChatService(ChatContext  context)
    {
        _context = context;
    }

    public IEnumerable<ChatDataByProd> ChatDataByProds()
    {
       return _context.ChatDataByProds;
    }
}

ChatHub

    public class ChatHub : Hub
{
}


答:
As always, you can do that with window functions:</p>

```<code>WITH tbl (active_dates) AS
         (
             VALUES
                    ('["2015-05-21","2018-10-01")'::TSRANGE),
                    ('["2016-08-13","2018-09-01")'::TSRANGE),
                    ('["2019-03-01","2019-05-01")'::TSRANGE)
         ),
   /* get all time points where something changes */
   points AS (
       SELECT upper(active_dates) AS p
       FROM tbl
       UNION SELECT lower(active_dates)
       FROM tbl
   ),
   /*
    * Get all date ranges between these time points.
    * The first time range will start with NULL,
    * but that will be excluded in the next CTE anyway.
    */
   inter AS (
      SELECT tsrange(
                lag(p) OVER (ORDER BY p),
                p
             ) i
      FROM points
   )
/*
 * Get all date ranges that are contained
 * in at least one of the intervals.
 */
SELECT DISTINCT i
FROM inter
   CROSS JOIN tbl
WHERE i <@ active_dates
ORDER BY i;
</code>```

Title: Query for distinct set of non-overlapping ranges in PostgreSQL

Body:
Given a column of overlapping and/or discontinuous ranges:

WITH tbl (active_dates) AS
         (
             VALUES
                    ('["2015-05-21","2018-10-01")'::TSRANGE),
                    ('["2016-08-13","2018-09-01")'::TSRANGE),
                    ('["2019-03-01","2019-05-01")'::TSRANGE)
         )
SELECT *
FROM tbl;

How can we generate an output that identifies all the discrete time periods  like so:

active_dates
------------
["2015-05-21 00:00:00","2016-08-13 00:00:00")
["2016-08-13 00:00:00","2018-09-01 00:00:00")
["2018-09-01 00:00:00","2018-10-01 00:00:00")
["2019-03-01 00:00:00","2018-05-01 00:00:00")

Body:
As always, you can do that with window functions:

WITH tbl (active_dates) AS
         (
             VALUES
                    ('["2015-05-21","2018-10-01")'::TSRANGE),
                    ('["2016-08-13","2018-09-01")'::TSRANGE),
                    ('["2019-03-01","2019-05-01")'::TSRANGE)
         ),
   /* get all time points where something changes */
   points AS (
       SELECT upper(active_dates) AS p
       FROM tbl
       UNION SELECT lower(active_dates)
       FROM tbl
   ),
   /*
    * Get all date ranges between these time points.
    * The first time range will start with NULL,
    * but that will be excluded in the next CTE anyway.
    */
   inter AS (
      SELECT tsrange(
                lag(p) OVER (ORDER BY p),
                p
             ) i
      FROM points
   )
/*
 * Get all date ranges that are contained
 * in at least one of the intervals.
 */
SELECT DISTINCT i
FROM inter
   CROSS JOIN tbl
WHERE i <@ active_dates
ORDER BY i;


问:
If a function is called more than million times in a second, print an error
There is a function in a class if it is called more than one million times in a second we need to print an error. It is basically a design question of what approach we should use.

I am thinking of using a time counter and a count variable. The time counter would reset the count variable whenever its value gets above one million or after every second.

答:
If you get 900K calls in 0.1 seconds, and then the counter gets reset by timer, and then you get another 900K calls in 0.1 seconds, then you will have gotten 1.8M calls in a second, but you will fail to print an error.

I would do something like this:

Every 100K calls, read the clock and store the time in a circular buffer

Keep 10 times in the buffer, so after at least 1M calls, then whenever you add a new time, it replaces one from 1M calls earlier.  If the difference between these times is less than 1 second, then you should print an error.

In the worst case you could still get up to 1.1M calls in a second without raising an error, but it's probably close enough.  You can use more buffer slots and smaller batches if you need more precision.


问:
Connecting to elasticsearch cluster in NEST
Let's assume I have several elasticsearch machines in a cluster: 192.168.1.1, 192.168.1.2 and 192.168.1.3

Any of the machines can go down. It doesn't look like NEST supports providing a range of IPs to try to connect.

So how do I make sure I connect to any of the available machines from Nest? Just try to open connection to one, if TryConnect didn't work, try another?

答:
Since you have a small set of nodes, you can use a StaticConnectionPool:

```<code>var uri1 = new Uri("192.168.1.1");
var uri2 = new Uri("192.168.1.2");
var uri3 = new Uri("192.168.1.3");
var uris = new List<Uri> { uri1, uri2, uri3 };
var connectionPool = new StaticConnectionPool(uris);
var connectionSettings = new ConnectionSettings(connectionPool); // <-- need to be reused
var client = new ElasticClient(connectionSettings);
</code>```

An important point to keep in mind is to reuse the same ConnectionSetting when creating a new elastic client, since elasticsearch cache is per ConnectionSetting. See this GitHub post:

...In any case its important to share the same ConnectionSettings
  instance across any elastic client you instantiate. ElasticClient can
  be a singleton or not as long as each instance shares the same
  ConnectionSettings instance.

All of our caches are per ConnectionSettings, this includes
  serialization caches.

Also a single ConnectionSettings holds a single IConnectionPool and
  IConnection something you definitely want to reuse across requests.

Body:
Since you have a small set of nodes, you can use a StaticConnectionPool:

var uri1 = new Uri("192.168.1.1");
var uri2 = new Uri("192.168.1.2");
var uri3 = new Uri("192.168.1.3");
var uris = new List<Uri> { uri1, uri2, uri3 };
var connectionPool = new StaticConnectionPool(uris);
var connectionSettings = new ConnectionSettings(connectionPool); // <-- need to be reused
var client = new ElasticClient(connectionSettings);

An important point to keep in mind is to reuse the same ConnectionSetting when creating a new elastic client, since elasticsearch cache is per ConnectionSetting. See this GitHub post:

...In any case its important to share the same ConnectionSettings
  instance across any elastic client you instantiate. ElasticClient can
  be a singleton or not as long as each instance shares the same
  ConnectionSettings instance.

All of our caches are per ConnectionSettings, this includes
  serialization caches.

Also a single ConnectionSettings holds a single IConnectionPool and
  IConnection something you definitely want to reuse across requests.


问:
Android: UnitTest
Need some advice. I have an App. And I need do write some UnitTest. But I really don't know what to test. I already test Settings and all preferences, that's easy. What else usually people test ? Lets say that I have 3 Activities. Main one is list activity, when you click on list item its forward you on a second List Activity...and on list item click its forward you on third Activity. I think maybe I should test the switching between activities ? How to simulate click on list item in UnitTest and how to check that activity was open or not ? Thanks !</p>

答:
For Android applications there is a  tool for testing called Robotium. It is a UI testing tool which simulates touching, clicks, typing, and other users' actions relevant for Android applications.Try this example for Robotium and can develop for your apps,

Robotium example pdf

i think this may be little bit useful to your search.

Title: Android: UnitTest