问:
Highchart polar, align left x labels - interrupt the labels distance
I use polar-highchart.

I want my x-axis labels to have text-align: left.

The problem is that when I do that, the distance of the labels is interrupted.

It start dry the label from the left side of the distance point.

I only want it to align-text to left, not take the label to other place...

Code sample:

```<code>xAxis: {
            type: 'category',
            tickmarkPlacement: 'on',
            lineWidth: 0,
            labels: {
                distance: 35,
                style:{
                    color: 'red',
                    width: 100,
                    cursor: 'pointer',

                },
                align:'left',
                staggerLines: 1,
                events: {},
                format: this.labelFormat,

            },
        },
</code>```

I have tried to use 'reserveSpace' property - but not helped.
See images:

Defult align:

Left align:

答:
Your requirements need to use some custom code to set those labels as you want.

Here is my idea how to achieve it:

Demo: https://jsfiddle.net/BlackLabel/7whqnv1s/

```<code>events: {
  render() {
    let chart = this,
      ticks = chart.xAxis[0].ticks;

    for (let i in ticks) {
      if (ticks[i].label.alignValue !== 'left') {
        let labelWidth = ticks[i].label.getBBox().width;

        ticks[i].label.attr({
          'text-anchor': 'left'
        })
                    //set the center label on the middle
        if (ticks[i].label.alignValue === 'center') {
          ticks[i].label.translate(-labelWidth / 2, 0)
        } else {
        //move the left labels to the left
          ticks[i].label.translate(-labelWidth, 0)
        }
      }
    }
  }
}
</code>```

API: https://api.highcharts.com/highcharts/chart.events.render

If something is unclear - feel free to ask!

Body:
I use polar-highchart.

I want my x-axis labels to have text-align: left.

The problem is that when I do that, the distance of the labels is interrupted.

It start dry the label from the left side of the distance point.

I only want it to align-text to left, not take the label to other place...

Code sample:

xAxis: {
            type: 'category',
            tickmarkPlacement: 'on',
            lineWidth: 0,
            labels: {
                distance: 35,
                style:{
                    color: 'red',
                    width: 100,
                    cursor: 'pointer',

                },
                align:'left',
                staggerLines: 1,
                events: {},
                format: this.labelFormat,

            },
        },

I have tried to use 'reserveSpace' property - but not helped.
See images:

Defult align:

Left align:

Body:
Your requirements need to use some custom code to set those labels as you want.

Here is my idea how to achieve it:

Demo: https://jsfiddle.net/BlackLabel/7whqnv1s/

events: {
  render() {
    let chart = this,
      ticks = chart.xAxis[0].ticks;

    for (let i in ticks) {
      if (ticks[i].label.alignValue !== 'left') {
        let labelWidth = ticks[i].label.getBBox().width;

        ticks[i].label.attr({
          'text-anchor': 'left'
        })
                    //set the center label on the middle
        if (ticks[i].label.alignValue === 'center') {
          ticks[i].label.translate(-labelWidth / 2, 0)
        } else {
        //move the left labels to the left
          ticks[i].label.translate(-labelWidth, 0)
        }
      }
    }
  }
}

API: https://api.highcharts.com/highcharts/chart.events.render

If something is unclear - feel free to ask!


来源: stackexchange

问:
There are possible way of dividing two float numbers which was casted from unsigned int make negative float result?
```<code>unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");
</code>```

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

```<code>mTotalFrameRateTimeAsASecond += timeOfGap;
</code>```

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

答:
You can do a simple test to verify the cast from unsigned int to float.

Try this :

```<code>unsigned int toto = 0xFFFFFFFF;
float convertedToto = float(toto);
</code>```

convertedToto will equals -1 if the convertion (unsigned int -> float) is in fact (int -> float). You should get 2*10e31 with a proper conversion.

ContentLicense: CC BY-SA 3.0

Body:
unsigned int deltaTime = now() - last();
unsigned int freq = getFreq();
float timeOfGap = float(deltaTime) / float(freq);

ASSERT(0.0f <= timeOfGap, "WHAT?");

I got a really weired result from my program. I didn't catch a scene which is happened. But I have a log which said that really raised at least multiple times.

There are possible way of dividing between two float numbers which was casted from unsigned int make negative float result?

OK, thank you guys. I'm glad to see your attentions.
Let me try to add some descriptions about it. It'll be helpful for you.

I'm working for an online game, and this situation was raised rarely but frequently while hundreds of million times game was serving. I can't debug or catch the exact shot, but it is logged on the db error messages.

The timeOfGap should be NaN as you noticed, but the log didn't alert the value exactly. The timeOfGap is accumulated like below;

mTotalFrameRateTimeAsASecond += timeOfGap;

And this program logs mTotalFrameRateTimeAsASecond, that was a negative value. But except this sign of value was a negative, it is correct value. Meaning, it point time as look as good if I divide the final value with a framerate. A hypothetical play time was 500 sec, it is -30000(with 60 framerate per sec).

Body:
You can do a simple test to verify the cast from unsigned int to float.

Try this :

unsigned int toto = 0xFFFFFFFF;
float convertedToto = float(toto);

convertedToto will equals -1 if the convertion (unsigned int -> float) is in fact (int -> float). You should get 2*10e31 with a proper conversion.


问:
Find component element by name in jest enzyme
component:

```<code><input name="search" onChange={this.onChange}>

console.log(component.find('div').at(0).childAt(0).find('input').find('search').debug())
</code>```

error:

doesn't show anything

答:
You can find components by specifying their properties which is called as Object Property Selector. Please find details here.

As you said you want to find component using name property then please try this:

```<code>component.find({ name: "search" }).debug();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
component:

<input name="search" onChange={this.onChange}>

console.log(component.find('div').at(0).childAt(0).find('input').find('search').debug())

error:

doesn't show anything

Body:
You can find components by specifying their properties which is called as Object Property Selector. Please find details here.

As you said you want to find component using name property then please try this:

component.find({ name: "search" }).debug();


问:
hashmap or hashset?
I have two list containing

```<code>List<MyObj>.
</code>```

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?

答:
Well, using HashMap you will be forced to store data in this way :

```<code><ID1><MyObject>
<ID2><MyObject>
</code>```

That isn't the best way, because you already have ID field in MyObject.

Using HashSet you will be able to store only unique instances of MyObject and you also will need to implement hashCode() in MyObject.

It's up to you to choose.

Title: hashmap or hashset?

Body:
I have two list containing

List<MyObj>.

and MyObj has a "String ID" member.

I need to iterate them from time to time and sometimes I need to find objects which are similar on both.

I want a quicker way than lists.  so I can know I can use  hashMap
(than ask contains (String ) when comparing )

should I use hashmap or hashset?

note: in a hashset - I need to do implement my equals and when I run contains() - i think it will be slower than hashmap where  upon inserting I put the string id in the key.
Am I correct?

Body:
Well, using HashMap you will be forced to store data in this way :

<ID1><MyObject>
<ID2><MyObject>

That isn't the best way, because you already have ID field in MyObject.

Using HashSet you will be able to store only unique instances of MyObject and you also will need to implement hashCode() in MyObject.

It's up to you to choose.


问:
Recursive SQL Query with Postgres Ranges To Find Availability
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

```

<p>and found this function to be buggy when I've inserted rows with duration back to back</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

</code>```

```<code>INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));
</code>```

This works as expected at this point.

```<code>SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
</code>```

```<code>available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)
</code>```

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));
```

<p>And re-run</p>

```SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;
```

<p>I get</p>

```available_dates
-------------------------
empty
```

