问:
Read text on card
I'm trying to read some text on a pokemon card using python opencv module. I want to read the title and the bottom right numbers.
RIght now i wrote the code for read the bottm right numbers but it is not working.

For 'it isn't working' I mean the the text is not being detected, so instead of the numbers 77/127 an empty string is printed, not that this code throws errors.

This is the card

This is what i do:

Read the card and convert it to grayscale

```<code>import cv2
import numpy as np
import pytesseract
from PIL import Image

frame = cv2.imread("./images/1.jpg")
imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
</code>```

Get the outer contour and resize the image

```<code>edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        # find the biggest countour (c) by the area
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        # draw the biggest contour (c) in green
        # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (450, 600), interpolation=cv2.INTER_AREA)
</code>```

Cut the bottom right corner

```<code>height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[560: 600, 300: 450]
</code>```

Read the bottom corner text with pytesseract ocr

```<code>gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_)
</code>```

Final code

```<code>import cv2
import numpy as np
import pytesseract
from PIL import Image

frame = cv2.imread("./images/1.jpg")
imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        # find the biggest countour (c) by the area
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        # draw the biggest contour (c) in green
        # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (450, 600), interpolation=cv2.INTER_AREA)
height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[560: 600, 300: 450]
gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
cv2.waitKey(0)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_)
print("Text: ", text)

</code>```

答:
It very much depends on the right crop, upsampling, and whitelisting.

I managed to get the text recognized in your code by upsampling, a bit tighter crop and whitelisting characters

Additional tools if a small crop is not possible that help in this task are

Crop: A more accurate crop in the target area

Using psm mode 6: Assume a single uniform block of text.

Upscale: Using resize

Threshold

Denoising: Your sample image is noisy in the area

Whitelisting: Only the possible characters (numbers and "/" ) are evaluated

Upscaling, Threshold, Denoising and Whitelisting are optional if the crop is accurate enough

A small enough crop will lead to the characters being recognized correctly

Using all methods, the pre-processed picture to be scanned:

The minimum code to extract the searched text 77/127 from your sample image:

```<code>import cv2
import pytesseract
from PIL import Image

image = cv2.imread('card.jpg', 0)
x,y,w,h = 379, 634, 38, 13
image = image[y:y+h,x:x+w]
#image = cv2.resize(image, (200, 60))
#image = cv2.fastNlMeansDenoising(image,h=3,templateWindowSize =7,searchWindowSize=21)
#image = 255 - cv2.threshold(image, 170, 255,cv2.ADAPTIVE_THRESH_MEAN_C)[1]

data = pytesseract.image_to_string(image,config='--psm 6 -c tessedit_char_whitelist=0123456789/ ')
cv2.imshow('image', image)
cv2.waitKey()
print(f"TEXT: {data}")

OUT: TEXT: 77/127
</code>```

If you want to stick with your code, the key is setting a threshold, resizing, whitelisting characters and the crop:

```<code>frame = cv2.imread("card.jpg")
frame = 255 - cv2.threshold(frame, 180, 255,cv2.ADAPTIVE_THRESH_MEAN_C)[1]

imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (900, 1200), interpolation=cv2.INTER_AREA)
height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[1100: 1200, 700: 820]
gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
cv2.waitKey(0)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_,config=' -c tessedit_char_whitelist=0123456789/')
print("Text: ", text)

OUT: TEXT: 77/127
</code>```

Title: Read text on card

Body:
I'm trying to read some text on a pokemon card using python opencv module. I want to read the title and the bottom right numbers.
RIght now i wrote the code for read the bottm right numbers but it is not working.

For 'it isn't working' I mean the the text is not being detected, so instead of the numbers 77/127 an empty string is printed, not that this code throws errors.

This is the card

This is what i do:

Read the card and convert it to grayscale

import cv2
import numpy as np
import pytesseract
from PIL import Image

frame = cv2.imread("./images/1.jpg")
imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

Get the outer contour and resize the image

edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        # find the biggest countour (c) by the area
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        # draw the biggest contour (c) in green
        # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (450, 600), interpolation=cv2.INTER_AREA)

Cut the bottom right corner

height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[560: 600, 300: 450]

Read the bottom corner text with pytesseract ocr

gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_)

Final code

import cv2
import numpy as np
import pytesseract
from PIL import Image

frame = cv2.imread("./images/1.jpg")
imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        # find the biggest countour (c) by the area
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        # draw the biggest contour (c) in green
        # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (450, 600), interpolation=cv2.INTER_AREA)
height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[560: 600, 300: 450]
gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
cv2.waitKey(0)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_)
print("Text: ", text)

Body:
It very much depends on the right crop, upsampling, and whitelisting.

I managed to get the text recognized in your code by upsampling, a bit tighter crop and whitelisting characters

Additional tools if a small crop is not possible that help in this task are

Crop: A more accurate crop in the target area

Using psm mode 6: Assume a single uniform block of text.

Upscale: Using resize

Threshold

Denoising: Your sample image is noisy in the area

Whitelisting: Only the possible characters (numbers and "/" ) are evaluated

Upscaling, Threshold, Denoising and Whitelisting are optional if the crop is accurate enough

A small enough crop will lead to the characters being recognized correctly

Using all methods, the pre-processed picture to be scanned:

The minimum code to extract the searched text 77/127 from your sample image:

import cv2
import pytesseract
from PIL import Image

image = cv2.imread('card.jpg', 0)
x,y,w,h = 379, 634, 38, 13
image = image[y:y+h,x:x+w]
#image = cv2.resize(image, (200, 60))
#image = cv2.fastNlMeansDenoising(image,h=3,templateWindowSize =7,searchWindowSize=21)
#image = 255 - cv2.threshold(image, 170, 255,cv2.ADAPTIVE_THRESH_MEAN_C)[1]

data = pytesseract.image_to_string(image,config='--psm 6 -c tessedit_char_whitelist=0123456789/ ')
cv2.imshow('image', image)
cv2.waitKey()
print(f"TEXT: {data}")

OUT: TEXT: 77/127

If you want to stick with your code, the key is setting a threshold, resizing, whitelisting characters and the crop:

frame = cv2.imread("card.jpg")
frame = 255 - cv2.threshold(frame, 180, 255,cv2.ADAPTIVE_THRESH_MEAN_C)[1]

imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(imgray, 30, 200)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
        c = max(contours, key=cv2.contourArea)
        x, y, w, h = cv2.boundingRect(c)
        crop_frame = frame[y: y + h, x: x + w]
        crop_frame = cv2.resize(crop_frame, (900, 1200), interpolation=cv2.INTER_AREA)
