问:
How to create solr service for starting solr on reboot
I am trying to create a solr service script that I can use to start solr automatically on reboot.  Here is a script I saw recommended:

```<code>#!/bin/sh

# Starts, stops, and restarts Apache Solr.
#
# chkconfig: 35 92 08
# description: Starts and stops Apache Solr

SOLR_DIR="/var/www/html/fas/solr/solr-latest"
JAVA_OPTIONS="-Xmx1024m -DSTOP.PORT=8983 -DSTOP.KEY=mustard -jar /var/www/html/fas/solr/solr-latest/server/start.jar"
LOG_FILE="/var/log/solr.log"
JAVA="/bin/java"

case $1 in
    start)
        echo "Starting Solr"
        cd $SOLR_DIR
        $JAVA $JAVA_OPTIONS 2> $LOG_FILE &
        ;;
    stop)
        echo "Stopping Solr"
        cd $SOLR_DIR
        $JAVA $JAVA_OPTIONS --stop
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}" >&2
        exit 1
        ;;
esac
</code>```

I think I have set the appropriate values for the variables in the script. But when I try to run the script, I get "Connection refused."

```<code>$ service solr stop
Stopping Solr
java.net.ConnectException: Connection refused (Connection refused)
</code>```

I get the same result whether I run the script as root or not.

I can stop and start solr this way, though:

```<code>/path/to/my/solr/bin/solr start
</code>```

So I also tried creating this script at /etc/init.d/solr-start

```<code>#!/bin/sh

# Starts Apache Solr.
#
# chkconfig: 35 92 08
# description: Starts Apache Solr

/var/www/html/fas/solr/solr-latest/bin/solr start
</code>```

This script works at the command line, but it doesn't work on reboot. To try to make it run on reboot, I did...

```<code>sudo systemctl enable solr-start
</code>```

But solr is not started on reboot.

My versions:
RHEL 7, Solr 6.6.6

答:
Unfortunately you're providing nearly no details about your specific Solr installation. The following systemd unit example might provide a starting point though.

Create the file /etc/systemd/system/solr.service with the following content (and perform adaptions to make it suitable to your Solr installation):

```<code>[Unit]
Description=Apache SOLR
After=syslog.target network.target remote-fs.target nss-lookup.target systemd-journald-dev-log.socket
Before=multi-user.target
Conflicts=shutdown.target

[Service]
User=solr
# Assumes SOLR_PID_DIR; change port if it differs
PIDFile=/var/lib/solr/solr-8983.pid
# Assumes proper configuration in /etc/default/solr.in.sh
Environment=SOLR_INCLUDE=/etc/default/solr.in.sh
ExecStart=/path/to/my/solr/bin/solr start
ExecStop=/path/to/my/solr/bin/solr stop
Restart=on-failure

[Install]
WantedBy=multi-user.target
</code>```

Perform the following commands either as root or prefix them with sudo:

systemctl daemon-reload

systemctl enable solr.service

systemctl start solr.service

systemctl status solr.service

If you need different (or more) options in the systemd unit, this GitHub Gist was suggested to upstream as possible starting point for upstream inclusion.

Body:
I am trying to create a solr service script that I can use to start solr automatically on reboot.  Here is a script I saw recommended:

#!/bin/sh

# Starts, stops, and restarts Apache Solr.
#
# chkconfig: 35 92 08
# description: Starts and stops Apache Solr

SOLR_DIR="/var/www/html/fas/solr/solr-latest"
JAVA_OPTIONS="-Xmx1024m -DSTOP.PORT=8983 -DSTOP.KEY=mustard -jar /var/www/html/fas/solr/solr-latest/server/start.jar"
LOG_FILE="/var/log/solr.log"
JAVA="/bin/java"

case $1 in
    start)
        echo "Starting Solr"
        cd $SOLR_DIR
        $JAVA $JAVA_OPTIONS 2> $LOG_FILE &
        ;;
    stop)
        echo "Stopping Solr"
        cd $SOLR_DIR
        $JAVA $JAVA_OPTIONS --stop
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}" >&2
        exit 1
        ;;
esac

I think I have set the appropriate values for the variables in the script. But when I try to run the script, I get "Connection refused."

$ service solr stop
Stopping Solr
java.net.ConnectException: Connection refused (Connection refused)

I get the same result whether I run the script as root or not.

I can stop and start solr this way, though:

/path/to/my/solr/bin/solr start

So I also tried creating this script at /etc/init.d/solr-start

#!/bin/sh

# Starts Apache Solr.
#
# chkconfig: 35 92 08
# description: Starts Apache Solr

/var/www/html/fas/solr/solr-latest/bin/solr start

This script works at the command line, but it doesn't work on reboot. To try to make it run on reboot, I did...

sudo systemctl enable solr-start

But solr is not started on reboot.

My versions:
RHEL 7, Solr 6.6.6

Body:
Unfortunately you're providing nearly no details about your specific Solr installation. The following systemd unit example might provide a starting point though.

Create the file /etc/systemd/system/solr.service with the following content (and perform adaptions to make it suitable to your Solr installation):

[Unit]
Description=Apache SOLR
After=syslog.target network.target remote-fs.target nss-lookup.target systemd-journald-dev-log.socket
Before=multi-user.target
Conflicts=shutdown.target

[Service]
User=solr
# Assumes SOLR_PID_DIR; change port if it differs
PIDFile=/var/lib/solr/solr-8983.pid
# Assumes proper configuration in /etc/default/solr.in.sh
Environment=SOLR_INCLUDE=/etc/default/solr.in.sh
ExecStart=/path/to/my/solr/bin/solr start
ExecStop=/path/to/my/solr/bin/solr stop
Restart=on-failure

[Install]
WantedBy=multi-user.target

Perform the following commands either as root or prefix them with sudo:

systemctl daemon-reload

systemctl enable solr.service

systemctl start solr.service

systemctl status solr.service

If you need different (or more) options in the systemd unit, this GitHub Gist was suggested to upstream as possible starting point for upstream inclusion.


来源: stackexchange

问:
How to ensure a constant inside a component is only calculated once on start in React (Native) with hooks?
I am currently creating a React Native app and still am unsure about how to best handle states for my use case.

I use react-native-svg to create a rather complex figure in the app, which is stored in a component, stays constant and is retrieved in a parent component. This parent component is then regularly rotated and translated on the canvas, but the path of the complex figure does not change. Therefore, and because the calculations are rather heavy, I would like to calculate the SVG path of that figure only on the start of the app, but not whenever I rotate or translate the parent component. Currently, my code structure looks like this:

Figure Component

```<code>const Figure = (props) => {
    const [path, setPath] = useState({FUNCTION TO CALCULATE THE SVG PATH});

    return(
        <G>
            <Path d={path} />
        </G>
    )
}
</code>```

Parent Component

```<code>const Parent = (props) => {
    return (
        <View>
            <Svg>
                <G transform={ROTATE AND TRANSFORM BASED ON INTERACTION}>
                    <Figure />
                </G>
            </Svg>
        </View>
    )
}
</code>```

As you can see I am using a state for the path data. My questions now:

Am I ensuring here that this path is only calculated once on start?

Is there a more elegant/better way of doing this (e.g. I am not using the setter function at all right now, so I don't feel like this is the best practice)

EDIT:

The function to calculate the path depends on some props I am passing from the parent component.

答:
You can use the hook useMemo, it returns the value to your const, it receives the function that returns the value and also an array, send an empty one to calculate just once, you can send some dependencies, props or state if needed to recalculate the value when they change.

In your case you can do something like this:

```<code>const Figure = (props) => {
    const path = React.useMemo(() => {
      // calculate and return value for path
    }, []);

    return(
        <G>
            <Path d={path} />
        </G>
    )
}
</code>```

It was created for that porpuse.

Hope it helps ;)!

ContentLicense: CC BY-SA 4.0

Body:
I am currently creating a React Native app and still am unsure about how to best handle states for my use case.

I use react-native-svg to create a rather complex figure in the app, which is stored in a component, stays constant and is retrieved in a parent component. This parent component is then regularly rotated and translated on the canvas, but the path of the complex figure does not change. Therefore, and because the calculations are rather heavy, I would like to calculate the SVG path of that figure only on the start of the app, but not whenever I rotate or translate the parent component. Currently, my code structure looks like this:

Figure Component

const Figure = (props) => {
    const [path, setPath] = useState({FUNCTION TO CALCULATE THE SVG PATH});

    return(
        <G>
            <Path d={path} />
        </G>
    )
}

Parent Component

const Parent = (props) => {
    return (
        <View>
            <Svg>
                <G transform={ROTATE AND TRANSFORM BASED ON INTERACTION}>

                </G>
            </Svg>
        </View>
    )
}

As you can see I am using a state for the path data. My questions now:

Am I ensuring here that this path is only calculated once on start?

Is there a more elegant/better way of doing this (e.g. I am not using the setter function at all right now, so I don't feel like this is the best practice)

EDIT:

The function to calculate the path depends on some props I am passing from the parent component.

Body:
You can use the hook useMemo, it returns the value to your const, it receives the function that returns the value and also an array, send an empty one to calculate just once, you can send some dependencies, props or state if needed to recalculate the value when they change.

In your case you can do something like this:

const Figure = (props) => {
    const path = React.useMemo(() => {
      // calculate and return value for path
    }, []);

    return(
        <G>
            <Path d={path} />
        </G>
    )
}

It was created for that porpuse.

Hope it helps ;)!