答:
I had originally forgot the clause for the "center" area. Here it is below:

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT a.center AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.center <> b.center AND
        a.center @> b.center
    GROUP BY a.center
    HAVING NOT bool_or(COALESCE(a.center @> b.center, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
WHERE NOT isempty(a.available_dates)
$$ LANGUAGE SQL STABLE;
```

Body:
I followed this blogpost: https://info.crunchydata.com/blog/range-types-recursion-how-to-search-availability-with-postgresql

CREATE TABLE travels (
    id serial PRIMARY KEY,
    travel_dates daterange NOT NULL,
    EXCLUDE USING spgist (travel_dates WITH &&)
);

and found this function to be buggy when I've inserted rows with duration back to back

CREATE OR REPLACE FUNCTION travels_get_available_dates(daterange)
RETURNS TABLE(available_dates daterange)
AS $$
    WITH RECURSIVE calendar AS (
        SELECT
            $1 AS left,
             $1 AS center,
             $1 AS right
        UNION
        SELECT
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN daterange(lower(calendar.left), lower(travels.travel_dates * calendar.left))
                ELSE daterange(lower(calendar.right), lower(travels.travel_dates * calendar.right))
            END AS left,
            CASE travels.travel_dates && calendar.left
                WHEN TRUE THEN travels.travel_dates * calendar.left
                ELSE travels.travel_dates * calendar.right
            END AS center,
            CASE travels.travel_dates && calendar.right
                WHEN TRUE THEN daterange(upper(travels.travel_dates * calendar.right), upper(calendar.right))
                ELSE daterange(upper(travels.travel_dates * calendar.left), upper(calendar.left))
            END AS right
        FROM calendar
        JOIN travels ON
            travels.travel_dates && $1 AND
            travels.travel_dates <> calendar.center AND (
                travels.travel_dates && calendar.left OR
                travels.travel_dates && calendar.right
            )
)
SELECT *
FROM (
    SELECT
        a.left AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.left <> b.left AND
        a.left @> b.left
    GROUP BY a.left
    HAVING NOT bool_or(COALESCE(a.left @> b.left, FALSE))
    UNION
    SELECT
        a.right AS available_dates
    FROM calendar a
    LEFT OUTER JOIN calendar b ON
        a.right <> b.right AND
        a.right @> b.right
    GROUP BY a.right
    HAVING NOT bool_or(COALESCE(a.right @> b.right, FALSE))
) a
$$ LANGUAGE SQL STABLE;

INSERT INTO travels (travel_dates)
VALUES
    (daterange('2018-03-02', '2018-03-02', '[]')),
    (daterange('2018-03-06', '2018-03-09', '[]')),
    (daterange('2018-03-11', '2018-03-12', '[]')),
    (daterange('2018-03-16', '2018-03-17', '[]')),
    (daterange('2018-03-25', '2018-03-27', '[]'));

This works as expected at this point.

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

available_dates
-------------------------
[2018-03-01,2018-03-02)
[2018-03-03,2018-03-06)
[2018-03-10,2018-03-11)
[2018-03-13,2018-03-16)
[2018-03-18,2018-03-25)
[2018-03-28,2018-04-01)

But when this row is added:

INSERT INTO travels (travel_dates)
VALUES
(daterange('2018-03-03', '2018-03-05', '[]'));

And re-run

SELECT *
FROM travels_get_available_dates(daterange('2018-03-01', '2018-04-01'))
ORDER BY available_dates;

I get

available_dates
-------------------------
empty


问:
Keyboard shortcut to comment lines in Sublime Text 3
In Sublime Text 2 it was possible to comment out a line or a block of lines with  Ctrl+/ and Ctrl+Shift+/. According to the menu Edit > Comment these shortcuts should be valid, but in Sublime Text 3 (build 3047) they no longer seem to work. Does anybody know the right default keyboard shortcuts for Linux and MacOS? Or is it a bug?

答:
i am ubuntu 18 with sublime text 3.2

CTR + /


问:
Reconstructing the list of items from a space optimized 0/1 knapsack implementation
A space optimization for the 0/1 knapsack dynamic programming algorithm is to use a 1-d array (say, A) of size equal to the knapsack capacity, and simply overwrite A[w] (if required) at each iteration i, where A[w] denotes the total value if the first i items are considered and knapsack capacity is w.
If this optimization is used, is there a way to reconstruct the list of items picked, perhaps by saving some extra information at each iteration of the DP algorithm? For example, in the Bellman Ford Algorithm a similar space optimization can be implemented, and the shortest path can still be reconstructed as long as we keep a list of the predecessor pointers, ie the last hop (or first, depending on if a source/destination oriented algorithm is being written).

For reference, here is my C++ function for the 0/1 knapsack problem using dynamic programming where I construct a 2-d vector ans such that ans[i][j] denotes the total value considering the first i items and knapsack capacity j. I reconstruct the items picked by reverse traversing this vector ans:

```<code>void knapsack(vector<int> v,vector<int>w,int cap){
 //v[i]=value of item i-1
 //w[i]=weight of item i-1, cap=knapsack capacity
 //ans[i][j]=total value if considering 1st i items and capacity j
 vector <vector<int> > ans(v.size()+1,vector<int>(cap+1));

 //value with 0 items is 0
 ans[0]=vector<int>(cap+1,0);

 //value with 0 capacity is 0
 for (uint i=1;i<v.size()+1;i++){
    ans[i][0]=0;
 }

 //dp
 for (uint i=1;i<v.size()+1;i++) {
    for (int x=1;x<cap+1;x++) {
        if (ans[i-1][x]>=ans[i-1][x-w[i-1]]+v[i-1]||x<w[i-1])
            ans[i][x]=ans[i-1][x];
        else {
            ans[i][x]=ans[i-1][x-w[i-1]]+v[i-1];
        }
    }
 }
 cout<<"Total value: "<<ans[v.size()][cap]<<endl;

 //reconstruction
 cout<<"Items to carry: \n";
 for (uint i=v.size();i>0;i--) {
    for (int x=cap;x>0;x--) {
        if (ans[i][x]==ans[i-1][x]) //item i not in knapsack
            break;
        else if (ans[i][x]==ans[i-1][x-w[i-1]]+v[i-1]) { //item i in knapsack
            cap-=w[i-1];
            cout<<i<<"("<<v[i-1]<<"), ";
            break;
        }
    }
 }
 cout<<endl;
}
</code>```

答: Even though this is an old question I recently ran into the same problem so I figured I would write my solution here. What you need is Hirschberg's algorithm. Although this algorithm is written for reconstructing edit distances, the same principle applies here. The idea is that when searching for n items in capacity c, the knapsack state at (n/2)th item corresponding to the final maximum value is determined in the first scan. Let's call this state weight_m and value_m. This can be with keeping track of an additional 1d array of size c. So the memory is still O(c). Then the problem is divided into two parts: items 0 to n/2 with a capacity of weight_m, and items n/2 to n with a capacity of c-weight_m. The reduced problems in total is of size nc/2. Continuing this approach we can determine the knapsack state (occupied weight and current value) after each item, after which we can simply check to see which items were included. This algorithm completes in O(2nc) while using O(c) memory, so in terms of big-O nothing is changed even though the algorithm is at least twice as slow. I hope this helps to anyone who is facing a similar problem.

Body:
A space optimization for the 0/1 knapsack dynamic programming algorithm is to use a 1-d array (say, A) of size equal to the knapsack capacity, and simply overwrite A[w] (if required) at each iteration i, where A[w] denotes the total value if the first i items are considered and knapsack capacity is w.
If this optimization is used, is there a way to reconstruct the list of items picked, perhaps by saving some extra information at each iteration of the DP algorithm? For example, in the Bellman Ford Algorithm a similar space optimization can be implemented, and the shortest path can still be reconstructed as long as we keep a list of the predecessor pointers, ie the last hop (or first, depending on if a source/destination oriented algorithm is being written).

For reference, here is my C++ function for the 0/1 knapsack problem using dynamic programming where I construct a 2-d vector ans such that ans[i][j] denotes the total value considering the first i items and knapsack capacity j. I reconstruct the items picked by reverse traversing this vector ans:

void knapsack(vector<int> v,vector<int>w,int cap){
 //v[i]=value of item i-1
 //w[i]=weight of item i-1, cap=knapsack capacity
 //ans[i][j]=total value if considering 1st i items and capacity j
 vector <vector<int> > ans(v.size()+1,vector<int>(cap+1));

 //value with 0 items is 0
 ans[0]=vector<int>(cap+1,0);

 //value with 0 capacity is 0
 for (uint i=1;i<v.size()+1;i++){
    ans[i][0]=0;
 }

 //dp
 for (uint i=1;i<v.size()+1;i++) {
    for (int x=1;x<cap+1;x++) {
        if (ans[i-1][x]>=ans[i-1][x-w[i-1]]+v[i-1]||x<w[i-1])
            ans[i][x]=ans[i-1][x];
        else {
            ans[i][x]=ans[i-1][x-w[i-1]]+v[i-1];
        }
    }
 }
 cout<<"Total value: "<<ans[v.size()][cap]<<endl;

 //reconstruction
 cout<<"Items to carry: \n";
 for (uint i=v.size();i>0;i--) {
    for (int x=cap;x>0;x--) {
        if (ans[i][x]==ans[i-1][x]) //item i not in knapsack
            break;
        else if (ans[i][x]==ans[i-1][x-w[i-1]]+v[i-1]) { //item i in knapsack
            cap-=w[i-1];
            cout<<i<<"("<<v[i-1]<<"), ";
            break;
        }
    }
 }
 cout<<endl;
}


问:
Couldn't connect to Docker daemon at http+docker://localhost with docker-compose
I have this React app that I want to run on an Apache HTTP Docker container.

So I created a Dockerfile that works with sudo docker build and sudo docker run <name>

```<code>FROM httpd:2.4
COPY ./dist/ /usr/local/apache2/htdocs/
</code>```

I created a docker-compose.yml

```<code>version: '3'
services:
  frontend:
    build: .
    ports:
     - "8080:80"
    container_name: frontend
</code>```

But when I run sudo docker-compose build I get this error:

ERROR: Couldn't connect to Docker daemon at http+docker://localhost -
  is it running?

If it's at a non-standard location, specify the URL with the
  DOCKER_HOST environment variable.

What is the problem?

答:
Check your privileges, Following command solved my problem :

```<code>sudo chown $USER /var/run/docker.sock
</code>```

It happens when you try to start docker as non super user and it couldn't get access to it own sockets.

Body:
I have this React app that I want to run on an Apache HTTP Docker container.

So I created a Dockerfile that works with sudo docker build and sudo docker run <name>

FROM httpd:2.4
COPY ./dist/ /usr/local/apache2/htdocs/

I created a docker-compose.yml

version: '3'
services:
  frontend:
    build: .
    ports:
     - "8080:80"
    container_name: frontend

But when I run sudo docker-compose build I get this error:

ERROR: Couldn't connect to Docker daemon at http+docker://localhost -
  is it running?

If it's at a non-standard location, specify the URL with the
  DOCKER_HOST environment variable.

What is the problem?

Body:
Check your privileges, Following command solved my problem :

sudo chown $USER /var/run/docker.sock

It happens when you try to start docker as non super user and it couldn't get access to it own sockets.


问:
Can I control the flashlight without using android.hardware.Camera?
The use of front light option with zxing1.6 barcode scanner does not work on my Nexus One. I need to be able to use the flashlight in my app, but you can't have two instances of the camera running. Is there a way to use the flashlight without accessing the camera? Or can I somehow access a camera that is already in use?

I am using the Google IntentIntegrator.java patch to be able to scan barcodes.

答:
The short answer is "no"; the front LED is controlled as a flash mode, which is a property of the camera. It is mode "torch". And no two apps can't open the camera at the same time.

(A longer answer is that there used to be a hidden API for this, which is what Barcode Scanner tries to access, but it doesn't work on almost any device anymore. You can dig into the source code to see FlashlightManager.)

Since Android 2.x there is this proper API for turning on the light, and the beta of the next version of Barcode Scanner does use it. You can try it here.


问:
Switching 2 methods parameter(different type) to use overloading
I'm a High school student, I studied a little bit of Java by myself.
My teacher asked if you can write two methods with switched but same parameters. For example:

```<code>public void method (String arg1, int arg2){
}

public void method(int arg1, String arg2){
}
</code>```

I said yes, the teacher said that I don't know what overloading means, but I tested and it worked, and then she said "JDK has a bug" and she got mad at me.

I need a super and complete answer.

答:
As mentioned in the official Oracle Java tutorial:

Java can distinguish between methods with different method signatures

On the same page, "method signature" is defined as

Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.

Since the parameter types are a list, they also have a fixed order (Unlike e.g. a set).

Thus two parameter lists with the same types (But a different order) are considered different parameter type lists, which in turn allows you to declare two methods with the same name and these two parameter type lists without causing compile time errors.

Edit: For more details refer to the Java Language Specification, chapter 8.4.2.

Body:
I'm a High school student, I studied a little bit of Java by myself.
My teacher asked if you can write two methods with switched but same parameters. For example:

public void method (String arg1, int arg2){
}

public void method(int arg1, String arg2){
}

I said yes, the teacher said that I don't know what overloading means, but I tested and it worked, and then she said "JDK has a bug" and she got mad at me.

I need a super and complete answer.


问:
Required field with sensible default
Consider the following

```<code>from pydantic import BaseModel, Field
class Model(BaseModel):
    required: str
</code>```

This will make required a required field for Model, however, in the FastAPI autogenerated Swagger docs it will have an example value of "string".

How can I make a required field with a sensible default? If I make a model like

```<code>from pydantic import BaseModel, Field
class Model(BaseModel):
    required: str = 'Sensible default'
</code>```

Then the field required is no longer required, but it shows up with a sensible default in the docs. Is there an easy workaround for this?

答:
You can use Field() to set up those options and check.

```<code>from pydantic import BaseModel, Field
class Model(BaseModel):
    something: str # required, shows "string"
    something: str = None # not required, shows "string"
    something: str = Field(..., example="this is the default display") # required, shows example
    something: str = Field(None, example="Foobar") #not required, show example
</code>```

There are a multitude of different parameters that Field() can validate against.

Title: Required field with sensible default

Body:
Consider the following

from pydantic import BaseModel, Field
class Model(BaseModel):
    required: str

This will make required a required field for Model, however, in the FastAPI autogenerated Swagger docs it will have an example value of "string".

How can I make a required field with a sensible default? If I make a model like

from pydantic import BaseModel, Field
class Model(BaseModel):
    required: str = 'Sensible default'

Then the field required is no longer required, but it shows up with a sensible default in the docs. Is there an easy workaround for this?

Body:
You can use Field() to set up those options and check.

from pydantic import BaseModel, Field
class Model(BaseModel):
    something: str # required, shows "string"
    something: str = None # not required, shows "string"
    something: str = Field(..., example="this is the default display") # required, shows example
    something: str = Field(None, example="Foobar") #not required, show example

There are a multitude of different parameters that Field() can validate against.


问:
Python Pandas load csv is not loading full CSV
Working on a project that creates a pdf report from a set of CSV metadata exported from Davinci Resolve.

The program runs and gernerates a report but there are some columns missing, I can't figure out what is happening. I have passed the usecols attribute with the columns that I want but it still misses some out.

I thought that this might be somthing to do with data types not getting loaded into the data frame correctly, but I have tried that and it does not work.

I would like the PDF report to contain the colums in the order that I have specified in the usecols section in the example code.
example csv:

https://www.dropbox.com/s/jsup7f5qrfnqc7e/A003.csv?dl=0

Project uses pandas, jinja2 and weasyprint

```<code>print(sourcefile, outfile)

df = pd.read_csv(sourcefile,
    encoding="utf-16",
    usecols=['File Name', 'Camera #', 'Resolution', 'Duration TC', 'Video Codec', 'Camera FPS', 'Comments'],
    dtype={"File Name": str,
        "Camera #": str,
        "Resolution": str,
        "Duration TC": str,
        "Video Codec": str,
        "Camera FPS": float,
        "Comments": str,
        'Date Modified': str,
        'Date Recorded': str
        },
    na_values=['.', '??', ' ']  # Take any '.' or '??' values as NA
)

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("report_template.html")

template_vars = {"title": title,
                    "data": df.to_html(),
                    "date": self.date,
                    }

html_output = template.render(template_vars)
HTML(string=html_output).write_pdf(outfile)
</code>```

df.head() outputs the following:

```<code>                  File Name  Duration TC   Resolution        Video Codec Comments Camera #  Camera FPS
0  A003C001_191024_R48G.mov  00:01:21:08  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
1  A003C002_191024_R48G.mov  00:01:04:20  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
2  A003C003_191024_R48G.mov  00:01:16:14  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
3  A003C004_191024_R48G.mov  00:01:16:08  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
4  A003C005_191024_R48G.mov  00:02:30:04  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
</code>```

output example below:

答:
Caveat:

This is not a complete answer.  This answer is to address the request to show column re-ordering in more detail from the comment on the OP's question.

Source Data:

```<code>File Name,Duration TC,Resolution,Video Codec,Comments,Camera #,Camera FPS
A003C001_191024_R48G.mov,00:01:21:08,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C002_191024_R48G.mov,00:01:04:20,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C003_191024_R48G.mov,00:01:16:14,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C004_191024_R48G.mov,00:01:16:08,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C005_191024_R48G.mov,00:02:30:04,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
</code>```

Sample Code:

This example code shows how to re-order the DataFrame columns using a filtering technique, per user requirement.

```<code>import pandas as pd

# Define column order.
col_order = ['File Name', 'Camera #', 'Resolution', 'Duration TC',
             'Video Codec', 'Camera FPS', 'Comments']
# Read CSV file.
df = pd.read_csv('./cameradata.csv')
# Use column name filter to re-order columns.
df = df[col_order]
# Show results.
print(df)
</code>```

Output:

```<code>                  File Name Camera #   Resolution  Duration TC  \
0  A003C001_191024_R48G.mov        A  3200 x 1800  00:01:21:08
1  A003C002_191024_R48G.mov        A  3200 x 1800  00:01:04:20
2  A003C003_191024_R48G.mov        A  3200 x 1800  00:01:16:14
3  A003C004_191024_R48G.mov        A  3200 x 1800  00:01:16:08
4  A003C005_191024_R48G.mov        A  3200 x 1800  00:02:30:04

         Video Codec  Camera FPS Comments
0  Apple ProRes 4444     50000.0     PASS
1  Apple ProRes 4444     50000.0     PASS
2  Apple ProRes 4444     50000.0     PASS
3  Apple ProRes 4444     50000.0     PASS
4  Apple ProRes 4444     50000.0     PASS
</code>```

Body:
Working on a project that creates a pdf report from a set of CSV metadata exported from Davinci Resolve.

The program runs and gernerates a report but there are some columns missing, I can't figure out what is happening. I have passed the usecols attribute with the columns that I want but it still misses some out.

I thought that this might be somthing to do with data types not getting loaded into the data frame correctly, but I have tried that and it does not work.

I would like the PDF report to contain the colums in the order that I have specified in the usecols section in the example code.
example csv:

https://www.dropbox.com/s/jsup7f5qrfnqc7e/A003.csv?dl=0

Project uses pandas, jinja2 and weasyprint

print(sourcefile, outfile)

df = pd.read_csv(sourcefile,
    encoding="utf-16",
    usecols=['File Name', 'Camera #', 'Resolution', 'Duration TC', 'Video Codec', 'Camera FPS', 'Comments'],
    dtype={"File Name": str,
        "Camera #": str,
        "Resolution": str,
        "Duration TC": str,
        "Video Codec": str,
        "Camera FPS": float,
        "Comments": str,
        'Date Modified': str,
        'Date Recorded': str
        },
    na_values=['.', '??', ' ']  # Take any '.' or '??' values as NA
)

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("report_template.html")

template_vars = {"title": title,
                    "data": df.to_html(),
                    "date": self.date,
                    }

html_output = template.render(template_vars)
HTML(string=html_output).write_pdf(outfile)

df.head() outputs the following:

                  File Name  Duration TC   Resolution        Video Codec Comments Camera #  Camera FPS
0  A003C001_191024_R48G.mov  00:01:21:08  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
1  A003C002_191024_R48G.mov  00:01:04:20  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
2  A003C003_191024_R48G.mov  00:01:16:14  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
3  A003C004_191024_R48G.mov  00:01:16:08  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0
4  A003C005_191024_R48G.mov  00:02:30:04  3200 x 1800  Apple ProRes 4444     PASS        A     50000.0

output example below:

Body:
Caveat:

This is not a complete answer.  This answer is to address the request to show column re-ordering in more detail from the comment on the OP's question.

Source Data:

File Name,Duration TC,Resolution,Video Codec,Comments,Camera #,Camera FPS
A003C001_191024_R48G.mov,00:01:21:08,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C002_191024_R48G.mov,00:01:04:20,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C003_191024_R48G.mov,00:01:16:14,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C004_191024_R48G.mov,00:01:16:08,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0
A003C005_191024_R48G.mov,00:02:30:04,3200 x 1800,Apple ProRes 4444,PASS,A,50000.0

Sample Code:

This example code shows how to re-order the DataFrame columns using a filtering technique, per user requirement.

import pandas as pd

# Define column order.
col_order = ['File Name', 'Camera #', 'Resolution', 'Duration TC',
             'Video Codec', 'Camera FPS', 'Comments']
# Read CSV file.
df = pd.read_csv('./cameradata.csv')
# Use column name filter to re-order columns.
df = df[col_order]
# Show results.
print(df)

Output:

                  File Name Camera #   Resolution  Duration TC  \
0  A003C001_191024_R48G.mov        A  3200 x 1800  00:01:21:08
1  A003C002_191024_R48G.mov        A  3200 x 1800  00:01:04:20
2  A003C003_191024_R48G.mov        A  3200 x 1800  00:01:16:14
3  A003C004_191024_R48G.mov        A  3200 x 1800  00:01:16:08
4  A003C005_191024_R48G.mov        A  3200 x 1800  00:02:30:04

         Video Codec  Camera FPS Comments
0  Apple ProRes 4444     50000.0     PASS
1  Apple ProRes 4444     50000.0     PASS
2  Apple ProRes 4444     50000.0     PASS
3  Apple ProRes 4444     50000.0     PASS
4  Apple ProRes 4444     50000.0     PASS


问:
html2canvas 1.0.0-rc.5 2019 not working with rounded corners/border-radius (image is always rectangular)?
I used the 2016 (0.5.0) version of html2canvas for a long time because it always worked well for what I needed it for. Now I have to switch to the current version, but I have some problems:

The image that is created no longer has rounded corners. The png is always rectangular. And now I ask myself if I am doing something wrong, or if it might be a bug in the current version of html2canvas? I wanted to ask here first before posting this as an "issue" on GitHub.

The result with the 2016 0.5.5 version: https://i.imgur.com/gxutBEY.png (rounded corners)

The result with the 2019 1.0.0 version: https://i.imgur.com/LLY9WpI.png (rectangular corners)

Here's a JSFiddle that shows the issue: https://jsfiddle.net/ROPfiddle/jskLuw3v/3/

This is the current version (1.0.0-rc.5) of html2canvas: https://html2canvas.hertzen.com/dist/html2canvas.js

This is my CSS:

```<code>body {
  font-family: system-ui, Helvetica, Arial, sans-serif;
  margin: 19px 20px 0 20px;
  background-color: #000;
}
#wrapper {
  position: absolute;
  white-space: nowrap;
}
#badge {
  padding: 70px 67px 63px 71px;
  border: 13px solid #a6a6a6;
  border-radius: 110px;
  line-height: 1;
  background-color: #000;
  color: #fff;
}
.icon img {
  width: 273px;
  height: auto;
  border-radius: 62px;
}
.icon {
  float: left;
}
.typo {
  margin-top: -3px;
  margin-left: 336px;
}
.text {
  font-size: 92px;
  font-weight: 500;
  color: #a6a6a6;
  letter-spacing: 0.04em;
}
.name {
  font-size: 191px;
  font-weight: 700;
  margin-left: -6px;
  letter-spacing: -0.0125em;
}
.finalbadge {
  width: 100%;
  height: auto;
}
</code>```

This is my HTML (w/o the base64 encoded image):

```<code><div id="wrapper">
  <div id="badge">
    <div class="icon">
      <img src="data:image/png;base64, "/>
    </div>
    <div class="typo">
      <span class="text">Listen on</span><br />
      <span class="name">iTunes</span>
    </div>
  </div>