height, width, channels = crop_frame.shape
bottom_right_corner = crop_frame[1100: 1200, 700: 820]
gray = cv2.cvtColor(bottom_right_corner, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", gray)
cv2.waitKey(0)
image_ = Image.fromarray(gray)
text = pytesseract.image_to_string(image_,config=' -c tessedit_char_whitelist=0123456789/')
print("Text: ", text)

OUT: TEXT: 77/127


来源: stackexchange

问:
Laravel Pivot table id column
In Laravel and Eloquent you can use ManyToMany-Relations with a pivot table. The problem in my case is the automatic ID of the pivot row. Can I change how the ID is generated? I want to use UUIDs for that matter.

For other Objects you can just implement this behaviour in the Model, but there is no model for pivot objects.

Did I miss something?

答: Be careful here : id on a pivot table can cause confusion when doing a join, as it will end up on the same row as joined table's id, and can cause fairly nasty bugs, as the latter will override the former. If you really need one, at least change its name.

ContentLicense: CC BY-SA 3.0

Title: Laravel Pivot table id column

ContentLicense: CC BY-SA 4.0


问:
Configuration binding extension 'system.serviceModel/bindings/basicHttpsBinding' could not be found
I am getting this error when I try to navigate to my .svc file.  It appears that it's not finding my basicHttpsBinding; here's that section of my web.config:

```<code><system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
</code>```

I tried searching through Google but any answers I could find didn't seem to apply to what I'm doing here.  Most of what I found talked about custom bindings, of which I don't think I have any.  I'm honestly not even close to sure what could be causing this error, so any help would be greatly appreciated.  If you need more information let me know and I'll add it.

答:
if you use framework 4.5 or up you can add below code to your web.config

The following attributes can be set on the  tag.

```<code>  <system.Web>
    <httpRuntime targetFramework="4.8" />
  </system.Web>
</code>```

Body:
I am getting this error when I try to navigate to my .svc file.  It appears that it's not finding my basicHttpsBinding; here's that section of my web.config:

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>

I tried searching through Google but any answers I could find didn't seem to apply to what I'm doing here.  Most of what I found talked about custom bindings, of which I don't think I have any.  I'm honestly not even close to sure what could be causing this error, so any help would be greatly appreciated.  If you need more information let me know and I'll add it.

Body:
if you use framework 4.5 or up you can add below code to your web.config

The following attributes can be set on the  tag.

  <system.Web>
    <httpRuntime targetFramework="4.8" />
  </system.Web>


问:
How to remove elements from a LinkedList in Java? How to set the first element to be the head of the Linked List in Java?
I'm learning Linked Lists, and I'm a bit confused by the Node that is created when the LinkedList is created in the first place. So I use an empty constructor just to create the List but it also creates the root node and sets "next" to "null", but then the initial value of "int data" is always "0", and I don't want that (if I do print details it prints the 0).

See the printing below the code, the initial 0 remains after new elements appear on the list. In fact, it continues to exist, which should not be the case.

Another thing, my remove function does not work, what is the issue?

```<code>public class LinkedList {
    Node root;//the beginning  - root element of type Node(check inner class below
    int size;//keeps track of the size of the list

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.prepend(234);
        linkedList.prepend(45);
        linkedList.prepend(33);
        linkedList.prepend(222);
        System.out.println("Root: " + linkedList.root);
        System.out.println(linkedList.printDetails());
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.remove(222);
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.find(33).setData(34);
        System.out.println(linkedList.printDetails());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.append(6565);
        linkedList.append(144);
        System.out.println("Root: " + linkedList.root.getData());
        System.out.println(linkedList.getSize());
        System.out.println(linkedList.printDetails());
    }

    public LinkedList() {
        root = new Node();
        size = 0;
    }

    public int getSize() {
        System.out.println("Size: " + size);
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public StringBuilder printDetails() {
        System.out.print("Linked List: ");
        StringBuilder details = new StringBuilder("[");
        Node currentNode = this.root;
        while (currentNode != null) {
            details.append(currentNode.getData()).append(",");
            currentNode = currentNode.getNext();
        }
        details.deleteCharAt(details.length() - 1);
        details.append("]");
        return details;
    }

    public void prepend(int data) {
        this.root = new Node(data, root);
        this.size++;
    }

    public void append(int data) {
        Node currentNode = this.root;
        Node newNode = new Node(data);
        while (currentNode.getNext() != null) {
            currentNode = currentNode.getNext();
        }
        currentNode.setNext(newNode);
        this.size++;
    }

    public Node find(int data) {
        Node currentNode = this.root;
        while (currentNode != null) {
            if (currentNode.getData() == data)
                return currentNode;
            currentNode = currentNode.getNext();
        }
        return null;
    }

    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = new Node();

        while (currentNode != null) {
            if (currentNode.getData() == data) {
                previousNode.setNext(currentNode.getNext());
                this.setSize(this.getSize() - 1);
                return;
            } else {
                previousNode = currentNode;
                currentNode = currentNode.getNext();
            }
        }
    }

    private static class Node {
        private int data;
        private Node next;

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getNext() {
            try {
                return next;
            } catch (NullPointerException e) {
                System.out.println((char[]) null);
            }
            return null;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        private Node() {
        }

        private Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }

        private Node(int data) {
            this.data = data;
        }
    }
}

</code>```

The printing:

```<code>Size: 0
0
Root: 0
Root: LinkedList$Node@548c4f57
Linked List: [222,33,45,234,0]
Size: 4
4
Root: 222
Size: 4
Root: 222
Linked List: [222,34,45,234,0]
Root: 222
Root: 222
Size: 5
5
Linked List: [222,34,45,234,0,6565,144]

</code>```

答:
Your remove method's implementation does not take into consideration that root element can be the one which you wan't to remove. Append this to the head of your remove method

  if (this.root.getData() == data) {
    this.root = this.root.getNext() != null
      ? this.root.getNext()
      : new Node();
  }
```

And about the fact that data is always initialized with 0. Im not sure if i understand the issue, what do you wan't it to be?

Body:
I'm learning Linked Lists, and I'm a bit confused by the Node that is created when the LinkedList is created in the first place. So I use an empty constructor just to create the List but it also creates the root node and sets "next" to "null", but then the initial value of "int data" is always "0", and I don't want that (if I do print details it prints the 0).

See the printing below the code, the initial 0 remains after new elements appear on the list. In fact, it continues to exist, which should not be the case.

Another thing, my remove function does not work, what is the issue?

public class LinkedList {
    Node root;//the beginning  - root element of type Node(check inner class below
    int size;//keeps track of the size of the list

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.prepend(234);
        linkedList.prepend(45);
        linkedList.prepend(33);
        linkedList.prepend(222);
        System.out.println("Root: " + linkedList.root);
        System.out.println(linkedList.printDetails());
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.remove(222);
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.find(33).setData(34);
        System.out.println(linkedList.printDetails());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.append(6565);
        linkedList.append(144);
        System.out.println("Root: " + linkedList.root.getData());
        System.out.println(linkedList.getSize());
        System.out.println(linkedList.printDetails());
    }

    public LinkedList() {
        root = new Node();
        size = 0;
    }

    public int getSize() {
        System.out.println("Size: " + size);
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public StringBuilder printDetails() {
        System.out.print("Linked List: ");
        StringBuilder details = new StringBuilder("[");
        Node currentNode = this.root;
        while (currentNode != null) {
            details.append(currentNode.getData()).append(",");
            currentNode = currentNode.getNext();
        }
        details.deleteCharAt(details.length() - 1);
        details.append("]");
        return details;
    }

    public void prepend(int data) {
        this.root = new Node(data, root);
        this.size++;
    }

    public void append(int data) {
        Node currentNode = this.root;
        Node newNode = new Node(data);
        while (currentNode.getNext() != null) {
            currentNode = currentNode.getNext();
        }
        currentNode.setNext(newNode);
        this.size++;
    }

    public Node find(int data) {
        Node currentNode = this.root;
        while (currentNode != null) {
            if (currentNode.getData() == data)
                return currentNode;
            currentNode = currentNode.getNext();
        }
        return null;
    }

    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = new Node();

        while (currentNode != null) {
            if (currentNode.getData() == data) {
                previousNode.setNext(currentNode.getNext());
                this.setSize(this.getSize() - 1);
                return;
            } else {
                previousNode = currentNode;
                currentNode = currentNode.getNext();
            }
        }
    }

    private static class Node {
        private int data;
        private Node next;

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getNext() {
            try {
                return next;
            } catch (NullPointerException e) {
                System.out.println((char[]) null);
            }
            return null;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        private Node() {
        }

        private Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }

        private Node(int data) {
            this.data = data;
        }
    }
}

The printing:

Size: 0
0
Root: 0
Root: LinkedList$Node@548c4f57
Linked List: [222,33,45,234,0]
Size: 4
4
Root: 222
Size: 4
Root: 222
Linked List: [222,34,45,234,0]
Root: 222
Root: 222
Size: 5
5
Linked List: [222,34,45,234,0,6565,144]

Body:
Your remove method's implementation does not take into consideration that root element can be the one which you wan't to remove. Append this to the head of your remove method

  if (this.root.getData() == data) {
    this.root = this.root.getNext() != null
      ? this.root.getNext()
      : new Node();
  }

And about the fact that data is always initialized with 0. Im not sure if i understand the issue, what do you wan't it to be?


问:
automatic differentiation vector-Jacobian products in linear time?
I'm new to the inner workings of automatic differentiation and came across some papers and slides that state that vector-Jacobian products can be computed in linear time using automatic differentiation. Specifically written:

```<code>$e^\top ( \frac{\partial f}{\partial x} )$
</code>```

can be computed for any e in O(N).
The Jacobian is N-by-N. I would think it's N^2, but I don't fully understand how automatic differentiation can reduce the time complexity.

答:
I don't fully understand how automatic differentiation can reduce the time complexity.

I'll assume you understand how backpropagation and/or reverse-mode automatic differentiation works for a scalar function y = f(x), where f : R^n -> R. Suppose computing f takes time O(1).

If you remember from backpropagation, you start by setting dy/dy = 1, then computing dy/dx using the chain rule. What you're doing here is you are computing the product of the vector [1.0] with the Jacobian, which is a row vector, to get the vector-Jacobian product which is a column vector. So you are computing the VJP, your vector is just a length-1 vector. You do this in time O(1).

Now suppose that I'm computing the derivative of a multivariate function y = f(x), where f : R^n -> R^m. Then the Jacobian is indeed m x n, and computing the full Jacobian with reverse mode AD would take time O(m). However, you can compute the vector-Jacobian product in time O(1) with a vector v by setting the values of dy_i/dy_i = v_i, for i={1,...,m}. Then you just backpropagate like normal, and get the VJP in a single backwards pass.

Body:
I'm new to the inner workings of automatic differentiation and came across some papers and slides that state that vector-Jacobian products can be computed in linear time using automatic differentiation. Specifically written:

$e^\top ( \frac{\partial f}{\partial x} )$

can be computed for any e in O(N).
The Jacobian is N-by-N. I would think it's N^2, but I don't fully understand how automatic differentiation can reduce the time complexity.


问:
Set AllowAutoRedirect false in existing HttpClient for just one request
This answer to the question on how to make HttpClient not follow redirects gives a solution to be set upon creating the actual client:

```<code>var handler = new HttpClientHandler { AllowAutoRedirect = false };
var client = new HttpClient(handler);
</code>```

The comment below the answer is my actual question:

Is it possible to do this on a per-request basis without needing two separate HttpClient instances (i.e. one that allows redirects and one that does not)?

I have a specific reason too for now wanting separate clients: I want the client to retain its cookies from earlier requests. I'm trying to do a few requests first that include valid redirects, but only the last one in the chain I don't want to be a redirect.

I've searched, and looked through the overloads of .GetAsync(url, ...), and looked through the properties and methods of HttpClient, but found no solution yet.

Is this possible?

答:
The question asks whether following redirects can be done on a case-by-case basis. While certainly useful for many common cases, I found the existing answers lacking in that regard.

The following implementation allows the decision on whether to follow a redirect or not to be configured on a true case-by-case basis via a predicate.
The solution is to override the SendAsync() method of HttpClientHandler.

```<code>using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace HttpClientCustomRedirectBehavior
{
    static class Program
    {
        private const string REDIRECTING_URL = "http://stackoverflow.com/";

        static async Task Main(string[] args)
        {
            HttpMessageHandler followRedirectAlwaysHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => true);
            HttpMessageHandler followRedirectOnlyToSpecificHostHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => response.Headers.Location.Host == "example.com");

            HttpResponseMessage response;
            using (HttpClient followRedirectAlwaysHttpClient = new HttpClient(followRedirectAlwaysHandler))
            {
                response = await followRedirectAlwaysHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // OK
            }

            using (HttpClient followRedirectOnlyToSpecificHostHttpClient = new HttpClient(followRedirectOnlyToSpecificHostHandler))
            {
                response = await followRedirectOnlyToSpecificHostHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // Moved
            }

            followRedirectOnlyToSpecificHostHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => response.Headers.Location.Host == "stackoverflow.com");
            using (HttpClient followRedirectOnlyToSpecificHostHttpClient = new HttpClient(followRedirectOnlyToSpecificHostHandler))
            {
                response = await followRedirectOnlyToSpecificHostHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // OK
            }
        }
    }

    public class RestrictedRedirectFollowingHttpClientHandler : HttpClientHandler
    {
        private static readonly HttpStatusCode[] redirectStatusCodes = new[] {
                     HttpStatusCode.Moved,
                     HttpStatusCode.Redirect,
                     HttpStatusCode.RedirectMethod,
                     HttpStatusCode.TemporaryRedirect,
                     HttpStatusCode.PermanentRedirect
                 };

        private readonly Predicate<HttpResponseMessage> isRedirectAllowed;

        public override bool SupportsRedirectConfiguration { get; }

        public RestrictedRedirectFollowingHttpClientHandler(Predicate<HttpResponseMessage> isRedirectAllowed)
        {
            AllowAutoRedirect = false;
            SupportsRedirectConfiguration = false;
            this.isRedirectAllowed = response => {
                return Array.BinarySearch(redirectStatusCodes, response.StatusCode) >= 0
              && isRedirectAllowed.Invoke(response);
            };
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            int redirectCount = 0;
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
            while (isRedirectAllowed.Invoke(response)
                && (response.Headers.Location != request.RequestUri || response.StatusCode == HttpStatusCode.RedirectMethod && request.Method != HttpMethod.Get)
                && redirectCount < this.MaxAutomaticRedirections)
            {
                if (response.StatusCode == HttpStatusCode.RedirectMethod)
                {
                    request.Method = HttpMethod.Get;
                }
                request.RequestUri = response.Headers.Location;
                response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
                ++redirectCount;
            }
            return response;
        }
    }
}
</code>```

The Main method shows three example requests to http://stackoverflow.com (which is a URI that redirects to https://stackoverflow.com):

The first GET request will follow the redirect and therefore we see the status code OK of the response to the redirected request, because the handler is configured to follow all redirects.

The second GET request will not follow the redirect and therefore we see the status code Moved, because the handler is configured to follow redirects to the host example.com exclusively.

The third GET request will follow the redirect and therefore we see the status code OK of the response to the redirected request, because the handler is configured to follow redirects to the host stackoverflow.com exclusively.

Of course, you can substitute any custom logic for the predicate.

Body:
This answer to the question on how to make HttpClient not follow redirects gives a solution to be set upon creating the actual client:

var handler = new HttpClientHandler { AllowAutoRedirect = false };
var client = new HttpClient(handler);

The comment below the answer is my actual question:

Is it possible to do this on a per-request basis without needing two separate HttpClient instances (i.e. one that allows redirects and one that does not)?

I have a specific reason too for now wanting separate clients: I want the client to retain its cookies from earlier requests. I'm trying to do a few requests first that include valid redirects, but only the last one in the chain I don't want to be a redirect.

I've searched, and looked through the overloads of .GetAsync(url, ...), and looked through the properties and methods of HttpClient, but found no solution yet.

Is this possible?

Body:
The question asks whether following redirects can be done on a case-by-case basis. While certainly useful for many common cases, I found the existing answers lacking in that regard.

The following implementation allows the decision on whether to follow a redirect or not to be configured on a true case-by-case basis via a predicate.
The solution is to override the SendAsync() method of HttpClientHandler.

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace HttpClientCustomRedirectBehavior
{
    static class Program
    {
        private const string REDIRECTING_URL = "http://stackoverflow.com/";

        static async Task Main(string[] args)
        {
            HttpMessageHandler followRedirectAlwaysHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => true);
            HttpMessageHandler followRedirectOnlyToSpecificHostHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => response.Headers.Location.Host == "example.com");

            HttpResponseMessage response;
            using (HttpClient followRedirectAlwaysHttpClient = new HttpClient(followRedirectAlwaysHandler))
            {
                response = await followRedirectAlwaysHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // OK
            }

            using (HttpClient followRedirectOnlyToSpecificHostHttpClient = new HttpClient(followRedirectOnlyToSpecificHostHandler))
            {
                response = await followRedirectOnlyToSpecificHostHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // Moved
            }

            followRedirectOnlyToSpecificHostHandler = new RestrictedRedirectFollowingHttpClientHandler(
                response => response.Headers.Location.Host == "stackoverflow.com");
            using (HttpClient followRedirectOnlyToSpecificHostHttpClient = new HttpClient(followRedirectOnlyToSpecificHostHandler))
            {
                response = await followRedirectOnlyToSpecificHostHttpClient.GetAsync(REDIRECTING_URL);
                Console.WriteLine(response.StatusCode); // OK
            }
        }
    }

    public class RestrictedRedirectFollowingHttpClientHandler : HttpClientHandler
    {
        private static readonly HttpStatusCode[] redirectStatusCodes = new[] {
                     HttpStatusCode.Moved,
                     HttpStatusCode.Redirect,
                     HttpStatusCode.RedirectMethod,
                     HttpStatusCode.TemporaryRedirect,
                     HttpStatusCode.PermanentRedirect
                 };

        private readonly Predicate<HttpResponseMessage> isRedirectAllowed;

        public override bool SupportsRedirectConfiguration { get; }

        public RestrictedRedirectFollowingHttpClientHandler(Predicate<HttpResponseMessage> isRedirectAllowed)
        {
            AllowAutoRedirect = false;
            SupportsRedirectConfiguration = false;
            this.isRedirectAllowed = response => {
                return Array.BinarySearch(redirectStatusCodes, response.StatusCode) >= 0
              && isRedirectAllowed.Invoke(response);
            };
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            int redirectCount = 0;
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
            while (isRedirectAllowed.Invoke(response)
                && (response.Headers.Location != request.RequestUri || response.StatusCode == HttpStatusCode.RedirectMethod && request.Method != HttpMethod.Get)
                && redirectCount < this.MaxAutomaticRedirections)
            {
                if (response.StatusCode == HttpStatusCode.RedirectMethod)
                {
                    request.Method = HttpMethod.Get;
                }
                request.RequestUri = response.Headers.Location;
                response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
                ++redirectCount;
            }
            return response;
        }
    }
}

The Main method shows three example requests to http://stackoverflow.com (which is a URI that redirects to https://stackoverflow.com):

The first GET request will follow the redirect and therefore we see the status code OK of the response to the redirected request, because the handler is configured to follow all redirects.

The second GET request will not follow the redirect and therefore we see the status code Moved, because the handler is configured to follow redirects to the host example.com exclusively.

The third GET request will follow the redirect and therefore we see the status code OK of the response to the redirected request, because the handler is configured to follow redirects to the host stackoverflow.com exclusively.

Of course, you can substitute any custom logic for the predicate.


答:
In your remove method there were cases that you weren't taking into account, I have explained in the comments on the code. Here is a first approach

```<code>    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = null;
        while (currentNode != null && currentNode.data != data) {
//Here we are searching if the element exists on the list
            previousNode = currentNode;
            currentNode = currentNode.next;
        }
        if (currentNode == null) //If we enter here, the element doesn't exist
        {
            System.out.println("Value not found");
        } else {
            int value = currentNode.data;
            if (previousNode == null) { //Check if the element is the first one in our list
                this.root = currentNode.next;
                this.setSize(this.getSize() - 1);
                return;
            }
            if (currentNode.next != null) { //Check if the element is the last one in our list
                previousNode.next = currentNode.next;
                System.out.println("Value " + value +  " found");

            } else {
                previousNode.next = null;
                System.out.println("Value " + value + " found");
            }
            this.setSize(this.getSize() - 1);
        }
    }
