问:
Open CV trivial circle detection -- how to get least squares instead of a contour?
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

```<code>(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image
</code>```

答:
An approach is to Gaussian blur
 then Otsu's threshold the image to obtain a binary image. From here, we perform morphological opening with a elliptical shaped kernel. This step will effectively remove the tiny noise particles. To obtain a nice estimate of the circle, we find contours and use cv2.minEnclosingCircle() which also gives us the center point and the radius. Here's a visualization:

Input image (screenshoted)

Binary image

Morph open

Result -> Result w/ radius

```<code>Radius: 122.11396026611328
</code>```

From here you can convert the radius in pixels to mm based on your calibration scale

Code

```<code>import cv2
import numpy as np

# Load image, convert to grayscale, Gaussian blur, then Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph open with a elliptical shaped kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

# Find contours and draw minimum enclosing circle
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    ((x, y), r) = cv2.minEnclosingCircle(c)
    cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 2)
    print('Radius: {}'.format(r))

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()
</code>```

Body:
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image

Body:
An approach is to Gaussian blur
 then Otsu's threshold the image to obtain a binary image. From here, we perform morphological opening with a elliptical shaped kernel. This step will effectively remove the tiny noise particles. To obtain a nice estimate of the circle, we find contours and use cv2.minEnclosingCircle() which also gives us the center point and the radius. Here's a visualization:

Input image (screenshoted)

Binary image

Morph open

Result -> Result w/ radius

Radius: 122.11396026611328

From here you can convert the radius in pixels to mm based on your calibration scale

Code

import cv2
import numpy as np

# Load image, convert to grayscale, Gaussian blur, then Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Morph open with a elliptical shaped kernel
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)

# Find contours and draw minimum enclosing circle
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    ((x, y), r) = cv2.minEnclosingCircle(c)
    cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 2)
    print('Radius: {}'.format(r))

cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('image', image)
cv2.waitKey()


来源: stackexchange

问:
Cannot decide about condition in while loop
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.</p>

```<code>#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}
</code>```

答:
Even though other answers correct they might too complicated for a beginners eyes. I would strongly advise the use a for loop for less confusion. Also give better names for your variables to make even more clear what is going on.

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

int main()
{
    int n, sum_even = 0, sum_odd = 0, number;

    printf("Enter Number of Integers:");
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        printf("Enter Number:");
        scanf("%d", &number);

        if (number % 2)
            sum_odd += number;
        else
            sum_even += number;

    }
    printf("Sum of Even Numbers: %d\n", sum_even);
    printf("Sum of Odd Numbers: %d\n", sum_odd);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.

#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}

Body:
Even though other answers correct they might too complicated for a beginners eyes. I would strongly advise the use a for loop for less confusion. Also give better names for your variables to make even more clear what is going on.

#include<stdio.h>

int main()
{
    int n, sum_even = 0, sum_odd = 0, number;

    printf("Enter Number of Integers:");
    scanf("%d", &n);

    for (int i = 0; i < n; i++)
    {
        printf("Enter Number:");
        scanf("%d", &number);

        if (number % 2)
            sum_odd += number;
        else
            sum_even += number;

    }
    printf("Sum of Even Numbers: %d\n", sum_even);
    printf("Sum of Odd Numbers: %d\n", sum_odd);
}


问:
Dynamics 365 WebAPI - How to get user access to an entity?
How can I retrieve the user access for an entity using Dynamics Web API? I am using v9.0

ie; Check if a user have read / create / edit access for an entity.

答:
These web api endpoints will help you to understand the things & achieve what you want.

```<code>https://crmdev.crm.dynamics.com/api/data/v9.1/systemusers(3bd2aded-20b2-e911-a98e-000d3a374b53)/Microsoft.Dynamics.CRM.RetrieveUserPrivileges()

https://crmdev.crm.dynamics.com/api/data/v9.1/privileges?$select=name
</code>```

For ex. When I pass my System User GUID to the first function - the second url result says I have Global (Organisation) level Create privilege.

```<code>{"Depth":"Global","PrivilegeId":"a8bff87f-0df0-41d4-babd-f093faf1e32c","BusinessUnitId":"b08c8c6c-5c20-e511-80f7-c4346bac59ac"}

{"@odata.etag":"W/\"101387508\"","name":"prvCreateContact","privilegeid":"a8bff87f-0df0-41d4-babd-f093faf1e32c"}
</code>```

Glossary:

Basic (User)

Local (Business Unit)

Deep (Parent: Child)

Global (Organisation)

Body:
These web api endpoints will help you to understand the things & achieve what you want.

https://crmdev.crm.dynamics.com/api/data/v9.1/systemusers(3bd2aded-20b2-e911-a98e-000d3a374b53)/Microsoft.Dynamics.CRM.RetrieveUserPrivileges()

https://crmdev.crm.dynamics.com/api/data/v9.1/privileges?$select=name

For ex. When I pass my System User GUID to the first function - the second url result says I have Global (Organisation) level Create privilege.

{"Depth":"Global","PrivilegeId":"a8bff87f-0df0-41d4-babd-f093faf1e32c","BusinessUnitId":"b08c8c6c-5c20-e511-80f7-c4346bac59ac"}

{"@odata.etag":"W/\"101387508\"","name":"prvCreateContact","privilegeid":"a8bff87f-0df0-41d4-babd-f093faf1e32c"}

Glossary:

Basic (User)

Local (Business Unit)

Deep (Parent: Child)

Global (Organisation)


问:
Create one unified ditamap by replacing all maprefs with actual topicrefs
I have a set of ditamaps that are called recursively to create a single unified book. However, due to some issues with how chunking works in DITA, I would like to process the map files to replace all maprefs with actual topicrefs. I seek help in developing an XSLT to achieve this.
For example, the current implementation is:

```<code>map a
|_____map a1
|_____map a2
      |_______map a21
      |_______map a22
              |_______map a221
</code>```

This is achieved using maprefs to map a1, map a2, map a21...

What I need is one single map (Map_unified.ditamap) with all the topic refs in map a1, map a2, map a21, map a22, and map a221.

Can anyone please help me?

答:
There are ways to use XSLT or other scripting languages like Python to do what you want, but you can probably use the DITA Open Toolkit instead. If you use a late-model version of the DITA OT (like 3.4), try the Normalized DITA output. You get this by using the dita transtype. The command line would look something like this:

```<code>dita-ot-3.4>bin\dita --input=mymap.ditamap --format=dita
</code>```

So if you have an input map that looks like this:

```<code><map>
  <title>normalize map</title>
  <mapref keyref="api1"/>
  <keydef keys="api1" href="sub.ditamap" format="ditamap"></keydef>
</map>
</code>```

And sub.ditamap looks like this:

```<code><map>
  <title>submap</title>
  <topicref href="api-syntax/api-syntax.dita"/>
</map>
</code>```

It will output something like this:

```<code><map cascade="merge">
  <title>normalize map</title>
  <topicref href="api-syntax/api-syntax.dita" type="concept">
    <topicmeta>
      <navtitle>API Syntax</navtitle>
      <linktext>API Syntax</linktext>
    </topicmeta>
  </topicref>

  <keydef href="api-syntax/api-syntax.dita" processing-role="resource-only" type="concept">
    <topicmeta>
      <navtitle>API Syntax</navtitle>
      <linktext>API Syntax</linktext>
    </topicmeta>
  </keydef>
</map>
</code>```

You can get rid of the <keydef> element.

Body:
I have a set of ditamaps that are called recursively to create a single unified book. However, due to some issues with how chunking works in DITA, I would like to process the map files to replace all maprefs with actual topicrefs. I seek help in developing an XSLT to achieve this.
For example, the current implementation is:

map a
|_____map a1
|_____map a2
      |_______map a21
      |_______map a22
              |_______map a221

This is achieved using maprefs to map a1, map a2, map a21...

What I need is one single map (Map_unified.ditamap) with all the topic refs in map a1, map a2, map a21, map a22, and map a221.

Can anyone please help me?

Body:
There are ways to use XSLT or other scripting languages like Python to do what you want, but you can probably use the DITA Open Toolkit instead. If you use a late-model version of the DITA OT (like 3.4), try the Normalized DITA output. You get this by using the dita transtype. The command line would look something like this:

dita-ot-3.4>bin\dita --input=mymap.ditamap --format=dita

So if you have an input map that looks like this:

<map>
  <title>normalize map</title>
  <mapref keyref="api1"/>
  <keydef keys="api1" href="sub.ditamap" format="ditamap"></keydef>
</map>

And sub.ditamap looks like this:

<map>
  <title>submap</title>
  <topicref href="api-syntax/api-syntax.dita"/>
</map>

It will output something like this:

<map cascade="merge">
  <title>normalize map</title>
  <topicref href="api-syntax/api-syntax.dita" type="concept">
    <topicmeta>
      <navtitle>API Syntax</navtitle>
      <linktext>API Syntax</linktext>
    </topicmeta>
  </topicref>

  <keydef href="api-syntax/api-syntax.dita" processing-role="resource-only" type="concept">
    <topicmeta>
      <navtitle>API Syntax</navtitle>
      <linktext>API Syntax</linktext>
    </topicmeta>
  </keydef>
</map>

You can get rid of the <keydef> element.


问:
How to add argparser subcommands for a specific mode in this case?
I want to run my application in different modes, for example:

```<code>python3 ./myapp.py --mode server
</code>```

To do this, I created an argument parser and specified modes based on choices:

```<code>    _parser = argparse.ArgumentParser(description='some application')
    _parser.add_argument('--mode', dest='mode', action='store',  nargs=1, required=True,
                        choices={'server', 'client', 'stat', 'cli'}, help='Run app in selected mode')
</code>```

In 'cli' mode, I want to specify additional parameters, for example:

```<code>python3 ./myapp.py --mode cli run-command --with-arguments
</code>```

How to make such an option for processing arguments? Use a subparser for each mode instead of selecting from a 'choices'? Or are there other ways?

答: Use a subparser. AFAIK, arguments don't support nesting like you want.</p>