</div>
</code>```

And this is my JS:

```<code>html2canvas(document.getElementById("badge")).then(function(canvas) {
    document.body.appendChild(canvas);

    var img = canvas.toDataURL("image/png");
    document.body.innerHTML = '<img class="finalbadge" src="'+img+'"/>';
});
</code>```

Am I doing something wrong? Or must it be html2canvas?

Since the question has already been answered, here's the JSFiddle that shows the solution/answer: https://jsfiddle.net/ROPfiddle/zyj9b6dc/2/

答:
I can't tell you if this is a change from  the 0.5.5 to the 1.0.0 version of html2canvas.

Nevertheless beside the required HTML element, html2canvas() accepts an optional second parameter which is a Javascript object. Among these options is a property called backgroundColor which accepts a rgba value - thus including transparency. If you set all 4 values to null you get your transparent rounded corners back.

So simply change

```<code>html2canvas(document.getElementById("badge"))
</code>```

to

```<code>html2canvas(document.getElementById("badge"), {backgroundColor: "rgba(0,0,0,0)"})
</code>```

Body:
I used the 2016 (0.5.0) version of html2canvas for a long time because it always worked well for what I needed it for. Now I have to switch to the current version, but I have some problems:

The image that is created no longer has rounded corners. The png is always rectangular. And now I ask myself if I am doing something wrong, or if it might be a bug in the current version of html2canvas? I wanted to ask here first before posting this as an "issue" on GitHub.

The result with the 2016 0.5.5 version: https://i.imgur.com/gxutBEY.png (rounded corners)

The result with the 2019 1.0.0 version: https://i.imgur.com/LLY9WpI.png (rectangular corners)

Here's a JSFiddle that shows the issue: https://jsfiddle.net/ROPfiddle/jskLuw3v/3/

This is the current version (1.0.0-rc.5) of html2canvas: https://html2canvas.hertzen.com/dist/html2canvas.js

This is my CSS:

body {
  font-family: system-ui, Helvetica, Arial, sans-serif;
  margin: 19px 20px 0 20px;
  background-color: #000;
}
#wrapper {
  position: absolute;
  white-space: nowrap;
}
#badge {
  padding: 70px 67px 63px 71px;
  border: 13px solid #a6a6a6;
  border-radius: 110px;
  line-height: 1;
  background-color: #000;
  color: #fff;
}
.icon img {
  width: 273px;
  height: auto;
  border-radius: 62px;
}
.icon {
  float: left;
}
.typo {
  margin-top: -3px;
  margin-left: 336px;
}
.text {
  font-size: 92px;
  font-weight: 500;
  color: #a6a6a6;
  letter-spacing: 0.04em;
}
.name {
  font-size: 191px;
  font-weight: 700;
  margin-left: -6px;
  letter-spacing: -0.0125em;
}
.finalbadge {
  width: 100%;
  height: auto;
}

This is my HTML (w/o the base64 encoded image):

      Listen on

      iTunes

And this is my JS:

html2canvas(document.getElementById("badge")).then(function(canvas) {
    document.body.appendChild(canvas);

    var img = canvas.toDataURL("image/png");
    document.body.innerHTML = '';
});

Am I doing something wrong? Or must it be html2canvas?

Since the question has already been answered, here's the JSFiddle that shows the solution/answer: https://jsfiddle.net/ROPfiddle/zyj9b6dc/2/

Body:
I can't tell you if this is a change from  the 0.5.5 to the 1.0.0 version of html2canvas.

Nevertheless beside the required HTML element, html2canvas() accepts an optional second parameter which is a Javascript object. Among these options is a property called backgroundColor which accepts a rgba value - thus including transparency. If you set all 4 values to null you get your transparent rounded corners back.

So simply change

html2canvas(document.getElementById("badge"))

to

html2canvas(document.getElementById("badge"), {backgroundColor: "rgba(0,0,0,0)"})


问:
Calling a function defined in a TypeScript file from an HTML input onchange attribute
If I had a JavaScript index.js file like this:

```<code>function foo(val) {
  console.log(val);
}
</code>```

and a index.html HTML file like this:

```<code>...
<script src="./index.js"></script>
<div id="container">
  <label>bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>
  </label>
  <label>baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>
  </label>