</code>```

PS: You should keep track of both ends

Title: How to remove elements from a LinkedList in Java? How to set the first element to be the head of the Linked List in Java?

Body:
In your remove method there were cases that you weren't taking into account, I have explained in the comments on the code. Here is a first approach

    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = null;
        while (currentNode != null && currentNode.data != data) {
//Here we are searching if the element exists on the list
            previousNode = currentNode;
            currentNode = currentNode.next;
        }
        if (currentNode == null) //If we enter here, the element doesn't exist
        {
            System.out.println("Value not found");
        } else {
            int value = currentNode.data;
            if (previousNode == null) { //Check if the element is the first one in our list
                this.root = currentNode.next;
                this.setSize(this.getSize() - 1);
                return;
            }
            if (currentNode.next != null) { //Check if the element is the last one in our list
                previousNode.next = currentNode.next;
                System.out.println("Value " + value +  " found");

            } else {
                previousNode.next = null;
                System.out.println("Value " + value + " found");
            }
            this.setSize(this.getSize() - 1);
        }
    }

PS: You should keep track of both ends


问:
Container filled with widgets beond hight and width without getting overflowed
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

```<code>Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);
</code>```

Here is the issue that occuring.

答:
This should work(just replace your code "I am overflowed" with the padding with my code):

```<code>_width == MediaQuery.of(context).size.width ? Padding(
   padding: const EdgeInsets.all(16.0),
   child: Text('I am overflowed'),
) : Container()
</code>```

Hope it helped

Body:
I have a tricky one to solve.
In this case I have a container which expands the height and width of the size of the device.
Inside this widget I have other widgets that are placed beond the scope of the visible area.
So now I get the error that the bottom area in this case is overflowed. I thought that I could just set the opacity to 0 and the flip it to 1 when I change state but that not the case since Flutter still knows that there is something there. In good old android you could set the visibility to "gone" to make it don't take up space.

Here is my code for the layout:

Container(
  color: primaryColor,
  child: Stack(
    fit: StackFit.loose,
    children: [
      SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Align(
            alignment: Alignment.topCenter,
            child: Column(
              children: [
                Icon(
                  Icons.swap_calls,
                  size: 100,
                  color: Colors.white,
                ),
                Text(
                  'TCM Sensory',
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 24,
                      fontWeight: FontWeight.w600),
                ),
                Text(
                  'Made to be perfect',
                  style: TextStyle(color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ),
      Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              height: _height,
              width: _width,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: secondaryColor,
                borderRadius: BorderRadius.circular(_radius),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          if (!_toggle) {
                            _radius = 0;
                            _width = MediaQuery.of(context).size.width;
                            _height = MediaQuery.of(context).size.height;
                            _title = "Press to Stop";
                            _color = primaryColor;
                            _toggle = true;
                          } else {
                            _radius = 10;
                            _width = 150;
                            _height = 50;
                            _title = "Press to Start";
                            _color = secondaryColor;
                            _toggle = false;
                          }
                        });
                      },
                      child: Container(
                        width: 140,
                        height: 30,
                        decoration: BoxDecoration(
                          color: _color,
                          borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text(
                            _title,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text('I am overflowed'),
                  )],
                ),
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);

Here is the issue that occuring.

Body:
This should work(just replace your code "I am overflowed" with the padding with my code):

_width == MediaQuery.of(context).size.width ? Padding(
   padding: const EdgeInsets.all(16.0),
   child: Text('I am overflowed'),
) : Container()

Hope it helped


问:
Python CSV Logic
I am trying to create a python program that tests if certain cells in a csv have the value 4, and if they do, it should write that whole row to a csv file called grade4.csv. This is the code I have so far:

```<code>import csv
with open('register-all-subs-2020-05-31.csv') as csvDataFile:
      csvReader = csv.reader(csvDataFile)
      data = [row for row in csv.reader(csvDataFile)]
      r=0
      c=0
      for r in range(33):
           for c in range(7):
                 print(data[r][c])