问:
My code throws an error about a NoneType, but it should be defined
I've tried to redefine the location, but it won't stop throwing a NoneType error.

I've also tried to define the direction as well in the class, but to no avail. I've also tried to remove the declaring off the location in the Head init function, with no change.

```<code>Traceback (most recent call last):
  File "main.py", line 55, in <module>
    head.draw()
  File "main.py", line 39, in draw
    start_point = (self.location[0] + paddingSize, self.location[0] + paddingSize)
TypeError: 'NoneType' object is not subscriptable
</code>```

import pygame

size = 24
paddingSize = 1
displaySize = 960

def add(a, b):
    a = list(a)
    for xi in range(len(a)):
        a[xi] += b[xi]

class SnakePart:
    location = (0, 0)  # x, y
    direction = (0, 0)

    def __init__(self, next_part, direction):
        self.direction = direction
        self.location = next_part.location
        if direction[0]:  # up
            self.location[0] += 1
        elif not direction[0]:  # down
            self.location[0] -= 1
        elif direction[1]:  # right
            self.location[0] += 1
        elif not direction[1]:  # left
            self.location[0] -= 1

class Head(SnakePart):
    def __init__(self, start_pos, direction):
        self.location = start_pos
        self.direction = direction

    def move(self, direction):
        self.direction = direction

    def draw(self):
        start_point = (self.location[0] + paddingSize, self.location[0] + paddingSize)
        end_point = (start_point[0] + paddingSize + sizeOfSquare, start_point[1] + paddingSize + sizeOfSquare)
        self.location = add(self.location, self.direction)
        pygame.draw.rect(surface, (52, 60, 107), pygame.Rect(start_point, end_point))

pygame.display.init()
display = pygame.display.set_mode(size=(displaySize, displaySize))
surface = pygame.display.get_surface()
sizeOfSquare = (displaySize/size)-paddingSize*2
clock = pygame.time.Clock()
pygame.key.set_repeat(100)
head = Head((0, 0), (-1, 0))
while True:
    clock.tick(60)
    display.fill((0, 0, 0))
    head.draw()
```

答: add() doesn't return a value, so location becomes None, leading to your Exception.</p>

Body:
I've tried to redefine the location, but it won't stop throwing a NoneType error.

I've also tried to define the direction as well in the class, but to no avail. I've also tried to remove the declaring off the location in the Head init function, with no change.

Traceback (most recent call last):
  File "main.py", line 55, in <module>
    head.draw()
  File "main.py", line 39, in draw
    start_point = (self.location[0] + paddingSize, self.location[0] + paddingSize)
TypeError: 'NoneType' object is not subscriptable

import pygame

size = 24
paddingSize = 1
displaySize = 960

def add(a, b):
    a = list(a)
    for xi in range(len(a)):
        a[xi] += b[xi]

class SnakePart:
    location = (0, 0)  # x, y
    direction = (0, 0)

    def __init__(self, next_part, direction):
        self.direction = direction
        self.location = next_part.location
        if direction[0]:  # up
            self.location[0] += 1
        elif not direction[0]:  # down
            self.location[0] -= 1
        elif direction[1]:  # right
            self.location[0] += 1
        elif not direction[1]:  # left
            self.location[0] -= 1

class Head(SnakePart):
    def __init__(self, start_pos, direction):
        self.location = start_pos
        self.direction = direction

    def move(self, direction):
        self.direction = direction

    def draw(self):
        start_point = (self.location[0] + paddingSize, self.location[0] + paddingSize)
        end_point = (start_point[0] + paddingSize + sizeOfSquare, start_point[1] + paddingSize + sizeOfSquare)
        self.location = add(self.location, self.direction)
        pygame.draw.rect(surface, (52, 60, 107), pygame.Rect(start_point, end_point))

pygame.display.init()
display = pygame.display.set_mode(size=(displaySize, displaySize))
surface = pygame.display.get_surface()
sizeOfSquare = (displaySize/size)-paddingSize*2
clock = pygame.time.Clock()
pygame.key.set_repeat(100)
head = Head((0, 0), (-1, 0))
while True:
    clock.tick(60)
    display.fill((0, 0, 0))
    head.draw()


问:
Use multiquantile groups from a large dataframe in a grouped dataframe in R
I have the next problem, I have a large dataframe, in which I have to extract the quantiles from a variable but by group, by instance:

```<code>list_q <- list()

for (i in 3:5){

  tmp <- mtcars %>%
    filter(gear == i) %>%
    pull(mpg) %>%
    quantile(probs = seq(0, 1, 0.25), na.rm = TRUE)

  list_q[[i]] <- tmp

}

list_q
</code>```

With this output:

```<code>[[3]]
  0%  25%  50%  75% 100%
10.4 14.5 15.5 18.4 21.5

[[4]]
    0%    25%    50%    75%   100%
17.800 21.000 22.800 28.075 33.900

[[5]]
  0%  25%  50%  75% 100%
15.0 15.8 19.7 26.0 30.4
</code>```

Now, I need to group the variable means and determine which quantile it belongs but using the original measures:

```<code>a <- mtcars %>%
  group_by(gear, carb) %>%
  summarize(mpg_mean = mean(mpg)) %>%
  ungroup()

    gear  carb mpg_mean
   <dbl> <dbl>    <dbl>
 1     3     1     20.3
 2     3     2     17.2
 3     3     3     16.3
 4     3     4     12.6
 5     4     1     29.1
 6     4     2     24.8
 7     4     4     19.8
 8     5     2     28.2
 9     5     4     15.8
10     5     6     19.7
11     5     8     15
</code>```

So I could do this:

```<code>
g3 <- a %>%
  filter(gear == 3) %>%
  mutate(quantile = cut(mpg_mean, list_q[[3]], labels = FALSE, include.lowest = TRUE))

g4 <- a %>%
  filter(gear == 4) %>%
  mutate(quantile = cut(mpg_mean, list_q[[4]], labels = FALSE, include.lowest = TRUE))

g5 <- a %>%
  filter(gear == 5) %>%
  mutate(quantile = cut(mpg_mean, list_q[[5]], labels = FALSE, include.lowest = TRUE))

bind_rows(g3, g4, g5)
</code>```

Obtaining:

```<code># A tibble: 11 x 4
    gear  carb mpg_mean quantile
   <dbl> <dbl>    <dbl>    <int>
 1     3     1     20.3        4
 2     3     2     17.2        3
 3     3     3     16.3        3
 4     3     4     12.6        1
 5     4     1     29.1        4
 6     4     2     24.8        3
 7     4     4     19.8        1
 8     5     2     28.2        4
 9     5     4     15.8        1
10     5     6     19.7        2
11     5     8     15          1
</code>```

I wish to know if there is a way to do this more efficiently

答:
We can first group_by gear and store the quantiles for mpg in a list. We can then also group_by carb to get mean of mpg value and use the quantiles stored in the list previously to cut this mean of mpg column.

```<code>library(dplyr)

mtcars %>%
  group_by(gear) %>%
  mutate(gear_q = list(quantile(mpg))) %>%
  group_by(carb, add = TRUE) %>%
  summarize(mpg_mean = mean(mpg),
            gear_q = list(first(gear_q))) %>%
  mutate(quantile = cut(mpg_mean, first(gear_q),
                        labels = FALSE, include.lowest = TRUE)) %>%
  select(-gear_q)