...
</code>```

this would log bar or baz as I check a radio button.

I want to call foo(value) which is defined in a index.ts TypeScript file like this:

```<code>let foo = (value: string): void => {
  console.log(value);
};
</code>```

In index.html I change  to , then I use parcel to build the app, but the resulting built file is not able to call the function, logging  referenceError: setLayer is not defined.

I know that in theory the browser does not know anything about TypeScript and only knows JavaScript, but after compiling with parcel in my dist dir I see a bunch of *js files, one of which I thought might have included the compiled foo() function.

So the question is: how can I call a function inside a TS file from a HTML input onchange attribute like I would do with a JS file?

Last but not least: to build my app I invoke parcel start (or even parcel run build), and my package.json looks like this:

```<code>{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}
</code>```

答:
The problem:

Tools like Parcel and Webpack that bundle your js wrap all your modules in IIFEs so, after Parcel process your index.ts the function foo is not global and you can't simple access it from your html file any more. Without processing (like in this case: ) foo is global.

Solution:

Make foo global.

// index.ts
function foo(val: string) {
  console.log(val);
}

window.foo = foo;
```

Codesandbox

Body:
If I had a JavaScript index.js file like this:

function foo(val) {
  console.log(val);
}

and a index.html HTML file like this:

...

  bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>

  baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>

