问:
Using Docker as service registry for microservices
I've followed some tutorial that walks through setting up 3 microservices (app, products and feedback) and 1 service registry.

After working with Docker for a while I feel the service registry is redundant. Because Docker can kick instances while injecting hostnames and ports via environment variables to each other.

For instance in the following Docker Compose file, I'm passing db credentials from a MySQL microservice to Node.js microservice and in the similar way, if there were other Node.js microservices, I could wire them up.

```<code>version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password

  products_service:
    build: .
    command: bash -c "/wait && npm start"
    volumes:
      - "./src/:/service/src/"
    image: "node"
    container_name: "products"
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    environment:
      DATABASE_HOST: mysql
      MYSQL_PORT: 3306
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password
      WAIT_HOSTS: mysql:3306
    restart: on-failure
</code>```

Do I really need to code and program a registry service in Node.js?

答:
You do really need some sort of automation beyond just composing up containers, if you want to be reactive to traffic loads and service failures. All of the major container management tools have some strategy to do service discovery for you. Also there are various ways to do service discovery ( like heart-beats and SWIM ).

Frankly, you can start with starting up some instances for your services and serve your users. But you won't be able to react to loads and failures and also be resource efficient. That's where tools like k8s shine and handle service discovery and resource utilization for you.

Check this talk to understand more about service discovery.

Body:
I've followed some tutorial that walks through setting up 3 microservices (app, products and feedback) and 1 service registry.

After working with Docker for a while I feel the service registry is redundant. Because Docker can kick instances while injecting hostnames and ports via environment variables to each other.

For instance in the following Docker Compose file, I'm passing db credentials from a MySQL microservice to Node.js microservice and in the similar way, if there were other Node.js microservices, I could wire them up.

version: '3'

services:

  mysql:
    image: "mysql:5.7"
    container_name: "mysql"
    ports:
      - "6603:3306"
    volumes:
      - ./assets/schema.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      DATABASE_HOST: mysql
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password

  products_service:
    build: .
    command: bash -c "/wait && npm start"
    volumes:
      - "./src/:/service/src/"
    image: "node"
    container_name: "products"
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    environment:
      DATABASE_HOST: mysql
      MYSQL_PORT: 3306
      MYSQL_DATABASE: database
      MYSQL_USER: mysql
      MYSQL_PASSWORD: password
      WAIT_HOSTS: mysql:3306
    restart: on-failure

Do I really need to code and program a registry service in Node.js?


来源: stackexchange

问:
Lazy load pages in UIScrollView
I have a UIScrollView that contains large images and am using paging to scroll between images. In order to save memory, I am loading only one image before and after the currently visible one and loading/releasing new images after a scroll has completed.

The problem occurs when one scrolls quickly and scrollViewDidEndDecelerating is not called.

How can I detect continuous scrolling?

I could check item location on every scrollViewDidScroll but this seems a bit heavy...

答: Perhaps a table view with custom cell content would work better for you, since it has a lot of logic built in for only loading cells that are visible as opposed to everything at once. There are lots of tutorials for how to manage table views in various ways.</p>

ContentLicense: CC BY-SA 2.5

Title: Lazy load pages in UIScrollView

ContentLicense: CC BY-SA 3.0


问:
Disable automatic Id field generation in Doctrine
Disable automatic Id field generation in Doctrine

this a part of my entity file:

```<code><?php

namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Variables
 * @ORM\Table(name="variables")
 * @ORM\Entity(repositoryClass="MyBundle\Repository\VariablesRepository")
 */

class Variables
{

    /**
     * @var int
     * @ORM\Column(name="variablesRef", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $variablesRef;

    /**
     * @var string
     * @ORM\Column(name="variablesLibelle", type="string", length=250)
     */
    private $variablesLibelle;
</code>```

when i try to create a schema :

erreur

Property MyBundle\Entity\Employeursecteur::$id does not exist

i want to Disable automatic Id field generation in Doctrine
i don't need the id  Column
please help

答:
If you want a primary key field without a generated value you just have to set the strategy of generation to none:</p>

```<code>@ORM\GeneratedValue(strategy="NONE")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Disable automatic Id field generation in Doctrine

this a part of my entity file:

<?php

namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Variables
 * @ORM\Table(name="variables")
 * @ORM\Entity(repositoryClass="MyBundle\Repository\VariablesRepository")
 */

class Variables
{

    /**
     * @var int
     * @ORM\Column(name="variablesRef", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $variablesRef;

    /**
     * @var string
     * @ORM\Column(name="variablesLibelle", type="string", length=250)
     */
    private $variablesLibelle;

when i try to create a schema :

erreur

Property MyBundle\Entity\Employeursecteur::$id does not exist

i want to Disable automatic Id field generation in Doctrine
i don't need the id  Column
please help

Body:
If you want a primary key field without a generated value you just have to set the strategy of generation to none:

@ORM\GeneratedValue(strategy="NONE")


问:
Update a subtype attribute using TREAT (Oracle 11g)
I want to be able to update a subtype attribute, and some research has led me to believe it can be done with TREAT. I have tried a couple of variations on this syntax:

```<code>UPDATE table1 t SET TREAT(VALUE(t) AS myType).attributeToUpdate = 10 WHERE id=1;
</code>```

myType is a subtype of the type of table1.

Keep getting the error ORA-00927 missing equals sign.

Thanks

答:
That should work for you:<br>
</p>

```<code>DECLARE
    s subclass;

BEGIN
    SELECT treat(value(p) as subclass) INTO s FROM superclass p WHERE id = search;
    s.attributeToChange = 'new value';
    UPDATE superclass p SET value(p) = s WHERE id = search;
END;
</code>```

Body:
I want to be able to update a subtype attribute, and some research has led me to believe it can be done with TREAT. I have tried a couple of variations on this syntax:

UPDATE table1 t SET TREAT(VALUE(t) AS myType).attributeToUpdate = 10 WHERE id=1;

myType is a subtype of the type of table1.

Keep getting the error ORA-00927 missing equals sign.

Thanks

Body:
That should work for you:

DECLARE
    s subclass;

BEGIN
    SELECT treat(value(p) as subclass) INTO s FROM superclass p WHERE id = search;
    s.attributeToChange = 'new value';
    UPDATE superclass p SET value(p) = s WHERE id = search;
END;


问:
Updating list inside for loop, which is using this list
I am working on a dataframe with some values inside. The problem is, I might have duplicates.

I went on this link but i couldn't find what I needed

What I tried is to create a list of duplicates using df.duplicated() which gives me True and False values for each indexes.
 Then for each index in this list where the result is True, I get the id from the df using df.loc[(df['id']== df['id'][dups]) ]. Depending on this result I call a function giveID() which returns a list of indexes to delete from the duplicates list. Because i don't need to iterate on the duplicates that are supposed to be deleted, is it possible to delete these indexes from the duplicates list during the for loop without breaking everything ?

Here is an example of my df (the duplicates are based on id column) :

```<code>   | id | type
--------------
0  | 312| data2
1  | 334| data
2  | 22 | data1
3  | 312| data8
#Here 0 and 3 are duplicates based on ID
</code>```

Here is a part of my code:

duplicates = df.duplicated(subset='column_name',keep=False)
duplicates = duplicates[duplicates]

df_dup = df
listidx = []
i=0
for dups in duplicates.index:

    dup_id = df.loc[(df['id']== df['id'][dups])]
    for a in giveID(dup_id):
        if a not in listid:
            listidx.append(a)

#here i want to delete the all listidx from duplicates inside the for loop
#so that I don't iterate over unnecessary duplicates

def giveID(id)
#some code that returns a list of indexes

```

<p>This is how looks <code>duplicates</code> in my code:</p>

<pre class="lang-py prettyprint-override"><code>0          True
1          True
582        True
583        True
605        True
606        True
622        True
623        True
624        True
625        True
626        True
627        True
628        True
629        True
630        True
631        True
           ...
1990368    True
1991030    True
</code>```

And i would like get the same but without unnecessary duplicates

答:
If you need indexes of non-duplicated IDs:</p>

```<code>df = pd.DataFrame({'ID':[0,1,1,3], 'B':[0,1,2,3]})
   B  ID
0  0   0
1  1   1
2  2   1
3  3   3

# List of indexes
non_duplicated = df.drop_duplicates(subset='ID', keep=False).index

df.loc[df.index.isin(non_duplicated)]
   B  ID
0  0   0
3  3   3

</code>```

Body:
I am working on a dataframe with some values inside. The problem is, I might have duplicates.

I went on this link but i couldn't find what I needed

What I tried is to create a list of duplicates using df.duplicated() which gives me True and False values for each indexes.
 Then for each index in this list where the result is True, I get the id from the df using df.loc[(df['id']== df['id'][dups]) ]. Depending on this result I call a function giveID() which returns a list of indexes to delete from the duplicates list. Because i don't need to iterate on the duplicates that are supposed to be deleted, is it possible to delete these indexes from the duplicates list during the for loop without breaking everything ?

Here is an example of my df (the duplicates are based on id column) :

   | id | type
--------------
0  | 312| data2
1  | 334| data
2  | 22 | data1
3  | 312| data8
#Here 0 and 3 are duplicates based on ID

Here is a part of my code:

duplicates = df.duplicated(subset='column_name',keep=False)
duplicates = duplicates[duplicates]

df_dup = df
listidx = []
i=0
for dups in duplicates.index:

    dup_id = df.loc[(df['id']== df['id'][dups])]
    for a in giveID(dup_id):
        if a not in listid:
            listidx.append(a)

#here i want to delete the all listidx from duplicates inside the for loop
#so that I don't iterate over unnecessary duplicates

def giveID(id)
#some code that returns a list of indexes

This is how looks duplicates in my code:

0          True
1          True
582        True
583        True
605        True
606        True
622        True
623        True
624        True
625        True
626        True
627        True
628        True
629        True
630        True
631        True
           ...
1990368    True
1991030    True

And i would like get the same but without unnecessary duplicates

Body:
If you need indexes of non-duplicated IDs:

df = pd.DataFrame({'ID':[0,1,1,3], 'B':[0,1,2,3]})
   B  ID
0  0   0
1  1   1
2  2   1
3  3   3

# List of indexes
non_duplicated = df.drop_duplicates(subset='ID', keep=False).index

df.loc[df.index.isin(non_duplicated)]
   B  ID
0  0   0
3  3   3


问:
Centre Align CAShape layer in a UIView
The following is a image for which the the code does not align the centre of the UIView , white color.

```<code>CAShapeLayer *layer = [CAShapeLayer layer];
layer.anchorPoint=CGPointMake(0.5, 0.5);