#    gear  carb mpg_mean quantile
#   <dbl> <dbl>    <dbl>    <int>
# 1     3     1     20.3        4
# 2     3     2     17.2        3
# 3     3     3     16.3        3
# 4     3     4     12.6        1
# 5     4     1     29.1        4
# 6     4     2     24.8        3
# 7     4     4     19.8        1
# 8     5     2     28.2        4
# 9     5     4     15.8        1
#10     5     6     19.7        2
#11     5     8     15          1
</code>```

Body:
I have the next problem, I have a large dataframe, in which I have to extract the quantiles from a variable but by group, by instance:

list_q <- list()

for (i in 3:5){

  tmp <- mtcars %>%
    filter(gear == i) %>%
    pull(mpg) %>%
    quantile(probs = seq(0, 1, 0.25), na.rm = TRUE)

  list_q[[i]] <- tmp

}

list_q

With this output:

[[3]]
  0%  25%  50%  75% 100%
10.4 14.5 15.5 18.4 21.5

[[4]]
    0%    25%    50%    75%   100%
17.800 21.000 22.800 28.075 33.900

[[5]]
  0%  25%  50%  75% 100%
15.0 15.8 19.7 26.0 30.4

Now, I need to group the variable means and determine which quantile it belongs but using the original measures:

a <- mtcars %>%
  group_by(gear, carb) %>%
  summarize(mpg_mean = mean(mpg)) %>%
  ungroup()

    gear  carb mpg_mean
   <dbl> <dbl>    <dbl>
 1     3     1     20.3
 2     3     2     17.2
 3     3     3     16.3
 4     3     4     12.6
 5     4     1     29.1
 6     4     2     24.8
 7     4     4     19.8
 8     5     2     28.2
 9     5     4     15.8
10     5     6     19.7
11     5     8     15

So I could do this:

g3 <- a %>%
  filter(gear == 3) %>%
  mutate(quantile = cut(mpg_mean, list_q[[3]], labels = FALSE, include.lowest = TRUE))

g4 <- a %>%
  filter(gear == 4) %>%
  mutate(quantile = cut(mpg_mean, list_q[[4]], labels = FALSE, include.lowest = TRUE))

g5 <- a %>%
  filter(gear == 5) %>%
  mutate(quantile = cut(mpg_mean, list_q[[5]], labels = FALSE, include.lowest = TRUE))

bind_rows(g3, g4, g5)

Obtaining:

# A tibble: 11 x 4
    gear  carb mpg_mean quantile
   <dbl> <dbl>    <dbl>    <int>
 1     3     1     20.3        4
 2     3     2     17.2        3
 3     3     3     16.3        3
 4     3     4     12.6        1
 5     4     1     29.1        4
 6     4     2     24.8        3
 7     4     4     19.8        1
 8     5     2     28.2        4
 9     5     4     15.8        1
10     5     6     19.7        2
11     5     8     15          1

I wish to know if there is a way to do this more efficiently

Body:
We can first group_by gear and store the quantiles for mpg in a list. We can then also group_by carb to get mean of mpg value and use the quantiles stored in the list previously to cut this mean of mpg column.

library(dplyr)

mtcars %>%
  group_by(gear) %>%
  mutate(gear_q = list(quantile(mpg))) %>%
  group_by(carb, add = TRUE) %>%
  summarize(mpg_mean = mean(mpg),
            gear_q = list(first(gear_q))) %>%
  mutate(quantile = cut(mpg_mean, first(gear_q),
                        labels = FALSE, include.lowest = TRUE)) %>%
  select(-gear_q)

#    gear  carb mpg_mean quantile
#   <dbl> <dbl>    <dbl>    <int>
# 1     3     1     20.3        4
# 2     3     2     17.2        3
# 3     3     3     16.3        3
# 4     3     4     12.6        1
# 5     4     1     29.1        4
# 6     4     2     24.8        3
# 7     4     4     19.8        1
# 8     5     2     28.2        4
# 9     5     4     15.8        1
#10     5     6     19.7        2
#11     5     8     15          1


问:
Check if double are given with a specific accuracy
I have a vector of double. Those numbers are given with a precision such as 0.001 meaning that the numbers are given with a thousandth of units accuracy. For example I'm expecting to have 123456789.012 but not 123456789.01231. In practice, because of floating-point arithmetic the actual numbers are more like 123456789.01199999452 which is the valid and closest representation of 123456789.012.

I'd like to robustly test if my numbers are actually given with the accuracy there are supposed to be. For example I'd like to warn if I have the 123456789.01231 which does not match with the accuracy 0.001. Another valid option to me is to find the accuracy of a given number.

What I've done so far is to test if (x - offset)/accuracy is an integer. The offset protects against integer overflow. In practice, because of floating-point arithmetic, it cannot be an integer so I added an arbitrary threshold. It works but it is not a robust solution in my opinion.

dx = (x[i]-offset)/accuracy;
ix = std::round(dx);
if (std::abs(dx - ix) > 1e-5)
  throw exception("...");
```

No string is involved in this process. The numbers come from binary files or from runtime computations. The accuracy is given by the user and the numbers are expected to be compliant with this accuracy. In my previous example of 123456789.012 I do know that this number does not actually exist but 123456789.01199999452 is valid because it is its best representation with double. But 123456789.01231 (actually 123456789.01230999827) is not valid because it is not the best representation of the 3 digits rounded value.

答:
The problem stated in the question is suggestive of an attempt to use floating-point in ways it was not designed for, but there is insufficient information given to suggest alternatives. So, with some reluctance, here is a solution for the problem as stated.

```<code>/*  IsNearestValue(x, A) returns true iff x is the double number nearest to the
    nearest multiple of A', where A' is the unit fraction nearest A.  (All
    negative powers of 10, such as 10**-3, are unit fractions.)

    For example, IsNearestValue(x, .001) returns true iff x is the result of
    converting some number with three decimal digits after the decimal point
    to double.

    This routine presumes x/A <= 2**53.
*/
bool IsNearestValue(double x, double A)
{
    //  Calculate 1/A'.  The result has no rounding error.
    double reciprocal = std::round(1/A);

    /*  Find what multiple of A' x must be near.  This produces an exact
        result.  That is, t is an integer such that t * A' = x, with
        real-number arithmetic, not floating-point arithmetic.
    */
    double t = std::round(x * reciprocal);

    //  Calculate the double nearest t/A'.
    t /= reciprocal;

    //  Return true iff x is the double nearest t/A'.
    return x == t;
}
</code>```

The concept here is pretty simple. First, we correct the problem that A is given as a double, but none of the desired numbers (.1, .01, .001) can be represented in a double. However, their reciprocals can, so we take the reciprocal and round to get exactly the reciprocal of the desired number.

Then we multiply x by the reciprocal and round to the nearest integer. Then we divide that integer by the reciprocal, and that gives us the double that x must be if it is indeed the double nearest some multiply of the desired A.

I am not sure the constraint x/A ≤ 253 is necessary, but I have not tried to prove it is not, so I am leaving that bound unless there is further request.

Body:
I have a vector of double. Those numbers are given with a precision such as 0.001 meaning that the numbers are given with a thousandth of units accuracy. For example I'm expecting to have 123456789.012 but not 123456789.01231. In practice, because of floating-point arithmetic the actual numbers are more like 123456789.01199999452 which is the valid and closest representation of 123456789.012.

I'd like to robustly test if my numbers are actually given with the accuracy there are supposed to be. For example I'd like to warn if I have the 123456789.01231 which does not match with the accuracy 0.001. Another valid option to me is to find the accuracy of a given number.

What I've done so far is to test if (x - offset)/accuracy is an integer. The offset protects against integer overflow. In practice, because of floating-point arithmetic, it cannot be an integer so I added an arbitrary threshold. It works but it is not a robust solution in my opinion.

dx = (x[i]-offset)/accuracy;
ix = std::round(dx);
if (std::abs(dx - ix) > 1e-5)
  throw exception("...");

No string is involved in this process. The numbers come from binary files or from runtime computations. The accuracy is given by the user and the numbers are expected to be compliant with this accuracy. In my previous example of 123456789.012 I do know that this number does not actually exist but 123456789.01199999452 is valid because it is its best representation with double. But 123456789.01231 (actually 123456789.01230999827) is not valid because it is not the best representation of the 3 digits rounded value.

Body:
The problem stated in the question is suggestive of an attempt to use floating-point in ways it was not designed for, but there is insufficient information given to suggest alternatives. So, with some reluctance, here is a solution for the problem as stated.

/*  IsNearestValue(x, A) returns true iff x is the double number nearest to the
    nearest multiple of A', where A' is the unit fraction nearest A.  (All
    negative powers of 10, such as 10**-3, are unit fractions.)

    For example, IsNearestValue(x, .001) returns true iff x is the result of
    converting some number with three decimal digits after the decimal point
    to double.

    This routine presumes x/A <= 2**53.
*/
bool IsNearestValue(double x, double A)
{
    //  Calculate 1/A'.  The result has no rounding error.
    double reciprocal = std::round(1/A);

    /*  Find what multiple of A' x must be near.  This produces an exact
        result.  That is, t is an integer such that t * A' = x, with
        real-number arithmetic, not floating-point arithmetic.
    */
    double t = std::round(x * reciprocal);

    //  Calculate the double nearest t/A'.
    t /= reciprocal;

    //  Return true iff x is the double nearest t/A'.
    return x == t;
}

The concept here is pretty simple. First, we correct the problem that A is given as a double, but none of the desired numbers (.1, .01, .001) can be represented in a double. However, their reciprocals can, so we take the reciprocal and round to get exactly the reciprocal of the desired number.

Then we multiply x by the reciprocal and round to the nearest integer. Then we divide that integer by the reciprocal, and that gives us the double that x must be if it is indeed the double nearest some multiply of the desired A.

I am not sure the constraint x/A ≤ 253 is necessary, but I have not tried to prove it is not, so I am leaving that bound unless there is further request.


问:
Android SIP DTMF
I have set up my asterisk sip server in such a way where I would transfer a call by first dialling "*2",then the server would prompt me asking for the number to which I want to transfer the call and then I could dial the number. I want to make a JAVA function using the native android library.
In the code below base_call is the instance of SipAudioCall that hold the instance of the ongoing call.

```<code> public void transferCall() {
    base_call.sendDtmf(10);
    base_call.sendDtmf(2);
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    base_call.sendDtmf(7);
    base_call.sendDtmf(0);
    base_call.sendDtmf(0);
    base_call.sendDtmf(3);
}
</code>```

Here I am trying to transfer the call to 7003.The "*2" works and the server is prompting me to dial a number but the dialling of numbers does not work.

答: This worked by setting appropriate time lag between sending the dtmf codes.</p>

Title: Android SIP DTMF