...

this would log bar or baz as I check a radio button.

I want to call foo(value) which is defined in a index.ts TypeScript file like this:

let foo = (value: string): void => {
  console.log(value);
};

In index.html I change  to , then I use parcel to build the app, but the resulting built file is not able to call the function, logging  referenceError: setLayer is not defined.

I know that in theory the browser does not know anything about TypeScript and only knows JavaScript, but after compiling with parcel in my dist dir I see a bunch of *js files, one of which I thought might have included the compiled foo() function.

So the question is: how can I call a function inside a TS file from a HTML input onchange attribute like I would do with a JS file?

Last but not least: to build my app I invoke parcel start (or even parcel run build), and my package.json looks like this:

{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}

Body:
The problem:

Tools like Parcel and Webpack that bundle your js wrap all your modules in IIFEs so, after Parcel process your index.ts the function foo is not global and you can't simple access it from your html file any more. Without processing (like in this case: <script src="./index.js"></script>) foo is global.

Solution:

Make foo global.

// index.ts
function foo(val: string) {
  console.log(val);
}

window.foo = foo;

Codesandbox


问:
How does Worker.setForegroundAsync work behind the scene?
Currently, after quit the app, to complete a long running task in foreground (So that it will not be killed by OS), this is what I did by using WorkManager.