Body:
I want to run my application in different modes, for example:

python3 ./myapp.py --mode server

To do this, I created an argument parser and specified modes based on choices:

    _parser = argparse.ArgumentParser(description='some application')
    _parser.add_argument('--mode', dest='mode', action='store',  nargs=1, required=True,
                        choices={'server', 'client', 'stat', 'cli'}, help='Run app in selected mode')

In 'cli' mode, I want to specify additional parameters, for example:

python3 ./myapp.py --mode cli run-command --with-arguments

How to make such an option for processing arguments? Use a subparser for each mode instead of selecting from a 'choices'? Or are there other ways?


问:
Java 9.0.1 OpenJdk crashed the JVM with problem with AdaptiveWeightedAverage
My application failed for a customer crashing the JVM

I have these details:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0xb6b48b12, pid=31447, tid=31508
#
# JRE version: OpenJDK Runtime Environment (9.0+11) (build 9.0.1+11)
# Java VM: OpenJDK Client VM (9.0.1+11, mixed mode, serial gc, linux-)
# Problematic frame:
# V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55
#
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /mnt/system/config/Apps/SongKong/songkong/hs_err_pid31447.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#
</code>```

Does it look familar to anyone, I have search both https://bugs.java.com/bugdatabase/ and https://bugs.openjdk.java.net/secure/Dashboard.jspa without finding anything.

Here is the start of the hs_err_id log file

```<code>    #
    # A fatal error has been detected by the Java Runtime Environment:
    #
    #  SIGSEGV (0xb) at pc=0xb6aacb12, pid=13032, tid=13074
    #
    # JRE version: OpenJDK Runtime Environment (9.0+11) (build 9.0.1+11)
    # Java VM: OpenJDK Client VM (9.0.1+11, mixed mode, serial gc, linux-)
    # Problematic frame:
    # V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55
    #
    # No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
    #
    # If you would like to submit a bug report, please visit:
    #   http://bugreport.java.com/bugreport/crash.jsp
    #

    ---------------  S U M M A R Y ------------

    Command Line: -Duser.home=/mnt/disk1/share -Xms150m -Xmx900m -Dcom.mchange.v2.log.MLog=com.mchange.v2.log.jdk14logging.Jdk14MLog -Dorg.jboss.logging.provider=jdk -Djava.util.logging.config.class=com.jthink.songkong.logging.StandardLogging --add-opens=java.base/java.lang=ALL-UNNAMED lib/songkong-6.8.jar -r

    Host: Marvell PJ4Bv7 Processor rev 1 (v7l), 1 cores, 1G, Buildroot 2014.11-rc1
    Time: Fri Feb  7 01:50:35 2020 GMT elapsed time: 53621 seconds (0d 14h 53m 41s)

    ---------------  T H R E A D  ---------------

    Current thread (0xb6657d00):  VMThread "VM Thread" [stack: 0x7b7e9000,0x7b869000] [id=13074]

    Stack: [0x7b7e9000,0x7b869000],  sp=0x7b8677a0,  free space=505k
    Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
    V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55

    [error occurred during error reporting (printing native stack), id 0xb]

    siginfo: si_signo: 11 (SIGSEGV), si_code: 1 (SEGV_MAPERR), si_addr: 0x0000000a

    Register to memory mapping:

      r0  = 0x00000000
    0x00000000 is an unknown value

      r1  = 0x00000100
    0x00000100 is an unknown value

      r2  = 0x000001fc
    0x000001fc is an unknown value

      r3  = 0x00000023
    0x00000023 is an unknown value

      r4  = 0x783bf970
    0x783bf970 is an unknown value

      r5  = 0x00000000
    0x00000000 is an unknown value

      r6  = 0x0e6a0000
    0x0e6a0000 is an unknown value

      r7  = 0x00000000
    0x00000000 is an unknown value

      r8  = 0x783bf940
    0x783bf940 is an unknown value

      r9  = 0x0e6a0000
    0x0e6a0000 is an unknown value

      r10 = 0x7b8679ec
    0x7b8679ec is an unknown value

      fp  = 0xb6657c38
    0xb6657c38 is an unknown value

      r12 = 0xfffffefe
    0xfffffefe is an unknown value

      sp  = 0x7b8677a0
    0x7b8677a0 is an unknown value

      lr  = 0xb6c62daf
    0xb6c62daf: <offset 0x0038fdaf> in /mnt/system/config/Apps/SongKong/songkong/jre/lib/client/libjvm.so at 0xb68d3000

      pc  = 0xb6aacb12
    0xb6aacb12: <offset 0x001d9b12> in /mnt/system/config/Apps/SongKong/songkong/jre/lib/client/libjvm.so at 0xb68d3000

    Registers:
      r0  = 0x00000000
      r1  = 0x00000100
      r2  = 0x000001fc
      r3  = 0x00000023
      r4  = 0x783bf970
      r5  = 0x00000000
      r6  = 0x0e6a0000
      r7  = 0x00000000
      r8  = 0x783bf940
      r9  = 0x0e6a0000
      r10 = 0x7b8679ec
      fp  = 0xb6657c38
      r12 = 0xfffffefe
      sp  = 0x7b8677a0
      lr  = 0xb6c62daf
      pc  = 0xb6aacb12
      cpsr = 0x80000030

    Top of Stack: (sp=0x7b8677a0)
    0x7b8677a0:   00000000 404e0000 00000001 000b6448
    0x7b8677b0:   7b8677b8 b6c62daf b6d4c8b8 783bf910
    0x7b8677c0:   00000000 b660d800 7b867808 b6d1f000
    0x7b8677d0:   b662f310 b6c62f43 7b8679f6 b6cac9cc
    0x7b8677e0:   7b8677f0 b6d1f000 7b8679ec b6b1d987
    0x7b8677f0:   7b867820 7b8679f0 7b867800 b6a068a3
    0x7b867800:   00000400 7b867820 00000000 00000012
    0x7b867810:   b660d800 00000000 00000012 b660d800

    Instructions: (pc=0xb6aacb12)
    0xb6aacaf2:   ee064603 eeb83a10 ee377a46 ee286ac7
    0xb6aacb02:   ee667a07 ee876a86 eec67a27 ee777aa7
    0xb6aacb12:   edc47a87 46bd7a00 8b02ecbd 2064bd98
    0xb6aacb22:   f9e1f1fd 6a00edd4 0000e7db 480642c8

    VM_Operation (0x77c5daa0): GenCollectForAllocation, mode: safepoint, requested by thread 0x77a0d790

    ---------------  P R O C E S S  ---------------

    Java Threads: ( => current thread )
      0x742a7448 JavaThread "Thread-513" daemon [_thread_blocked, id=11706, stack(0x76a70000,0x76ac0000)]
      0x73db7458 JavaThread "Thread-510" daemon [_thread_blocked, id=11027, stack(0x773b6000,0x77406000)]
      0x732b66f0 JavaThread "Thread-509" daemon [_thread_blocked, id=10757, stack(0x77b70000,0x77bc0000)]
      0x762428e0 JavaThread "Thread-508" daemon [_thread_blocked, id=10130, stack(0x79310000,0x79360000)]
      0x74284f48 JavaThread "Thread-503" daemon [_thread_blocked, id=8094, stack(0x78210000,0x78260000)]
      0x76d60e10 JavaThread "qtp9318356-11036" [_thread_blocked, id=4101, stack(0x78410000,0x78460000)]
      0x762dc8f0 JavaThread "qtp9318356-11035" [_thread_blocked, id=4100, stack(0x79bc0000,0x79c10000)]
      0x783bf910 JavaThread "qtp9318356-9925" [_thread_blocked, id=22685, stack(0x78260000,0x782b0000)]
      0x732170a8 JavaThread "qtp9318356-5567" [_thread_blocked, id=9426, stack(0x76810000,0x76860000)]
      0x760e2708 JavaThread "qtp9318356-5564" [_thread_blocked, id=9423, stack(0x768b0000,0x76900000)]
      0x77a0d790 JavaThread "Worker:12" [_thread_blocked, id=18002, stack(0x77c10000,0x77c60000)]
      0x77a0daf0 JavaThread "pool-1639-thread-1" [_thread_blocked, id=17984, stack(0x77186000,0x771d6000)]
      0x76db5e88 JavaThread "Worker:11" [_thread_blocked, id=17983, stack(0x77316000,0x77366000)]
      0x783c9df8 JavaThread "Worker:10" [_thread_blocked, id=17982, stack(0x77406000,0x77456000)]
      0x77a25388 JavaThread "SongLoaderWorker:9" [_thread_blocked, id=17942, stack(0x77366000,0x773b6000)]
      0x76d6bce8 JavaThread "com.jthink.songkong.server.callback.ServerFixSongs:8" [_thread_blocked, id=17922, stack(0x793b0000,0x79400000)]
      0x769c7cb8 JavaThread "pool-1636-thread-2" [_thread_blocked, id=17764, stack(0x77276000,0x772c6000)]
      0x732c50d8 JavaThread "pool-1636-thread-1" [_thread_blocked, id=17763, stack(0x77036000,0x77086000)]
      0x7690e140 JavaThread "pool-1601-thread-2" [_thread_blocked, id=11810, stack(0x771d6000,0x77226000)]
      0x769077c8 JavaThread "pool-1601-thread-1" [_thread_blocked, id=11809, stack(0x77226000,0x77276000)]
      0x769368a8 JavaThread "MappedByteBufferSource Async Flush Thread" daemon [_thread_blocked, id=8920, stack(0x76fe6000,0x77036000)]
      0x77d9d990 JavaThread "com.jthink.songkong.fileloader.LoadFolderWorker:3" [_thread_blocked, id=380, stack(0x77eb0000,0x77f00000)]
      0x77d940d8 JavaThread "pool-429-thread-1" [_thread_blocked, id=374, stack(0x77e60000,0x77eb0000)]
      0x77d9c740 JavaThread "SongLoaderCountFiles:2" [_thread_blocked, id=373, stack(0x77cb0000,0x77d00000)]
      0x7b670218 JavaThread "qtp9318356-91" [_thread_blocked, id=32431, stack(0x79360000,0x793b0000)]
      0x7833f418 JavaThread "qtp9318356-90" [_thread_in_native, id=32430, stack(0x79db0000,0x79e00000)]
      0x7b6e7478 JavaThread "MVStore background writer async:/mnt/disk1/share/SongKong/Prefs/Database/Database.mv.db" daemon [_thread_blocked, id=27227, stack(0x79270000,0x792c0000)]
      0x7b670cf8 JavaThread "H2 File Lock Watchdog (Socket) async:/mnt/disk1/share/SongKong/Prefs/Database/Database.lock.db" daemon [_thread_blocked, id=27222, stack(0x7a61c000,0x7a66c000)]
      0x7b694750 JavaThread "Scheduler-7136558" [_thread_blocked, id=13763, stack(0x78560000,0x785b0000)]
      0x7b6786c0 JavaThread "Scheduler-14033461" [_thread_blocked, id=13428, stack(0x785b0000,0x78600000)]
      0x7b6717d8 JavaThread "qtp9318356-45-acceptor-0@4cfe9c-ServerConnector@8b18a5{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}" [_thread_in_native, id=13427, stack(0x7904c000,0x7909c000)]
      0x789c3e20 JavaThread "Thread-10" [_thread_blocked, id=13405, stack(0x791d0000,0x79220000)]
      0x7a0b4f10 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#2" daemon [_thread_blocked, id=13275, stack(0x7a66c000,0x7a6bc000)]
      0x7a0b4958 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#1" daemon [_thread_blocked, id=13274, stack(0x79b70000,0x79bc0000)]
      0x7a0b43c0 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#0" daemon [_thread_blocked, id=13273, stack(0x79920000,0x79970000)]
      0x7a0feb80 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-AdminTaskTimer" daemon [_thread_blocked, id=13272, stack(0x79c10000,0x79c60000)]
      0x7adb1358 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=13146, stack(0x7a7e3000,0x7a833000)]
      0xb66f12d8 JavaThread "Service Thread" daemon [_thread_blocked, id=13114, stack(0x7b2b6000,0x7b306000)]
      0xb66a1a20 JavaThread "Common-Cleaner" daemon [_thread_blocked, id=13105, stack(0x7b306000,0x7b356000)]
      0xb6675c88 JavaThread "Sweeper thread" daemon [_thread_blocked, id=13104, stack(0x7b356000,0x7b3a6000)]
      0xb6674978 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=13103, stack(0x7b3a6000,0x7b426000)]
      0xb666cdc8 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=13102, stack(0x7b426000,0x7b476000)]
      0xb6667688 JavaThread "Finalizer" daemon [_thread_blocked, id=13099, stack(0x7b748000,0x7b798000)]
      0xb665a900 JavaThread "Reference Handler" daemon [_thread_blocked, id=13088, stack(0x7b798000,0x7b7e8000)]
      0xb6609308 JavaThread "main" [_thread_blocked, id=13037, stack(0xb67d9000,0xb6828000)]

    Other Threads:
    =>0xb6657d00 VMThread "VM Thread" [stack: 0x7b7e9000,0x7b869000] [id=13074]
      0xb66f2a90 WatcherThread [stack: 0x7b236000,0x7b2b6000] [id=13115]

    Threads with active compile tasks:

VM state:at safepoint (normal execution)

VM Mutex/Monitor currently owned by a thread:  ([mutex/lock_event])
[0xb6608520] Threads_lock - owner thread: 0xb6657d00
[0xb6608930] Heap_lock - owner thread: 0x77a0d790

Heap:
 def new generation   total 265600K, used 265599K [0x7c000000, 0x8e020000, 0x8ec00000)
  eden space 236160K, 100% used [0x7c000000, 0x8a6a0000, 0x8a6a0000)
  from space 29440K,  99% used [0x8c360000, 0x8e01fff8, 0x8e020000)
  to   space 29440K,   0% used [0x8a6a0000, 0x8a6a0000, 0x8c360000)
 tenured generation   total 589672K, used 298477K [0x8ec00000, 0xb2bda000, 0xb4400000)
   the space 589672K,  50% used [0x8ec00000, 0xa0f7b5c0, 0xa0f7b600, 0xb2bda000)
 Metaspace       used 45545K, capacity 46775K, committed 46976K, reserved 47408K

Card table byte_map: [0x7be3d000,0x7c000000] byte_map_base: 0x7ba5d000

Polling page: 0xb6f30000
</code>```

答:
But surely the question is what does AdaptiveWeightedAverage do ?

If this was the intended question. Then you might have a look into the source.

hotspot/src/share/vm/gc/shared/gcUtil.cpp

```<code>// A weighted average maintains a running, weighted average
// of some float value (templates would be handy here if we
// need different types).
//
// The average is adaptive in that we smooth it for the
// initial samples; we don't use the weight until we have
// enough samples for it to be meaningful.
//
// This serves as our best estimate of a future unknown.
//
class AdaptiveWeightedAverage : public CHeapObj<mtGC> {
 private:
  float            _average;        // The last computed average
  unsigned         _sample_count;   // How often we've sampled this average
  unsigned         _weight;         // The weight used to smooth the averages
                                    //   A higher weight favors the most
                                    //   recent data.
  bool             _is_old;         // Has enough historical data
</code>```

hotspot/src/share/vm/gc/shared/gcUtil.hpp

```<code>void AdaptiveWeightedAverage::sample(float new_sample) {
  increment_count();

  // Compute the new weighted average
  float new_avg = compute_adaptive_average(new_sample, average());
  set_average(new_avg);
  _last_sample = new_sample;
}
</code>```

and

```<code>float AdaptiveWeightedAverage::compute_adaptive_average(float new_sample,
                                                        float average) {
  // We smooth the samples by not using weight() directly until we've
  // had enough data to make it meaningful. We'd like the first weight
  // used to be 1, the second to be 1/2, etc until we have
  // OLD_THRESHOLD/weight samples.
</code>```

It's used by the garbage collector.

Maybe somehow related to a problem with available memory. (it's a guess, don't have much experience with Java on ARM platform)

This lead me to this guess max heap -Xmx900m vs system memory 1G.

Body:
My application failed for a customer crashing the JVM

I have these details:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0xb6b48b12, pid=31447, tid=31508
#
# JRE version: OpenJDK Runtime Environment (9.0+11) (build 9.0.1+11)
# Java VM: OpenJDK Client VM (9.0.1+11, mixed mode, serial gc, linux-)
# Problematic frame:
# V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55
#
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /mnt/system/config/Apps/SongKong/songkong/hs_err_pid31447.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#

Does it look familar to anyone, I have search both https://bugs.java.com/bugdatabase/ and https://bugs.openjdk.java.net/secure/Dashboard.jspa without finding anything.

Here is the start of the hs_err_id log file

    #
    # A fatal error has been detected by the Java Runtime Environment:
    #
    #  SIGSEGV (0xb) at pc=0xb6aacb12, pid=13032, tid=13074
    #
    # JRE version: OpenJDK Runtime Environment (9.0+11) (build 9.0.1+11)
    # Java VM: OpenJDK Client VM (9.0.1+11, mixed mode, serial gc, linux-)
    # Problematic frame:
    # V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55
    #
    # No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
    #
    # If you would like to submit a bug report, please visit:
    #   http://bugreport.java.com/bugreport/crash.jsp
    #

    ---------------  S U M M A R Y ------------

    Command Line: -Duser.home=/mnt/disk1/share -Xms150m -Xmx900m -Dcom.mchange.v2.log.MLog=com.mchange.v2.log.jdk14logging.Jdk14MLog -Dorg.jboss.logging.provider=jdk -Djava.util.logging.config.class=com.jthink.songkong.logging.StandardLogging --add-opens=java.base/java.lang=ALL-UNNAMED lib/songkong-6.8.jar -r

    Host: Marvell PJ4Bv7 Processor rev 1 (v7l), 1 cores, 1G, Buildroot 2014.11-rc1
    Time: Fri Feb  7 01:50:35 2020 GMT elapsed time: 53621 seconds (0d 14h 53m 41s)

    ---------------  T H R E A D  ---------------

    Current thread (0xb6657d00):  VMThread "VM Thread" [stack: 0x7b7e9000,0x7b869000] [id=13074]

    Stack: [0x7b7e9000,0x7b869000],  sp=0x7b8677a0,  free space=505k
    Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
    V  [libjvm.so+0x1d9b12]  AdaptiveWeightedAverage::sample(float)+0x55

    [error occurred during error reporting (printing native stack), id 0xb]

    siginfo: si_signo: 11 (SIGSEGV), si_code: 1 (SEGV_MAPERR), si_addr: 0x0000000a

    Register to memory mapping:

      r0  = 0x00000000
    0x00000000 is an unknown value

      r1  = 0x00000100
    0x00000100 is an unknown value

      r2  = 0x000001fc
    0x000001fc is an unknown value

      r3  = 0x00000023
    0x00000023 is an unknown value

      r4  = 0x783bf970
    0x783bf970 is an unknown value

      r5  = 0x00000000
    0x00000000 is an unknown value

      r6  = 0x0e6a0000
    0x0e6a0000 is an unknown value

      r7  = 0x00000000
    0x00000000 is an unknown value

      r8  = 0x783bf940
    0x783bf940 is an unknown value

      r9  = 0x0e6a0000
    0x0e6a0000 is an unknown value

      r10 = 0x7b8679ec
    0x7b8679ec is an unknown value

      fp  = 0xb6657c38
    0xb6657c38 is an unknown value

      r12 = 0xfffffefe
    0xfffffefe is an unknown value

      sp  = 0x7b8677a0
    0x7b8677a0 is an unknown value

      lr  = 0xb6c62daf
    0xb6c62daf: <offset 0x0038fdaf> in /mnt/system/config/Apps/SongKong/songkong/jre/lib/client/libjvm.so at 0xb68d3000

      pc  = 0xb6aacb12
    0xb6aacb12: <offset 0x001d9b12> in /mnt/system/config/Apps/SongKong/songkong/jre/lib/client/libjvm.so at 0xb68d3000

    Registers:
      r0  = 0x00000000
      r1  = 0x00000100
      r2  = 0x000001fc
      r3  = 0x00000023
      r4  = 0x783bf970
      r5  = 0x00000000
      r6  = 0x0e6a0000
      r7  = 0x00000000
      r8  = 0x783bf940
      r9  = 0x0e6a0000
      r10 = 0x7b8679ec
      fp  = 0xb6657c38
      r12 = 0xfffffefe
      sp  = 0x7b8677a0
      lr  = 0xb6c62daf
      pc  = 0xb6aacb12
      cpsr = 0x80000030

    Top of Stack: (sp=0x7b8677a0)
    0x7b8677a0:   00000000 404e0000 00000001 000b6448
    0x7b8677b0:   7b8677b8 b6c62daf b6d4c8b8 783bf910
    0x7b8677c0:   00000000 b660d800 7b867808 b6d1f000
    0x7b8677d0:   b662f310 b6c62f43 7b8679f6 b6cac9cc
    0x7b8677e0:   7b8677f0 b6d1f000 7b8679ec b6b1d987
    0x7b8677f0:   7b867820 7b8679f0 7b867800 b6a068a3
    0x7b867800:   00000400 7b867820 00000000 00000012
    0x7b867810:   b660d800 00000000 00000012 b660d800

    Instructions: (pc=0xb6aacb12)
    0xb6aacaf2:   ee064603 eeb83a10 ee377a46 ee286ac7
    0xb6aacb02:   ee667a07 ee876a86 eec67a27 ee777aa7
    0xb6aacb12:   edc47a87 46bd7a00 8b02ecbd 2064bd98
    0xb6aacb22:   f9e1f1fd 6a00edd4 0000e7db 480642c8

    VM_Operation (0x77c5daa0): GenCollectForAllocation, mode: safepoint, requested by thread 0x77a0d790

    ---------------  P R O C E S S  ---------------

    Java Threads: ( => current thread )
      0x742a7448 JavaThread "Thread-513" daemon [_thread_blocked, id=11706, stack(0x76a70000,0x76ac0000)]
      0x73db7458 JavaThread "Thread-510" daemon [_thread_blocked, id=11027, stack(0x773b6000,0x77406000)]
      0x732b66f0 JavaThread "Thread-509" daemon [_thread_blocked, id=10757, stack(0x77b70000,0x77bc0000)]
      0x762428e0 JavaThread "Thread-508" daemon [_thread_blocked, id=10130, stack(0x79310000,0x79360000)]
      0x74284f48 JavaThread "Thread-503" daemon [_thread_blocked, id=8094, stack(0x78210000,0x78260000)]
      0x76d60e10 JavaThread "qtp9318356-11036" [_thread_blocked, id=4101, stack(0x78410000,0x78460000)]
      0x762dc8f0 JavaThread "qtp9318356-11035" [_thread_blocked, id=4100, stack(0x79bc0000,0x79c10000)]
      0x783bf910 JavaThread "qtp9318356-9925" [_thread_blocked, id=22685, stack(0x78260000,0x782b0000)]
      0x732170a8 JavaThread "qtp9318356-5567" [_thread_blocked, id=9426, stack(0x76810000,0x76860000)]
      0x760e2708 JavaThread "qtp9318356-5564" [_thread_blocked, id=9423, stack(0x768b0000,0x76900000)]
      0x77a0d790 JavaThread "Worker:12" [_thread_blocked, id=18002, stack(0x77c10000,0x77c60000)]
      0x77a0daf0 JavaThread "pool-1639-thread-1" [_thread_blocked, id=17984, stack(0x77186000,0x771d6000)]
      0x76db5e88 JavaThread "Worker:11" [_thread_blocked, id=17983, stack(0x77316000,0x77366000)]
      0x783c9df8 JavaThread "Worker:10" [_thread_blocked, id=17982, stack(0x77406000,0x77456000)]
      0x77a25388 JavaThread "SongLoaderWorker:9" [_thread_blocked, id=17942, stack(0x77366000,0x773b6000)]
      0x76d6bce8 JavaThread "com.jthink.songkong.server.callback.ServerFixSongs:8" [_thread_blocked, id=17922, stack(0x793b0000,0x79400000)]
      0x769c7cb8 JavaThread "pool-1636-thread-2" [_thread_blocked, id=17764, stack(0x77276000,0x772c6000)]
      0x732c50d8 JavaThread "pool-1636-thread-1" [_thread_blocked, id=17763, stack(0x77036000,0x77086000)]
      0x7690e140 JavaThread "pool-1601-thread-2" [_thread_blocked, id=11810, stack(0x771d6000,0x77226000)]
      0x769077c8 JavaThread "pool-1601-thread-1" [_thread_blocked, id=11809, stack(0x77226000,0x77276000)]
      0x769368a8 JavaThread "MappedByteBufferSource Async Flush Thread" daemon [_thread_blocked, id=8920, stack(0x76fe6000,0x77036000)]
      0x77d9d990 JavaThread "com.jthink.songkong.fileloader.LoadFolderWorker:3" [_thread_blocked, id=380, stack(0x77eb0000,0x77f00000)]
      0x77d940d8 JavaThread "pool-429-thread-1" [_thread_blocked, id=374, stack(0x77e60000,0x77eb0000)]
      0x77d9c740 JavaThread "SongLoaderCountFiles:2" [_thread_blocked, id=373, stack(0x77cb0000,0x77d00000)]
      0x7b670218 JavaThread "qtp9318356-91" [_thread_blocked, id=32431, stack(0x79360000,0x793b0000)]
      0x7833f418 JavaThread "qtp9318356-90" [_thread_in_native, id=32430, stack(0x79db0000,0x79e00000)]
      0x7b6e7478 JavaThread "MVStore background writer async:/mnt/disk1/share/SongKong/Prefs/Database/Database.mv.db" daemon [_thread_blocked, id=27227, stack(0x79270000,0x792c0000)]
      0x7b670cf8 JavaThread "H2 File Lock Watchdog (Socket) async:/mnt/disk1/share/SongKong/Prefs/Database/Database.lock.db" daemon [_thread_blocked, id=27222, stack(0x7a61c000,0x7a66c000)]
      0x7b694750 JavaThread "Scheduler-7136558" [_thread_blocked, id=13763, stack(0x78560000,0x785b0000)]
      0x7b6786c0 JavaThread "Scheduler-14033461" [_thread_blocked, id=13428, stack(0x785b0000,0x78600000)]
      0x7b6717d8 JavaThread "qtp9318356-45-acceptor-0@4cfe9c-ServerConnector@8b18a5{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}" [_thread_in_native, id=13427, stack(0x7904c000,0x7909c000)]
      0x789c3e20 JavaThread "Thread-10" [_thread_blocked, id=13405, stack(0x791d0000,0x79220000)]
      0x7a0b4f10 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#2" daemon [_thread_blocked, id=13275, stack(0x7a66c000,0x7a6bc000)]
      0x7a0b4958 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#1" daemon [_thread_blocked, id=13274, stack(0x79b70000,0x79bc0000)]
      0x7a0b43c0 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-HelperThread-#0" daemon [_thread_blocked, id=13273, stack(0x79920000,0x79970000)]
      0x7a0feb80 JavaThread "C3P0PooledConnectionPoolManager[identityToken->1hge13oa8796in41o2hlgl|1df6bb7]-AdminTaskTimer" daemon [_thread_blocked, id=13272, stack(0x79c10000,0x79c60000)]
      0x7adb1358 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=13146, stack(0x7a7e3000,0x7a833000)]
      0xb66f12d8 JavaThread "Service Thread" daemon [_thread_blocked, id=13114, stack(0x7b2b6000,0x7b306000)]
      0xb66a1a20 JavaThread "Common-Cleaner" daemon [_thread_blocked, id=13105, stack(0x7b306000,0x7b356000)]
      0xb6675c88 JavaThread "Sweeper thread" daemon [_thread_blocked, id=13104, stack(0x7b356000,0x7b3a6000)]
      0xb6674978 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=13103, stack(0x7b3a6000,0x7b426000)]
      0xb666cdc8 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=13102, stack(0x7b426000,0x7b476000)]
      0xb6667688 JavaThread "Finalizer" daemon [_thread_blocked, id=13099, stack(0x7b748000,0x7b798000)]
      0xb665a900 JavaThread "Reference Handler" daemon [_thread_blocked, id=13088, stack(0x7b798000,0x7b7e8000)]
      0xb6609308 JavaThread "main" [_thread_blocked, id=13037, stack(0xb67d9000,0xb6828000)]

    Other Threads:
    =>0xb6657d00 VMThread "VM Thread" [stack: 0x7b7e9000,0x7b869000] [id=13074]
      0xb66f2a90 WatcherThread [stack: 0x7b236000,0x7b2b6000] [id=13115]

    Threads with active compile tasks:

VM state:at safepoint (normal execution)

VM Mutex/Monitor currently owned by a thread:  ([mutex/lock_event])
[0xb6608520] Threads_lock - owner thread: 0xb6657d00
[0xb6608930] Heap_lock - owner thread: 0x77a0d790

Heap:
 def new generation   total 265600K, used 265599K [0x7c000000, 0x8e020000, 0x8ec00000)
  eden space 236160K, 100% used [0x7c000000, 0x8a6a0000, 0x8a6a0000)
  from space 29440K,  99% used [0x8c360000, 0x8e01fff8, 0x8e020000)
  to   space 29440K,   0% used [0x8a6a0000, 0x8a6a0000, 0x8c360000)
 tenured generation   total 589672K, used 298477K [0x8ec00000, 0xb2bda000, 0xb4400000)
   the space 589672K,  50% used [0x8ec00000, 0xa0f7b5c0, 0xa0f7b600, 0xb2bda000)
 Metaspace       used 45545K, capacity 46775K, committed 46976K, reserved 47408K

Card table byte_map: [0x7be3d000,0x7c000000] byte_map_base: 0x7ba5d000

Polling page: 0xb6f30000

Body:
But surely the question is what does AdaptiveWeightedAverage do ?

If this was the intended question. Then you might have a look into the source.

hotspot/src/share/vm/gc/shared/gcUtil.cpp

// A weighted average maintains a running, weighted average
// of some float value (templates would be handy here if we
// need different types).
//
// The average is adaptive in that we smooth it for the
// initial samples; we don't use the weight until we have
// enough samples for it to be meaningful.
//
// This serves as our best estimate of a future unknown.
//
class AdaptiveWeightedAverage : public CHeapObj<mtGC> {
 private:
  float            _average;        // The last computed average
  unsigned         _sample_count;   // How often we've sampled this average
  unsigned         _weight;         // The weight used to smooth the averages
                                    //   A higher weight favors the most
                                    //   recent data.
  bool             _is_old;         // Has enough historical data

hotspot/src/share/vm/gc/shared/gcUtil.hpp

void AdaptiveWeightedAverage::sample(float new_sample) {
  increment_count();

  // Compute the new weighted average
  float new_avg = compute_adaptive_average(new_sample, average());
  set_average(new_avg);
  _last_sample = new_sample;
}

and

float AdaptiveWeightedAverage::compute_adaptive_average(float new_sample,
                                                        float average) {
  // We smooth the samples by not using weight() directly until we've
  // had enough data to make it meaningful. We'd like the first weight
  // used to be 1, the second to be 1/2, etc until we have
  // OLD_THRESHOLD/weight samples.

It's used by the garbage collector.

Maybe somehow related to a problem with available memory. (it's a guess, don't have much experience with Java on ARM platform)

This lead me to this guess max heap -Xmx900m vs system memory 1G.


问:
What can be used as an identifier for a #define directive in C/C++
I'm curious as to what can be used as an identifier for the #define directive in C and/or C++. Is every string token legal?

For example, would the following code compile?

```<code>#define EMPTY ;;

for(EMPTY){
  function();
}
</code>```

答:
The rules are more or less the same as for other identifiers. Some names (e.g., those with a leading underscore followed by another underscore or a capital letter) are reserved for the implementation. In C++, names with two successive underscores (anywhere, not just the beginning) are reserved as well.

There is one other proviso that's specific to #define's in C++ (but not C): you're not allowed to re-define a reserved word. So a name like EMPTY is fine, but a name like for or auto would not be.

Body:
I'm curious as to what can be used as an identifier for the #define directive in C and/or C++. Is every string token legal?

For example, would the following code compile?

#define EMPTY ;;

for(EMPTY){
  function();
}


问:
Default assignment operator checks for self assignment
i would like to know if the default implementation of the assignment operator checks for self assignment, and so which of those two implementation can be considered the closest to the default one:

```<code>class A{
    int x;
public :
    ...
    // first one
    A& operator=(const A& a){
        if(this != &a) x = a.x;
        return *this;
    }
    // second one
    A& operator=(const A& a){
        x = a.x;
        return *this;
    }
}
</code>```

I've searched for C++ standard but the only one that i can found is this but there is nothing about this

答:
No, implementations do not check for "self":

https://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)

The copy assignment operator, often just called the "assignment
  operator", is a special case of assignment operator where the source
  (right-hand side) and destination (left-hand side) are of the same
  class type.

It is one of the special member functions, which means
  that a default version of it is generated automatically by the
  compiler if the programmer does not declare one.

The default version
  performs a memberwise copy, where each member is copied by its own
  copy assignment operator (which may also be programmer-declared or
  compiler-generated).

Body:
i would like to know if the default implementation of the assignment operator checks for self assignment, and so which of those two implementation can be considered the closest to the default one:

class A{
    int x;
public :
    ...
    // first one
    A& operator=(const A& a){
        if(this != &a) x = a.x;
        return *this;
    }
    // second one
    A& operator=(const A& a){
        x = a.x;
        return *this;
    }
}

I've searched for C++ standard but the only one that i can found is this but there is nothing about this


问:
alarmManager.cancel not working

I'm  trying to stop a repeating alarm.

I already looked all over the web for solution, but my code seems fine...

Still it doesn't stop the alarm...
Here's a little bit of code (FM is a file-writing object)

```<code>public void StartAlarm() {
     Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
     PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

     AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
     Calendar alarm = Calendar.getInstance();
     alarm.setTimeInMillis(System.currentTimeMillis());
     alarm.set(Calendar.HOUR_OF_DAY, 15);
     alarm.set(Calendar.MINUTE, 0);
     long alarmCal=alarm.getTimeInMillis();
     if (alarmCal<=new Date().getTime()) {
        alarm.add(Calendar.DAY_OF_MONTH, 1);
     }
     am.setRepeating(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
     FM.Write("startAlarm()");
     }

 public void StopAlarm() {
        if (isAlarmRunning()) {
             Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
             PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.cancel(sender);
            FM.Write("alarm canceled");
            isAlarmRunning();
        }
public boolean isAlarmRunning() {
    Intent intentToCheck = new Intent(getApplicationContext(),AlarmReciever.class);
    boolean alarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intentToCheck,
            PendingIntent.FLAG_NO_CREATE) != null;
    FM.Write("alarm = "+alarm);
    if (!alarm) {
        return false;
    }
    else
        return true;
}
</code>```

Thanks!

答:
Totally agree with Nokolay Elenkov, answer; just as mentioned from the question's comments the user is setting a ToggleButton based on whether the PendingIntent is active or not. And this is something different than if the alarm still registered or not.

And to match both things you have to cancel both of them; i.e. cancel the alarm, and cancel the PendingIntent.

```<code> Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE);
 myToggleButton.setChecked(pendingIntent != null);

 // Setting the alarm
 AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
 alarmManager.setRepeating();

 // Canceling the alarm
 alarmManager.cancel(pendingIntent);

 // canceling the pendingIntent
 PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE).cancel();
</code>```

ContentLicense: CC BY-SA 3.0

Title: alarmManager.cancel not working

Body:
I'm  trying to stop a repeating alarm.

I already looked all over the web for solution, but my code seems fine...

Still it doesn't stop the alarm...
Here's a little bit of code (FM is a file-writing object)

public void StartAlarm() {
     Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
     PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

     AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
     Calendar alarm = Calendar.getInstance();
     alarm.setTimeInMillis(System.currentTimeMillis());
     alarm.set(Calendar.HOUR_OF_DAY, 15);
     alarm.set(Calendar.MINUTE, 0);
     long alarmCal=alarm.getTimeInMillis();
     if (alarmCal<=new Date().getTime()) {
        alarm.add(Calendar.DAY_OF_MONTH, 1);
     }
     am.setRepeating(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
     FM.Write("startAlarm()");
     }

 public void StopAlarm() {
        if (isAlarmRunning()) {
             Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
             PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.cancel(sender);
            FM.Write("alarm canceled");
            isAlarmRunning();
        }
public boolean isAlarmRunning() {
    Intent intentToCheck = new Intent(getApplicationContext(),AlarmReciever.class);
    boolean alarm = PendingIntent.getBroadcast(getApplicationContext(), 0, intentToCheck,
            PendingIntent.FLAG_NO_CREATE) != null;
    FM.Write("alarm = "+alarm);
    if (!alarm) {
        return false;
    }
    else
        return true;
}

Thanks!

Body:
Totally agree with Nokolay Elenkov, answer; just as mentioned from the question's comments the user is setting a ToggleButton based on whether the PendingIntent is active or not. And this is something different than if the alarm still registered or not.

And to match both things you have to cancel both of them; i.e. cancel the alarm, and cancel the PendingIntent.

 Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE);
 myToggleButton.setChecked(pendingIntent != null);

 // Setting the alarm
 AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
 alarmManager.setRepeating();

 // Canceling the alarm
 alarmManager.cancel(pendingIntent);

 // canceling the pendingIntent
 PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE).cancel();


问:
Little help boxes for sign up form
I created a signup page for my website with Django.

In this form, I want to put little boxes or ballons next to input fields.

For example, when user click or hover the box next to password input field, it should be written that "The password should be 8 letter and includes 1 uppercase" etc.

How can I do it?

signup.html

```<code><!DOCTYPE html>
<html lang="en">

{% load static %}
    <link rel="stylesheet" href="{% static 'css/signup.css' %}">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <input type="radio" id="toggle--signup" name="toggle" class="ghost" />