Body:
I have set up my asterisk sip server in such a way where I would transfer a call by first dialling "*2",then the server would prompt me asking for the number to which I want to transfer the call and then I could dial the number. I want to make a JAVA function using the native android library.
In the code below base_call is the instance of SipAudioCall that hold the instance of the ongoing call.

 public void transferCall() {
    base_call.sendDtmf(10);
    base_call.sendDtmf(2);
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    base_call.sendDtmf(7);
    base_call.sendDtmf(0);
    base_call.sendDtmf(0);
    base_call.sendDtmf(3);
}

Here I am trying to transfer the call to 7003.The "*2" works and the server is prompting me to dial a number but the dialling of numbers does not work.


问:
MySQL - Join by only append a row of aggregated values from source table to each of selected rows on host table
I have a situation which I can describe in a simple way as below.

Table A has fields X, Y, and Z.

Table B is a reference table with fields P and Q.

Y targets to P as foreign reference.

X-Y is not set as unique because the paired values is repeatable.

X-Y-Z is generally distinct but Z is only text in type so it is not indexed.

In a select query from table A, I only want to append to each row based on their value of Y, the sum of all values of Q. But when I do something like below, it shows only one single row for each distinct X-Y value.

```<code>select X, Z, sum(Q) from A where ___ join B on Y = P group by X, Y
</code>```

Is there any other way I could try before I consider adding an ID field as last option?

答:
If you perform the aggregation from B in a derived table, you can then JOIN that to table A to get the SUM on every row of A:

```<code>SELECT A.*, B.Q
FROM A
JOIN (SELECT P, SUM(Q) AS Q
      FROM B
      GROUP BY P) B ON B.P = A.Y
</code>```

Body:
I have a situation which I can describe in a simple way as below.

Table A has fields X, Y, and Z.

Table B is a reference table with fields P and Q.

Y targets to P as foreign reference.

X-Y is not set as unique because the paired values is repeatable.

X-Y-Z is generally distinct but Z is only text in type so it is not indexed.

In a select query from table A, I only want to append to each row based on their value of Y, the sum of all values of Q. But when I do something like below, it shows only one single row for each distinct X-Y value.

select X, Z, sum(Q) from A where ___ join B on Y = P group by X, Y

Is there any other way I could try before I consider adding an ID field as last option?

Body:
If you perform the aggregation from B in a derived table, you can then JOIN that to table A to get the SUM on every row of A:

SELECT A.*, B.Q
FROM A
JOIN (SELECT P, SUM(Q) AS Q
      FROM B
      GROUP BY P) B ON B.P = A.Y


问:
Serialize and Deserialize from Vec<u32>
I have a struct of 5 u32s that implements serialize/deserialize by simply serializing: (s.first, s.second, s.third, s.fourth, s.fifth).

However this needs to be packed and unpacked from a flat buffer of Vec<u32> or an Option<Vec32> that represent the data: essentially every 5 u32s is a new struct. I keep struggling with the visitor implementation. Is there an easy way to do this while sharing code between the Option and non Option cases?

I really want to do impl Serialize for Vec<MyType> (and Deserialize) but that doesn't work.

答:
I ended up abandoning my Serialize and Deserialize impls and went with #[serde(with="my_mod"] for the Vec<MyType> case.

For the Option<Vec<MyType>> case I ended up creating wrapper types that inverted the relationship so that what I was really serializing/deserializing were Option<Wrapper { Vec<T> }>

Title: Serialize and Deserialize from Vec<u32>


问:
Member function template to call a funcion on a data member with arbitrary arguments
I'm working on a C++11 code base and wondering how I can call any function on a member type passing arbitrary arguments. Note that since I'm using C++11 I can't use something like std::invoke.

I started creating a function template in the Outer class, but my initial try gives me a compile error.

```<code>#include <iostream>
#include <utility>
#include <type_traits>

struct Inner {
  void bar(int x) {
    std::cout << "Called: x=" << x << std::endl;
  }
};

struct Outer {
  explicit Outer(Inner *i) : b{i} {}
  void foo(int) {}
  Inner* b;

  template <typename Func, typename ... Args>
  void CallInner(Func&& f, Args&& ... args) {
    b->f(std::forward<Args>(args)...);
  }
};

int main() {
  Inner inner{};
  Outer outer(&inner);
  outer.CallInner(&Inner::bar, 5);
}
</code>```

Try it out yourself

Again, I would like to keep the signature of the function CallInner unchanged from the above sample code.

答:
You don't have much choice with regards to changing the signature, because at least one additional template is required.

The correct syntax is a little bit more complicated:

```<code>struct Outer {
  explicit Outer(Inner *i) : b{i} {}
  void foo(int) {}
  Inner* b;

    template <typename Ret, typename ...FuncArgs,  typename ... Args>
    void CallInner(Ret (Inner::*f)(FuncArgs...), Args&& ... args) {
        (b->*f)(std::forward<Args>(args)...);
  }
};
</code>```

The first parameter to CallInner must be a method pointer, and, in a template context, it needs to be templated not just by a set of variadic template parameters, FuncArgs, but also its return type, Ret. Then you also need a second set of variadic template parameters for the forwarding references of the arguments you're forwarding (which may not necessarily be the same as FuncArgs, hence the need for a separate set of variadic template types).

Body:
I'm working on a C++11 code base and wondering how I can call any function on a member type passing arbitrary arguments. Note that since I'm using C++11 I can't use something like std::invoke.

I started creating a function template in the Outer class, but my initial try gives me a compile error.

#include <iostream>
#include <utility>
#include <type_traits>

struct Inner {
  void bar(int x) {
    std::cout << "Called: x=" << x << std::endl;
  }
};

struct Outer {
  explicit Outer(Inner *i) : b{i} {}
  void foo(int) {}
  Inner* b;

  template <typename Func, typename ... Args>
  void CallInner(Func&& f, Args&& ... args) {
    b->f(std::forward<Args>(args)...);
  }
};

int main() {
  Inner inner{};
  Outer outer(&inner);
  outer.CallInner(&Inner::bar, 5);
}

Try it out yourself

Again, I would like to keep the signature of the function CallInner unchanged from the above sample code.

Body:
You don't have much choice with regards to changing the signature, because at least one additional template is required.

The correct syntax is a little bit more complicated:

struct Outer {
  explicit Outer(Inner *i) : b{i} {}
  void foo(int) {}
  Inner* b;

    template <typename Ret, typename ...FuncArgs,  typename ... Args>
    void CallInner(Ret (Inner::*f)(FuncArgs...), Args&& ... args) {
        (b->*f)(std::forward<Args>(args)...);
  }
};

The first parameter to CallInner must be a method pointer, and, in a template context, it needs to be templated not just by a set of variadic template parameters, FuncArgs, but also its return type, Ret. Then you also need a second set of variadic template parameters for the forwarding references of the arguments you're forwarding (which may not necessarily be the same as FuncArgs, hence the need for a separate set of variadic template types).


答:
Since f is a pointer a member function it needs to be dereferenced first before being called:

```<code>(b->*f)(std::forward<Args>(args)...);
</code>```

Title: Member function template to call a funcion on a data member with arbitrary arguments

Body:
Since f is a pointer a member function it needs to be dereferenced first before being called:

(b->*f)(std::forward<Args>(args)...);


问:
"Unknown bits set in runtime_flags: 0x8000" warning in Logcat on Android Q emulator
I'm getting this warning as the first line from my app in logcat, and I have no idea what it refers to and how I should go about fixing it. Google doesn't offer much info on this (in fact, none at all). Please advise. What kind of flags might this be about? Is there a way to find out what the specified bit might refer to (or, perhaps, has been referring to on older Android versions but has become invalid in Android 10)? There is no such line in the log on Android 9 or earlier versions.</p>

答:
I bring a stone to the building. I retrace the code for the error message. It is at line 345 in the C ++ file dalvik_system_ZygoteHooks.cc
At a minimum, if (runtime_flags! = 0) then the error message will be printed. 0x8000 also corresponds to the USE_APP_IMAGE_STARTUP_CACHE flag (see line 157). The test on the USE_APP_IMAGE_STARTUP_CACHE flag is done on line 340. Normally, runtime_flags should no longer have a raised bit for USE_APP_IMAGE_STARTUP_CACHE but this does not seem to be the case since the error is printed.

But in the end, the error does not seem to have an impact on the application.


问:
react useEffect fetch data is completed but returning a value is undefined
I am using useEffect to fetch array data then display items. When I fetch data I could see that the data is fetched successfully.

But when I try to display data in the view it gives me an error Cannot read property 'name' of undefined

I think the view is rendering before the fetch. But I used async await to make sure the useEffect is called first.

Any idea of how to get the data display in the view?

Any comments or advice would be really helpful. Thanks in advance :)

```<code>const FetchUsers = () => {

    const [data, setData] = useState([])
    const [loading, setLoading] = useState([])
    const URL = "myurl..."

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get(URL, {headers: {"x-access-token":memberToken}});
            const response = await res;
            console.log(response.data.data,'data')
            //when I console log
            // [{…}, {…}] "data"
            //0: { name: "kevin", age: 39}
            //1: { name: "john", age: 23}
            console.log(response.data.data[0].title, 'name')
            setData(response.data.data);
            setLoading(false);
        }
        fetchData()
    }, [])

  return(

    <View>
      //I am trying to display fetched data
      <Text>{data[0].name}</Text>
    </View>
    )
  }
</code>```