layer.path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 75.0, 75.0)].CGPath;
layer.fillColor =[UIColor redColor].CGColor;

[self.shapeView.layer addSublayer:layer];
</code>```

答:
For those still have issue with centering this approach worked for me:

1- Set the shape layer frame equal to parent view frame.

```<code>shapeLayer.frame = view.frame
</code>```

2- remove the shape layer position property.

```<code>// shapeLayer.position = CGPoint(x: ,y: )
</code>```

3- set x and y value of your bezier path equal to zero.

```<code>UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: self.width, height:
self.height))
</code>```

Only these should be enough, get rid of the rest.

======

If that didn't work, then try this one:

```<code>@IBDesignable class YourView: UIView {

private var shapeLayer: CAShapeLayer!

override func draw(_ rect: CGRect) {
    self.shapeLayer = CAShapeLayer()
    self.shapeLayer.path = bezierPath.cgPath
    self.shapeLayer.fillColor = UIColor.blue.cgColor

    let bezierPathHeight = self.bezierPath.cgPath.boundingBox.height
    let bezierPathWidth = self.bezierPath.cgPath.boundingBox.width

    self.shapeLayer.setAffineTransform(CGAffineTransform.init(translationX: self.bounds.width / bezierPathWidth, y: self.bounds.height / bezierPathHeight))

    self.shapeLayer.setAffineTransform(CGAffineTransform.init(scaleX: self.bounds.width / bezierPathHeight, y: self.bounds.height / bezierPathHeight))

    self.layer.addSublayer(self.shapeLayer)

}
</code>```

Title: Centre Align CAShape layer in a UIView

Body:
The following is a image for which the the code does not align the centre of the UIView , white color.

CAShapeLayer *layer = [CAShapeLayer layer];
layer.anchorPoint=CGPointMake(0.5, 0.5);

layer.path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 75.0, 75.0)].CGPath;
layer.fillColor =[UIColor redColor].CGColor;

[self.shapeView.layer addSublayer:layer];

Body:
For those still have issue with centering this approach worked for me:

1- Set the shape layer frame equal to parent view frame.

shapeLayer.frame = view.frame

2- remove the shape layer position property.

// shapeLayer.position = CGPoint(x: ,y: )

3- set x and y value of your bezier path equal to zero.

UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: self.width, height:
self.height))

Only these should be enough, get rid of the rest.

======

If that didn't work, then try this one:

@IBDesignable class YourView: UIView {

private var shapeLayer: CAShapeLayer!

override func draw(_ rect: CGRect) {
    self.shapeLayer = CAShapeLayer()
    self.shapeLayer.path = bezierPath.cgPath
    self.shapeLayer.fillColor = UIColor.blue.cgColor

    let bezierPathHeight = self.bezierPath.cgPath.boundingBox.height
    let bezierPathWidth = self.bezierPath.cgPath.boundingBox.width

    self.shapeLayer.setAffineTransform(CGAffineTransform.init(translationX: self.bounds.width / bezierPathWidth, y: self.bounds.height / bezierPathHeight))

    self.shapeLayer.setAffineTransform(CGAffineTransform.init(scaleX: self.bounds.width / bezierPathHeight, y: self.bounds.height / bezierPathHeight))

    self.layer.addSublayer(self.shapeLayer)

}


问:
trying to convert rgb value to hex
i got the output as
rgb(250, 219, 233) none repeat scroll 0% 0% / auto padding-box border-box

i want to convert this to hex value.

```<code>List<WebElement> datesOfMonths = driver.findElements(
         By.xpath("//a[@class=\"ui-state-default\"]"));
System.out.println(datesOfMonths.size());
for (int i = 0; i < datesOfMonths.size(); i++) {
    String backgroundValue = datesOfMonths.get(i).getCssValue("background");
    if (backgroundValue.contains("250") || backgroundValue.contains("71")
            || backgroundValue.contains("134") || backgroundValue.contains("248")) {
        System.out.println(backgroundValue);
    } else  {
    }
}
</code>```

答:
rgb convert hex

public class Rgb2Hex {
    public static void main(String[] args) {
        int r = 255;
        int g = 255;
        int b = 255;
        String hex = String.format("#%02x%02x%02x", r, g, b);
        System.out.println(hex);
    }
}
```

Title: trying to convert rgb value to hex

Body:
i got the output as
rgb(250, 219, 233) none repeat scroll 0% 0% / auto padding-box border-box

i want to convert this to hex value.

List<WebElement> datesOfMonths = driver.findElements(
         By.xpath("//a[@class=\"ui-state-default\"]"));
System.out.println(datesOfMonths.size());
for (int i = 0; i < datesOfMonths.size(); i++) {
    String backgroundValue = datesOfMonths.get(i).getCssValue("background");
    if (backgroundValue.contains("250") || backgroundValue.contains("71")
            || backgroundValue.contains("134") || backgroundValue.contains("248")) {
        System.out.println(backgroundValue);
    } else  {
    }
}


问:
How to efficiently find the latest partition from a S3 dataset using Spark
I have dataset that has data added almost everyday, and needs to be processed everyday in a part of a larger ETL.
When I select the partition directly, the query is really fast:

```<code>SELECT * FROM JSON.`s3://datalake/partitoned_table/?partition=2019-05-20`
</code>```

Yet, the issue is that the event type does not generate data on some Sundays, resulting in a non-existing partition on that particular day. Because of this, I cannot use the previous statement to run my daily job.

Another attempt led me to try to have spark find the latest partition of that dataset, in order to be sure the bigger query wouldn't fail:

```<code>SELECT * FROM JSON.`s3://datalake/partitoned_table/`
WHERE partition = (SELECT MAX(partition) FROM JSON.`s3://datalake/partitoned_table/`)
</code>```

This works every time, but it is unbelievably slow.

I found numerous articles and reference on how to build and maintain partitions, yet nothing about how to read them correctly.

Any idea how to have this done properly?

答:
WorkAround when you don't have Hive-

```<code>FileSystem.get(URI.create("s3://datalake/partitoned_table"), conf).listStatus(new Path("s3://datalake/partitoned_table/"))
</code>```

Above code will give you list of file partitions example - List(s3://datalake/partitoned_table/partition=2019-05-20, s3://datalake/partitoned_table/partition=2019-05-21....)

This is very efficient because it is only fetching metadata from the s3 location.

Just take the latest file partitions and use it your SQL.

Body:
I have dataset that has data added almost everyday, and needs to be processed everyday in a part of a larger ETL.
When I select the partition directly, the query is really fast:

SELECT * FROM JSON.`s3://datalake/partitoned_table/?partition=2019-05-20`

Yet, the issue is that the event type does not generate data on some Sundays, resulting in a non-existing partition on that particular day. Because of this, I cannot use the previous statement to run my daily job.

Another attempt led me to try to have spark find the latest partition of that dataset, in order to be sure the bigger query wouldn't fail:

SELECT * FROM JSON.`s3://datalake/partitoned_table/`
WHERE partition = (SELECT MAX(partition) FROM JSON.`s3://datalake/partitoned_table/`)

This works every time, but it is unbelievably slow.

I found numerous articles and reference on how to build and maintain partitions, yet nothing about how to read them correctly.

Any idea how to have this done properly?

Body:
WorkAround when you don't have Hive-

FileSystem.get(URI.create("s3://datalake/partitoned_table"), conf).listStatus(new Path("s3://datalake/partitoned_table/"))

Above code will give you list of file partitions example - List(s3://datalake/partitoned_table/partition=2019-05-20, s3://datalake/partitoned_table/partition=2019-05-21....)

This is very efficient because it is only fetching metadata from the s3 location.

Just take the latest file partitions and use it your SQL.


问:
How to Store Obtained Packet into a variable for pkt.show() command?
I wanted to store the Raw packet obtained through sniff command of scapy and use it further.
How can I do this?

I could print data on command prompt but unable to store it.

This is my code:

```<code>def pkt_callback(pkt):
    self.S = pkt.show()
    self.P = sniff(count = self.C, filter="udp", prn = pkt_callback)
</code>```

When I run this code I receive data but unable to store them

I expect to store load/ Raw data into a variable

```<code>load = '\x17\x03\x01\x01`\ngD\xdb/\xe5m!jEm\xe1%\x88\xa9~ *y\xcc\xd1T\xb6Vg\xb3\x82\\\x00\x91\r\xc1\xe4\xe0\xdb\xa2|\xc2\x86\xa2\x99J0\x86V\xc5\xad}y\xb4k&\x1e$\xcb\xcc\x99\xe0\xdb\xcf<\x1e\xc1\x10ZD\xc5\x8b\xaa\xa0\x0c\x08\xc4\xa1\xa0&\xd6.\x1f\
</code>```

but unable to do it.

答:
I have an answer which worked for me, hoping this might help someone:

```<code>    pkts = sniff(count =self.c,filter = "dst host %s or src host %s and udp" % (self.dst, self.src))

    pkt = pkts[0]

    pkt_raw = raw(pkt)
    print("Raw packet data",pkt_raw)
</code>```

found the solution from https://buildmedia.readthedocs.org/media/pdf/scapy/stable/scapy.pdf

Body:
I wanted to store the Raw packet obtained through sniff command of scapy and use it further.
How can I do this?

I could print data on command prompt but unable to store it.

This is my code:

def pkt_callback(pkt):
    self.S = pkt.show()
    self.P = sniff(count = self.C, filter="udp", prn = pkt_callback)

When I run this code I receive data but unable to store them

I expect to store load/ Raw data into a variable

load = '\x17\x03\x01\x01`\ngD\xdb/\xe5m!jEm\xe1%\x88\xa9~ *y\xcc\xd1T\xb6Vg\xb3\x82\\\x00\x91\r\xc1\xe4\xe0\xdb\xa2|\xc2\x86\xa2\x99J0\x86V\xc5\xad}y\xb4k&\x1e$\xcb\xcc\x99\xe0\xdb\xcf<\x1e\xc1\x10ZD\xc5\x8b\xaa\xa0\x0c\x08\xc4\xa1\xa0&\xd6.\x1f\