 <! ––  <img class="logo framed" src="https://www.tumblr.com/images/logo/logo_large.png?v=7ea0eb57dd627a95f82be5bde0c43d59" alt="Tumblr logo" /> ––>

  <form class="form form--signup framed" method="post">
      {% csrf_token %}

      <h1 class=" text--centered">PHARSYS</h1>
      <h2 class="text text--centered text--omega">Join Us!</h2>

    <input type="text" placeholder="Username" name="username" maxlength="150" autofocus required id="id_username" class="input input--top">
    <input type="text" placeholder="First name" name="first_name" maxlength="30" id="id_first_name" class="input">
    <input type="text" placeholder="Last name" name="last_name" maxlength="30" id="id_last_name" class="input">
    <input type="email" placeholder="Email" class="input" name="email" maxlength="254" id="id_email"/>
    <input type="password" placeholder="Password" class="input" name="password1" required id="id_password1">
    <input type="password" placeholder="Confirm password" class="input" name="password2" required id="id_password2">

        <select class="input" name="user_type" required id="id_user_type">
            <option value="" selected>User Type</option>
            <option value="pharmacist">Pharmacist</option>
            <option value="manager">Medical Repository Manager</option>
        </select>
      <button type="submit" class="input input--submit">Sign Up!</button>

    <a class="text text--small text--centered" href="/users/login">I am already a member</a>