答:
useEffect() will only trigger once the component is finished rendering and when the state or props changes. In your case, you are displaying the name attribute at initial render. This is the lifecycle, render > useEffect > props/state change? > useEffect > render.

use this instead:

```<code>return (
    <View>
        <Text>{data.length > 0 ? data[0].name : 'Fetching...'}</Text>
    </View>
);
</code>```

Body:
I am using useEffect to fetch array data then display items. When I fetch data I could see that the data is fetched successfully.

But when I try to display data in the view it gives me an error Cannot read property 'name' of undefined

I think the view is rendering before the fetch. But I used async await to make sure the useEffect is called first.

Any idea of how to get the data display in the view?

Any comments or advice would be really helpful. Thanks in advance :)

const FetchUsers = () => {

    const [data, setData] = useState([])
    const [loading, setLoading] = useState([])
    const URL = "myurl..."

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get(URL, {headers: {"x-access-token":memberToken}});
            const response = await res;
            console.log(response.data.data,'data')
            //when I console log
            // [{…}, {…}] "data"
            //0: { name: "kevin", age: 39}
            //1: { name: "john", age: 23}
            console.log(response.data.data[0].title, 'name')
            setData(response.data.data);
            setLoading(false);
        }
        fetchData()
    }, [])

  return(

    <View>
      //I am trying to display fetched data
      <Text>{data[0].name}</Text>
    </View>
    )
  }

Body:
useEffect() will only trigger once the component is finished rendering and when the state or props changes. In your case, you are displaying the name attribute at initial render. This is the lifecycle, render > useEffect > props/state change? > useEffect > render.

use this instead:

return (
    <View>
        <Text>{data.length > 0 ? data[0].name : 'Fetching...'}</Text>
    </View>
);


问:
Got 'Cannot find module' error when I tried to import certain JS file
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

```<code>function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}
</code>```

And this blogpost.js import publication.js

```<code>import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}
</code>```

And finally main.js import blogpost.js

```<code>import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);
</code>```

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

```<code>> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js
</code>```

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

```<code>internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}
</code>```

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

```<code>babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1
</code>```

Lastley, about .babelrc

```<code>{
  "presets": ["env"]
}
</code>```

and package.json build,

```<code>{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }
</code>```

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

答:
Okay it turns out, I should combine both of answers above.

First, I have to check whether my import plugin is right or wrong.
So I just re-installed it.

```<code>npm install babel-plugin-import --save-dev
</code>```

Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc

```<code>{
    "presets": ["es2015"],
    "plugins": [["import", { "libraryName": "antd" }]]
}
</code>```

this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.

And also next stuff, I have to make import path to be corrected.

```<code>import { create as newBlogPost } from "blogpost.js";
</code>```

change this to

```<code>import { create as newBlogPost } from "./blogpost.js";
</code>```

By doing this, now I can get a result that I wanted so far.

```<code>PS C:\Users\leePC\babel\public\lib> node main.js

    Title: For and against let
    By: Kyle Simpson
    October 27, 2014
</code>```

So majorly,
1. Check whether I missed some plugins or packages ( in my cases, I forgot import package )
2. Make sure to check your import path

Thank you for help guys.

Body:
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}

And this blogpost.js import publication.js

import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}

And finally main.js import blogpost.js

import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1

Lastley, about .babelrc

{
  "presets": ["env"]
}

and package.json build,