but unable to do it.

Body:
I have an answer which worked for me, hoping this might help someone:

    pkts = sniff(count =self.c,filter = "dst host %s or src host %s and udp" % (self.dst, self.src))

    pkt = pkts[0]

    pkt_raw = raw(pkt)
    print("Raw packet data",pkt_raw)

found the solution from https://buildmedia.readthedocs.org/media/pdf/scapy/stable/scapy.pdf


问:
How to Redirect Powerbi click to a new web page
How can I redirect a certain click onto the powerbi visualizations to a certain web page, let say I want to redirect a embedded report click onto a certain webpage how can I do that, does this kind of visualization possible in Powerbi if yes then How??</p>

答:
I know this is an old thread, but if you are using Power BI Embedded reports, you can use the PowerBI-Javascript to catch events from the tiles or reports and do some action like redirecting the user to a specific link.</p>

```<code>var element = document.getElementById('reportContainer');
var report = powerbi.get(element);

report.on('dataSelected', function(event)
{
    console.log(event.detail.dataPoints[0].identity[0].equals);
});
</code>```

Body:
I know this is an old thread, but if you are using Power BI Embedded reports, you can use the PowerBI-Javascript to catch events from the tiles or reports and do some action like redirecting the user to a specific link.

var element = document.getElementById('reportContainer');
var report = powerbi.get(element);

report.on('dataSelected', function(event)
{
    console.log(event.detail.dataPoints[0].identity[0].equals);
});


问:
PHP exec and Batik rasterizer
I'm using Batik to convert SVG images to PDF. When converting them through the terminal everying is fine and the file gets converted. However, what I want is to convert it dynamically from PHP with exec().

This is what i see when I convert from the terminal:

```<code>About to convert 1 SVG file(s)

Converting output.svg to /opt/lampp/htdocs/tool/generated/output.pdf...

... success
</code>```

When using exec() the output is limited to 'Converting output.svg... Etc' without the ...success part. Its as if the server won't wait for the script to finish. Also, the resulting PDF-file that does get generated is completely empty.

This is the call in PHP:

$command = 'cd ~/Downloads/batik-1.7 && java -jar batik-rasterizer.jar /opt/lampp/htdocs/tool/generated/output.svg -m "application/pdf"';

$string = exec($command);

```<code>echo '{"success": true, "message": "Design saved as generated/output.svg' . $string . '"}';`
</code>```

This is what I see in the js console:

Design saved as generated/output.svgConverting output.svg to /opt/lampp/htdocs/tool/generated/output.pdf ...

Edit:

Using stderr I got:

No protocol specified
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.

Edit 2:

After some googling I found the solution:

-Djava.awt.headless=true :)

Thanks all for guiding me in finding the answer!

答: Learn about the standard streams stdout and stderr.</p>

Title: PHP exec and Batik rasterizer

Body:
I'm using Batik to convert SVG images to PDF. When converting them through the terminal everying is fine and the file gets converted. However, what I want is to convert it dynamically from PHP with exec().

This is what i see when I convert from the terminal:

About to convert 1 SVG file(s)

Converting output.svg to /opt/lampp/htdocs/tool/generated/output.pdf...

... success

When using exec() the output is limited to 'Converting output.svg... Etc' without the ...success part. Its as if the server won't wait for the script to finish. Also, the resulting PDF-file that does get generated is completely empty.

This is the call in PHP:

$command = 'cd ~/Downloads/batik-1.7 && java -jar batik-rasterizer.jar /opt/lampp/htdocs/tool/generated/output.svg -m "application/pdf"';

$string = exec($command);

echo '{"success": true, "message": "Design saved as generated/output.svg' . $string . '"}';`

This is what I see in the js console:

Design saved as generated/output.svgConverting output.svg to /opt/lampp/htdocs/tool/generated/output.pdf ...

Edit:

Using stderr I got:

No protocol specified
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.

Edit 2:

After some googling I found the solution:

-Djava.awt.headless=true :)

Thanks all for guiding me in finding the answer!


问:
Typecasting a Double value to Int64 in Swift, number of digits is 13, but the system that its running on is a 32 bit system, would it fail?
I am trying to typecast a Double value to Int64 in Swift language, number of digits is 13 or more after getting final Int, it runs fine in a 64 bit system, but what happens if the system that it's running on is a 32 bit system?</p>

答:
It makes no difference: A Double is a 64-bit floating point number, and an Int64 is a 64-bit signed integer – no matter if the code is compiled for a 32-bit or a 64-bit platform.

Platform-dependent types are for example Int and CGFloat.


问:
Kubernetes Dashboard by kops on AWS show only json
I've installed Kubernetes by kops on aws, and basically every function is fine so far, except for Dashboad.

I've installed it by following this URL, and received no error.
https://github.com/kubernetes/kops/blob/master/docs/addons.md#installing-kubernetes-addons

However, the browser ( chrome, firefox, safari ) just shows me json text like below. The URL is like 'https://api.clustername.xxxx.com/ui'

"paths": [
      "/apis",
      "/apis/",
      "/apis/apiextensions.k8s.io",
      "/apis/apiextensions.k8s.io/v1beta1",
      "/healthz",
      "/healthz/etcd",
      "/healthz/ping",
      "/healthz/poststarthook/generic-apiserver-start-informers",
      "/healthz/poststarthook/start-apiextensions-controllers",
      "/healthz/poststarthook/start-apiextensions-informers",
      "/metrics",
      "/openapi/v2",
      "/swagger-2.0.0.json",
      "/swagger-2.0.0.pb-v1",
      "/swagger-2.0.0.pb-v1.gz",
      "/swagger.json",
      "/swaggerapi",
      "/version"
    ]

I would like see the real dashboard...
What shall I do ?

答:
kubectl  cluster-info

Kubernetes master:- Use this url

Append that url with:-
 /api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/

Username and password will be prompted on browser

kubectl config view

you will get username :- admin (default) and password

Next we need token
So create user by below step
https://github.com/kubernetes/dashboard/wiki/Creating-sample-user
create

Get token once user is created with admin access

kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')


问:
Create a waiting page with PHP and twig
I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:

```<code>....functions that take time

echo $twig->render('template.html.twig',[ variables ....]);
</code>```

Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.

I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.

```<code>echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable
</code>```

How can I achieve a waiting page?

答:
The solution I ended up doing was the following:

Call the page by Ajax and display a waiting page.

```<code>    function submit_form(file_method) {
        var spinner = $('#loader');
        spinner.show(); //show waiting div
        var request = $.ajax({
        url: "upload.php",
        cache: false,
        contentType: false,
        processData: false,
        async: true,
        data: form_data,
        type: 'POST',
        success: function (res, status) {
        if (status == 'success') {
            window.location.href = 'results.php';
        } },
        error: function (jqXHR, textStatus,res) {
            spinner.hide();
            alert('Error encountered: '+textStatus+'-'+jqXHR.responseText);

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

In the php page, store the output as an array in a session variable.

```<code>....functions that take time
 $_SESSION['result'] = [RESULTS .......]