  </form>
  <div class="fullscreen-bg"></div>

</body>
</html>
</code>```

答:
I've just found a solution to this here, but I'll show you how it'd be used in your code:

CSS:

```<code>a.info{
position:relative; /*this is the key*/
z-index:24; background-color:#ccc;
color:#000;
text-decoration:none}

a.info:hover{z-index:25; background-color:#ff0}

a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:2em; left:2em; width:15em;
    border:1px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center}
</code>```

This'll control what the box actually looks like when you hover over something it's being used on, so feel free to change it as you see fit, obviously. Putting it in your signup.html would look a bit like this:

HTML:

```<code><a class=info href="#"><input type="text" placeholder="Username" name="username" maxlength="150" autofocus required id="id_username" class="input input--top">
<span>I'm a tooltip!</span></a>
</code>```

Title: Little help boxes for sign up form

Body:
I created a signup page for my website with Django.

In this form, I want to put little boxes or ballons next to input fields.

For example, when user click or hover the box next to password input field, it should be written that "The password should be 8 letter and includes 1 uppercase" etc.

How can I do it?

signup.html

<!DOCTYPE html>

{% load static %}
    <link rel="stylesheet" href="{% static 'css/signup.css' %}">

    <meta charset="UTF-8">
    <title>Title</title>

  <input type="radio" id="toggle--signup" name="toggle" class="ghost" />

 <! ––   ––>

  <form class="form form--signup framed" method="post">
      {% csrf_token %}

PHARSYS

Join Us!

    <input type="text" placeholder="Username" name="username" maxlength="150" autofocus required id="id_username" class="input input--top">
    <input type="text" placeholder="First name" name="first_name" maxlength="30" id="id_first_name" class="input">
    <input type="text" placeholder="Last name" name="last_name" maxlength="30" id="id_last_name" class="input">
    <input type="email" placeholder="Email" class="input" name="email" maxlength="254" id="id_email"/>
    <input type="password" placeholder="Password" class="input" name="password1" required id="id_password1">
    <input type="password" placeholder="Confirm password" class="input" name="password2" required id="id_password2">

        <select class="input" name="user_type" required id="id_user_type">
            <option value="" selected>User Type</option>
            <option value="pharmacist">Pharmacist</option>
            <option value="manager">Medical Repository Manager</option>
        </select>
      <button type="submit" class="input input--submit">Sign Up!</button>

    I am already a member

  </form>

Body:
I've just found a solution to this here, but I'll show you how it'd be used in your code:

CSS:

a.info{
position:relative; /*this is the key*/
z-index:24; background-color:#ccc;
color:#000;
text-decoration:none}

a.info:hover{z-index:25; background-color:#ff0}

a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:2em; left:2em; width:15em;
    border:1px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center}

This'll control what the box actually looks like when you hover over something it's being used on, so feel free to change it as you see fit, obviously. Putting it in your signup.html would look a bit like this:

HTML:

<a class=info href="#"><input type="text" placeholder="Username" name="username" maxlength="150" autofocus required id="id_username" class="input input--top">
<span>I'm a tooltip!</span></a>


问:
How do I change the font size to export the pdf in datatables plug in
How do I change the font size to export the pdf at datatables plug in?
I looked at the sources and could not find where does it!

any body can help me??
thanks

答:
As Adam stated, you must modify the action script. In TableTools 2.0.1 the file i the one that Adam stated.
In the action script Fonts are defined on line 212 for the title:

```<code>        pdf.setFont( new CoreFont(FontFamily.HELVETICA), 14 );//14 is the font size
        if ( title != "" )
        {
            pdf.writeText(11, title+"\n");
        }
</code>```

and on line 218 for the other text

```<code>        pdf.setFont( new CoreFont(FontFamily.HELVETICA), 11 );
        if ( message != "" )
        {
            pdf.writeText(11, message+"\n");
        }
</code>```

There is full reference for the library used to generate the PDF (i point out the font-part) here : http://alivepdf.bytearray.org/alivepdf-asdoc/org/alivepdf/fonts/FontFamily.html

After you have modified the action script you must compile a new copy_cvs_xls_pdf.swf with the command found on top of the action script file:
Compile using: mxmlc --target-player=10.0.0 -static-link-runtime-shared-libraries=true -library-path+=lib ZeroClipboardPdf.as

You'll need the Flex 4 SDK to build the SWF - which you can get free from the Adobe open source pages.

I tried it and it works.

You should always check out http://datatables.net/forums/ also, i found this that helped me compile the file!

hope it helps

Body:
As Adam stated, you must modify the action script. In TableTools 2.0.1 the file i the one that Adam stated.
In the action script Fonts are defined on line 212 for the title:

        pdf.setFont( new CoreFont(FontFamily.HELVETICA), 14 );//14 is the font size
        if ( title != "" )
        {
            pdf.writeText(11, title+"\n");
        }

and on line 218 for the other text

        pdf.setFont( new CoreFont(FontFamily.HELVETICA), 11 );
        if ( message != "" )
        {
            pdf.writeText(11, message+"\n");
        }

There is full reference for the library used to generate the PDF (i point out the font-part) here : http://alivepdf.bytearray.org/alivepdf-asdoc/org/alivepdf/fonts/FontFamily.html

After you have modified the action script you must compile a new copy_cvs_xls_pdf.swf with the command found on top of the action script file:
Compile using: mxmlc --target-player=10.0.0 -static-link-runtime-shared-libraries=true -library-path+=lib ZeroClipboardPdf.as

You'll need the Flex 4 SDK to build the SWF - which you can get free from the Adobe open source pages.

I tried it and it works.

You should always check out http://datatables.net/forums/ also, i found this that helped me compile the file!

hope it helps


问:
WARNING:tensorflow:sample_weight modes were coerced from ... to ['...']
Training an image classifier using .fit_generator() or .fit() and passing a dictionary to class_weight= as an argument.

I never got errors in TF1.x but in 2.1 I get the following output when starting training:

WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']
```

What does it mean to coerce something from ... to ['...']?

The source for this warning on tensorflow's repo is here, comments placed are:

Attempt to coerce sample_weight_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation.

答:
I believe this is a bug with tensorflow that will happen when you call model.compile() with default parameter sample_weight_mode=None and then call model.fit() with specified sample_weight or class_weight.

From the tensorflow repos:

fit() eventually calls _process_training_inputs()

_process_training_inputs() sets sample_weight_modes = [None] based on model.sample_weight_mode = None and then creates a DataAdapter with sample_weight_modes = [None]

the DataAdapter calls broadcast_sample_weight_modes() with sample_weight_modes = [None] during initialization

broadcast_sample_weight_modes() seems to expect sample_weight_modes = None but receives [None]

it asserts that [None] is a different structure from sample_weight / class_weight, overwrites it back to None by fitting to the structure of sample_weight / class_weight and outputs a warning

Warning aside this has no effect on fit() as sample_weight_modes in the DataAdapter is set back to None.

Note that tensorflow documentation states that sample_weight must be a numpy-array. If you call fit() with sample_weight.tolist() instead, you will not get a warning but sample_weight is silently overwritten to None when _process_numpy_inputs() is called in preprocessing and receives an input of length greater than one.

Body:
Training an image classifier using .fit_generator() or .fit() and passing a dictionary to class_weight= as an argument.

I never got errors in TF1.x but in 2.1 I get the following output when starting training:

WARNING:tensorflow:sample_weight modes were coerced from
  ...
    to
  ['...']

What does it mean to coerce something from ... to ['...']?

The source for this warning on tensorflow's repo is here, comments placed are:

Attempt to coerce sample_weight_modes to the target structure. This implicitly depends on the fact that Model flattens outputs for its internal representation.


问:
React Click Counter: Updating State of just one element
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

```<code>class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (
      <div>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
        <button className="block" onClick={this.handleClick}>
          <div className="counter">{this.state.count}</div>
        </button>
      </div>
    );
  }
}
</code>```

答:
If your buttons are dynamic you can set your state to be an array and update the relevant index </p>

```<code>class Block extends React.Component {
  state = [];

  handleClick = index => {
    this.setState(state => {
       const newState = [...state]; //keep state immutable
       !newState[index] && (newState[index] = 0)
       newState[index]++

       return newState
    });
  };

  render() {
    return (
      <div>
        {[1,2,3].map((value, index) => <button className="block" onClick={() => this.handleClick(index)}>
          <div className="counter">{this.state[index]}</div>
        </button>)}
      </div>
    );
  }
}
</code>```

Body:
This should be pretty simple, but I can't figure out how to do it.

I have a component with multiple buttons, each with a "count" value, set with state. When a user clicks, the count goes up.

Right now, when I click one of the buttons, both counters change. How can I make it so only the div that was clicked updates, using the same state?

Edit: I don't want to have different counts, as I'd like for this component to render buttons dynamically. What if I don't know how many buttons I'll have at first?

class Block extends React.Component {
  state = {
    count: 0
  };