Use Worker to call ContextCompat.startForegroundService, for starting an IntentService.

Worker will then return Result.success() immediately.

In onHandleIntent on IntentService, it will execute startForeground, before performing long running task.

Here's the code snippet.

```<code>public class SyncWorker extends Worker {
    @NonNull
    @Override
    public Result doWork() {
        final Intent intent = new Intent(WeNoteApplication.instance(), SyncForegroundIntentService.class);

        ContextCompat.startForegroundService(
                WeNoteApplication.instance(),
                intent
        );

        return Result.success();
    }
}

public class SyncForegroundIntentService extends IntentService {
    private static final String TAG = "com.yocto.wenote.sync.SyncIntentService";

    public SyncForegroundIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        final Context context = WeNoteApplication.instance();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(...

        startForeground(SYNC_FOREGROUND_INTENT_SERVICE_ID, builder.build());

        // Perform networking operation within foreground service.

        stopForeground(true);
</code>```

I have strong intention to migrate the code, to make use of setForegroundAsync in WorkManager. The reason is that, under certain rare circumstance, I will get the following crash

Context.startForegroundService() did not then call
  Service.startForeground()

So, I thought migrating to setForegroundAsync might help eliminating this problem.

However, it isn't clear how setForegroundAsync work behind the scene, by looking at WorkForegroundUpdater souce code.

Here's the code snippet of setForegroundAsync code example from https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running

```<code>public class DownloadWorker extends Worker {
    public DownloadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters parameters) {
            ...
    }

    @NonNull
    @Override
    public Result doWork() {
        ...

        // What happens behind the scene?!
        setForegroundAsync(createForegroundInfo(progress));

        // The long running task is still executed in Worker thread.
        download(inputUrl, outputFile);

        return Result.success();
    }
</code>```

However, it isn't clear whether such migration will achieve equivalent outcome. As, here are their differences.

Before migration to setForegroundAsync

The long running task is executed by IntentService's user thread.

Before long running task is completed, Worker will return immediately.

After migration to setForegroundAsync

The long running task is executed by Worker's user thread.

Worker will only return after long running task is finished executing.

Currently, with my current implementation, I will able to avoid Excessive network usage (background) issue. I am not sure whether with setForegroundAsync, will I still able to avoid Excessive network usage (background) issue?

In short, does anyone has idea how Worker.setForegroundAsync work behind the scene?

答:
Behind the scene setForegroundAsync() starts a foreground service for you when you're on API >= 26, or on a normal service when running on older Android releases. This is documented in the reference:

Under the hood, WorkManager manages and runs a foreground service on your behalf to execute this WorkRequest, showing the notification provided in ForegroundInfo.

I think that the relevant source is in Processor.java.

Talking about vital's metric Excessive Mobile Network Usage in Background, I don't see how this would change in this case given that, also using WorkManager setForegroundAsync() will move your worker to a ForegroundService on Android Oreo+.

For additional information on how this vital's metric is measured, please, take a look at Play Console's guide.

Body:
Currently, after quit the app, to complete a long running task in foreground (So that it will not be killed by OS), this is what I did by using WorkManager.

Use Worker to call ContextCompat.startForegroundService, for starting an IntentService.

Worker will then return Result.success() immediately.

In onHandleIntent on IntentService, it will execute startForeground, before performing long running task.

Here's the code snippet.

public class SyncWorker extends Worker {
    @NonNull
    @Override
    public Result doWork() {
        final Intent intent = new Intent(WeNoteApplication.instance(), SyncForegroundIntentService.class);

        ContextCompat.startForegroundService(
                WeNoteApplication.instance(),
                intent
        );

        return Result.success();
    }
}

public class SyncForegroundIntentService extends IntentService {
    private static final String TAG = "com.yocto.wenote.sync.SyncIntentService";