</code>```

After the ajax call is completed successfully the user is redirected to a new page. The new page uses the session variable to call the template.

```<code>echo $twig->render('waiting.html.twig',$_SESSION['result'] );
unset($_SESSION['result']);
</code>```

Title: Create a waiting page with PHP and twig

Body:
I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:

....functions that take time

echo $twig->render('template.html.twig',[ variables ....]);

Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.

I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.

echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable

How can I achieve a waiting page?

Body:
The solution I ended up doing was the following:

Call the page by Ajax and display a waiting page.

    function submit_form(file_method) {
        var spinner = $('#loader');
        spinner.show(); //show waiting div
        var request = $.ajax({
        url: "upload.php",
        cache: false,
        contentType: false,
        processData: false,
        async: true,
        data: form_data,
        type: 'POST',
        success: function (res, status) {
        if (status == 'success') {
            window.location.href = 'results.php';
        } },
        error: function (jqXHR, textStatus,res) {
            spinner.hide();
            alert('Error encountered: '+textStatus+'-'+jqXHR.responseText);

            } })
    };

In the php page, store the output as an array in a session variable.

....functions that take time
 $_SESSION['result'] = [RESULTS .......]

After the ajax call is completed successfully the user is redirected to a new page. The new page uses the session variable to call the template.

echo $twig->render('waiting.html.twig',$_SESSION['result'] );
unset($_SESSION['result']);


问:
How to repeat sequence of days 1:7 based on continuous days to correspond with weeks
I want to add a column of days each week to my dataset which contains continuous days and continuous weeks already for a large dataset

I've tried to use the floor function and the rep function already

Edit I'm attempting to automate the final output mydata$day_of_week

```<code>time_in_hrs<-c(0,2,12,24,25,29,30,32,38,43,57,82,93,105,199,205,245,263)
mydata<-as.data.frame(time_in_hrs)
mydata$time_in_days<-floor(mydata$time_in_hrs/24)+1
mydata$time_in_weeks<-floor(mydata$time_in_days/8)+1
mydata$day_of_week<-c(1,1,1,2,2,2,2,2,2,2,3,4,4,5,2,2,4,4)
</code>```

答:
Assuming you're trying to automate the column mydata$day_of_week that you're now doing manually, you can do this as follows:

```<code>mydata$day_of_week_auto <- mydata$time_in_days - (mydata$time_in_weeks - 1) * 7
</code>```

Body:
I want to add a column of days each week to my dataset which contains continuous days and continuous weeks already for a large dataset

I've tried to use the floor function and the rep function already

Edit I'm attempting to automate the final output mydata$day_of_week

time_in_hrs<-c(0,2,12,24,25,29,30,32,38,43,57,82,93,105,199,205,245,263)
mydata<-as.data.frame(time_in_hrs)
mydata$time_in_days<-floor(mydata$time_in_hrs/24)+1
mydata$time_in_weeks<-floor(mydata$time_in_days/8)+1
mydata$day_of_week<-c(1,1,1,2,2,2,2,2,2,2,3,4,4,5,2,2,4,4)

Body:
Assuming you're trying to automate the column mydata$day_of_week that you're now doing manually, you can do this as follows:

mydata$day_of_week_auto <- mydata$time_in_days - (mydata$time_in_weeks - 1) * 7


问:
Check if a value is in an array or not with Excel VBA
I've got some code below, that is supposed to be checking if a value is in an Array or not.

```<code>Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").Value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").Value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

If the cell A1 contains the word Examples for some reason both of the IsInArray detects it as existing for both Arrays when it should only find it existing in the vars1 array

What do I need to change to make my IsInArray function to make it an exact match?

答:
I would like to provide another variant that should be both performant and powerful, because

it does not use the sometimes slower Match)

supports String, Integer, Boolean etc. (not String-only)

returns the index of the searched-for item

supports nth-occurrence

...

```<code>'-1 if not found
'https://stackoverflow.com/a/56327647/1915920
Public Function IsInArray( _
  item As Variant, _
  arr As Variant, _
  Optional nthOccurrence As Long = 1 _
  ) As Long

    IsInArray = -1

    Dim i As Long:  For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = item Then
            If nthOccurrence > 1 Then
                nthOccurrence = nthOccurrence - 1
                GoTo continue
            End If
            IsInArray = i
            Exit Function
        End If
continue:
    Next i

End Function
</code>```

use it like this:

```<code>Sub testInt()
  Debug.Print IsInArray(2, Array(1, 2, 3))  '=> 1
End Sub

Sub testString1()
  Debug.Print IsInArray("b", Array("a", "b", "c", "a"))  '=> 1
End Sub

Sub testString2()
  Debug.Print IsInArray("b", Array("a", "b", "c", "b"), 2)  '=> 3
End Sub

Sub testBool1()
  Debug.Print IsInArray(False, Array(True, False, True))  '=> 1
End Sub

Sub testBool2()
  Debug.Print IsInArray(True, Array(True, False, True), 2)  '=> 2
End Sub
</code>```

Body:
I've got some code below, that is supposed to be checking if a value is in an Array or not.

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").Value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").Value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

If the cell A1 contains the word Examples for some reason both of the IsInArray detects it as existing for both Arrays when it should only find it existing in the vars1 array

What do I need to change to make my IsInArray function to make it an exact match?

Body:
I would like to provide another variant that should be both performant and powerful, because

it does not use the sometimes slower Match)

supports String, Integer, Boolean etc. (not String-only)

returns the index of the searched-for item

supports nth-occurrence

...

'-1 if not found
'https://stackoverflow.com/a/56327647/1915920
Public Function IsInArray( _
  item As Variant, _
  arr As Variant, _
  Optional nthOccurrence As Long = 1 _
  ) As Long

    IsInArray = -1

    Dim i As Long:  For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = item Then
            If nthOccurrence > 1 Then
                nthOccurrence = nthOccurrence - 1
                GoTo continue
            End If
            IsInArray = i
            Exit Function
        End If
continue:
    Next i

End Function

use it like this:

Sub testInt()
  Debug.Print IsInArray(2, Array(1, 2, 3))  '=> 1
End Sub

Sub testString1()
  Debug.Print IsInArray("b", Array("a", "b", "c", "a"))  '=> 1
End Sub

Sub testString2()
  Debug.Print IsInArray("b", Array("a", "b", "c", "b"), 2)  '=> 3
End Sub

Sub testBool1()
  Debug.Print IsInArray(False, Array(True, False, True))  '=> 1
End Sub

Sub testBool2()
  Debug.Print IsInArray(True, Array(True, False, True), 2)  '=> 2
End Sub


问:
error while setting image in imageView in iphone
I have written a code for setting imageview ...as per the button clicked...but my problem is when i press the button it is giving me the error like...too many arguments to function ImageNamed...while executing this line...

UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];

the whole code is....

```<code>-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView]; }
</code>```

答:
Try this</p>

```<code>-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
NSString *imageName = [NSString stringWithFormat:@"robort %d.jpg",x];
UIImage* photo = [UIImage imageNamed:imageName];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView];
}
</code>```

Body:
I have written a code for setting imageview ...as per the button clicked...but my problem is when i press the button it is giving me the error like...too many arguments to function ImageNamed...while executing this line...

UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];

the whole code is....

-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView]; }

Body:
Try this

-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
NSString *imageName = [NSString stringWithFormat:@"robort %d.jpg",x];
UIImage* photo = [UIImage imageNamed:imageName];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView];
}


问:
Df.mean returns imaginary numbers
I have a dataframe with around 50 columns and around 3000 rows. Most cells are empty but not all of them. I am trying to add a new row at the end of the dataframe, with the mean value of each column and I need it to ignore the empty cells.

I am using df.mean(axis=0), which somehows turns all values of the dataframe into imaginary numbers. All values stay the same but a +0j is added. I have no Idea why.

Turbine.loc['Mean_Values'] = Turbine.mean(axis=0)
```

I couldnt find a solution for this, is it because of the empty cells?

答:
Base on this, df.mean() will automatically skip the NaN/Null value with parameter value of skipna=True. Example:

```<code>df=pd.DataFrame({'value':[1,2,3,np.nan,5,6,np.nan]})
df=df.append({'value':df.mean(numeric_only=True).value}, ignore_index=True,)
print(df)
</code>```

Output:

```<code>   value
0    1.0
1    2.0
2    3.0
3    NaN
4    5.0
5    6.0
6    NaN
7    3.4
</code>```

But if there is a complex number in a cell, the result of df.mean() will be cast to complex number. Example:

```<code>df=pd.DataFrame({'value':[1,2,3,np.nan,5,6,np.nan, complex(1,0)]})
print(df)
print('\n')
df=df.append({'value':df.mean(numeric_only=True).value}, ignore_index=True,)
print(df)
</code>```

Output with a complex value in a cell:

```<code>    value
0  (1+0j)
1  (2+0j)
2  (3+0j)
3     NaN
4  (5+0j)
5  (6+0j)
6     NaN
7  (1+0j)

    value
0  (1+0j)
1  (2+0j)
2  (3+0j)
3     NaN
4  (5+0j)
5  (6+0j)
6     NaN
7  (1+0j)
8  (3+0j)
</code>```

Hope this can help you :)

Title: Df.mean returns imaginary numbers

Body:
I have a dataframe with around 50 columns and around 3000 rows. Most cells are empty but not all of them. I am trying to add a new row at the end of the dataframe, with the mean value of each column and I need it to ignore the empty cells.

I am using df.mean(axis=0), which somehows turns all values of the dataframe into imaginary numbers. All values stay the same but a +0j is added. I have no Idea why.

Turbine.loc['Mean_Values'] = Turbine.mean(axis=0)

I couldnt find a solution for this, is it because of the empty cells?

Body:
Base on this, df.mean() will automatically skip the NaN/Null value with parameter value of skipna=True. Example:

df=pd.DataFrame({'value':[1,2,3,np.nan,5,6,np.nan]})
df=df.append({'value':df.mean(numeric_only=True).value}, ignore_index=True,)
print(df)

Output:

   value
0    1.0
1    2.0
2    3.0
3    NaN
4    5.0
5    6.0
6    NaN
7    3.4

But if there is a complex number in a cell, the result of df.mean() will be cast to complex number. Example:

df=pd.DataFrame({'value':[1,2,3,np.nan,5,6,np.nan, complex(1,0)]})
print(df)
print('\n')
df=df.append({'value':df.mean(numeric_only=True).value}, ignore_index=True,)
print(df)

Output with a complex value in a cell:

    value
0  (1+0j)
1  (2+0j)
2  (3+0j)
3     NaN
4  (5+0j)
5  (6+0j)
6     NaN
7  (1+0j)

    value
0  (1+0j)
1  (2+0j)
2  (3+0j)
3     NaN
4  (5+0j)
5  (6+0j)
6     NaN
7  (1+0j)
8  (3+0j)

Hope this can help you :)


问:
Multiple References Between 2 Tables, one-to-many as well as many-to-many
I'm just started learning RoR and decided to create a side project to learn more. I've been stuck on this problem for about a week now :(

Basically, I'm trying to set up relationships between 2 tables, Users and Recipes.

2 relationships need to form for the purpose of my app.

a recipe is created by a user so it's a one-to-many association.

a user can have favourite recipes and a recipe can be favourited by multiple users. So, this is a many-to-many association.

This is what I've done so far.

user model

```<code>  has_many :recipes
  has_many :user_recipes
  has_many :recipe, through: :user_recipes