  handleClick = e => {
    const count = this.state.count;
    this.setState({ count: count + 1 });
  };

  render() {
    return (

        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>
        <button className="block" onClick={this.handleClick}>

{this.state.count}

        </button>

    );
  }
}

Body:
If your buttons are dynamic you can set your state to be an array and update the relevant index

class Block extends React.Component {
  state = [];

  handleClick = index => {
    this.setState(state => {
       const newState = [...state]; //keep state immutable
       !newState[index] && (newState[index] = 0)
       newState[index]++

       return newState
    });
  };

  render() {
    return (
      <div>
        {[1,2,3].map((value, index) => <button className="block" onClick={() => this.handleClick(index)}>
          <div className="counter">{this.state[index]}</div>
        </button>)}
      </div>
    );
  }
}


问:
How can I use no-typescript React component in TypeScript?
I am beginner in React and Typescript. I have a problem with using react component e.g. https://www.npmjs.com/package/react-toggle-button in typescript.

I generated types by Visual Studio.

Btw import  ToggleButton from 'react-toggle-button'; error :/ClientApp/types/react-toggle-button"' has no default export.

So, I imported this way:

```<code>import * as ToggleButton from 'react-toggle-button';

 <ToggleButton
                        value={this.state.influencer.billingVATPayer || false}
                        onChange={(e: any) => { console.log(e) }}
                    />
</code>```

My error:
(TS) JSX element type 'index' is not a constructor function for JSX elements.
  Property 'context' is missing in type 'index'.

Can no-typescript modules be imported in some way?

My Typescript version: 3.2.4
My React version: 16.7.0

Thank you advance

答:
Sometimes, packages have an "@types/" version you can install instead of the normal one which includes the types for the items you need/want to import (e.g https://www.npmjs.com/package/@types/react). In cases where this is not an option, you can either:

A) Create your own .d.ts file and create your own types for the package your trying to import as @hazardous mentioned.

Or you can

B) Edit your tsconfig.json file and add the property "allowJs" and set it to true which allows JS files to be imported into Typescript files without the linter or compiler complaining. This is particularly useful in large codebases (or even small) that are transitioning to Typescript and can't immediately convert all of there files/components to Typescript. Shout out to @Juraj Kocan for mentioning this as well.