</code>```

However, I can't figure out how to go about testing certain values in the cell and writing the row to a csv. It would be great if anyone could help.

答:
Try this and modify it little bit according to your purpose :</p>

```<code>def check_four(row):
    for cell in row:
        if "4" in cell:
            return True
    return False

def main():
    with open("file.csv","r") as f:
        data = f.read()
    rows = data.split(",")
    new_rows = []
    for row in rows:
        if check_four(row):
            new_rows.append(row)
    new_data = ','.join(new_rows)
    with open("grade4.csv","w") as f:
        f.write(new_data)

if __name__ == "__main__":
    main()
</code>```

Title: Python CSV Logic

Body:
I am trying to create a python program that tests if certain cells in a csv have the value 4, and if they do, it should write that whole row to a csv file called grade4.csv. This is the code I have so far:

import csv
with open('register-all-subs-2020-05-31.csv') as csvDataFile:
      csvReader = csv.reader(csvDataFile)
      data = [row for row in csv.reader(csvDataFile)]
      r=0
      c=0
      for r in range(33):
           for c in range(7):
                 print(data[r][c])

However, I can't figure out how to go about testing certain values in the cell and writing the row to a csv. It would be great if anyone could help.

Body:
Try this and modify it little bit according to your purpose :

def check_four(row):
    for cell in row:
        if "4" in cell:
            return True
    return False

def main():
    with open("file.csv","r") as f:
        data = f.read()
    rows = data.split(",")
    new_rows = []
    for row in rows:
        if check_four(row):
            new_rows.append(row)
    new_data = ','.join(new_rows)
    with open("grade4.csv","w") as f:
        f.write(new_data)

if __name__ == "__main__":
    main()


问:
How the ftell() function works?
I have this code and I don't understand how it works:

```<code>void print(char * fileName)
{
    FILE * fp;
    int ch;
    fp = fopen(fileName, "r");
    while (ftell(fp) < 20)
    {
        ch = fgetc(fp);
        putchar(ch);
    }
    fclose(fp);
}
</code>```

How does ftell(fp) work in the loop?
Because there is nothing inside the loop that get it up.
How it is progressive?

答:
ftell returns the current value of the file position indicator, and fgetc does advance the file position indicator within the loop.

But this program is wrong. For a stream opened in text mode ("r"), the return value of ftell cannot be used portably for anything else except for seeking to a previous position. From C11 draft n1570 7.21.9.4p2

[...] For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

Indeed it doesn't make any sense to use ftell in this program. Either open the file in binary mode, "rb", and then it is guaranteed that

[...] the value is the number of characters from the beginning of the file.

or for counting characters read from text file, use a counter variable:

```<code>int c_read = 0;
while (c_read < 20)
{
    ch = fgetc(fp);
    putchar(ch);
    c_read ++;
}
</code>```

Finally neither your original version or mine does not work correctly if the file has less than 20 characters. In that case EOF is returned from fgetc and putchar would write (unsigned char)EOF to the stream (most likely a byte of value 255!)

Thus the correct code would be

```<code>int c_read = 0;
while (c_read < 20)
{
    ch = fgetc(fp);
    if (ch == EOF) {
        // report the error
        perror("Failed to read 20 characters");
        break;
    }
    putchar(ch);
    c_read ++;
}
</code>```

Title: How the ftell() function works?

Body:
I have this code and I don't understand how it works:

void print(char * fileName)
{
    FILE * fp;
    int ch;
    fp = fopen(fileName, "r");
    while (ftell(fp) < 20)
    {
        ch = fgetc(fp);
        putchar(ch);
    }
    fclose(fp);
}

How does ftell(fp) work in the loop?
Because there is nothing inside the loop that get it up.
How it is progressive?

Body:
ftell returns the current value of the file position indicator, and fgetc does advance the file position indicator within the loop.

But this program is wrong. For a stream opened in text mode ("r"), the return value of ftell cannot be used portably for anything else except for seeking to a previous position. From C11 draft n1570 7.21.9.4p2

[...] For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

Indeed it doesn't make any sense to use ftell in this program. Either open the file in binary mode, "rb", and then it is guaranteed that

[...] the value is the number of characters from the beginning of the file.

or for counting characters read from text file, use a counter variable:

int c_read = 0;
while (c_read < 20)
{
    ch = fgetc(fp);
    putchar(ch);
    c_read ++;
}

Finally neither your original version or mine does not work correctly if the file has less than 20 characters. In that case EOF is returned from fgetc and putchar would write (unsigned char)EOF to the stream (most likely a byte of value 255!)

Thus the correct code would be

int c_read = 0;
while (c_read < 20)
{
    ch = fgetc(fp);
    if (ch == EOF) {
        // report the error
        perror("Failed to read 20 characters");
        break;
    }
    putchar(ch);
    c_read ++;
}


问:
Is there a way for loading images from local storage to the backgroundImage property of the CircleAvatar widget in Flutter?
I'm having a hard time reading the Flutter doc for the CircleAvatar widget trying to figure out what type is the backgroundImage exactly is.

As far as I know, this property is of ImageProvider type and it can be one of the Asset classes as they extends the ImageProvider.

I came to the conclusion that the only way to get images is via a url or a predefined assets folder.

I want to load images from local storage. I'm currently experimentng this on Android 10.

PLEASE, tell me there is a way to do that.

答:
I believe the ImageProvider you are looking for is FileImage. You will only need to pass it the file from local storage. Here are the official docs:

https://api.flutter.dev/flutter/painting/FileImage-class.html


问:
usin javascript 4.15 api unable to creating featurelayer using geojson collection feature from webapi core 3.1 rest
Please note  that I was able to consume the geojson data and create a layer on leaflet map with ease. Also, tried using lib arcgis-to-geojson-utils but not able to get it working.
Here is my code.

Your help is greatly appreciated.

```<code>view.when()
        .then(fetchData)
        .then(createGraphics)
        .then(createLayer)
        .then(addToView)
        .catch(function(e) {
                console.error("Creating FeatureLayer   failed", e);
        })

 function fetchData() {
    return  fetch(url,options)
    .then(response =>   {
      return response.json()
    });
}

 function createGraphics(schoolsGeoData) {
  const geoData = JSON.parse(schoolsGeoData);
  return geoData.features.map((school, i) => {
        let schoolAttr = {
                    OBJECTID: school.properties["id"],
                    name: school.properties["name"]
        }
            return new Graphic({
                      //  type: "point",
                        attributes: schoolAttr,
                        geometry: new Point({
                          x: school.geometry.coordinates[0],
                          y: school.geometry.coordinates[1]
                        }),
                     });
           })
}

 function createLayer(graphics) {
   return new FeatureLayer({
            source: graphics,
            objectIdField: "OBJECTID",
            fields: schoolFeilds(),
            popupTemplate: schoolTemplate(),
            renderer: myRenderer(),
            geometryType: "point" ,
            spatialReference: {
              wkid: 4326
            },
        });
}

 function addToView(layer) {
  if(layer) {
     view.map.add(layer);
   }
}
</code>```

答:
Your code have a reasonable logic, of course there are thing missing that I can not know it they are working. For example, I don't know what options you add to fetch operation, but by default it will get you the data correctly, and you do not have to convert to JSON because it realize that.

I was actually going to ask you for more code, or what exactly was your problem, but I decide to remind you that you actually have a specific layer to handle GeoJSON data, GeoJSONLayer.

ArcGIS API - GeoJSONLayer

ArcGIS Examples - GeoJSONLayer

But, anyway I will leave you here a running example of what you are trying to do, fetching the data and using FeatureLayer, using the data from the example I mention,

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>GeoJSON with FeatureLayer - 4.15</title>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.15/esri/themes/light/main.css"
    />

```