</code>```

recipe Model

```<code>  belongs_to :user, dependent: :destroy
  has_many :user_recipes
  has_many :users, through: :user_recipes
</code>```

user_recipes model

```<code>  belongs_to :user
  belongs_to :recipe
</code>```

user_recipe migration file

```<code>  t.belongs_to :recipe, index: true
  t.belongs_to :user, index: true
</code>```

recipe migration file

```<code>  t.belongs_to :user
</code>```

user migration file has nothing related to recipes.

From what I did. I was able to:
1. assign a user to a recipe (the creator) and check using recipe.user
2. assign favourite relationships using recipe.users << user

The problem
when I type user.recipes it tells me which recipes a user has created and not which recipes a user likes. I think there should be a better way to set my associates up to be able to use all functionalities properly.

I'd appreciate all the help. Thank you in advance!

答:
Give an alias to your created recipes, so that you don't have to use "user.recipes" to access it.

Edit your user model this way:

replace your row

```<code>has_many :recipes
</code>```

with something like this:

```<code>has_many :created_recipes, foreign_key: :user_id, class_name: "Recipe"
</code>```

By doing this, you can access the recipes your user created by typing "user.created_recipes", and the recipes your user likes by typing "user.recipes".

Body:
I'm just started learning RoR and decided to create a side project to learn more. I've been stuck on this problem for about a week now :(

Basically, I'm trying to set up relationships between 2 tables, Users and Recipes.

2 relationships need to form for the purpose of my app.

a recipe is created by a user so it's a one-to-many association.

a user can have favourite recipes and a recipe can be favourited by multiple users. So, this is a many-to-many association.

This is what I've done so far.

user model

  has_many :recipes
  has_many :user_recipes
  has_many :recipe, through: :user_recipes

recipe Model

  belongs_to :user, dependent: :destroy
  has_many :user_recipes
  has_many :users, through: :user_recipes

user_recipes model

  belongs_to :user
  belongs_to :recipe

user_recipe migration file

  t.belongs_to :recipe, index: true
  t.belongs_to :user, index: true

recipe migration file

  t.belongs_to :user

user migration file has nothing related to recipes.

From what I did. I was able to:
1. assign a user to a recipe (the creator) and check using recipe.user
2. assign favourite relationships using recipe.users << user

The problem
when I type user.recipes it tells me which recipes a user has created and not which recipes a user likes. I think there should be a better way to set my associates up to be able to use all functionalities properly.

I'd appreciate all the help. Thank you in advance!

Body:
Give an alias to your created recipes, so that you don't have to use "user.recipes" to access it.

Edit your user model this way:

replace your row

has_many :recipes

with something like this:

has_many :created_recipes, foreign_key: :user_id, class_name: "Recipe"

By doing this, you can access the recipes your user created by typing "user.created_recipes", and the recipes your user likes by typing "user.recipes".


问:
Spring cloud gateway gives connection closed prematurely
I am using spring cloud gateway as API gateway in my micro service setup with consul as service discovery.

In some case when API of some microservice take more then 2 minutes, gateway throws below error:

```<code>java.io.IOException: Connection closed prematurely
at reactor.ipc.netty.http.client.HttpClientOperations.onInboundClose(HttpClientOperations.java:269)
at reactor.ipc.netty.channel.ChannelOperationsHandler.channelInactive(ChannelOperationsHandler.java:113)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelInactive(CombinedChannelDuplexHandler.java:420)
at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:377)
at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:342)
at io.netty.handler.codec.http.HttpClientCodec$Decoder.channelInactive(HttpClientCodec.java:282)
at io.netty.channel.CombinedChannelDuplexHandler.channelInactive(CombinedChannelDuplexHandler.java:223)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1429)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:947)
at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:822)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:313)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
at java.lang.Thread.run(Thread.java:745)
</code>```

I tried the same API multiple time, I got this error exactly after 2 minutes.

Is there any property settings.
Version and dependency details:

```<code>compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.cloud:spring-cloud-starter-gateway')
compile('org.springframework.cloud:spring-cloud-starter-openfeign')

springBootVersion=2.0.3.RELEASE
springDMPVersion=1.0.4.RELEASE
springPlatformBomVersion=Cairo-SR2
</code>```

Ribbon settings:

```<code>ribbon:
  ConnectTimeout: 3000
  ReadTimeout: 3000
</code>```

答:
There was an issue in downstream service.

In my application, there is nodejs application is running behind the spring cloud gateway and default time out is 2 min.

Ref: https://github.com/expressjs/express/issues/3330

In my case after 2 min, nodejs application gives timeout and that is why I get an error in the gateway.

I resolved it by changing timeout values in node application

Body:
I am using spring cloud gateway as API gateway in my micro service setup with consul as service discovery.

In some case when API of some microservice take more then 2 minutes, gateway throws below error:

java.io.IOException: Connection closed prematurely
at reactor.ipc.netty.http.client.HttpClientOperations.onInboundClose(HttpClientOperations.java:269)
at reactor.ipc.netty.channel.ChannelOperationsHandler.channelInactive(ChannelOperationsHandler.java:113)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelInactive(CombinedChannelDuplexHandler.java:420)
at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:377)
at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:342)
at io.netty.handler.codec.http.HttpClientCodec$Decoder.channelInactive(HttpClientCodec.java:282)
at io.netty.channel.CombinedChannelDuplexHandler.channelInactive(CombinedChannelDuplexHandler.java:223)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1429)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)
at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:947)
at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:822)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:313)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
at java.lang.Thread.run(Thread.java:745)

I tried the same API multiple time, I got this error exactly after 2 minutes.

Is there any property settings.
Version and dependency details:

compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.cloud:spring-cloud-starter-gateway')
compile('org.springframework.cloud:spring-cloud-starter-openfeign')

springBootVersion=2.0.3.RELEASE
springDMPVersion=1.0.4.RELEASE
springPlatformBomVersion=Cairo-SR2

Ribbon settings:

ribbon:
  ConnectTimeout: 3000
  ReadTimeout: 3000


问:
Can you mock a value rather than a method?
Hi there I have a private method that has a few different bits going on inside. This method is passed a Future[A], is there anyway to mock this future value, as I don't what to mock the whole method as I am mocking the method calls going on inside this method. Thanks, Jackie

```<code>private def showSomething(id: String, accountData: Future[AccountData]): = {
  accountData zip someService.getSomething(id) map {
    case (accountData, somethingElse) => // do something
  }
}
</code>```

So I would like to mock the accountData Future passed into the showSomething method, is there any way to do this? Thanks

答: If you know what value you need in accountData Future, why not just pass Future.successful(yourMockedValue)?

Body:
Hi there I have a private method that has a few different bits going on inside. This method is passed a Future[A], is there anyway to mock this future value, as I don't what to mock the whole method as I am mocking the method calls going on inside this method. Thanks, Jackie

private def showSomething(id: String, accountData: Future[AccountData]): = {
  accountData zip someService.getSomething(id) map {
    case (accountData, somethingElse) => // do something
  }
}

So I would like to mock the accountData Future passed into the showSomething method, is there any way to do this? Thanks


问:
Encrypt JSON with SHA256 hash, got 512 characters back instead of 64
Based on Google document and cryptography.io.

I attempt to encrypt a queried result which is in a JSON format which look like this {"data":"abc"}. As I know, when encrypting with SHA256, the encrypted data will be in a form of 64 characters but after I looked on and tried it with the code in the link and some modification, I got a result of 512 characters instead of 64 characters.

This is my code:

```<code>def encrypt_rsa(_rsa_pub, plaintext):
    key_txt = _rsa_pub.encode()
    public_key = serialization.load_pem_public_key(key_txt, default_backend())

    # encrypt plaintext
    pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                       algorithm=hashes.SHA256(),
                       label=None)
    return public_key.encrypt(plaintext, pad)

pk = ....#public key
message = .... #query result (JSON)
x = json.dumps(message).encode('utf-8')
enc = encrypt_rsa(pk , x)
enc = base64.b64encode(enc).decode()
dec = decrypt_rsa(enc)
</code>```

There is no error but I got a long encrypted data with 512 characters which is really weird. I have tried decrypting it with the code from cryptography.io and got an error:

```<code>AttributeError: 'str' object has no attribute 'decrypt'
</code>```

which I think this error might occured because of the wrong encrypted data that should be 64 characters but the input is 512 characters. So, based on my case, what did I forgot or what should be add to this code to make it become an encrypted data with 64 characters that can be decrypted?

Edit: decrypt function

```<code>def decrypt_rsa(ciphertext):
    private_key = .....
    pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                   algorithm=hashes.SHA256(),
                   label=None)
    return private_key.decrypt(ciphertext, pad)