Body:
I am beginner in React and Typescript. I have a problem with using react component e.g. https://www.npmjs.com/package/react-toggle-button in typescript.

I generated types by Visual Studio.

Btw import  ToggleButton from 'react-toggle-button'; error :/ClientApp/types/react-toggle-button"' has no default export.

So, I imported this way:

import * as ToggleButton from 'react-toggle-button';

 <ToggleButton
                        value={this.state.influencer.billingVATPayer || false}
                        onChange={(e: any) => { console.log(e) }}
                    />

My error:
(TS) JSX element type 'index' is not a constructor function for JSX elements.
  Property 'context' is missing in type 'index'.

Can no-typescript modules be imported in some way?

My Typescript version: 3.2.4
My React version: 16.7.0

Thank you advance


问:
How to remove the nth element from a tuple?
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

```<code>constexpr auto t = std::tuple(1, 2, 3, 4);
</code>```

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

```<code>std::tuple(1, 2, 4);
</code>```

This is the closest I got until now:

```<code>template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}
</code>```

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

```<code>return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);
</code>```

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

```<code>template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}
</code>```

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

```<code>if constexpr(sizeof...(tail) - 1 == N)
</code>```

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

答:
What about

```<code>return std::tuple_cat( foo<is, N>::func(std::get<is>(tp)) ...);
</code>```

where foo is a struct with specialization as follows?

```<code>template <std::size_t, std::size_t>
struct foo
 {
   template <typename T>
   static auto func (T const & t)
    { return std::make_tuple(t); }
 }

template <std::size_t N>
struct foo<N, N>
 {
   template <typename T>
   static std::tuple<> func (T const &)
    { return {}; }
 }
</code>```

(caution: code not tested).

This is almost your ternary operator idea but without the problem of matching the types in both sides: only the right type is instantiated.

Body:
I'm trying to write a function that creates a new std::tuple from an existing one, with skipping the element on a given index. In example:

I have a tuple t defined as below:

constexpr auto t = std::tuple(1, 2, 3, 4);

And I want to copy it to another tuple. However, I want to skip the nth element. Let's say that in this case, the nth element I want to skip is 3 (this would mean that I want to skip the element with the index 2). This would result in a new tuple defined as:

std::tuple(1, 2, 4);

This is the closest I got until now:

template<std::size_t N, typename T, std::size_t ... is>
constexpr auto fun(T&& tp, std::index_sequence<is...>&& i) noexcept {
    return std::tuple((is != N ? std::get<is>(tp) : 0) ...);
}

template<std::size_t N, std::size_t... elems>
constexpr auto fun2() noexcept {
    constexpr auto t = std::tuple(elems...);
    return fun<N>(std::forward_as_tuple(elems...), std::make_index_sequence<sizeof...(elems)>());
}

However, instead of removing the nth element, I set it to 0.

Ideally, I would change the return argument in the function fun() to create a new tuple using multiple temporary tuples:

return std::tuple_cat((is != N ? std::tuple(std::get<is>(tp)) : std::tuple()) ...);

However, the issue with this is that the ternary operator has to have matching types on both sides.

Another approach I tried was based on recursion:

template<std::size_t N, std::size_t head, std::size_t... tail>
constexpr auto fun3() noexcept {
    if constexpr(!sizeof...(tail))
        return std::tuple(head);

    if constexpr(sizeof...(tail) - 1 == N)
        return std::tuple_cat(fun3<N, tail...>());

    if constexpr(sizeof...(tail) - 1 != N)
        return std::tuple_cat(std::tuple(head), fun3<N, tail...>());
}

However, that was even more unsuccessful. In this case, if N is equal to 0, the nth element (which is the first element here as well) will still be used in the new tuple. Also, this won't even compile, because there's an issue with the second statement:

if constexpr(sizeof...(tail) - 1 == N)

What am I missing here? How can I copy a tuple and skip one of its elements during the copy?

I'm using C++17, and I need the function to be evaluated during compile-time.

Body:
What about

return std::tuple_cat( foo<is, N>::func(std::get<is>(tp)) ...);

where foo is a struct with specialization as follows?

template <std::size_t, std::size_t>
struct foo
 {
   template <typename T>
   static auto func (T const & t)
    { return std::make_tuple(t); }
 }

template <std::size_t N>
struct foo<N, N>
 {
   template <typename T>
   static std::tuple<> func (T const &)
    { return {}; }
 }

(caution: code not tested).

This is almost your ternary operator idea but without the problem of matching the types in both sides: only the right type is instantiated.


问:
How does Python exchanges data with Javascript in Jupyter
As Jupyter is becoming so popular, I just want to integrate data processing and visualization together using Jupyter. But matplotlib and R ggplot2 are not flexible enough, so I want to use Javascript in Jupyter to draw cool graphs. I have noticed in the newest jupyter, I can write js code with %%javascript in the first line of a cell. But I haven't figured it out that how to exchange data between python and js. For example, in python, I process the data using some algorithms and want to visualize it using D3.js. How can I do that? Thanks for any reply.</p>

答:
I've been looking for similar solutions.  This helped plus kernal.execute method. I wrote a class to wrap all of this up - interaction between python f-strings and converting into javascript variable

```<code>class setvariables {
constructor(IPython) {
    //super(IPython);
    this.__inprogress = {};
    this.__kernel = IPython.notebook.kernel;
}

// results come back asynchronously.   Check struct that records request is emply
// before calling requested callback after variables have been set
sync (callback) {
    if (Object.keys(this.__inprogress).length === 0){
        callback();
    } else {
        new Promise(resolve => setTimeout(resolve, 200)).then(() => {this.sync(callback);});
    }
}

// can run anything - doing print("f{var}") and getting results in promise callbacks
execute(cmd) {
    return new Promise((resolve, reject) => {
        var callbacks = {
            iopub: { output: (data) => resolve(data.content.text.trim()) }
        };
        this.__kernel.execute(cmd, callbacks);
    });
}

// build an f-string to get variable from IPython environment
// format results execute callback function to assign to javascript variable
setjs(name, type, callback) {
    var inprogress = this.__inprogress;
    inprogress[name] = {"type": typeof(type)};
    if (inprogress[name].type==="object" && type instanceof Array) {
        inprogress[name].type="array";
    } else if (inprogress[name].type==="object" && !(type instanceof Array)) {
        inprogress[name].type="dict";
    }
    var cmd = 'print(f"{' + name + '}"';
    // for dict and array replace double quotes to single quotes so JSON.parse works
    if (["dict","array"].includes(inprogress[name].type)) {
        cmd = cmd + '.replace(chr(39),chr(34))';
    }
    cmd = cmd + ')';
    var p = this.execute(cmd);
    p.then((result) => {
        if (["dict","array"].includes(inprogress[name].type)) {
            result = JSON.parse(result);
        } else if (inprogress[name].type === "string") {
            result = result.trim();
        } else {
            result = Number(result);
        }
        /// fetch complete so remove from dict of variables being fetched.
        // Allows sync() to be reliable
        delete inprogress[name];
        callback(result);
    }, (err) => {
        console.warn(err, execute);
    })
 }
</code>```

}

I intend to put this into a .js file and use require to load it into a %%javascript Jupyter cell.   Sample usage below

```<code>var td = {};
var data = {};
var array = [];
var num = 0.0;
var str = "";

var py = new setvariables(IPython);
py.setjs("td", td, (result) => { td = result; } );
py.setjs("data", data, (result) => { data = result; } );
py.setjs("array", array, (result) => { array = result; } );
py.setjs("num", num, (result) => { num = result; } );
py.setjs("str", str, (result) => { str = result; } );

// everything is async - all code that depends on values from python needs to be called
// from this block
py.sync(() => {
    console.log(td,"done");
    console.log(data,"done");
    console.log(array,"done");
    console.log(num + 1,"done");
    str = str + " Rob";
    console.log(str,'done');

})
</code>```

Body:
I've been looking for similar solutions.  This helped plus kernal.execute method. I wrote a class to wrap all of this up - interaction between python f-strings and converting into javascript variable

class setvariables {
constructor(IPython) {
    //super(IPython);
    this.__inprogress = {};
    this.__kernel = IPython.notebook.kernel;
}

// results come back asynchronously.   Check struct that records request is emply
// before calling requested callback after variables have been set
sync (callback) {
    if (Object.keys(this.__inprogress).length === 0){
        callback();
    } else {
        new Promise(resolve => setTimeout(resolve, 200)).then(() => {this.sync(callback);});
    }
}

// can run anything - doing print("f{var}") and getting results in promise callbacks
execute(cmd) {
    return new Promise((resolve, reject) => {
        var callbacks = {
            iopub: { output: (data) => resolve(data.content.text.trim()) }
        };
        this.__kernel.execute(cmd, callbacks);
    });
}

// build an f-string to get variable from IPython environment
// format results execute callback function to assign to javascript variable
setjs(name, type, callback) {
    var inprogress = this.__inprogress;
    inprogress[name] = {"type": typeof(type)};
    if (inprogress[name].type==="object" && type instanceof Array) {
        inprogress[name].type="array";
    } else if (inprogress[name].type==="object" && !(type instanceof Array)) {
        inprogress[name].type="dict";
    }
    var cmd = 'print(f"{' + name + '}"';
    // for dict and array replace double quotes to single quotes so JSON.parse works
    if (["dict","array"].includes(inprogress[name].type)) {
        cmd = cmd + '.replace(chr(39),chr(34))';
    }
    cmd = cmd + ')';
    var p = this.execute(cmd);
    p.then((result) => {
        if (["dict","array"].includes(inprogress[name].type)) {
            result = JSON.parse(result);
        } else if (inprogress[name].type === "string") {
            result = result.trim();
        } else {
            result = Number(result);
        }
        /// fetch complete so remove from dict of variables being fetched.
        // Allows sync() to be reliable
        delete inprogress[name];
        callback(result);
    }, (err) => {
        console.warn(err, execute);
    })
 }

}