Body:
Please note  that I was able to consume the geojson data and create a layer on leaflet map with ease. Also, tried using lib arcgis-to-geojson-utils but not able to get it working.
Here is my code.

Your help is greatly appreciated.

view.when()
        .then(fetchData)
        .then(createGraphics)
        .then(createLayer)
        .then(addToView)
        .catch(function(e) {
                console.error("Creating FeatureLayer   failed", e);
        })

 function fetchData() {
    return  fetch(url,options)
    .then(response =>   {
      return response.json()
    });
}

 function createGraphics(schoolsGeoData) {
  const geoData = JSON.parse(schoolsGeoData);
  return geoData.features.map((school, i) => {
        let schoolAttr = {
                    OBJECTID: school.properties["id"],
                    name: school.properties["name"]
        }
            return new Graphic({
                      //  type: "point",
                        attributes: schoolAttr,
                        geometry: new Point({
                          x: school.geometry.coordinates[0],
                          y: school.geometry.coordinates[1]
                        }),
                     });
           })
}

 function createLayer(graphics) {
   return new FeatureLayer({
            source: graphics,
            objectIdField: "OBJECTID",
            fields: schoolFeilds(),
            popupTemplate: schoolTemplate(),
            renderer: myRenderer(),
            geometryType: "point" ,
            spatialReference: {
              wkid: 4326
            },
        });
}

 function addToView(layer) {
  if(layer) {
     view.map.add(layer);
   }
}