</code>```

The error occured at decrypt at the line that return the result. I actually passed the encrypted data into this function. And I think it not because of the key since it should not provide error result like this

答:
You are encrypting data with RSA. (Not SHA256, that's just a parameter of the RSA encryption.) Note that RSA is typically only used to encrypt/decrypt very small amounts of data. Typically it is used to encrypt/decrypt another symmetric key, e.g. for AES, and then the bulk encryption/decryption is done with AES.

The size of the RSA cipher text is determined by the RSA key size. In this case you are probably using a 4096 bit RSA keys, which results in 4096 / 8 = 512 byte messages. Messages that are smaller are OK, those are padded. Messages that are larger will not work.

Finally, you are trying to call decrypt on a string, which is not a thing. You need to pass the data to a decrypt_rsa function instead, which does the reverse of the encrypt_rsa function that you've shown.

edit, after decrypt_rsa function added to question: the error message shows that private_key is not actually a private key as it should be, but a string. Why that is we can't say because the code to initialize private_key is not shown.

Body:
Based on Google document and cryptography.io.

I attempt to encrypt a queried result which is in a JSON format which look like this {"data":"abc"}. As I know, when encrypting with SHA256, the encrypted data will be in a form of 64 characters but after I looked on and tried it with the code in the link and some modification, I got a result of 512 characters instead of 64 characters.

This is my code:

def encrypt_rsa(_rsa_pub, plaintext):
    key_txt = _rsa_pub.encode()
    public_key = serialization.load_pem_public_key(key_txt, default_backend())

    # encrypt plaintext
    pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                       algorithm=hashes.SHA256(),
                       label=None)
    return public_key.encrypt(plaintext, pad)

pk = ....#public key
message = .... #query result (JSON)
x = json.dumps(message).encode('utf-8')
enc = encrypt_rsa(pk , x)
enc = base64.b64encode(enc).decode()
dec = decrypt_rsa(enc)

There is no error but I got a long encrypted data with 512 characters which is really weird. I have tried decrypting it with the code from cryptography.io and got an error:

AttributeError: 'str' object has no attribute 'decrypt'

which I think this error might occured because of the wrong encrypted data that should be 64 characters but the input is 512 characters. So, based on my case, what did I forgot or what should be add to this code to make it become an encrypted data with 64 characters that can be decrypted?

Edit: decrypt function

def decrypt_rsa(ciphertext):
    private_key = .....
    pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                   algorithm=hashes.SHA256(),
                   label=None)
    return private_key.decrypt(ciphertext, pad)

The error occured at decrypt at the line that return the result. I actually passed the encrypted data into this function. And I think it not because of the key since it should not provide error result like this


答:
You need to use:</p>

```<code>UIImage* photo = [UIImage imageNamed:[NSString stringWithFormat:@"robort %d.jpg",x]];
</code>```

Title: error while setting image in imageView in iphone

Body:
You need to use:

UIImage* photo = [UIImage imageNamed:[NSString stringWithFormat:@"robort %d.jpg",x]];


问:
Changing my Google Map from type FragmentActivity to a simple Fragment for a BottomNavigationView?
I wanted to implement a BottomNavigationView (toolbar at the bottom) in my app. My GoogleMap fragment is of type FragmentActivity, not fragment. Would this be a problem? Is there an easy way to convert it to a fragment? I've checked a lot of tutorials and none of them fit the situation I'm in or address it at all. Thanks in advance.</p>

答:
Hope this answer can help you !

Example Activity

```<code>public class ExampleActivity extends AppCopmactActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example_activity);

        initFragment(savedInstanceState);

    }

    private void initFragment(Bundle savedInstanceState) {

        if (findViewById(R.id.mainFragmentContainer) != null) {

            if (savedInstanceState != null) {
                return;
            }
            ExampleFragment exampleFragment = new ExampleFragment ();
            getSupportFragmentManager().beginTransaction().add(R.id.mainFragmentContainer, exampleFragment ).commit();
        }
    }
</code>```

Example Fragment

```<code>   public class ExampleFragment extends Fragment{

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_example, container, false);
            return view;
        }

        @Override
        public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

 }

}
</code>```

example_activity.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.Base">

    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:id="@+id/mainFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tool_bar" />

</LinearLayout>
</code>```

Body:
Hope this answer can help you !

Example Activity

public class ExampleActivity extends AppCopmactActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example_activity);

        initFragment(savedInstanceState);

    }

    private void initFragment(Bundle savedInstanceState) {

        if (findViewById(R.id.mainFragmentContainer) != null) {

            if (savedInstanceState != null) {
                return;
            }
            ExampleFragment exampleFragment = new ExampleFragment ();
            getSupportFragmentManager().beginTransaction().add(R.id.mainFragmentContainer, exampleFragment ).commit();
        }
    }

Example Fragment

   public class ExampleFragment extends Fragment{

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_example, container, false);
            return view;
        }

        @Override
        public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

 }

}

example_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.Base">

    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:id="@+id/mainFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tool_bar" />

</LinearLayout>


问:
How can i initialize a linked list node with a single init call?
I am trying to create a linked list in Python. My question is in the init function of the below code

```<code>class Node(object):

    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

firstNode = Node(15)

secondNode = Node(20)

thirdNode = Node(25)

firstNode.next_node = secondNode

</code>```

I want to ask if we can initialize a node (along with its data and the next node link) in a single init call?

In the above code, I am first passing the data attribute of the node in the init call, and then i am setting the link with the help of the next_node attribute. Is there a way to do both the things in a single init call?

答:
Yes, You can achieve that by nesting your class instances.

For example, a one liner to set all three nodes in one call

```<code>thirdNode = Node(25, Node(20, Node(15)))
print(thirdNode.data)
print(thirdNode.next_node.data)
print(thirdNode.next_node.next_node.data)
</code>```

Or breaking your code in calls such that the next_nodeis called into the constructor while instantiating the new Node object

```<code>firstNode = Node(15)
secondNode = Node(20, firstNode)
thirdNode = Node(25, secondNode)
print(thirdNode.data)
print(secondNode.data)
print(firstNode.data)
</code>```

The output will be

```<code>25
20
15
</code>```

Body:
I am trying to create a linked list in Python. My question is in the init function of the below code

class Node(object):

    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next_node

    def set_next(self, new_next):
        self.next_node = new_next

firstNode = Node(15)

secondNode = Node(20)

thirdNode = Node(25)

firstNode.next_node = secondNode

I want to ask if we can initialize a node (along with its data and the next node link) in a single init call?

In the above code, I am first passing the data attribute of the node in the init call, and then i am setting the link with the help of the next_node attribute. Is there a way to do both the things in a single init call?

Body:
Yes, You can achieve that by nesting your class instances.

For example, a one liner to set all three nodes in one call

thirdNode = Node(25, Node(20, Node(15)))
print(thirdNode.data)
print(thirdNode.next_node.data)
print(thirdNode.next_node.next_node.data)

Or breaking your code in calls such that the next_nodeis called into the constructor while instantiating the new Node object

firstNode = Node(15)
secondNode = Node(20, firstNode)
thirdNode = Node(25, secondNode)
print(thirdNode.data)
print(secondNode.data)
print(firstNode.data)

The output will be

25
20
15


问:
How to print column name inside function applied to all columns with dplyr 0.8.1
I had a working function under previous version of dplyr (0.8.0.1), but now it prints dots instead of the column name.

The print is merely a dummy approach. In my real code I print the column name in a sweetalert message that keeps the user of my R Shiny app updated on progress of a long calculation. The dummy code here is part of a more extensive dplyr code

Perhaps there is a bug in the new dplyr, but if anyone knows how to achieve retrieving the column names inside the function while sticking to dplyr approach, i'd be glad to hear it.

I have tried with clean sessions, loading only dplyr and multimode, and the behavior changes with the version of dplyr

```<code>library(dplyr) # version 0.8.1 vs 0.8.0.1 used here
library(multimode)
funx <- function(x) {
    print(substitute(x))
    multires <- multimode::modetest(x, method = 'SI')
    p <- multires$p.value}

mtcars %>%
    select(1:2) %>%
    summarise_all(list(~ funx(.)))
</code>```

答:
Ironically, after getting feedback on the github post, with the new version we can now do this:

```<code>   mtcars %>%
      select(1:2) %>%
        summarise_all(funx)
</code>```

Which was actually the exact same syntax as I started my problem with when posting this question, but at the time of the previous dplyr version, this was not possible yet.
So, good work that the dplyr team has made the syntax more 'natural' I would say.

Body:
I had a working function under previous version of dplyr (0.8.0.1), but now it prints dots instead of the column name.

The print is merely a dummy approach. In my real code I print the column name in a sweetalert message that keeps the user of my R Shiny app updated on progress of a long calculation. The dummy code here is part of a more extensive dplyr code

Perhaps there is a bug in the new dplyr, but if anyone knows how to achieve retrieving the column names inside the function while sticking to dplyr approach, i'd be glad to hear it.

I have tried with clean sessions, loading only dplyr and multimode, and the behavior changes with the version of dplyr

library(dplyr) # version 0.8.1 vs 0.8.0.1 used here
library(multimode)
funx <- function(x) {
    print(substitute(x))
    multires <- multimode::modetest(x, method = 'SI')
    p <- multires$p.value}

mtcars %>%
    select(1:2) %>%
    summarise_all(list(~ funx(.)))

Body:
Ironically, after getting feedback on the github post, with the new version we can now do this:

   mtcars %>%
      select(1:2) %>%
        summarise_all(funx)

Which was actually the exact same syntax as I started my problem with when posting this question, but at the time of the previous dplyr version, this was not possible yet.
So, good work that the dplyr team has made the syntax more 'natural' I would say.