I intend to put this into a .js file and use require to load it into a %%javascript Jupyter cell.   Sample usage below

var td = {};
var data = {};
var array = [];
var num = 0.0;
var str = "";

var py = new setvariables(IPython);
py.setjs("td", td, (result) => { td = result; } );
py.setjs("data", data, (result) => { data = result; } );
py.setjs("array", array, (result) => { array = result; } );
py.setjs("num", num, (result) => { num = result; } );
py.setjs("str", str, (result) => { str = result; } );

// everything is async - all code that depends on values from python needs to be called
// from this block
py.sync(() => {
    console.log(td,"done");
    console.log(data,"done");
    console.log(array,"done");
    console.log(num + 1,"done");
    str = str + " Rob";
    console.log(str,'done');

})


问:
I have a LINQ statement that is partially query and partially method. How can I do this using one or the other?
Here is my query as it stands now:

```<code>Goals = await (from p in _context.FixtureActivityTb
               where p.ActivityType.Trim() == "G"
               group p by p.PlayerId into x
               join j in _context.PlayerTb on x.Key equals j.PlayerId
               select new Stats
               {
                   Name = j.GivenName,
                   pID = j.PlayerId,
                   TeamId = j.TeamId,
                   Count = x.Count()
               })
   .OrderByDescending(s => s.Count)
   .ThenBy(s => s.Name)
   .Take(10)
   .ToListAsync();
</code>```

As you can see this is a mix of method and query. I should be able to do a join, where, and add the data to a custom class all in Method, however so far I have not been able to put it all together. Any guidance will be appreciated.

I will include these other items, however, I think they are beside the point.

Variable Declaration:

```<code>public IList<Stats> Goals { get; set; }
</code>```

Class:

```<code>public class Stats
{
    public Guid pID { get; set; }
    public string TeamId { get; set; }
    public string Name { get; set; }
    public int Count { get; set; }
}
</code>```

答:
It's quite acceptable to mix the two, especially where you have a base query, and a paging part, as here.  You can even compose the queries over multiple statements, eg:</p>

```<code>var q = from p in _context.FixtureActivityTb
        where p.ActivityType.Trim() == "G"
        group p by p.PlayerId into x
        join j in _context.PlayerTb on x.Key equals j.PlayerId
        select new Stats
        {
            Name = j.GivenName,
            pID = j.PlayerId,
            TeamId = j.TeamId,
            Count = x.Count()
        };

Goals = await q.OrderByDescending(s => s.Count)
               .ThenBy(s => s.Name)
               .Take(10)
               .ToListAsync();
</code>```

Body:
Here is my query as it stands now:

Goals = await (from p in _context.FixtureActivityTb
               where p.ActivityType.Trim() == "G"
               group p by p.PlayerId into x
               join j in _context.PlayerTb on x.Key equals j.PlayerId
               select new Stats
               {
                   Name = j.GivenName,
                   pID = j.PlayerId,
                   TeamId = j.TeamId,
                   Count = x.Count()
               })
   .OrderByDescending(s => s.Count)
   .ThenBy(s => s.Name)
   .Take(10)
   .ToListAsync();

As you can see this is a mix of method and query. I should be able to do a join, where, and add the data to a custom class all in Method, however so far I have not been able to put it all together. Any guidance will be appreciated.

I will include these other items, however, I think they are beside the point.

Variable Declaration:

public IList<Stats> Goals { get; set; }

Class:

public class Stats
{
    public Guid pID { get; set; }
    public string TeamId { get; set; }
    public string Name { get; set; }
    public int Count { get; set; }
}

Body:
It's quite acceptable to mix the two, especially where you have a base query, and a paging part, as here.  You can even compose the queries over multiple statements, eg:

var q = from p in _context.FixtureActivityTb
        where p.ActivityType.Trim() == "G"
        group p by p.PlayerId into x
        join j in _context.PlayerTb on x.Key equals j.PlayerId
        select new Stats
        {
            Name = j.GivenName,
            pID = j.PlayerId,
            TeamId = j.TeamId,
            Count = x.Count()
        };

Goals = await q.OrderByDescending(s => s.Count)
               .ThenBy(s => s.Name)
               .Take(10)
               .ToListAsync();


问:
How to discount the percentage type with total price?
I need to discount with percentage type with a total price of the cart?

the prices:

```<code>total_cart: 11,000

discoutn(percentage): 10%
</code>```

my shut:

```<code>if ($this->coupon->type === "percentage") {
   return $total_cart * ($this->coupon->value / 100);
}
</code>```

With this code I got this result 1,100 |: !

答:
```<code>if ($this->coupon->type === "percentage") {
   return $total_cart * ((100-$this->coupon->value) / 100);
}
</code>```

Body:
I need to discount with percentage type with a total price of the cart?

the prices:

total_cart: 11,000

discoutn(percentage): 10%

my shut:

if ($this->coupon->type === "percentage") {
   return $total_cart * ($this->coupon->value / 100);
}

With this code I got this result 1,100 |: !


问:
Import data from 2 csv files in neo4j
As a continue to this post in which I completely explained what I'm supposed to do, in case my central node is located in another .csv file, how can I import it in my graph?

The content of names.csv (2 columns: Lname & Fname):

```<code>Lname,Fname
Brown,Helen
Right,Eliza
Green,Helen
Pink,Kate
Yellow,Helen
</code>```

The content of central.csv (2 columns: central & value):

```<code>central,value
cent1,10
</code>```

I tried something like this:

```<code>LOAD CSV WITH HEADERS FROM 'file:///central.csv' AS frow
MERGE (c:center {name: frow.central})
WITH *
LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS srow
WITH srow.Fname AS first, srow.Lname AS last
MERGE (p:la {last: last})
MERGE (o:fi {first: first})
MERGE (c)-[r:CONTAINS {first:first}]->(o)
MERGE (o)-[rel:CONTAINS {first: first}]->(p)
RETURN count(o)
</code>```

but it didn't work for me. It created the central node for me, but my central node is not connected to first nodes as it was supposed to. What's wrong. I wanted it to be like this:

答:
Your second WITH clause does not contain c, so c becomes an unbound variable after that clause.

Change this:

```<code>WITH srow.Fname AS first, srow.Lname AS last
</code>```

to this:

```<code>WITH c, srow.Fname AS first, srow.Lname AS last
</code>```

By the way, your query will only work as you expect if central.csv contains just one data row (as it does currently).

Title: Import data from 2 csv files in neo4j

Body:
As a continue to this post in which I completely explained what I'm supposed to do, in case my central node is located in another .csv file, how can I import it in my graph?

The content of names.csv (2 columns: Lname & Fname):

Lname,Fname
Brown,Helen
Right,Eliza
Green,Helen
Pink,Kate
Yellow,Helen

The content of central.csv (2 columns: central & value):

central,value
cent1,10

I tried something like this:

LOAD CSV WITH HEADERS FROM 'file:///central.csv' AS frow
MERGE (c:center {name: frow.central})
WITH *
LOAD CSV WITH HEADERS FROM 'file:///names.csv' AS srow
WITH srow.Fname AS first, srow.Lname AS last
MERGE (p:la {last: last})
MERGE (o:fi {first: first})
MERGE (c)-[r:CONTAINS {first:first}]->(o)
MERGE (o)-[rel:CONTAINS {first: first}]->(p)
RETURN count(o)

but it didn't work for me. It created the central node for me, but my central node is not connected to first nodes as it was supposed to. What's wrong. I wanted it to be like this:

Body:
Your second WITH clause does not contain c, so c becomes an unbound variable after that clause.

Change this:

WITH srow.Fname AS first, srow.Lname AS last

to this:

WITH c, srow.Fname AS first, srow.Lname AS last

By the way, your query will only work as you expect if central.csv contains just one data row (as it does currently).


问:
How to remove the border highlight on an input text element
When an HTML element is 'focused' (currently selected/tabbed into), many browsers (at least Safari and Chrome) will put a blue border around it.

For the layout I am working on, this is distracting and does not look right.

```<code><input type="text" name="user" class="middle" id="user" tabindex="1" />
</code>```

Firefox does not seem to do this, or at least, will let me control it with:

```<code>border: x;
</code>```

If someone can tell me how IE performs, I would be curious.

Getting Safari to remove this little bit of flare would be nice.

答:
The only solution that worked for me

The border is actually a shadow. So to hide it I had to do this:

```<code>input[type="text"]:focus{
     box-shadow: 0 0 0 rgb(255, 255, 255);
}

 input[type="checkbox"]:focus{
      box-shadow: 0 0 0 rgb(255, 255, 255);
 }
</code>```

Body:
When an HTML element is 'focused' (currently selected/tabbed into), many browsers (at least Safari and Chrome) will put a blue border around it.

For the layout I am working on, this is distracting and does not look right.

<input type="text" name="user" class="middle" id="user" tabindex="1" />

Firefox does not seem to do this, or at least, will let me control it with:

border: x;

If someone can tell me how IE performs, I would be curious.

Getting Safari to remove this little bit of flare would be nice.

Body:
The only solution that worked for me

The border is actually a shadow. So to hide it I had to do this:

input[type="text"]:focus{
     box-shadow: 0 0 0 rgb(255, 255, 255);
}

 input[type="checkbox"]:focus{
      box-shadow: 0 0 0 rgb(255, 255, 255);
 }