    public SyncForegroundIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        final Context context = WeNoteApplication.instance();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(...

        startForeground(SYNC_FOREGROUND_INTENT_SERVICE_ID, builder.build());

        // Perform networking operation within foreground service.

        stopForeground(true);

I have strong intention to migrate the code, to make use of setForegroundAsync in WorkManager. The reason is that, under certain rare circumstance, I will get the following crash

Context.startForegroundService() did not then call
  Service.startForeground()

So, I thought migrating to setForegroundAsync might help eliminating this problem.

However, it isn't clear how setForegroundAsync work behind the scene, by looking at WorkForegroundUpdater souce code.

Here's the code snippet of setForegroundAsync code example from https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running

public class DownloadWorker extends Worker {
    public DownloadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters parameters) {
            ...
    }

    @NonNull
    @Override
    public Result doWork() {
        ...

        // What happens behind the scene?!
        setForegroundAsync(createForegroundInfo(progress));

        // The long running task is still executed in Worker thread.
        download(inputUrl, outputFile);

        return Result.success();
    }

However, it isn't clear whether such migration will achieve equivalent outcome. As, here are their differences.

Before migration to setForegroundAsync

The long running task is executed by IntentService's user thread.

Before long running task is completed, Worker will return immediately.

After migration to setForegroundAsync

The long running task is executed by Worker's user thread.

Worker will only return after long running task is finished executing.

Currently, with my current implementation, I will able to avoid Excessive network usage (background) issue. I am not sure whether with setForegroundAsync, will I still able to avoid Excessive network usage (background) issue?

In short, does anyone has idea how Worker.setForegroundAsync work behind the scene?


问:
ASP.NET - Event handler of programmatically-created button never invoked
So i need to write simple "Minesweeper" game in asp.net (Only for learning purposes - it should be almost only javascript but anyway...)

I'm creating the game board dynamically at PageLoad, by creating a Table when each TableCell contains an ImageButton.

When i create each button, i'm adding to it's Click event my own event handler:

```<code>cellButton.Click += new EventHandler(tryOpenCell);
</code>```

When i'm running the project, the game page loading exactly as expected, but when i click on any cell (which is an ImageButton as i said) the request goes back to the server code, but the button's Event Handler never invoked. Instead, the whole process just repeat itself, means regenerating the whole table game.

So my question is why my event handler never invoked?

答:
On Postback your button should be recreated and then it will handle the event..

```<code>protected void Page_Load(object sender, EventArgs e)
{
        ImageButton btn = new ImageButton();
        btn.ID = "Btn";
        btn.Click += new EventHandler(tryOpenCell);
        form1.Controls.Add(btn);
 }
</code>```

Your button should be recreated in the page load event, before it can handle the event handler.

Body:
So i need to write simple "Minesweeper" game in asp.net (Only for learning purposes - it should be almost only javascript but anyway...)

I'm creating the game board dynamically at PageLoad, by creating a Table when each TableCell contains an ImageButton.

When i create each button, i'm adding to it's Click event my own event handler:

cellButton.Click += new EventHandler(tryOpenCell);

When i'm running the project, the game page loading exactly as expected, but when i click on any cell (which is an ImageButton as i said) the request goes back to the server code, but the button's Event Handler never invoked. Instead, the whole process just repeat itself, means regenerating the whole table game.

So my question is why my event handler never invoked?

Body:
On Postback your button should be recreated and then it will handle the event..

protected void Page_Load(object sender, EventArgs e)
{
        ImageButton btn = new ImageButton();
        btn.ID = "Btn";
        btn.Click += new EventHandler(tryOpenCell);
        form1.Controls.Add(btn);
 }

Your button should be recreated in the page load event, before it can handle the event handler.


问:
Apache pyspark using oracle jdbc to pull data. Driver cannot be found
I am using apache spark pyspark (spark-1.5.2-bin-hadoop2.6) on windows 7.

I keep getting this error when I run my python script in pyspark.

An error occured while calling o23.load. java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:------------------------------------connection

Here is my python file

```<code>import os

os.environ["SPARK_HOME"] = "C:\\spark-1.5.2-bin-hadoop2.6"
os.environ["SPARK_CLASSPATH"] = "L:\\Pyspark_Snow\\ojdbc6.jar"

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

spark_config = SparkConf().setMaster("local[8]")
sc = SparkContext(conf=spark_config)
sqlContext = SQLContext(sc)

df = (sqlContext
    .load(source="jdbc",
          url="jdbc:oracle:thin://x.x.x.x/xdb?user=xxxxx&password=xxxx",
          dbtable="x.users")
 )
sc.stop()
</code>```

答:
To set the jars programatically set the following config:
spark.yarn.dist.jars with comma-separated list of jars.

Eg:

```<code>from pyspark.sql import SparkSession

spark = SparkSession \
        .builder \
        .appName("Spark config example") \
        .config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
        .getOrCreate()
</code>```

Or as below:

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

spark_config = SparkConf().setMaster("local[8]")
spark_config.set("spark.yarn.dist.jars", "L:\\Pyspark_Snow\\ojdbc6.jar")
sc = SparkContext(conf=spark_config)
sqlContext = SQLContext(sc)
</code>```

Or pass --jars with the path of jar files separated by , to spark-submit.

Body:
I am using apache spark pyspark (spark-1.5.2-bin-hadoop2.6) on windows 7.

I keep getting this error when I run my python script in pyspark.

An error occured while calling o23.load. java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:------------------------------------connection

Here is my python file

import os

os.environ["SPARK_HOME"] = "C:\\spark-1.5.2-bin-hadoop2.6"
os.environ["SPARK_CLASSPATH"] = "L:\\Pyspark_Snow\\ojdbc6.jar"

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

spark_config = SparkConf().setMaster("local[8]")
sc = SparkContext(conf=spark_config)
sqlContext = SQLContext(sc)

df = (sqlContext
    .load(source="jdbc",
          url="jdbc:oracle:thin://x.x.x.x/xdb?user=xxxxx&password=xxxx",
          dbtable="x.users")
 )
sc.stop()

Body:
To set the jars programatically set the following config:
spark.yarn.dist.jars with comma-separated list of jars.

Eg:

from pyspark.sql import SparkSession

spark = SparkSession \
        .builder \
        .appName("Spark config example") \
        .config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
        .getOrCreate()

Or as below:

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

spark_config = SparkConf().setMaster("local[8]")
spark_config.set("spark.yarn.dist.jars", "L:\\Pyspark_Snow\\ojdbc6.jar")
sc = SparkContext(conf=spark_config)
sqlContext = SQLContext(sc)

Or pass --jars with the path of jar files separated by , to spark-submit.


问:
Add comments to hive tables using pyspark
I am creating hive tables via PySpark.

Is there a way to add comments to each column before being written into hive?

Example:

df = spark.table('sometable')
   # add comments       df.write.saveAsTable('mytablewithcomments')

答:
The alias method of the column class takes a metadata option which may include a comment.

```<code>df_with_column_comment = df.select( df.col.alias( 'col',
    metadata = { 'comment': 'Column description' }
) )
</code>```

As far as I know, columns are immutable, so you cannot add a comment after it is created.

Body:
The alias method of the column class takes a metadata option which may include a comment.

df_with_column_comment = df.select( df.col.alias( 'col',
    metadata = { 'comment': 'Column description' }
) )

As far as I know, columns are immutable, so you cannot add a comment after it is created.


问:
Renaming object properties in an array of objects
I have the following structure:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};
</code>```

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};
</code>```

I have tried various things like the following for example:

```<code>var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});
</code>```

However the spread pushes CreditNoteNumber outside the object.

答:
There is no such operation as "renaming" a property in JavaScript.

You will need to delete the property you no longer wish to keep:

const data = {
  invoices: [
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    },
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    }
  ]
};

const changed = data.invoices.map(item => {
  const obj = {
    ...item,
    CreditNoteNumber: item.InvoiceNumber
  };
  delete obj.InvoiceNumber
  return obj
});

console.log(changed)```

Body:
I have the following structure:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

I have tried various things like the following for example:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

However the spread pushes CreditNoteNumber outside the object.


问:
Persistence.createEntityManagerFactory("something") returns null
I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow

JPA - createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .

Following Exception is always happening,

```<code>1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.test.jpa.App.main(App.java:19)
</code>```

Main class

```<code>public class App
{

    public static void main( String[] args )
    {
        System.out.println( "I am going to connect" );
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
            if(entityManagerFactory !=null ) {
                 System.out.println( "lalala" );
            }else {
                 System.out.println( "nullllllllllllll" );
            }

    }
}
</code>```

This is Mapping class,

```<code>package com.test.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "client")
public class User {

    @Column(name = "name")
    private String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "age")
    private int age = 0;

    @Id
    @Column(name = "No")
    private int No = 0;

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
     No = no;
   }
}
</code>```

pom file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>jpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version>1.7.30</version>
        </dependency>
        <dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>
         <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <optimize>true</optimize>
                <debug>true</debug>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-assembly-plugin</artifactId>
              <configuration>
                  <descriptorRefs>
                      <descriptorRef>jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <dependencySets>
                      <dependencySet>
                          <includes>
                              <include>*:jar:*</include>
                          </includes>
                          <excludes>
                              <exclude>*:sources</exclude>
                              <exclude>*:javadoc</exclude>
                          </excludes>
                      </dependencySet>
                  </dependencySets>
                 <archive>
                   <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.test.jpa.App</mainClass>
                   </manifest>
                 </archive>
               </configuration>
                 <executions>
                     <execution>
                         <id>make-assembly</id>
                         <phase>package</phase>
                         <goals>
                             <goal>single</goal>
                         </goals>
                     </execution>
                 </executions>
            </plugin>
        </plugins>
   </build>
</project>
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="boom"  >
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>com.test.jpa.User</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="atis"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.autocommit" value="false"/>
      <property name="hibernate.connection.provider_disables_autocommit" value="true"/>
    </properties>
  </persistence-unit>