问:
Discord.js Level System
My 'problem' is more of a feature I am looking to add, I used this guide:
https://anidiots.guide/coding-guides/sqlite-based-points-system
I changed the code a little to mainly give you a random amount of XP, I am looking to edit how much XP is needed to level up.

Right now it is a static amount, being 5000 needed to level up. I am trying to make it increase the amount needed to level up by an extra 5000 each time you level up.

Currently, it works like this:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 10000 total xp needed

Currently, the amount needed to level up is always 5000 between each level.

This is how I want it to work:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 15000 total XP needed

Which will be 5000 to level 2 and then 10000 to level 3 and so on (increasing the amount needed by 5000 each time you level up)

I spent the best part of 2 hours trying different things, and mainly looking at the code being completely out of my depth.
I believed that doing something like this would work, but I have no idea if it's correct

if (score.level == '1') {
    nextLevel = 5000
}
if (score.level == '2' {
    nextLevel = 10000
}
```

<p>I highly doubt this is correct, otherwise, my message event would be very long, as I plan to have 100 levels</p>

<p>The code in its entirety: </p>

<pre class="lang-js prettyprint-override"><code>    let score;
    if (message.guild) {
        score = bot.getScore.get(message.author.id, message.guild.id);
        if (!score) {
            score = {
                id: `${message.guild.id}-${message.author.id}`,
                user: message.author.id,
                guild: message.guild.id,
                points: 0,
                level: 1,
            };
        }
        const xpAdd = Math.floor(Math.random() * 10) + 50;
        const curxp = score.points;
        const curlvl = score.level;
        const nxtLvl = score.level * 5000;
        score.points = curxp + xpAdd;
        if (nxtLvl <= score.points) {
            score.level = curlvl + 1;
            const lvlup = new MessageEmbed()
                .setAuthor(
                    `Congrats ${message.author.username}`,
                    message.author.displayAvatarURL()
                )
                .setTitle('You have leveled up!')
                .setThumbnail('https://i.imgur.com/lXeBiMs.png')
                .setColor(color)
                .addField('New Level', curlvl + 1);
            message.channel.send(lvlup).then(msg => {
                msg.delete({
                    timeout: 10000,
                });
            });
        }
        bot.setScore.run(score);
    }
</code>```

The code as-is works fine and as expected, but as-is is not very good, as there is no reward from going from level 30-31 as it's the same amount of XP needed to get from level 1-2

答:
Try something like this:

```<code>const levels = [0, 5000, 15000, 30000, 50000, 75000];
....
nextLevel = levels[score.level];
</code>```

Edit

@Dan you mean like this:

```<code>nextLevel = 5000 * Math.round( score.level * (score.level + 1) / 2 );
</code>```

Title: Discord.js Level System

Body:
My 'problem' is more of a feature I am looking to add, I used this guide:
https://anidiots.guide/coding-guides/sqlite-based-points-system
I changed the code a little to mainly give you a random amount of XP, I am looking to edit how much XP is needed to level up.

Right now it is a static amount, being 5000 needed to level up. I am trying to make it increase the amount needed to level up by an extra 5000 each time you level up.

Currently, it works like this:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 10000 total xp needed

Currently, the amount needed to level up is always 5000 between each level.

This is how I want it to work:

Level 1 to 2 = 5000 total XP needed

Level 2 to 3 = 15000 total XP needed

Which will be 5000 to level 2 and then 10000 to level 3 and so on (increasing the amount needed by 5000 each time you level up)

I spent the best part of 2 hours trying different things, and mainly looking at the code being completely out of my depth.
I believed that doing something like this would work, but I have no idea if it's correct

if (score.level == '1') {
    nextLevel = 5000
}
if (score.level == '2' {
    nextLevel = 10000
}

I highly doubt this is correct, otherwise, my message event would be very long, as I plan to have 100 levels

The code in its entirety:

    let score;
    if (message.guild) {
        score = bot.getScore.get(message.author.id, message.guild.id);
        if (!score) {
            score = {
                id: `${message.guild.id}-${message.author.id}`,
                user: message.author.id,
                guild: message.guild.id,
                points: 0,
                level: 1,
            };
        }
        const xpAdd = Math.floor(Math.random() * 10) + 50;
        const curxp = score.points;
        const curlvl = score.level;
        const nxtLvl = score.level * 5000;
        score.points = curxp + xpAdd;
        if (nxtLvl <= score.points) {
            score.level = curlvl + 1;
            const lvlup = new MessageEmbed()
                .setAuthor(
                    `Congrats ${message.author.username}`,
                    message.author.displayAvatarURL()
                )
                .setTitle('You have leveled up!')
                .setThumbnail('https://i.imgur.com/lXeBiMs.png')
                .setColor(color)
                .addField('New Level', curlvl + 1);
            message.channel.send(lvlup).then(msg => {
                msg.delete({
                    timeout: 10000,
                });
            });
        }
        bot.setScore.run(score);
    }

The code as-is works fine and as expected, but as-is is not very good, as there is no reward from going from level 30-31 as it's the same amount of XP needed to get from level 1-2

Body:
Try something like this:

const levels = [0, 5000, 15000, 30000, 50000, 75000];
....
nextLevel = levels[score.level];

Edit

@Dan you mean like this:

nextLevel = 5000 * Math.round( score.level * (score.level + 1) / 2 );


问:
Get the HTML page using htmlunit
I am trying to get the HTML page of a website (ex http://htmlunit.sourceforge.net) but I get an error of IlleagalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver. My code is as follow:

```<code>public class Main1 {
    public static void main(String[] args) {
            try {
                homePage();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    public static void homePage() throws Exception {
            try (final WebClient webClient = new WebClient()) {
                final HtmlPage page = webClient.getPage("http://www.google.com");
                String text = page.asText();
                System.out.println(text);
            }
        }
    }
</code>```

Is there something wrong with the code? Thanks

答:
IlleagalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver

This looks like a wrong version of the HttpClient dependency. Please check your classpath to have only one (and only the correct) version of every dependency.

For the current version you can finde a list of dependencies here http://htmlunit.sourceforge.net/dependencies.html

Title: Get the HTML page using htmlunit

Body:
I am trying to get the HTML page of a website (ex http://htmlunit.sourceforge.net) but I get an error of IlleagalArgumentException: Cannot locate declared field class org.apache.http.impl.client.HttpClientBuilder.dnsResolver. My code is as follow:

public class Main1 {
    public static void main(String[] args) {
            try {
                homePage();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    public static void homePage() throws Exception {
            try (final WebClient webClient = new WebClient()) {
                final HtmlPage page = webClient.getPage("http://www.google.com");
                String text = page.asText();
                System.out.println(text);
            }
        }
    }

Is there something wrong with the code? Thanks


问:
Grouping and ordering using ActiveRecord Query interface
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

```<code>+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+
</code>```

And the station was the one with id 1 then I'd like the query to return...

```<code>[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]
</code>```

To achieve this I've been trying to use group to and order

```<code>ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)
</code>```

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.

答:
In Postgres, if you want the most recent version for each user/station, I would recommend distinct on:

```<code>select distinct on (station_id, user_id) cu.*
from ConnectedUser cu
order by station_id, user_id, created_at desc;
</code>```

Body:
I have a model, ConnectedUser, which belongs to 2 other models User and Station.

It is a simple model with just those relationships and a boolean active.

The results of the query I'm aiming for would be only each most recent ConnectedUser record for each User (where the Station is a specific id).

For example, if my ConnectedUser table looked like this...

+----+---------+------------+--------+------------+
| id | user_id | station_id | active | created_at |
+----+---------+------------+--------+------------+
|  1 |       1 |          1 | true   | 20 June    |
|  2 |       1 |          1 | false  | 19 June    |
|  3 |       1 |          2 | false  | 20 June    |
|  4 |       2 |          1 | false  | 18 June    |
|  5 |       2 |          1 | false  | 21 June    |
+----+---------+------------+--------+------------+

And the station was the one with id 1 then I'd like the query to return...

[
<ConnectedUser id: 1, user_id: 1, station_id: 1, active: true, created_at: "2019-06-20">,
<ConnectedUser id: 5, user_id: 2, station_id: 1, active: false, created_at: "2019-06-21">
]

To achieve this I've been trying to use group to and order

ConnectedUser.where(station: station).select(:user_id).group(:user_id).order(:created_at)

but have kept getting errors like this:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column
  "connected_users.created_at" must appear in the GROUP BY clause or be
  used in an aggregate function)

I am unable to get the specific ConnectedUser id, so feel like I'm missing some important understanding how to work with group and aggregate the results.

Is this possible in one ActiveRecord query?

Many thanks.

Body:
In Postgres, if you want the most recent version for each user/station, I would recommend distinct on:

select distinct on (station_id, user_id) cu.*
from ConnectedUser cu
order by station_id, user_id, created_at desc;


问:
Shorter if statement in Javascript
I'm newbe in Js I wanna check to statuses have same value:

```<code>if (data.a_status == 'approved' && data.b_status == 'approved' && data.c_status == 'approved')
</code>```

Can I write this shorter? I can't find any material how to check same value in three variables

答:
If you know the exact properties you want to access from data, put them into an array and access them via square bracket notation within an every loop against the data Object.

const data = {
  a_status : 'approved',
  b_status : 'approved',
  c_status : 'approved',
  foo: 'bar',
  hello: 'world'
}

const statuses = ['a_status', 'b_status', 'c_status']

const approved = statuses.every(s => data[s] === 'approved')

console.log(approved)```

Title: Shorter if statement in Javascript

Body:
I'm newbe in Js I wanna check to statuses have same value:

if (data.a_status == 'approved' && data.b_status == 'approved' && data.c_status == 'approved')

Can I write this shorter? I can't find any material how to check same value in three variables


问:
How to convert NSTimeInterval to int?
How do I convert NSTimeInterval into an Integer value?

My TimeInterval holds the value 83.01837. I need to convert it into 83. I have googled but couldn't find any help.

答:
Swift 4, Swift 5

I simply cast to Int64:

```<code>Int64(Date().timeIntervalSince1970)
</code>```

Title: How to convert NSTimeInterval to int?

Body:
Swift 4, Swift 5

I simply cast to Int64:

Int64(Date().timeIntervalSince1970)


答:
Use this</p>

```<code>UIImage* photo = [UIImage imageNamed:[NSString stringWithFormat:@"robort %d.jpg",x]];
</code>```

Body:
I have written a code for setting imageview ...as per the button clicked...but my problem is when i press the button it is giving me the error like...too many arguments to function ImageNamed...while executing this line...

UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];

the whole code is....

-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView]; }

Body:
Use this

UIImage* photo = [UIImage imageNamed:[NSString stringWithFormat:@"robort %d.jpg",x]];


问:
php form action php self
I have a php form like this.

```<code><form name="form1" id="mainForm" method="post"enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">

</form
</code>```

In form action I want to use page name with parameters. like house.php?p_id=10111 . But $_SERVER['PHP_SELF'] gives only the house.php (My page full url is house.php?p_id=10111 like this) Please help me to solve this problem. thanks.

答: If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Title: php form action php self

Body:
I have a php form like this.

<form name="form1" id="mainForm" method="post"enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">

</form

In form action I want to use page name with parameters. like house.php?p_id=10111 . But $_SERVER['PHP_SELF'] gives only the house.php (My page full url is house.php?p_id=10111 like this) Please help me to solve this problem. thanks.


问:
Webpack doesn't compile my javascript file due to Regexp
I'm working on a Symfony 4 project using Webpack Encore. Using yarn encore dev, I get this error :

```<code>ERROR  Failed to compile with 2 errors                                 11:45:38

These dependencies were not found:

* core-js/modules/es.regexp.exec in ./assets/js/poteauxskip.js
* core-js/modules/es.string.match in ./assets/js/poteauxskip.js

To install them, you can run: npm install --save core-js/modules/es.regexp.exec core-js/modules/es.string.match
</code>```

And the Regexp expression doesn't work. I tried to install as they say, but it's the beginning of all sorts of problems. But mainly, it doesn't solves the main problem, which is: why doesn't this work? I see no reason to import anything in my javascript file to use Regexp, I found no mention of this in my whole research for a solution.

poteauxskip.js file :

```<code>const $ = require('jquery');

$(".tableau").addClass("d-none");

$(".serie").change(function(){
    updateTableaux();
});

function updateTableaux() {
    var serie1 = $("select#serie1").val() == '?' ? '[0-9A-F]' : $("select#serie1").val();
    var serie2 = $("select#serie2").val() == '?' ? '[0-9A-F]' : $("select#serie2").val();
    var serie3 = $("select#serie3").val() == '?' ? '[0-9A-F]' : $("select#serie3").val();
    var serie4 = $("select#serie4").val() == '?' ? '[0-9A-F]' : $("select#serie4").val();
    var serie5 = $("select#serie5").val() == '?' ? '[0-9A-F]' : $("select#serie5").val();
    var serie6 = $("select#serie6").val() == '?' ? '[0-9A-F]' : $("select#serie6").val();

    var regex = new Regexp("/" + serie1 + serie2 + serie3 + serie4 + serie5 + serie6 + "$/");

    alert("12".match(regex));
}
</code>```

The alert works if I test it for something else. The other variables also work if I use it without any Regexp. Actually, the new Regexp() or the string.match() are enough to get a compilation error.

package.json :

```<code>{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.27.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper": "^1.0.1",
    "popper.js": "^1.15.0",
    "sass-loader": "^7.0.1",
    "webpack-notifier": "^1.6.0"
  },
  "name": "hyperbolic-world",
  "version": "2.0.0",
  "description": "Pour favoriser l'immersion dans un espace hyperbolique.",
  "main": "index.js",
  "author": "Julien Busset",
  "license": "CC-BY-4.0",
  "directories": {
    "test": "tests"
  }
}
</code>```

webpack.config.js :

```<code>var Encore = require('@symfony/webpack-encore');

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
     */
    .addEntry('app', './assets/js/app.js')
    .addEntry('poteauxskip', './assets/js/poteauxskip.js')
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // enables @babel/preset-env polyfills
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })

    // enables Sass/SCSS support
    .enableSassLoader()
    //.addStyleEntry('global', './assets/scss/global.scss')

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes()

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()

    // uncomment if you use API Platform Admin (composer req api-admin)
    //.enableReactPreset()
    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();
</code>```

答: Problem solved by adding core-js with yarn add core-js --dev.

Body:
I'm working on a Symfony 4 project using Webpack Encore. Using yarn encore dev, I get this error :

ERROR  Failed to compile with 2 errors                                 11:45:38

These dependencies were not found:

* core-js/modules/es.regexp.exec in ./assets/js/poteauxskip.js
* core-js/modules/es.string.match in ./assets/js/poteauxskip.js

To install them, you can run: npm install --save core-js/modules/es.regexp.exec core-js/modules/es.string.match

And the Regexp expression doesn't work. I tried to install as they say, but it's the beginning of all sorts of problems. But mainly, it doesn't solves the main problem, which is: why doesn't this work? I see no reason to import anything in my javascript file to use Regexp, I found no mention of this in my whole research for a solution.

poteauxskip.js file :

const $ = require('jquery');

$(".tableau").addClass("d-none");

$(".serie").change(function(){
    updateTableaux();
});

function updateTableaux() {
    var serie1 = $("select#serie1").val() == '?' ? '[0-9A-F]' : $("select#serie1").val();
    var serie2 = $("select#serie2").val() == '?' ? '[0-9A-F]' : $("select#serie2").val();
    var serie3 = $("select#serie3").val() == '?' ? '[0-9A-F]' : $("select#serie3").val();
    var serie4 = $("select#serie4").val() == '?' ? '[0-9A-F]' : $("select#serie4").val();
    var serie5 = $("select#serie5").val() == '?' ? '[0-9A-F]' : $("select#serie5").val();
    var serie6 = $("select#serie6").val() == '?' ? '[0-9A-F]' : $("select#serie6").val();

    var regex = new Regexp("/" + serie1 + serie2 + serie3 + serie4 + serie5 + serie6 + "$/");

    alert("12".match(regex));
}

The alert works if I test it for something else. The other variables also work if I use it without any Regexp. Actually, the new Regexp() or the string.match() are enough to get a compilation error.

package.json :

{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.27.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper": "^1.0.1",
    "popper.js": "^1.15.0",
    "sass-loader": "^7.0.1",
    "webpack-notifier": "^1.6.0"
  },
  "name": "hyperbolic-world",
  "version": "2.0.0",
  "description": "Pour favoriser l'immersion dans un espace hyperbolique.",
  "main": "index.js",
  "author": "Julien Busset",
  "license": "CC-BY-4.0",
  "directories": {
    "test": "tests"
  }
}

webpack.config.js :

var Encore = require('@symfony/webpack-encore');

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
     */
    .addEntry('app', './assets/js/app.js')
    .addEntry('poteauxskip', './assets/js/poteauxskip.js')
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // enables @babel/preset-env polyfills
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })

    // enables Sass/SCSS support
    .enableSassLoader()
    //.addStyleEntry('global', './assets/scss/global.scss')

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes()

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()

    // uncomment if you use API Platform Admin (composer req api-admin)
    //.enableReactPreset()
    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();


问:
How to use to_date function with c# datetime.now()
I need to include time in the database with this sql statement
the code works but the time is missing</p>

```<code>string query = "UPDATE
                  Pri_loc_payment
                SET
                  PAYMENT_STATUS_ID = " + status + $", SERVICE_STATUS = {ServiceStatus}  PAYMENT_DATE  = TO_DATE( '" + DateTime.Now.ToString("yyyy-MM-dd") + "', 'YYYY-MM-DD')
                WHERE
                  ID in (" + concatIds + ")";
</code>```

答:
Although I do agree with the previous comments, if you had to make something work you could try this: </p>

```<code>string query = $"UPDATE Pri_loc_payment SET PAYMENT_STATUS_ID = 1, SERVICE_STATUS = { "SomeServiceStatus"}, PAYMENT_DATE = TO_DATE({DateTime.Now:yyyy-MM-dd}) WHERE ID in ({"concatIds"})";
</code>```

Body:
I need to include time in the database with this sql statement
the code works but the time is missing

string query = "UPDATE
                  Pri_loc_payment
                SET
                  PAYMENT_STATUS_ID = " + status + $", SERVICE_STATUS = {ServiceStatus}  PAYMENT_DATE  = TO_DATE( '" + DateTime.Now.ToString("yyyy-MM-dd") + "', 'YYYY-MM-DD')
                WHERE
                  ID in (" + concatIds + ")";

Body:
Although I do agree with the previous comments, if you had to make something work you could try this:

string query = $"UPDATE Pri_loc_payment SET PAYMENT_STATUS_ID = 1, SERVICE_STATUS = { "SomeServiceStatus"}, PAYMENT_DATE = TO_DATE({DateTime.Now:yyyy-MM-dd}) WHERE ID in ({"concatIds"})";