{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

Body:
Okay it turns out, I should combine both of answers above.

First, I have to check whether my import plugin is right or wrong.
So I just re-installed it.

npm install babel-plugin-import --save-dev

Make sure not to forget put plugin opitions. In my cases, I use this in .babelrc

{
    "presets": ["es2015"],
    "plugins": [["import", { "libraryName": "antd" }]]
}

this "plugins": [["import", { "libraryName": "antd" }] line means import js modulary.

And also next stuff, I have to make import path to be corrected.

import { create as newBlogPost } from "blogpost.js";

change this to

import { create as newBlogPost } from "./blogpost.js";

By doing this, now I can get a result that I wanted so far.

PS C:\Users\leePC\babel\public\lib> node main.js

    Title: For and against let
    By: Kyle Simpson
    October 27, 2014

So majorly,
1. Check whether I missed some plugins or packages ( in my cases, I forgot import package )
2. Make sure to check your import path

Thank you for help guys.


问:
Glove: training with single text file. Does GLoVE try to read it into memory? Or is it streamed?
I need to train some glove models to compare them with word2vec and fasttext output.  It's implemented in C, and I can't read C code.  The github is here.

The training corpus needs to be formatted into a single text file.  For me, this would be >>100G -- way too big for memory.  Before I waste time constructing such a thing, I'd be grateful if someone could tell me whether the glove algo tries to read the thing into memory, or whether it streams it from disk.

If the former, then glove's current implementation wouldn't be compatible with my data (I think).  If the latter, I'd have at it.

答:
Glove first constructs a word co-occurrence matrix and later works on that. While constructing this matrix, the linked implementation streams the input file on several threads. Each thread reads one line at a time.

The required memory will be mainly dependent on the amount of unique words in your corpus, as long as lines are not excessively long.


问:
What's the proper way to set CachingStrategy to RecycleElement in Xamarin Forms?
I've been getting an error (but my code still runs with it so I've been ignoring it until now) saying that my BindableListView is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.

I'm guessing this is the cause of another crash I'm getting: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Xamarin.Forms.Platform.Android.FormsTextView'
because I've seen suggestions online saying that most of the time, this issue is related to the ListView, and that I should set the CachingStrategy to RecycleElement.

So I decided to finally take a look at the BindableListView and add in the CachingStrategy = "RecycleElement"

Now there was already some code implemented that seemed to try and add the CachingStrategy already:

BindableListView.cs:

```<code>namespace MyApp.Core.Controls
{
    [PropertyChanged.DoNotNotify]
    public class BindableListView : ListView
    {
        public static BindableProperty ItemClickedProperty = BindableProperty.Create(nameof(ItemClicked), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty ItemAppearsProperty = BindableProperty.Create(nameof(ItemAppears), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty AnimateScrollToSelectedItemProperty = BindableProperty.Create(nameof(AnimateScrollToSelectedItem), typeof(bool), typeof(BindableListView), true);

        /// <summary>
        /// Constructs a <see cref="BindableListView"/>
        /// </summary>
        /// <param name="cachingStrategy">Sets the caching strategy for the <see cref="ListView"/>.</param>
        /// <example><![CDATA[
        /// <controls:BindableListView>
        ///  <x:Arguments>
        ///    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
        ///  </x:Arguments>
        /// </controls:BindableListView>
        /// ]]></example>
        public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
        {
            ItemTapped += OnItemTapped;
            ItemAppearing += OnItemAppearing;
            ItemSelected += OnItemSelected;
    ...
</code>```

Then in all the .xaml files that use this ListView:

```<code><controls:BindableListView
      ...>
      <x:Arguments>
        <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
      </x:Arguments>
</code>```

Would this be the correct way to set CachingStrategy to Recycle Element? If so then how would I go about fixing my error(s)?

Or should I remove the parameter from the constructor in BindableListView.cs to make it parameterless, and then just add the one line CachingStrategy = "RecycleElement" ? I tried this and the error went away at least.. (app won't run now though, "missing default ctor") but I don't know if it's the right thing to do. If this is what I'm supposed to do, will this fix my second error as well?

Thanks!

答:
From your code, I think it is the correct way to set CachingStrategy to Recycle Element.

According to this document:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/performance

The solution to this issue is to specify a constructor on the subclassed ListView that accepts a ListViewCachingStrategy parameter and passes it into the base class:

```<code>public class CustomListView : ListView
{

   public CustomListView (ListViewCachingStrategy strategy) : base (strategy)
    {

    }
    ...
}
</code>```

Then the ListViewCachingStrategy enumeration value can be specified from XAML by using the x:Arguments syntax

```<code><local:CustomListView>
<x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
</x:Arguments>
</code>```

Body:
I've been getting an error (but my code still runs with it so I've been ignoring it until now) saying that my BindableListView is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.

I'm guessing this is the cause of another crash I'm getting: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Xamarin.Forms.Platform.Android.FormsTextView'
because I've seen suggestions online saying that most of the time, this issue is related to the ListView, and that I should set the CachingStrategy to RecycleElement.

So I decided to finally take a look at the BindableListView and add in the CachingStrategy = "RecycleElement"

Now there was already some code implemented that seemed to try and add the CachingStrategy already:

BindableListView.cs:

namespace MyApp.Core.Controls
{
    [PropertyChanged.DoNotNotify]
    public class BindableListView : ListView
    {
        public static BindableProperty ItemClickedProperty = BindableProperty.Create(nameof(ItemClicked), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty ItemAppearsProperty = BindableProperty.Create(nameof(ItemAppears), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty AnimateScrollToSelectedItemProperty = BindableProperty.Create(nameof(AnimateScrollToSelectedItem), typeof(bool), typeof(BindableListView), true);

        ///
        /// Constructs a <see cref="BindableListView"/>
        ///
        /// <param name="cachingStrategy">Sets the caching strategy for the <see cref="ListView"/>.</param>
        /// <example><![CDATA[
        /// <controls:BindableListView>
        ///  <x:Arguments>
        ///    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
        ///  </x:Arguments>
        /// </controls:BindableListView>
        /// ]]></example>
        public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
        {
            ItemTapped += OnItemTapped;
            ItemAppearing += OnItemAppearing;
            ItemSelected += OnItemSelected;
    ...

Then in all the .xaml files that use this ListView:

<controls:BindableListView
      ...>
      <x:Arguments>
        <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
      </x:Arguments>

Would this be the correct way to set CachingStrategy to Recycle Element? If so then how would I go about fixing my error(s)?

Or should I remove the parameter from the constructor in BindableListView.cs to make it parameterless, and then just add the one line CachingStrategy = "RecycleElement" ? I tried this and the error went away at least.. (app won't run now though, "missing default ctor") but I don't know if it's the right thing to do. If this is what I'm supposed to do, will this fix my second error as well?

Thanks!

Body:
From your code, I think it is the correct way to set CachingStrategy to Recycle Element.

According to this document:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/performance

The solution to this issue is to specify a constructor on the subclassed ListView that accepts a ListViewCachingStrategy parameter and passes it into the base class:

public class CustomListView : ListView
{

   public CustomListView (ListViewCachingStrategy strategy) : base (strategy)
    {

    }
    ...
}

Then the ListViewCachingStrategy enumeration value can be specified from XAML by using the x:Arguments syntax

<local:CustomListView>
<x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
</x:Arguments>


答:
When you pass a value to useState that value is used to initialize the state. It does not get set every time the component rerenders, so in your case the path is only ever set when the component mounts.

Even if the props change, the path state will not.

As your initial state depends on a prop, all you need to do is pull the relevant prop out of your props and pass it to the function that calculates the initial path value:

```<code>const Figure = (props) => {
  // get relevant prop
  const { importantProp } = props;

  // path will never change, even when props change
  const [path] = useState(calculatePath(importantProp));

  return(
    <G>
      <Path d={path} />
    </G>
  )
}
</code>```

However, the calculatePath function still gets evaluated every render, even though the path value is not re-initialized. If calculatePath is an expensive operation, then consider using useMemo instead:

You can ensure that path is updated only when a specific prop changes by adding that prop to the dependency array:

```<code>const Figure = (props) => {
  const { importantProp } = props;

  const path = useMemo(() => calculatePath(importantProp), [importantProp]);

  return(
    <G>
      <Path d={path} />
    </G>
  )
}
</code>```

And in that case, you don't need state at all.

Adding the importantProp to the useMemo dependency array means that every time importantProp changes, React will recalculate your path variable.

Using useMemo will prevent the expensive calculation from being evaluated on every render.

I've created a CodeSandbox example where you can see in the console that the path is only re-calculated when the specified prop important changes. If you change any other props, the path does not get recalculated.

Title: How to ensure a constant inside a component is only calculated once on start in React (Native) with hooks?

Body:
I am currently creating a React Native app and still am unsure about how to best handle states for my use case.

I use react-native-svg to create a rather complex figure in the app, which is stored in a component, stays constant and is retrieved in a parent component. This parent component is then regularly rotated and translated on the canvas, but the path of the complex figure does not change. Therefore, and because the calculations are rather heavy, I would like to calculate the SVG path of that figure only on the start of the app, but not whenever I rotate or translate the parent component. Currently, my code structure looks like this:

Figure Component

const Figure = (props) => {
    const [path, setPath] = useState({FUNCTION TO CALCULATE THE SVG PATH});

    return(
        <G>
            <Path d={path} />
        </G>
    )
}

Parent Component

const Parent = (props) => {
    return (
        <View>
            <Svg>
                <G transform={ROTATE AND TRANSFORM BASED ON INTERACTION}>

                </G>
            </Svg>
        </View>
    )
}

As you can see I am using a state for the path data. My questions now:

Am I ensuring here that this path is only calculated once on start?

Is there a more elegant/better way of doing this (e.g. I am not using the setter function at all right now, so I don't feel like this is the best practice)

EDIT:

The function to calculate the path depends on some props I am passing from the parent component.

Body:
When you pass a value to useState that value is used to initialize the state. It does not get set every time the component rerenders, so in your case the path is only ever set when the component mounts.

Even if the props change, the path state will not.

As your initial state depends on a prop, all you need to do is pull the relevant prop out of your props and pass it to the function that calculates the initial path value:

const Figure = (props) => {
  // get relevant prop
  const { importantProp } = props;

  // path will never change, even when props change
  const [path] = useState(calculatePath(importantProp));

  return(
    <G>
      <Path d={path} />
    </G>
  )
}

However, the calculatePath function still gets evaluated every render, even though the path value is not re-initialized. If calculatePath is an expensive operation, then consider using useMemo instead:

You can ensure that path is updated only when a specific prop changes by adding that prop to the dependency array:

const Figure = (props) => {
  const { importantProp } = props;

  const path = useMemo(() => calculatePath(importantProp), [importantProp]);

  return(
    <G>
      <Path d={path} />
    </G>
  )
}

And in that case, you don't need state at all.

Adding the importantProp to the useMemo dependency array means that every time importantProp changes, React will recalculate your path variable.

Using useMemo will prevent the expensive calculation from being evaluated on every render.

I've created a CodeSandbox example where you can see in the console that the path is only re-calculated when the specified prop important changes. If you change any other props, the path does not get recalculated.


问:
MySQL fetchall() - how to get data inside a dict rather than inside a tuple
I've a table having columns as id, col1, col2, col3. I executed the query in this way.

```<code>cur.execute(query)
row = cur.fetchall()
</code>```

Can I get the data of row inside a dict ,ie I want to pass this result as a result to an api.

cur.fetchall() will yield me result in the following format ((id,col1,col2,col3),(id,col1,col2,col3),(id,col1,col2,col3))

Can I get result in

```<code>[
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value}
]
</code>```

I know this concept that I can loop around fetchall(), and get values using dictionary concept, ie

```<code>rows = cursor.fetchall()
for row in rows:
   id = row['id']
   col1 = row['col1']
   and so on...
</code>```

Can I pass rows as a dictionary??

答:
The easiest way to do it is to use the DictCursor:

```<code>import MySQLdb
...
cursor = db.cursor(MySQLdb.cursors.DictCursor)
</code>```

You can also set this for all cursors generated by db by passing the cursor_class parameter to connect

Documentation for the different types of cursors is here: https://mysqlclient.readthedocs.io/user_guide.html#using-and-extending

ContentLicense: CC BY-SA 3.0

Body:
I've a table having columns as id, col1, col2, col3. I executed the query in this way.

cur.execute(query)
row = cur.fetchall()

Can I get the data of row inside a dict ,ie I want to pass this result as a result to an api.

cur.fetchall() will yield me result in the following format ((id,col1,col2,col3),(id,col1,col2,col3),(id,col1,col2,col3))

Can I get result in

[
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value},
   {id:value,col1:value,col2:value,col3:value}
]

I know this concept that I can loop around fetchall(), and get values using dictionary concept, ie

rows = cursor.fetchall()
for row in rows:
   id = row['id']
   col1 = row['col1']
   and so on...

Can I pass rows as a dictionary??

Body:
The easiest way to do it is to use the DictCursor:

import MySQLdb
...
cursor = db.cursor(MySQLdb.cursors.DictCursor)

You can also set this for all cursors generated by db by passing the cursor_class parameter to connect

Documentation for the different types of cursors is here: https://mysqlclient.readthedocs.io/user_guide.html#using-and-extending


问:
material design not recognize
Here is my folder:

```<code>-app
     -content
     -footer
     -header
       -main-header
         {other services - shortcut} <- I just shortcut this bec. it is too long.
         main-header.component.html
         main-header.component.scss
         main-header.component.spec.ts
         main-header.module.ts
         main-header.routing.ts
     app.component.html
     etc..
</code>```

main-header module

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MainHeaderComponent } from './main-header.component';
import { MainHeaderRouteModule } from './main-header.routing';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatCardModule } from '@angular/material/card';
import { MatSidenavModule } from '@angular/material/sidenav';
import { FormsModule } from '@angular/forms';
import { LayoutModule } from '@angular/cdk/layout';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';

@NgModule({
  declarations: [
    MainHeaderComponent
  ],
  imports: [
    MatCardModule,
    MatCheckboxModule,
    MatSidenavModule,
    FormsModule,
    LayoutModule,
    MatToolbarModule,
    MatButtonModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MainHeaderRouteModule,
    CommonModule
  ]
})
export class MainHeaderModule {}
</code>```

main-header.routing

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainHeaderComponent } from './main-header.component';

const routes: Routes = [
  {path: '', component: MainHeaderComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainHeaderRouteModule {}
</code>```

app module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MainHeaderComponent } from './header/main-header/main-header.component';

@NgModule({
  declarations: [
    AppComponent,
    MainHeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  exports: [
    MainHeaderComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.routing.module

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: '', redirectTo: 'main-header', pathMatch: 'full'},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

Since I am using a lazyloading route, it seems that the main-module doesn't recognize angular material:

'mat-sidenav-container' is not a known element:
1. If 'mat-sidenav-container' is an Angular component, then verify that it is part of this module.
2. If 'mat-sidenav-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]

答: i dont see you importing your MainHeaderModule anywhere in app.module</p>

Title: material design not recognize

Body:
Here is my folder:

-app
     -content
     -footer
     -header
       -main-header
         {other services - shortcut} <- I just shortcut this bec. it is too long.
         main-header.component.html
         main-header.component.scss
         main-header.component.spec.ts
         main-header.module.ts
         main-header.routing.ts
     app.component.html
     etc..

main-header module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MainHeaderComponent } from './main-header.component';
import { MainHeaderRouteModule } from './main-header.routing';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatCardModule } from '@angular/material/card';
import { MatSidenavModule } from '@angular/material/sidenav';
import { FormsModule } from '@angular/forms';
import { LayoutModule } from '@angular/cdk/layout';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';

@NgModule({
  declarations: [
    MainHeaderComponent
  ],
  imports: [
    MatCardModule,
    MatCheckboxModule,
    MatSidenavModule,
    FormsModule,
    LayoutModule,
    MatToolbarModule,
    MatButtonModule,
    MatIconModule,
    MatListModule,
    MatCardModule,
    MainHeaderRouteModule,
    CommonModule
  ]
})
export class MainHeaderModule {}

main-header.routing

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainHeaderComponent } from './main-header.component';

const routes: Routes = [
  {path: '', component: MainHeaderComponent}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MainHeaderRouteModule {}

app module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MainHeaderComponent } from './header/main-header/main-header.component';

@NgModule({
  declarations: [
    AppComponent,
    MainHeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  exports: [
    MainHeaderComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.routing.module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {path: '', redirectTo: 'main-header', pathMatch: 'full'},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Since I am using a lazyloading route, it seems that the main-module doesn't recognize angular material:

'mat-sidenav-container' is not a known element:
1. If 'mat-sidenav-container' is an Angular component, then verify that it is part of this module.
2. If 'mat-sidenav-container' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]


问:
How can I create a function that takes a parameter of unknown type in C?
Say I have the following code:

```<code>struct test* t1;
t1 = get_t(1);
</code>```

... where get_t is:

```<code>struct test* get_t(int);
</code>```

How can I refactor the above code and put it in a function? Something like the following:

```<code>void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);
</code>```

答:
I have two ideas:

[1] Pass void pointer to the variable/object, and type cast it in the function.

[2] Make a union of all datatypes along with an integer datatype which will identify which datatype variable in the union does hold the actual data. Pass this union as value or as void *

```<code>struct _unknown {
   union {
      int a;
      float b;
      char c;
      double d;
   } data;
   int type;
} unknown;
.
.
.
if (unknown.type == FLOAT)
{
  /* Process variable b */
}
else if (unknown.type == INT)
{
 /* Process variable a */
}
.
.
.
</code>```

Something like this.

You can hash define the FLOAT and INT and others as unique values.

Or simply

```<code>struct _unknown {
  void *data;
  int type;
} unknown;
.
.
.
if (unknown == FLOAT)
{
  /* process (float *) data */
}
else if (unknown == INT)
{
  /* process (int *) data */
}
else if (unknown == MY_DATA_TYPE)
{
  /* process (my_data_type *) data */
  /* where my_data_type could be a typedef, or struct */
}
</code>```

Body:
Say I have the following code:

struct test* t1;
t1 = get_t(1);

... where get_t is:

struct test* get_t(int);

How can I refactor the above code and put it in a function? Something like the following:

void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);

Body:
I have two ideas:

[1] Pass void pointer to the variable/object, and type cast it in the function.

[2] Make a union of all datatypes along with an integer datatype which will identify which datatype variable in the union does hold the actual data. Pass this union as value or as void *

struct _unknown {
   union {
      int a;
      float b;
      char c;
      double d;
   } data;
   int type;
} unknown;
.
.
.
if (unknown.type == FLOAT)
{
  /* Process variable b */
}
else if (unknown.type == INT)
{
 /* Process variable a */
}
.
.
.

Something like this.

You can hash define the FLOAT and INT and others as unique values.

Or simply

struct _unknown {
  void *data;
  int type;
} unknown;
.
.
.
if (unknown == FLOAT)
{
  /* process (float *) data */
}
else if (unknown == INT)
{
  /* process (int *) data */
}
else if (unknown == MY_DATA_TYPE)
{
  /* process (my_data_type *) data */
  /* where my_data_type could be a typedef, or struct */
}


问:
Parse nested fields in json from REST API into PostgreSQL with psycopg
I'm working on a project in python where I get a json from a REST API using requests and then proceed to load it into a PostgreSQL database. The json the API responds with is strctured like shown below. My main issue is concerning the nested fields, like location.lat and the fields nested in the info array, like info[0].value.

{

```<code>"items": [
    {
        "id": 300436,
        "item_id_parent": null,
        "reference": "",
        "subreference1": "CAMS\/1",
        "subreference2": "CAMS\/1",
        "reference_alpha": null,
        "reference_numeric": null,
        "oid": "CAMS\/1",
        "code": null,
        "code_custom": null,
        "name": "284",
        "image": "https:\/\/static.inventsys.com.br\/278\/thumb\/f-3298886-200x200c.jpg",
        "situations": [],
        "project_id": 10762,
        "project": {
            "id": 10762,
            "name": "Fauna EGR",
            "color": null
        },
        "category_id": 20685,
        "category": {
            "id": 20685,
            "name": "EGR FAUNA - Armadilhas"
        },
        "area_id": null,
        "area": null,
        "location": {
            "lat": -30.136699676514,
            "lng": -50.910511016846,
            "address": {
                "region": "RS",
                "city": "Viamão",
                "district": null,
                "zipcode": null,
                "street": "Rodovia Tapir Rocha",
                "street_number": null,
                "desc": null,
                "full": "Rodovia Tapir Rocha Viamão \/ BR"
            }
        },
        "event_last": null,
        "description": null,
        "search_terms": "CAMS\/1 284 Fauna EGR EGR FAUNA - Armadilhas Rodovia Tapir Rocha Viamão \/ BR",
        "info": [
            {
                "id": 42725,
                "name": "Observacoes",
                "type": "longtext",
                "value": null,
                "fvalue": null,
                "description": null,
                "ikey": null,
                "group": "Fauna EGR",
                "preload": false,
                "filling": false,
                "primary": false,
                "created": null
            },
            {
                "id": 44542,
                "name": "Data de instalacao",
                "type": "date",
                "value": null,
                "fvalue": null,
                "description": null,
                "ikey": null,
                "group": "Fauna EGR",
                "preload": false,
                "filling": false,
                "primary": false,
                "created": null
            },...
</code>```

So far I get that I need to name the fields and establish a placeholder for each variable in my table, and this is what I have thus far:

```<code>import psycopg2

conn = psycopg2.connect("host=localhost dbname=postgres user=guilhermeiablonovski") cur = conn.cursor()

dbarmadilhas = """DROP TABLE IF EXISTS egrfauna_armadilhas; CREATE UNLOGGED TABLE IF NOT EXISTS egrfauna_armadilhas( id text PRIMARY KEY, name text, image text, category_id integer, category_name text, latitude real, longitude real, imagem_orig text, observacoes text, instalacao DATE, IDcartao text, IDcamera text, IDbueiro text, estrada text, foto_armadilha text, gps_lat real, gps_long real, gps_alt real, gps_acc real);"""

cur.execute(dbarmadilhas) conn.commit()

armadilha_fields = [
    'id',
    'name',
    'image',
    'category_id',
    'category.name',
    'location.lat',
    'location.lng',
    'files[0].url_orig',
    'files[1].url_low',
    'info[0].value',
    'info[1].value',
    'info[2].value',
    'info[3].value',
    'info[4].value',
    'info[5].value',
    'info[6].value',
    'info[7].value',
    'info[8].value',
    'info[9].value',
    'info[10].value',
    'info[11].value' ]

for item in registros:
    my_data = [item[field] for field in armadilha_fields]
    # need a placeholder (%s) for each variable
    # refer to postgres docs on INSERT statement on how to specify order
    cur.execute("INSERT INTO egrfauna_armadilhas VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(my_data))

conn.commit()
</code>```

The issue here is that if I run the code with just the first four variables, it works fine, so I guess my syntax is all wrong when it comes to the nested fields I want to parse. How best could I refer to those fields?

Thank you all in advance!

答:
for future reference, solved it like so:</p>

```<code>for item in registros:
    armadilhafields = [
    item['id'],
    item['name'],
    item['image'],
    item['category_id'],
    item['category']['name'],
    item['location']['lat'],
    item['location']['lng'],
    item['files'][0]['url_orig'],
    item['info'][0]['value'],
    item['info'][1]['value'],
    item['info'][2]['value'],
    item['info'][3]['value'],
    item['info'][4]['value'],
    item['info'][5]['value'],
    item['info'][6]['value'],
    item['info'][7]['value'],
    item['info'][8]['value'],
    item['info'][9]['value'],
    item['info'][10]['value'],
    ]
    my_data = [field for field in armadilhafields]
    cur.execute("INSERT INTO egrfauna_armadilhas VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(my_data))

conn.commit()
</code>```

Body:
I'm working on a project in python where I get a json from a REST API using requests and then proceed to load it into a PostgreSQL database. The json the API responds with is strctured like shown below. My main issue is concerning the nested fields, like location.lat and the fields nested in the info array, like info[0].value.

{

"items": [
    {
        "id": 300436,
        "item_id_parent": null,
        "reference": "",
        "subreference1": "CAMS\/1",
        "subreference2": "CAMS\/1",
        "reference_alpha": null,
        "reference_numeric": null,
        "oid": "CAMS\/1",
        "code": null,
        "code_custom": null,
        "name": "284",
        "image": "https:\/\/static.inventsys.com.br\/278\/thumb\/f-3298886-200x200c.jpg",
        "situations": [],
        "project_id": 10762,
        "project": {
            "id": 10762,
            "name": "Fauna EGR",
            "color": null
        },
        "category_id": 20685,
        "category": {
            "id": 20685,
            "name": "EGR FAUNA - Armadilhas"
        },
        "area_id": null,
        "area": null,
        "location": {
            "lat": -30.136699676514,
            "lng": -50.910511016846,
            "address": {
                "region": "RS",
                "city": "Viamão",
                "district": null,
                "zipcode": null,
                "street": "Rodovia Tapir Rocha",
                "street_number": null,
                "desc": null,
                "full": "Rodovia Tapir Rocha Viamão \/ BR"
            }
        },
        "event_last": null,
        "description": null,
        "search_terms": "CAMS\/1 284 Fauna EGR EGR FAUNA - Armadilhas Rodovia Tapir Rocha Viamão \/ BR",
        "info": [
            {
                "id": 42725,
                "name": "Observacoes",
                "type": "longtext",
                "value": null,
                "fvalue": null,
                "description": null,
                "ikey": null,
                "group": "Fauna EGR",
                "preload": false,
                "filling": false,
                "primary": false,
                "created": null
            },
            {
                "id": 44542,
                "name": "Data de instalacao",
                "type": "date",
                "value": null,
                "fvalue": null,
                "description": null,
                "ikey": null,
                "group": "Fauna EGR",
                "preload": false,
                "filling": false,
                "primary": false,
                "created": null
            },...

So far I get that I need to name the fields and establish a placeholder for each variable in my table, and this is what I have thus far:

import psycopg2

conn = psycopg2.connect("host=localhost dbname=postgres user=guilhermeiablonovski") cur = conn.cursor()

dbarmadilhas = """DROP TABLE IF EXISTS egrfauna_armadilhas; CREATE UNLOGGED TABLE IF NOT EXISTS egrfauna_armadilhas( id text PRIMARY KEY, name text, image text, category_id integer, category_name text, latitude real, longitude real, imagem_orig text, observacoes text, instalacao DATE, IDcartao text, IDcamera text, IDbueiro text, estrada text, foto_armadilha text, gps_lat real, gps_long real, gps_alt real, gps_acc real);"""

cur.execute(dbarmadilhas) conn.commit()

armadilha_fields = [
    'id',
    'name',
    'image',
    'category_id',
    'category.name',
    'location.lat',
    'location.lng',
    'files[0].url_orig',
    'files[1].url_low',
    'info[0].value',
    'info[1].value',
    'info[2].value',
    'info[3].value',
    'info[4].value',
    'info[5].value',
    'info[6].value',
    'info[7].value',
    'info[8].value',
    'info[9].value',
    'info[10].value',
    'info[11].value' ]

for item in registros:
    my_data = [item[field] for field in armadilha_fields]
    # need a placeholder (%s) for each variable
    # refer to postgres docs on INSERT statement on how to specify order
    cur.execute("INSERT INTO egrfauna_armadilhas VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(my_data))

conn.commit()

The issue here is that if I run the code with just the first four variables, it works fine, so I guess my syntax is all wrong when it comes to the nested fields I want to parse. How best could I refer to those fields?

Thank you all in advance!

Body:
for future reference, solved it like so:

for item in registros:
    armadilhafields = [
    item['id'],
    item['name'],
    item['image'],
    item['category_id'],
    item['category']['name'],
    item['location']['lat'],
    item['location']['lng'],
    item['files'][0]['url_orig'],
    item['info'][0]['value'],
    item['info'][1]['value'],
    item['info'][2]['value'],
    item['info'][3]['value'],
    item['info'][4]['value'],
    item['info'][5]['value'],
    item['info'][6]['value'],
    item['info'][7]['value'],
    item['info'][8]['value'],
    item['info'][9]['value'],
    item['info'][10]['value'],
    ]
    my_data = [field for field in armadilhafields]
    cur.execute("INSERT INTO egrfauna_armadilhas VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(my_data))

conn.commit()


问:
Can not load the `model1` function of the processR package in a Jupyter Notebook
I am very new to the whole R programming and trying to follow this tutorial, where the model1 function is used to find the Andrew F. Hayes correlation between three variables. As indicated in the tutorial I have the packages installed:

install.packages("devtools")

install.packages("processR")

devtools::install_github("markhwhiteii/processr")

I have also followed the steps:

set.seed(1839)
var1 <- rnorm(100)
cond <- rbinom(100, 1, .5)
var2 <- var1 * cond + rnorm(100)
df3 <- data.frame(var1, var2, cond)
head(df3)
```

<p>accordingly. However, when running:</p>

```mod1result <- model1(iv = "var1", dv = "var2", mod = "cond", data = df3)
```

<p>I get the error message:</p>

<blockquote>
  <p>Error in model1(iv = "var1", dv = "var2", mod = "cond", data = df3): could not find function "model1"
  Traceback:</p>
</blockquote>

<p>and running</p>

```mod1result <- processr::model1(iv = "var1", dv = "var2", mod = "cond", data = df3)
```

Error in loadNamespace(name): there is no package called ‘processr’
  Traceback:

The strange thing is that the same code just worked yesterday and now it doesn't. I would appreciate it if you could help me understand what is wrong and how I can resolve it.

P.S.1. I'm not sure what .libPaths() is but for some reason it returns two paths on my mac:

/usr/local/lib/R/3.6/site-library

/usr/local/Cellar/r/3.6.2/lib/R/library

does it mean that I have two installations of R and this is the main cause of the above issues?

P.S.2. OK. This seems to be Jupyter's fault as everything is just working fine in the terminal.

P.S.3. What seems to be working in the terminal is:

sudo r

devtools::install_github("markhwhiteii/processr")

library(processr) notice lower case r in the processr

P.S.4. I'm not sure if this is Jupyter's fault.

P.S.5. I tried installing the packages on Windows as well. It was even worse. I can't get passed the issue:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove the prior installation of package ‘digest’

I think maybe the key to solving this problem is to understand what is the difference between these packages:

install.packages("processR")

devtools::install_github("markhwhiteii/processr")

devtools::install_github("cardiomoon/processR")

答:
OK, after a couple of hours of trial and error, I think I have a messy workaround, not a solution though!

run sudo r in one terminal

run jupyter notebook in another and open an R notebook (I suppose you have the kernel installed)

now you should understand that the devtools::install_github("markhwhiteii/processr") and install.packages("processR") are two different packages and you gave install both every time you restart your kernel in the Jupyter Notebook

install devtools::install_github("markhwhiteii/processr") first in the R terminal

now in the Jupyter side you should be able to library(processr) and run processr::model1

next install the install.packages("processR") on the R terminal

now import the library(processR)

now you should be able to run the functions such as pmacroModel etc

Basically you need both processr and processR!

BTW, the same issue is the R terminal. You have to run as sudo and follow the above steps to get everything working!

Body:
I am very new to the whole R programming and trying to follow this tutorial, where the model1 function is used to find the Andrew F. Hayes correlation between three variables. As indicated in the tutorial I have the packages installed:

install.packages("devtools")

install.packages("processR")

devtools::install_github("markhwhiteii/processr")

I have also followed the steps:

set.seed(1839)
var1 <- rnorm(100)
cond <- rbinom(100, 1, .5)
var2 <- var1 * cond + rnorm(100)
df3 <- data.frame(var1, var2, cond)
head(df3)

accordingly. However, when running:

mod1result <- model1(iv = "var1", dv = "var2", mod = "cond", data = df3)

I get the error message:

Error in model1(iv = "var1", dv = "var2", mod = "cond", data = df3): could not find function "model1"
  Traceback:

and running

mod1result <- processr::model1(iv = "var1", dv = "var2", mod = "cond", data = df3)

Error in loadNamespace(name): there is no package called ‘processr’
  Traceback:

The strange thing is that the same code just worked yesterday and now it doesn't. I would appreciate it if you could help me understand what is wrong and how I can resolve it.

P.S.1. I'm not sure what .libPaths() is but for some reason it returns two paths on my mac:

/usr/local/lib/R/3.6/site-library

/usr/local/Cellar/r/3.6.2/lib/R/library

does it mean that I have two installations of R and this is the main cause of the above issues?

P.S.2. OK. This seems to be Jupyter's fault as everything is just working fine in the terminal.

P.S.3. What seems to be working in the terminal is:

sudo r

devtools::install_github("markhwhiteii/processr")

library(processr) notice lower case r in the processr

P.S.4. I'm not sure if this is Jupyter's fault.

P.S.5. I tried installing the packages on Windows as well. It was even worse. I can't get passed the issue:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove the prior installation of package ‘digest’

I think maybe the key to solving this problem is to understand what is the difference between these packages:

install.packages("processR")

devtools::install_github("markhwhiteii/processr")

devtools::install_github("cardiomoon/processR")