</persistence>
</code>```

I created database with name User, table is "client" , cloumn are "No","age"-integer datatype, "name"-string datatype

update:

I tested with junit tool with follow class.

```<code>import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest {
    private EntityManagerFactory emf;

    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

        emf = Persistence.createEntityManagerFactory("boom");
        if(emf !=null)
        System.out.println("wooooooooooooooooooooo ");
        em = emf.createEntityManager();
    }

    @After
    public void cleanup() {
        em.close();
    }

    @Test
    public void emptyTest() {
    }
}
</code>```

When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.

```<code>844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@45312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@7fb95505] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@58be6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl  - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]
</code>```

But when execute using well packaged jar in command line,exeception is thrown

```<code>1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
</code>```

thanks

答:
Packing problem during build time

You configuration looks right. Probably it's a packing problem. Try build and run you project with the following commands and it will work:

```<code>mvn clean compile assembly:single
java -jar target/jpa-0.0.1-SNAPSHOT-jar-with-dependencies.jar
</code>```

Take a look this answer to see more about how to create a jar with dependencies.
Maven - Build with Dependencies

More details for the sake of correctness:

org.hibernate:hibernate-core is the right dependecy to be used.
org.hibernate:hibernate-entitymanager is deprecated and actually only points to hibernate-core.

Reference inside jar:

Hibernate's JPA support has been merged into the hibernate-core
  module, making this hibernate-entitymanager module obsolete.  This
  module will be removed in Hibernate ORM 6.0.  It is only kept here for
  various consumers that expect a static set of artifact names across a
  number of Hibernate releases. See
  https://hibernate.atlassian.net/browse/HHH-10823

Body:
I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow

JPA - createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .

Following Exception is always happening,

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.test.jpa.App.main(App.java:19)

Main class

public class App
{

    public static void main( String[] args )
    {
        System.out.println( "I am going to connect" );
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
            if(entityManagerFactory !=null ) {
                 System.out.println( "lalala" );
            }else {
                 System.out.println( "nullllllllllllll" );
            }

    }
}

This is Mapping class,

package com.test.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "client")
public class User {

    @Column(name = "name")
    private String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "age")
    private int age = 0;

    @Id
    @Column(name = "No")
    private int No = 0;

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
     No = no;
   }
}

pom file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>jpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version>1.7.30</version>
        </dependency>
        <dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>
         <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <optimize>true</optimize>
                <debug>true</debug>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
            </plugin>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-assembly-plugin</artifactId>
              <configuration>
                  <descriptorRefs>
                      <descriptorRef>jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <dependencySets>
                      <dependencySet>
                          <includes>
                              <include>*:jar:*</include>
                          </includes>
                          <excludes>
                              <exclude>*:sources</exclude>
                              <exclude>*:javadoc</exclude>
                          </excludes>
                      </dependencySet>
                  </dependencySets>
                 <archive>
                   <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.test.jpa.App</mainClass>
                   </manifest>
                 </archive>
               </configuration>
                 <executions>
                     <execution>
                         <id>make-assembly</id>
                         <phase>package</phase>
                         <goals>
                             <goal>single</goal>
                         </goals>
                     </execution>
                 </executions>
            </plugin>
        </plugins>
   </build>
</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="boom"  >
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>com.test.jpa.User</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="atis"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.autocommit" value="false"/>
      <property name="hibernate.connection.provider_disables_autocommit" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

I created database with name User, table is "client" , cloumn are "No","age"-integer datatype, "name"-string datatype

update:

I tested with junit tool with follow class.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest {
    private EntityManagerFactory emf;

    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

        emf = Persistence.createEntityManagerFactory("boom");
        if(emf !=null)
        System.out.println("wooooooooooooooooooooo ");
        em = emf.createEntityManager();
    }

    @After
    public void cleanup() {
        em.close();
    }

    @Test
    public void emptyTest() {
    }
}

When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.

844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@45312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@7fb95505] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@58be6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl  - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]

But when execute using well packaged jar in command line,exeception is thrown

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [org.hibernate.jpa.boot.internal.StandardJpaScanEnvironmentImpl@482e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [org.hibernate.boot.archive.scan.internal.StandardScanOptions@967906] into BootstrapContext; was [org.hibernate.boot.archive.scan.internal.StandardScanOptions@18dfcc1]
Exception in thread "main" java.lang.NullPointerException

thanks

Body:
Packing problem during build time

You configuration looks right. Probably it's a packing problem. Try build and run you project with the following commands and it will work:

mvn clean compile assembly:single
java -jar target/jpa-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Take a look this answer to see more about how to create a jar with dependencies.
Maven - Build with Dependencies

More details for the sake of correctness:

org.hibernate:hibernate-core is the right dependecy to be used.
org.hibernate:hibernate-entitymanager is deprecated and actually only points to hibernate-core.

Reference inside jar:

Hibernate's JPA support has been merged into the hibernate-core
  module, making this hibernate-entitymanager module obsolete.  This
  module will be removed in Hibernate ORM 6.0.  It is only kept here for
  various consumers that expect a static set of artifact names across a
  number of Hibernate releases. See
  https://hibernate.atlassian.net/browse/HHH-10823


问:
How to transform an Application.Transpose with a pastespecial to put only value and not format?
```<code>Dim ar as variable

Sheets("Sheet1").Range("A4").Resize(UBound(ar) + 1) =
Application.Transpose(ar)
</code>```

It work perfectly except it paste the format. I have strange number in my list and it should be paste as text because excel convert those number into date or different value.

How to add the following with the Application.Transpose?
.PasteSpecial xlPasteValues

Edit2: Below code should sort value in column B of sheet2 and transpose them in Sheet1. However, it does not transpose value. I did something wrong?

```<code>Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
DoEvents

Dim r As Range
Dim rng As Range
Dim ar As Variant
Dim var As Variant

With Sheets("Sheet2").Range("B2").CurrentRegion
With CreateObject("scripting.dictionary")
For Each rng In Range("B3", Range("B" & Rows.Count).End(xlUp))
var = .Item(rng.Value)
Next
ar = .Keys
End With
End With
With Sheets("Sheet1").Range("A4").Resize(UBound(ar) + 1)
.NumberFormat = "@"
.Value = Application.Transpose(ar)
End With
</code>```

答:
And what would be the change to make this code paste vertical instead of horizontal? By changing the ColumnSize by RowSize the value is pasted vertically but it does not sort all value. IE 1,2,3,4,5 it will only paste 1,1,1,1,1</p>

```<code>Dim r As Range
Dim rng As Range
Dim ar As Variant
Dim var As Variant

With Worksheets("Sheet2")
  Set r = .Range("B3", .Range("B" & .Rows.Count).End(xlUp))
End With

With CreateObject("scripting.dictionary")
    For Each rng In r
        var = .Item(rng.Value)
    Next
    ar = .Keys
End With

With Sheets("Sheet1").Range("A4").Resize(RowSize:=UBound(ar) + 1)
    .NumberFormat = "@"
    .Value = ar
End With

End Sub
</code>```

Body:
Dim ar as variable

Sheets("Sheet1").Range("A4").Resize(UBound(ar) + 1) =
Application.Transpose(ar)

It work perfectly except it paste the format. I have strange number in my list and it should be paste as text because excel convert those number into date or different value.

How to add the following with the Application.Transpose?
.PasteSpecial xlPasteValues

Edit2: Below code should sort value in column B of sheet2 and transpose them in Sheet1. However, it does not transpose value. I did something wrong?

Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
DoEvents

Dim r As Range
Dim rng As Range
Dim ar As Variant
Dim var As Variant

With Sheets("Sheet2").Range("B2").CurrentRegion
With CreateObject("scripting.dictionary")
For Each rng In Range("B3", Range("B" & Rows.Count).End(xlUp))
var = .Item(rng.Value)
Next
ar = .Keys
End With
End With
With Sheets("Sheet1").Range("A4").Resize(UBound(ar) + 1)
.NumberFormat = "@"
.Value = Application.Transpose(ar)
End With

Body:
And what would be the change to make this code paste vertical instead of horizontal? By changing the ColumnSize by RowSize the value is pasted vertically but it does not sort all value. IE 1,2,3,4,5 it will only paste 1,1,1,1,1

Dim r As Range
Dim rng As Range
Dim ar As Variant
Dim var As Variant

With Worksheets("Sheet2")
  Set r = .Range("B3", .Range("B" & .Rows.Count).End(xlUp))
End With

With CreateObject("scripting.dictionary")
    For Each rng In r
        var = .Item(rng.Value)
    Next
    ar = .Keys
End With

With Sheets("Sheet1").Range("A4").Resize(RowSize:=UBound(ar) + 1)
    .NumberFormat = "@"
    .Value = ar
End With

End Sub