Body:
Your code have a reasonable logic, of course there are thing missing that I can not know it they are working. For example, I don't know what options you add to fetch operation, but by default it will get you the data correctly, and you do not have to convert to JSON because it realize that.

I was actually going to ask you for more code, or what exactly was your problem, but I decide to remind you that you actually have a specific layer to handle GeoJSON data, GeoJSONLayer.

ArcGIS API - GeoJSONLayer

ArcGIS Examples - GeoJSONLayer

But, anyway I will leave you here a running example of what you are trying to do, fetching the data and using FeatureLayer, using the data from the example I mention,

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="initial-scale=1,maximum-scale=1,user-scalable=no"
    />
    <title>GeoJSON with FeatureLayer - 4.15</title>

    <style>
      html,
      body,
      #viewDiv {
        padding: 0;
        margin: 0;
        height: 100%;
        width: 100%;
      }
    </style>

    <link
      rel="stylesheet"
      href="https://js.arcgis.com/4.15/esri/themes/light/main.css"
    />

    <script src="https://js.arcgis.com/4.15/"></script>

    <script>
      require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/FeatureLayer",
        "esri/Graphic"
      ], function(Map, MapView, FeatureLayer, Graphic) {
        const map = new Map({
          basemap: "gray"
        });

        const view = new MapView({
          center: [-80, 35],
          zoom: 8,
          map,
          container: "viewDiv"
        });

        view.when()
          .then(fetchData)
          .then(createGraphics)
          .then(createLayer)
          .then(addToView)
          .catch(function(e) {
            console.error("Creating FeatureLayer   failed", e);
        })

        function fetchData() {
          return fetch(
            'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson'
          )
          .then(response =>   {
            return response.json()
          });
        }

        function createGraphics(data) {
          // const geoData = JSON.parse(data);
          return data.features.map((feature, i) => {
            return new Graphic({
              attributes: {
                OBJECTID: i,
                title: feature.properties["title"],
                mag: feature.properties["mag"],
                type: feature.properties["type"],
                place: feature.properties["place"],
                time: feature.properties["time"]
              },
              geometry: {
                type: "point",
                x: feature.geometry.coordinates[0],
                y: feature.geometry.coordinates[1]
              },
            });
          })
        }

        function createLayer(graphics) {
          const popupTemplate = {
            title: "{title}",
            content: "Magnitude {mag} {type} hit {place} on {time}",
            fieldInfos: [
              {
                fieldName: "time",
                format: {
                  dateFormat: "short-date-short-time"
                }
              }
            ],
            outFields: ["title", "mag", "type", "place", "time"]
          }
          const renderer = {
            type: "simple",
            field: "mag",
            symbol: {
              type: "simple-marker",
              color: "orange",
              outline: {
                color: "white"
              }
            },
            visualVariables: [
              {
                type: "size",
                field: "mag",
                stops: [
                  {
                    value: 2.5,
                    size: "10px"
                  },
                  {
                    value: 8,
                    size: "40px"
                  }
                ]
              }
            ]
          };
          return new FeatureLayer({
            source: graphics,
            fields: [{
              name: "OBJECTID",
              alias: "ObjectID",
              type: "oid"
            }, {
              name: "title",
              alias: "Title",
              type: "string"
            }
            , {
              name: "mag",
              alias: "Magnitude",
              type: "double"
            }
            , {
              name: "type",
              alias: "Type",
              type: "string"
            }, {
              name: "place",
              alias: "Place",
              type: "string"
            }, {
              name: "time",
              alias: "Time",
              type: "date"
            }],
            objectIdField: "OBJECTID",
            popupTemplate,
            renderer
          });
        }

        function addToView(layer) {
          if(layer) {
            view.map.add(layer);
          }
        }

      });
    </script>
  </head>

  <body>
    <div id="viewDiv"></div>
  </body>
</html>


问:
jQuery Simulate clicking a link on page load using the link attributes
I'm using Wordpress and working on an gallery website where the home page has a widget that shows the latest image added to the gallery page.

The gallery page shows all images and when you click on an image it opens a lightbox to view the image while remaining on the gallery page. It does this by checking for a specific class on the link and, if present, opens the lightbox. If not, it just goes wherever the link points as normal.

I want users who click on the preview image in the homepage widget to go to the gallery page and then have that image open up in the lightbox. I've made progress but I'm currently stuck on a very specific problem...

If the user clicks the link manually the browser "sees" the class that regulates whether to open in lightbox or not but if I use jQuery to simulate a user click on that link it doesn't see the class, so the lightbox doesn't open and instead the user is just sent to the image directly.

Is there a way to genuinely simulate a browser click on page load that takes into account the attributes on the link, such as the link class?

If not is there some other way I can accomplish this?

EDIT - this is the jQuery I'm using to accomplish what I have so far

```<code><script type='text/javascript'>

    jQuery(document).ready(function() {
    jQuery(\"a[href$='someimage.jpg']\")[0].click();

    });
</script>
</code>```

and this is the link it's working on

```<code><a href="someimage.jpg" class="foobox" target="_self" rel="available-works-
    figures"><img width="150" height="150"
    src="someimage.jpg" class="pt-cv-thumbnail" alt=""></a>
</code>```

The lighbox plugin checks to see if the link has the class "foobox" and if so, it opens in a lightbox. If it doesn't, it doesn't - just opens as a link normally would.

When the jQuery fires it seems to ignore the class "foobox" on the link because it also just opens as a normal link, going right to the image instead of displaying it in the lightbox the way it does if someone actually clicks on the link.

Hopefully that explains a little better what is going on.

答:
Have you tried the document ready event of jquery

https://api.jquery.com/ready/

```<code>$( document ).ready(function() {
  // Handler for .ready() called.
});

</code>```

You can use trigger metho inside document ready.

https://api.jquery.com/trigger/

```<code>$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});

$( document ).ready(function() {
  $( "#foo" ).trigger( "click" );
});

</code>```

Body:
I'm using Wordpress and working on an gallery website where the home page has a widget that shows the latest image added to the gallery page.

The gallery page shows all images and when you click on an image it opens a lightbox to view the image while remaining on the gallery page. It does this by checking for a specific class on the link and, if present, opens the lightbox. If not, it just goes wherever the link points as normal.

I want users who click on the preview image in the homepage widget to go to the gallery page and then have that image open up in the lightbox. I've made progress but I'm currently stuck on a very specific problem...

If the user clicks the link manually the browser "sees" the class that regulates whether to open in lightbox or not but if I use jQuery to simulate a user click on that link it doesn't see the class, so the lightbox doesn't open and instead the user is just sent to the image directly.

Is there a way to genuinely simulate a browser click on page load that takes into account the attributes on the link, such as the link class?

If not is there some other way I can accomplish this?

EDIT - this is the jQuery I'm using to accomplish what I have so far

and this is the link it's working on

The lighbox plugin checks to see if the link has the class "foobox" and if so, it opens in a lightbox. If it doesn't, it doesn't - just opens as a link normally would.

When the jQuery fires it seems to ignore the class "foobox" on the link because it also just opens as a normal link, going right to the image instead of displaying it in the lightbox the way it does if someone actually clicks on the link.

Hopefully that explains a little better what is going on.

Body:
Have you tried the document ready event of jquery

https://api.jquery.com/ready/

$( document ).ready(function() {
  // Handler for .ready() called.
});

You can use trigger metho inside document ready.

https://api.jquery.com/trigger/

$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});

$( document ).ready(function() {
  $( "#foo" ).trigger( "click" );
});


问:
How to filter myself out of Google Analytics with a dynamic IP address?
Does anyone know how to setup Google Analytics to filter yourself out if you're visiting the site from a dynamic IP address?  I don't want to include myself in my stats from home use where I have a dynamic IP address via Verizon FiOS.</p>

答:
There are a couple ways of doing this.  If you know the range of IP addresses you're accessing your site from (and don't mind filtering them all out) you can set up an "Exclude" filter for that range of IP addresses.  If that's too restrictive, you can set a cookie using the Google Analytics code and filter on that.  Both techniques are documented at Google's help system.

Alternatively, if you're dynamically producing the pages on the server, you could simply not write the Google Analytics code into the pages in the first place, based on the currently logged in user.  On my site, I'm choosing to write the code or not based on a few things, such as whether the website is running in debug mode or if an administrator is logged on.

OwnerDisplayName: magenta

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Chris B.


问:
Annoying Android - RSS problem
I'm struggling big time with a stupid problem which i can't seem to fix.
Basicly what i do in my application is the following:

I download all the RSS content to a local database, including the enclosure of every feed (images) but not every feed contains an image.

about 10 of the 100 feeds don't contain an image
What happens with the feeds that don't contain an image is shown in the following image:

http://i.stack.imgur.com/FTUBl.png

The feeds with no image get the image of the previouse feed for some reason...

I'll place all my code below in hope someone can tell me what in the world i'm doing wrong...

This part is where i download the image to the local storage, this function works correctly however for some reason the feed with no enclosure gets the enclosure of the previouse feed send back to it...

```<code>for (Message msg : wildLife){

                String imageURL = msg.getEnclosure();
                String imageName = imageURL.substring(imageURL.lastIndexOf("/"));
                String imagePath = ImageDir + imageName;

                //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }

                //-- We add all rows we find in the rrs feed to our local stored database.
                db.addWildlifeRow(
                    msg.getTitle(),
                    msg.getDescription(),
                    "Empty slot",
                    imagePath,
                    msg.getLink());
            }
</code>```

I checked in the RSS parser and it doesn't store the same URL twice. So no problem there. It goes wrong (for as far as i know) when requisting the URL enclosure from a message item.

Is there anyone who might have encountered this same problem?

All advice is welcome i've been stuck in this problem for days now, and i can't seem to figure it out...

If you would require more code to find a possible solution just ask and i will provide it.

P.S. it goes wrong before placing the data into my database, so when reading the info from the message out and placing it in the database, its already gone wrong there. The enclosure is copied from the reviouse one (if there was none)

Regards, joery

答:
Have you tried walking through it in debug?

I agree that it seems as though

```<code>String imageURL = msg.getEnclosure();
</code>```

must be always returning something - as if msg.getEnclosure() returned null for items with out an image then you would get NullPointerException on the following line at

```<code>String imageName = imageURL.substring(imageURL.lastIndexOf("/"));
</code>```

If you could provide the RSS parsing code that could be useful - I assume other than that there is no other pre-processing of the Wildlife message set?

Title: Annoying Android - RSS problem

Body:
I'm struggling big time with a stupid problem which i can't seem to fix.
Basicly what i do in my application is the following:

I download all the RSS content to a local database, including the enclosure of every feed (images) but not every feed contains an image.

about 10 of the 100 feeds don't contain an image
What happens with the feeds that don't contain an image is shown in the following image:

http://i.stack.imgur.com/FTUBl.png

The feeds with no image get the image of the previouse feed for some reason...

I'll place all my code below in hope someone can tell me what in the world i'm doing wrong...

This part is where i download the image to the local storage, this function works correctly however for some reason the feed with no enclosure gets the enclosure of the previouse feed send back to it...

for (Message msg : wildLife){

                String imageURL = msg.getEnclosure();
                String imageName = imageURL.substring(imageURL.lastIndexOf("/"));
                String imagePath = ImageDir + imageName;

                //-- Call upon the function that will download the image.
                if (imageURL !=null){
                    DownloadFromUrl(imageURL, imagePath);
                }

                //-- We add all rows we find in the rrs feed to our local stored database.
                db.addWildlifeRow(
                    msg.getTitle(),
                    msg.getDescription(),
                    "Empty slot",
                    imagePath,
                    msg.getLink());
            }

I checked in the RSS parser and it doesn't store the same URL twice. So no problem there. It goes wrong (for as far as i know) when requisting the URL enclosure from a message item.

Is there anyone who might have encountered this same problem?

All advice is welcome i've been stuck in this problem for days now, and i can't seem to figure it out...

If you would require more code to find a possible solution just ask and i will provide it.

P.S. it goes wrong before placing the data into my database, so when reading the info from the message out and placing it in the database, its already gone wrong there. The enclosure is copied from the reviouse one (if there was none)

Regards, joery

Body:
Have you tried walking through it in debug?

I agree that it seems as though

String imageURL = msg.getEnclosure();

must be always returning something - as if msg.getEnclosure() returned null for items with out an image then you would get NullPointerException on the following line at

String imageName = imageURL.substring(imageURL.lastIndexOf("/"));

If you could provide the RSS parsing code that could be useful - I assume other than that there is no other pre-processing of the Wildlife message set?


问:
How to remove this white HTML space below footer?
I've created a responsive webpage and everything is working fine. I mean the layout for mobile like smartphones and tablets is ok. If I switch to desktop it looks good too except for the footer and that's because there is an empty white space at the end of the webpage if I click on inspect the browser focus the HTML tag.

One thing you have to notice is that the height of this empty space depends on the width of the viewport. Also I'm using sass. I can't share all the code here because it's divided across too many files. If you want to see all the code go here: https://github.com/justanindieguy/podcast-landing-page

And also you can see the webpage in this github personal page: https://justanindieguy.github.io/podcast-landing-page/

Thanks a lot for all your answers. This is driving me nuts, I can't find the solution.

答:
Add this line to top of your CSS file</p>

```<code>* {
  padding:0;
  margin: 0;
}
</code>```

Body:
Add this line to top of your CSS file

* {
  padding:0;
  margin: 0;
}


问:
How to write jpa query using Like ,between and enum?
How to write jpa query in java

```<code>public class Record{

string id;
string senderId;
string reciverId;
@Enumerated(EnumType.STRING)
private RecordType recordType;
@Enumerated(EnumType.STRING)
private RecordStatus recordStatus;
@Column(name = "transfer_date", columnDefinition = "DATE")
Date transferDate;
}
</code>```

Here is JPA Query I tried.

```<code>@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 AND r.recordType Like ?6")

  List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, RecordStatus status, String recordType);
</code>```

findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(fromDate,toDate,"1","1",RecordStatus.COMPLETE,"ONLINE");

EnumType

```<code>ONLINE_TO_ONLINE,
OFFLINE_TO_OFFLINE,
ONLINE_TO_OFFLINE,
OFFLINE_TO_ONLINE
</code>```

For me getting always empty.Any one can help ?

答:
You are directly passing the enum to the query, modify to pass it as string. Try something like this.

```<code>@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 r.recordType Like ?6")
List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, RecordStatus status, String recordType);
</code>```

change RecordStatus status parameter to String recordStatus and pass the value to the parameter of this method findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType() like this.

```<code>RecordStatus.COMPLETE.toString()
</code>```

Changed code.

```<code>@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 r.recordType Like ?6")
List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, String recordStatus, String recordType);
</code>```

your calling method look like this.

```<code>findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType("", "", "", "", RecordStatus.COMPLETE.toString(), "");
</code>```

if your enum has values then you need to use constuructor to get the values. for example

```<code>RecordStatus.COMPLETE.getValue()
</code>```

Body:
How to write jpa query in java

public class Record{

string id;
string senderId;
string reciverId;
@Enumerated(EnumType.STRING)
private RecordType recordType;
@Enumerated(EnumType.STRING)
private RecordStatus recordStatus;
@Column(name = "transfer_date", columnDefinition = "DATE")
Date transferDate;
}

Here is JPA Query I tried.

@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 AND r.recordType Like ?6")

  List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, RecordStatus status, String recordType);

findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(fromDate,toDate,"1","1",RecordStatus.COMPLETE,"ONLINE");

EnumType

ONLINE_TO_ONLINE,
OFFLINE_TO_OFFLINE,
ONLINE_TO_OFFLINE,
OFFLINE_TO_ONLINE

For me getting always empty.Any one can help ?

Body:
You are directly passing the enum to the query, modify to pass it as string. Try something like this.

@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 r.recordType Like ?6")
List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, RecordStatus status, String recordType);

change RecordStatus status parameter to String recordStatus and pass the value to the parameter of this method findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType() like this.

RecordStatus.COMPLETE.toString()

Changed code.

@Query("select r from Record r where (t.transferDate BETWEEN ?1 AND ?2 ) and (senderId = ?3 or reciverId = ?4) and status =?5 r.recordType Like ?6")
List<TransactionBean> findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType(Date fromDate,Date toDate, String senderId, String reciverId, String recordStatus, String recordType);

your calling method look like this.

findByTransferDateBetweenAndReciverIdOrSenderIdAndRecordStatusAndRecordType("", "", "", "", RecordStatus.COMPLETE.toString(), "");

if your enum has values then you need to use constuructor to get the values. for example

RecordStatus.COMPLETE.getValue()


问:
Pandas groupby cumcount starting on row with a certain column value
I'd like to create two cumcount columns, depending on the values of two columns.

In the example below, I'd like one cumcount starting when colA is at least 100, and another cumcount starting when colB is at least 10.

```<code>columns = ['ID', 'colA', 'colB', 'cumcountA', 'cumountB']
data = [['A', 3, 1, '',''],
    ['A', 20, 4, '',''],
    ['A', 102, 8, 1, ''],
    ['A', 117, 10, 2, 1],
    ['B', 75, 0, '',''],
    ['B', 170, 12, 1, 1],
    ['B', 200, 13, 2, 2],
    ['B', 300, 20, 3, 3],
   ]

pd.DataFrame(columns=columns, data=data)

    ID  colA    colB    cumcountA   cumountB
0   A   3   1
1   A   20  4
2   A   102 8   1
3   A   117 10  2   1
4   B   75  0
5   B   170 12  1   1
6   B   200 13  2   2
7   B   300 20  3   3
</code>```

How would I calculate cumcountA and cumcountB?

答:
you can try setting df.clip lower = your values (here 100 and 10) and then compare then groupby ID and cumsum :

```<code>col_list = ['colA','colB']
val_list = [100,10]

df[['cumcountA','cumountB']] = (df[col_list].ge(df[col_list].clip(lower=val_list,axis=1))
                                 .groupby(df['ID']).cumsum().replace(0,''))
print(df)
</code>```

Or may be even better to compare directly:

```<code>df[['cumcountA','cumountB']] = (df[['colA','colB']].ge([100,10])
                               .groupby(df['ID']).cumsum().replace(0,''))
print(df)
</code>```

```<code>  ID  colA  colB cumcountA cumountB
0  A     3     1
1  A    20     4
2  A   102     8         1
3  A   117    10         2        1
4  B    75     0
5  B   170    12         1        1
6  B   200    13         2        2
7  B   300    20         3        3
</code>```

Body:
I'd like to create two cumcount columns, depending on the values of two columns.

In the example below, I'd like one cumcount starting when colA is at least 100, and another cumcount starting when colB is at least 10.

columns = ['ID', 'colA', 'colB', 'cumcountA', 'cumountB']
data = [['A', 3, 1, '',''],
    ['A', 20, 4, '',''],
    ['A', 102, 8, 1, ''],
    ['A', 117, 10, 2, 1],
    ['B', 75, 0, '',''],
    ['B', 170, 12, 1, 1],
    ['B', 200, 13, 2, 2],
    ['B', 300, 20, 3, 3],
   ]

pd.DataFrame(columns=columns, data=data)

    ID  colA    colB    cumcountA   cumountB
0   A   3   1
1   A   20  4
2   A   102 8   1
3   A   117 10  2   1
4   B   75  0
5   B   170 12  1   1
6   B   200 13  2   2
7   B   300 20  3   3

How would I calculate cumcountA and cumcountB?

Body:
you can try setting df.clip lower = your values (here 100 and 10) and then compare then groupby ID and cumsum :

col_list = ['colA','colB']
val_list = [100,10]

df[['cumcountA','cumountB']] = (df[col_list].ge(df[col_list].clip(lower=val_list,axis=1))
                                 .groupby(df['ID']).cumsum().replace(0,''))
print(df)

Or may be even better to compare directly:

df[['cumcountA','cumountB']] = (df[['colA','colB']].ge([100,10])
                               .groupby(df['ID']).cumsum().replace(0,''))
print(df)

  ID  colA  colB cumcountA cumountB
0  A     3     1
1  A    20     4
2  A   102     8         1
3  A   117    10         2        1
4  B    75     0
5  B   170    12         1        1
6  B   200    13         2        2
7  B   300    20         3        3


问:
Get nested inner content value of each div using jQuery
I am trying to get selected values of all the radio buttons and if one is not selected, then null value.
Here is my HTML code:

```<code><div class="question m-2">
    <div class="question-title">Question 1</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-1">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-1">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-1">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-1">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 2</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-2">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-2">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-2">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-2">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 3</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-3">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-3">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-3">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-3">Option d
        </label>
    </div>
</div>
</code>```

I want to store all the answers of each question, if selected then the selected value, if not selected, then null value. Can anyone help me with jQuery code?

答:
You can get the answers like this:

$("#submit").on("click", function() {
  let questions = $(".question");
  let answers = [];
  let answer;
  questions.each(function() {
     if ($(this).find("input[type='radio']:checked").length) {
        answer = $(this).find("input[type='radio']:checked").val();
     } else {
        answer = "null";
     }
     answers.push(answer);
  });
  console.log(answers);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question m-2">
    <div class="question-title">Question 1</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-1">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-1">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-1">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-1">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 2</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-2">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-2">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-2">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-2">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 3</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-3">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-3">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-3">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-3">Option d
        </label>
    </div>
</div>
<button id="submit">
Submit
</button></code>```

Body:
I am trying to get selected values of all the radio buttons and if one is not selected, then null value.
Here is my HTML code:

Question 1

            <input type="radio" class="form-check-input" value="a" name="q-1">Option a

            <input type="radio" class="form-check-input" value="b" name="q-1">Option b

            <input type="radio" class="form-check-input" value="c" name="q-1">Option c

            <input type="radio" class="form-check-input" value="d" name="q-1">Option d

Question 2

            <input type="radio" class="form-check-input" value="a" name="q-2">Option a

            <input type="radio" class="form-check-input" value="b" name="q-2">Option b

            <input type="radio" class="form-check-input" value="c" name="q-2">Option c

            <input type="radio" class="form-check-input" value="d" name="q-2">Option d

Question 3

            <input type="radio" class="form-check-input" value="a" name="q-3">Option a

            <input type="radio" class="form-check-input" value="b" name="q-3">Option b

            <input type="radio" class="form-check-input" value="c" name="q-3">Option c

            <input type="radio" class="form-check-input" value="d" name="q-3">Option d

I want to store all the answers of each question, if selected then the selected value, if not selected, then null value. Can anyone help me with jQuery code?

Body:
You can get the answers like this:

$("#submit").on("click", function() {
  let questions = $(".question");
  let answers = [];
  let answer;
  questions.each(function() {
     if ($(this).find("input[type='radio']:checked").length) {
        answer = $(this).find("input[type='radio']:checked").val();
     } else {
        answer = "null";
     }
     answers.push(answer);
  });
  console.log(answers);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="question m-2">
    <div class="question-title">Question 1</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-1">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-1">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-1">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-1">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 2</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-2">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-2">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-2">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-2">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 3</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-3">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-3">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-3">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-3">Option d
        </label>
    </div>
</div>
<button id="submit">
Submit
</button>