问:
Angular Observable combinelatest
I'm trying to build a component that access a service and return an observable with a list of objects to populate a table

My service has a  function :

public getTranches(): Observable<Tranche[]> {
    this.loadTranches(); //this calls the rest API to populate the variable _tranches
    return this._tranches.asObservable(); // return variable <BehaviourSubject>_tranches asObservable
  }
```

<p>My Component consists of a table displaying the data through:</p>

<pre class="lang-js prettyprint-override"><code>this.subscription = this.apiService
   .getTranches()
     .subscribe(
      (data) => {
       this.tranches = data;
       }
  );
</code>```

html:

<ng-container *ngFor="let tranche of tranches">
   // stuff
</ng-container>
```

<p>Up util here everything works fine.</p>

<p>I added a input and click events to the table headers</p>

<pre class="lang-html prettyprint-override"><code>//header example for sortby
<div (click)="this.filters.sortby = name"></div>

//input for filter
<input (keyup)="this.filters.search = $event.target.value" type="text">
</code>```

and a variable filters to store that information

can you show me how to transform the filter variable in a observable and merge it to a single subscription to feed the table so I can perform the filtering and sorting on the component?

I've tried using filter as behaviourSubject and use combineLatest to merge them unsuccessfully if that is the way to do it can I see an example?

答:
If I understand correctly, you have a class variable _tranches which is a BehaviorSubject and emits, via the next() method, an array arr of items that get displayed by the table.

If this is true, in order to achieve filtering and sorting, you have to do the following things:

store the array arr somewhere (e.g. as a private class variable)

when sort or filter commands are fired from UI, apply filter and
sort methods to the array arr

take the results of these methods and use them as arguments for the next() method of the BehaviorSubject

Then honestly I do not understand how the click and keyup events are managed in your code, but this does not affect the previous points.

Title: Angular Observable combinelatest

Body:
I'm trying to build a component that access a service and return an observable with a list of objects to populate a table

My service has a  function :

public getTranches(): Observable<Tranche[]> {
    this.loadTranches(); //this calls the rest API to populate the variable _tranches
    return this._tranches.asObservable(); // return variable <BehaviourSubject>_tranches asObservable
  }

My Component consists of a table displaying the data through:

this.subscription = this.apiService
   .getTranches()
     .subscribe(
      (data) => {
       this.tranches = data;
       }
  );

html:

<ng-container *ngFor="let tranche of tranches">
   // stuff
</ng-container>

Up util here everything works fine.

I added a input and click events to the table headers

//header example for sortby

//input for filter
<input (keyup)="this.filters.search = $event.target.value" type="text">

and a variable filters to store that information

can you show me how to transform the filter variable in a observable and merge it to a single subscription to feed the table so I can perform the filtering and sorting on the component?

I've tried using filter as behaviourSubject and use combineLatest to merge them unsuccessfully if that is the way to do it can I see an example?


来源: stackexchange

问:
Combine LaTeX with R markdown and pandoc
I have created a R markdown (RStudio) document and I would like to have that output in pdf combined with some part (i.e. first page) of my LaTeX document. So basically, I would like to do some bits with R Markdown (generating some R output) and write something down in LaTeX and have this two combined into 1 pdf document.

What would be the steps? Thx.

答:
To demonstrate how to insert pdf pages using the pdfpages package, I first create
a pdf file with four pages using the pdf() command.

The .Rnw (Knitr) script is as following

```<code>\documentclass[a4paper]{article}
\usepackage[final]{pdfpages}
\usepackage[pagestyles]{titlesec}
\usepackage{hyperref}
\title{An example on how to add external pdf pages}
\begin{document}
\maketitle
\tableofcontents
\section{First section}
\subsection{First subsection}
This is an empty section with a chunk to create one pdf with four pages

<<mtcarsplot, echo = TRUE, eval = TRUE,  fig.show='hide'>>=
library(knitr)
pdf(file="figure/mtcarsplot.pdf",onefile=TRUE)
ggplot(mpg, aes(drv, model)) +
      geom_point() +
      facet_grid(manufacturer ~ ., scales = "free", space = "free") +
      theme(strip.text.y = element_text(angle = 0))
ggplot(mtcars, aes(wt, mpg))+ geom_point(aes(colour=factor(cyl), size = qsec))
ggplot(mpg, aes(x=factor(cyl), y=hwy, fill=factor(cyl)))+ geom_violin(scale = "width")
mosaicplot(Titanic, color = TRUE)
dev.off()
@

\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}
\includepdf[pages={1-2,{},4},nup=2x2]{figure/mtcarsplot.pdf}

\end{document}
</code>```

To insert pages for the external document use

```<code>\includepdf[<key=val>]{<filename>}
</code>```

The simplest will be \includepdf[pages=-] which will include all the pages from the document.

The code to include pages is

```<code> \includepdf[pages={1-2,{},4}],nup=2x2]{figure/mtcarsplot.pdf}
</code>```

{1-2,{},4} means that I included page 1 to 2, a blank page, then page 4.

The other command is nup=2x2 which has included four pages in two rows and two columns withing the same page.

It is often usefull to include external pdf as sections or subsections of the document created, this is done with :

```<code>\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}
</code>```

The output shows the four pages in one page, with one left blank, and the table of contents with the phantom section.

ContentLicense: CC BY-SA 3.0

Body:
To demonstrate how to insert pdf pages using the pdfpages package, I first create
a pdf file with four pages using the pdf() command.

The .Rnw (Knitr) script is as following

\documentclass[a4paper]{article}
\usepackage[final]{pdfpages}
\usepackage[pagestyles]{titlesec}
\usepackage{hyperref}
\title{An example on how to add external pdf pages}
\begin{document}
\maketitle
\tableofcontents
\section{First section}
\subsection{First subsection}
This is an empty section with a chunk to create one pdf with four pages

<<mtcarsplot, echo = TRUE, eval = TRUE,  fig.show='hide'>>=
library(knitr)
pdf(file="figure/mtcarsplot.pdf",onefile=TRUE)
ggplot(mpg, aes(drv, model)) +
      geom_point() +
      facet_grid(manufacturer ~ ., scales = "free", space = "free") +
      theme(strip.text.y = element_text(angle = 0))
ggplot(mtcars, aes(wt, mpg))+ geom_point(aes(colour=factor(cyl), size = qsec))
ggplot(mpg, aes(x=factor(cyl), y=hwy, fill=factor(cyl)))+ geom_violin(scale = "width")
mosaicplot(Titanic, color = TRUE)
dev.off()
@

\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}
\includepdf[pages={1-2,{},4},nup=2x2]{figure/mtcarsplot.pdf}

\end{document}

To insert pages for the external document use

\includepdf[<key=val>]{<filename>}

The simplest will be \includepdf[pages=-] which will include all the pages from the document.

The code to include pages is

 \includepdf[pages={1-2,{},4}],nup=2x2]{figure/mtcarsplot.pdf}

{1-2,{},4} means that I included page 1 to 2, a blank page, then page 4.

The other command is nup=2x2 which has included four pages in two rows and two columns withing the same page.

It is often usefull to include external pdf as sections or subsections of the document created, this is done with :

\phantomsection
\addcontentsline{toc}{subsection}{Second subsection (phantom)}

The output shows the four pages in one page, with one left blank, and the table of contents with the phantom section.


问:
struct member gets overwritten by garbage value after successful initialization
I've been debugging this function for quite a while now and can't wrap my head around what could be going on with this piece of code.

```<code>    void make_points(DocSpec instance, Tree *myTree, Point *p){
int i, j, k, index = 0;

for(i = 0; i < instance.numPt; i++)
    {
        p[i].x = instance.xCoordinates[i];
        p[i].y = instance.yCoordinates[i];
        p[i].parent = myTree[i].parent;
        p[i].num_children = 0;
        for(k = 0; k < MAX_NUM_CHILDREN; k++)
            {
                p[i].child[k] = 0;
            }
        for(j = 0; j < instance.numPt; j++)
            {
                if((i != j) && (myTree[j].parent == i))
                    {
                        p[i].num_children++;
                        p[i].child[index] = j;
                        index++;
                    }
            }
         p[i].overlap_hv = -1;
         p[i].overlap_vh = -1;
         index = 0;
     }

printf("p[1].index = %d;\n", p[1].index);
printf("p[1].x = %d;\n", p[1].x);
printf("p[1].y = %d;\n", p[1].y);
printf("p[1].parent = %d;\n", p[1].parent);
printf("p[1].num_children = %d;\n", p[1].num_children);

printf("p[1].child[8] = {");
index = 0;
for(i = 0; i < MAX_NUM_CHILDREN; i++)
    {
        if(p[1].child[i] != 0 && index == 0)
            {
                printf("%d", p[1].child[i]);
            }
        elseif(p[1].child[i] != 0)
            printf(", %d", p[1].child[i]);
    }
print("};\n");
printf("p[1].overlap_hv = %d;\n", p[1].overlap_hv);
printf("p[1].overlap_vh = %d;\n", p[1].overlap_vh);
}
</code>```

The output I'm getting after running the function is the following:

```<code>p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {1563515760, 1768448814, 945513580, 540876893};
p[1].overlap_hv = 909455739;
p[1].overlap_vh = 892679225;
</code>```

But it should be:

```<code>p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {};
p[1].overlap_hv = -1;
p[1].overlap_vh = -1;
</code>```

When I ran gdb on my program, I noticed that the values of p[1] are initialized properly, but when

```<code>printf("p[1].x = %d;\n", p[1].x);
</code>```

is executed - p[1].child[4], p[1].child[5], p[1].child[6], p[1].child[7], p[1].overlap_hv, p[1].overlap_vh all get overwritten with the garbage values.

I have no idea why or how a printf statement could change the values of my struct members.

Any help would be greatly appreciated.

答:
Turns out I didn't use the proper typecast when reallocating memory. A quick check with Valgrind led me right to the culprit.

had

```<code>p = (Point*) realloc(p, instance.numPt * sizeof(p));
</code>```

and this fixed it

```<code>p = (Point*) realloc(p, instance.numPt * sizeof(Point));
</code>```

Thanks to all for the suggestions.

Body:
I've been debugging this function for quite a while now and can't wrap my head around what could be going on with this piece of code.

    void make_points(DocSpec instance, Tree *myTree, Point *p){
int i, j, k, index = 0;

for(i = 0; i < instance.numPt; i++)
    {
        p[i].x = instance.xCoordinates[i];
        p[i].y = instance.yCoordinates[i];
        p[i].parent = myTree[i].parent;
        p[i].num_children = 0;
        for(k = 0; k < MAX_NUM_CHILDREN; k++)
            {
                p[i].child[k] = 0;
            }
        for(j = 0; j < instance.numPt; j++)
            {
                if((i != j) && (myTree[j].parent == i))
                    {
                        p[i].num_children++;
                        p[i].child[index] = j;
                        index++;
                    }
            }
         p[i].overlap_hv = -1;
         p[i].overlap_vh = -1;
         index = 0;
     }

printf("p[1].index = %d;\n", p[1].index);
printf("p[1].x = %d;\n", p[1].x);
printf("p[1].y = %d;\n", p[1].y);
printf("p[1].parent = %d;\n", p[1].parent);
printf("p[1].num_children = %d;\n", p[1].num_children);

printf("p[1].child[8] = {");
index = 0;
for(i = 0; i < MAX_NUM_CHILDREN; i++)
    {
        if(p[1].child[i] != 0 && index == 0)
            {
                printf("%d", p[1].child[i]);
            }
        elseif(p[1].child[i] != 0)
            printf(", %d", p[1].child[i]);
    }
print("};\n");
printf("p[1].overlap_hv = %d;\n", p[1].overlap_hv);
printf("p[1].overlap_vh = %d;\n", p[1].overlap_vh);
}

The output I'm getting after running the function is the following:

p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {1563515760, 1768448814, 945513580, 540876893};
p[1].overlap_hv = 909455739;
p[1].overlap_vh = 892679225;

But it should be:

p[1].index = 1;
p[1].x = 0;
p[1].y = 90;
p[1].parent = 5;
p[1].num_children = 0;
p[1].child[8] = {};
p[1].overlap_hv = -1;
p[1].overlap_vh = -1;

When I ran gdb on my program, I noticed that the values of p[1] are initialized properly, but when

printf("p[1].x = %d;\n", p[1].x);

is executed - p[1].child[4], p[1].child[5], p[1].child[6], p[1].child[7], p[1].overlap_hv, p[1].overlap_vh all get overwritten with the garbage values.

I have no idea why or how a printf statement could change the values of my struct members.

Any help would be greatly appreciated.

Body:
Turns out I didn't use the proper typecast when reallocating memory. A quick check with Valgrind led me right to the culprit.

had

p = (Point*) realloc(p, instance.numPt * sizeof(p));

and this fixed it

p = (Point*) realloc(p, instance.numPt * sizeof(Point));

Thanks to all for the suggestions.


问:
Parse a binary file with Regular Expressions?
I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable

```<code>ciphertext = re.match(b'\S', ciphertext)
</code>```

It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong?

edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult

答: Ended up using str.rpartition to solve my problems. Wasn't the most obvious answer, but it worked. </p>

Body:
I've got two bytes-type variable that I've concatenated (separated by a space) so I can send it as one variable to a server (socket programming). What I'm trying to figure out is how to then separate them and assign them to their original variables using regular expressions. I've consulted regular expressions parsing a binary file but it wouldn't work for me. Here is my output after trying the expression as so just to get the cipher variable

ciphertext = re.match(b'\S', ciphertext)

It generally only matches the first couple characters and returns an object, which isn't what I'm wanting. What am I doing wrong?

edit: I'm probably doing it the hard way. Honestly, any recommendation on how to send 2 bytes objects over a socket using UDP. Its proving really difficult


问:
How do I get many @ManyToMany relationships to work?
I have a model with two many-to-many relationships. Play framework creates the relationship tabel for me, but none of the ids are nullable, resulting with me unable to get my code to work.

Play framework returns
    PersistenceException occured : insert into Costumer_Item (customersWhoIgnored_id, ignoredItems_id) values (?, ?)

```<code>19:20:54,530 ERROR ~ Field 'customersWhoBought_id' doesn't have a default value
19:20:54,531 ERROR ~ Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
</code>```

The code is Item.java:

```<code>@Entity
public class Item extends Model {
  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ownedItems")
  public List<Costumer> customersWhoBought;

  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ignoredItems")
  public List<Costumer> customersWhoIgnored;
}
</code>```

Customer.java:

```<code>@Entity
public class Customer extends Model {
  @Column(nullable = true)
  @ManyToMany(cascade = CascadeType.ALL)
  public List<Item> ownedItems;

  @Column(nullable = true)
  @ManyToMany(cascade = CascadeType.ALL)
  public List<Item> ignoredItems;

}
</code>```

How do I get many @ManyToMany relationships to work?

答:
I would strongly recommend not using the ManyToMany, and instead just use one-to-many and many-to-one relationships, with an explicit domain object for the middle.  It's very easy to get confused with ManyToMany (as you are finding), and you very often wind up having to add additional data to the ManyToMany anyways.

Also, FWIW, this is a lot more of a JPA/Hibernate issue than a Play framework issue.

ContentLicense: CC BY-SA 2.5

Body:
I have a model with two many-to-many relationships. Play framework creates the relationship tabel for me, but none of the ids are nullable, resulting with me unable to get my code to work.

Play framework returns
    PersistenceException occured : insert into Costumer_Item (customersWhoIgnored_id, ignoredItems_id) values (?, ?)

19:20:54,530 ERROR ~ Field 'customersWhoBought_id' doesn't have a default value
19:20:54,531 ERROR ~ Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update

The code is Item.java:

@Entity
public class Item extends Model {
  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ownedItems")
  public List<Costumer> customersWhoBought;

  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ignoredItems")
  public List<Costumer> customersWhoIgnored;
}

Customer.java:

@Entity
public class Customer extends Model {
  @Column(nullable = true)
  @ManyToMany(cascade = CascadeType.ALL)
  public List<Item> ownedItems;

  @Column(nullable = true)
  @ManyToMany(cascade = CascadeType.ALL)
  public List<Item> ignoredItems;

}

How do I get many @ManyToMany relationships to work?


问:
phpseclib sftp->put() command: File contents are just a string, not the expected PDF document

I'm trying to upload a PDF document from a stage server to a remote location using $sftp-put();

CODE:

```<code>$sftp = new SFTP($config::SFTP_SERVER);

// login to remote server
if (!$sftp->login($config::SFTP_USER, $config::SFTP_PASSWORD)) {
    throw new Exception('Login failed');
}

// move to relevant directory
$sftp->chdir('fatca');

// upload file
$uploadFile = $sftp->put('test-pdf-upload.pdf', '/srv/www/vhosts/stage.johno.com/fatca/src/uploads/pdfs/345-553453-434__05122017_16:45:26.pdf', NET_SFTP_LOCAL_FILE);

// Error checking for local env only
var_dump($uploadFile);
var_dump($sftp->getSFTPLog());
</code>```

I'm expecting to view the same PDF, that contains user data and some user uploaded images. I've also confirmed that the original PDF has been created successfully on the staging server, it is intact and shows the relevant information.

The resulting file is created in the new remote server location however it is damaged/unreadable.

The output from var_dump($sftp->getSFTPLog()); is not encouraging either:

```<code>bool(false)
</code>```

What am I doing wrong here? Feel like I've followed the phpseclib documentation well... Although its been one of those long, long days in front of the screen!

Any advice greatly appreciated as always.

答:
You're using phpseclib 2.0. I can tell because you're doing new SFTP() instead of new Net_SFTP(). For 2.0 you need to do SFTP::SOURCE_LOCAL_FILE. eg.

```<code>$uploadFile =
    $sftp->put(
      'test-pdf-upload.pdf',
      '/srv/www/vhosts/stage.johno.com/fatca/src/uploads/pdfs/345-553453-434__05122017_16:45:26.pdf',
      SFTP::SOURCE_LOCAL_FILE);
</code>```

Body:
I'm trying to upload a PDF document from a stage server to a remote location using $sftp-put();

CODE:

$sftp = new SFTP($config::SFTP_SERVER);

// login to remote server
if (!$sftp->login($config::SFTP_USER, $config::SFTP_PASSWORD)) {
    throw new Exception('Login failed');
}

// move to relevant directory
$sftp->chdir('fatca');

// upload file
$uploadFile = $sftp->put('test-pdf-upload.pdf', '/srv/www/vhosts/stage.johno.com/fatca/src/uploads/pdfs/345-553453-434__05122017_16:45:26.pdf', NET_SFTP_LOCAL_FILE);

// Error checking for local env only
var_dump($uploadFile);
var_dump($sftp->getSFTPLog());

I'm expecting to view the same PDF, that contains user data and some user uploaded images. I've also confirmed that the original PDF has been created successfully on the staging server, it is intact and shows the relevant information.

The resulting file is created in the new remote server location however it is damaged/unreadable.

The output from var_dump($sftp->getSFTPLog()); is not encouraging either:

bool(false)

What am I doing wrong here? Feel like I've followed the phpseclib documentation well... Although its been one of those long, long days in front of the screen!

Any advice greatly appreciated as always.

Body:
You're using phpseclib 2.0. I can tell because you're doing new SFTP() instead of new Net_SFTP(). For 2.0 you need to do SFTP::SOURCE_LOCAL_FILE. eg.

$uploadFile =
    $sftp->put(
      'test-pdf-upload.pdf',
      '/srv/www/vhosts/stage.johno.com/fatca/src/uploads/pdfs/345-553453-434__05122017_16:45:26.pdf',
      SFTP::SOURCE_LOCAL_FILE);

ContentLicense: CC BY-SA 4.0


问:
Angular natural sort array of objects
I'm fairly new to Angular so maybe I'm just searching for the wrong thing, but I can't seem to find an easy answer to this anywhere.

Let's say I have an array of objects:

```<code>[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...}
]
</code>```

This is array is being displayed as the options in a dropdown:

```<code><option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>
</code>```

I want to sort these objects to make sure they show up in alphanumeric order.

答:
Javascript : natural sort of alphanumerical strings

Found the answer from this thread.

```<code>profiles.sort((as, bs) => {
var a: any, b: any, a1: number, b1: number, i= 0, n: number , L,
    rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if(as.Label=== bs.Label) return 0;
a= as.Label.toLowerCase().match(rx);
b= bs.Label.toLowerCase().match(rx);
L= a.length;
while(i<L){
    if(!b[i]) return 1;
    a1= a[i],
        b1= b[i++];
    if(a1!== b1){
        n= a1-b1;
        if(!isNaN(n)) return n;
        return a1>b1? 1:-1;
    }
}
return b[i]? -1:0;
</code>```

});

Title: Angular natural sort array of objects

Body:
I'm fairly new to Angular so maybe I'm just searching for the wrong thing, but I can't seem to find an easy answer to this anywhere.

Let's say I have an array of objects:

[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...}
]

This is array is being displayed as the options in a dropdown:

<option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>

I want to sort these objects to make sure they show up in alphanumeric order.

Body:
Javascript : natural sort of alphanumerical strings

Found the answer from this thread.

profiles.sort((as, bs) => {
var a: any, b: any, a1: number, b1: number, i= 0, n: number , L,
    rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if(as.Label=== bs.Label) return 0;
a= as.Label.toLowerCase().match(rx);
b= bs.Label.toLowerCase().match(rx);
L= a.length;
while(i<L){
    if(!b[i]) return 1;
    a1= a[i],
        b1= b[i++];
    if(a1!== b1){
        n= a1-b1;
        if(!isNaN(n)) return n;
        return a1>b1? 1:-1;
    }
}
return b[i]? -1:0;

});


问:
Can we change size of an array in java
Can we change size of an array in  java . i am confused. every one know about array : we can't change the size of an array.

but after writing this code i am confused.

```<code>class Test {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9,10,11};
        int[] array1 = {1,1};

        System.out.println("befor : " + array1.length);   //I get 2
        array1 = array;
        System.out.println("intialize : "+array1.length); //I get 11

        for(int a : array1) {
            System.out.println(a);
        }

        System.out.println("after : " + array1.length);
    }
}
</code>```

if we can't change the size of an array then we are supposed to get Runtime: ArrayIndexOutOfBoundsException error at

```<code>array1 = array;
</code>```

but i got output as:

```<code>befor : 26
intialize : 11
1
2
3
4
5
6
7
8
9
10
11
after : 11
</code>```

答:
Array1:

Index->Value

0->A

1->B

2->C

3->D

4->E

Array 1 size = 5

Array2:

Index->Value

0->X

1->y

Array 2 size = 2

You need to be clear about the idea behind when we talk about immutability in arrays.

Array1 = Array2?

‘=’ is assignment operator. This means when you write the above line, you are deciding to replace entirely array1. There won’t be any reference of what Array1 had before after this line.

“if we can't change the size of an array then we are supposed to get Runtime: ArrayIndexOutOfBoundsException error at”: You would not get this since you have assigned new values to Array1.

Array1 now does not even remember that it consisted of 5 values during its birth.

Title: Can we change size of an array in java

Body:
Can we change size of an array in  java . i am confused. every one know about array : we can't change the size of an array.

but after writing this code i am confused.

class Test {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9,10,11};
        int[] array1 = {1,1};

        System.out.println("befor : " + array1.length);   //I get 2
        array1 = array;
        System.out.println("intialize : "+array1.length); //I get 11

        for(int a : array1) {
            System.out.println(a);
        }

        System.out.println("after : " + array1.length);
    }
}

if we can't change the size of an array then we are supposed to get Runtime: ArrayIndexOutOfBoundsException error at

array1 = array;

but i got output as:

befor : 26
intialize : 11
1
2
3
4
5
6
7
8
9
10
11
after : 11


问:
Regex matching extra characters
using: this tool to evaluate my expression

My test string: "Little" Timmy (tim) McGraw

my regex:
    ^[()"]|.["()]

It looks like I'm properly catching the characters I want but my matches are including whatever character comes just before the match.  I'm not sure what, or if anything, I'm doing wrong to be catching the preceding characters like that?  The goal is to capture characters we don't want in the name field of one of our systems.

答:
Brief

Your current regex ^[()"]|.["()] says the following:

^[()"]|.["()] Match either of the following

^[()"] Match the following

^ Assert position at the start of the line

[()"] Match any character present in the list ()"

.["()] Match the following

. Match any character (this is the issue you were having)

["()] Match any character present in the list "()

Code

You can actually shorten your regex to just [()"].

Ultimately, however, it would be much easier to create a negated set that determines which characters are valid rather than those that are invalid. This approach would get you something like [^\w ]. This means match anything not present in the set. So match any non-word and non-space characters (in your sample string this will match the symbols ()" since they are not in the set).

Title: Regex matching extra characters


问:
Set up identifying a user for Appcues in a ReactJS project
I am trying to set up Appcues in a ReactJS project and the documentation states to add the following to identify the current user:

```<code>  Appcues.identify({UNIQUE_USER_ID}, { // Unique identifier for current user
    name: "John Doe",   // Current user's name
    email: "john.doe@example.com", // Current user's email
    created_at: 1234567890,    // Unix timestamp of user signup date
  });
</code>```

However, this throws the error that:

'Appcues' is not defined

This error makes sense to me since the object, Appcues, is referenced but not imported or created.

Attempt to fix:

Since Appcues is imported from a script, I tried accessing Appcues through the window, but it results in my demo not being loaded when I go to my project in the browser:

```<code>  window.Appcues.identify({UNIQUE_USER_ID}, { // Unique identifier for current user
    name: "John Doe",   // Current user's name
    email: "john.doe@example.com", // Current user's email
    created_at: 1234567890,    // Unix timestamp of user signup date
  });
</code>```

Does anyone understand how to set up identifying a user for Appcues in a ReactJS project?

答:
Your mileage may vary, however we use the npm package load-script to bootstrap Appcues into our application dynamically, rather than using the script tag in the html that comes down from the server.

This way we only touch the Appcues once we can confirm the script has loaded.

Body:
I am trying to set up Appcues in a ReactJS project and the documentation states to add the following to identify the current user:

  Appcues.identify({UNIQUE_USER_ID}, { // Unique identifier for current user
    name: "John Doe",   // Current user's name
    email: "john.doe@example.com", // Current user's email
    created_at: 1234567890,    // Unix timestamp of user signup date
  });

However, this throws the error that:

'Appcues' is not defined

This error makes sense to me since the object, Appcues, is referenced but not imported or created.

Attempt to fix:

Since Appcues is imported from a script, I tried accessing Appcues through the window, but it results in my demo not being loaded when I go to my project in the browser:

  window.Appcues.identify({UNIQUE_USER_ID}, { // Unique identifier for current user
    name: "John Doe",   // Current user's name
    email: "john.doe@example.com", // Current user's email
    created_at: 1234567890,    // Unix timestamp of user signup date
  });

Does anyone understand how to set up identifying a user for Appcues in a ReactJS project?


问:
Check data attribute and change class
How do I check if data attribute has special value and then change the class?

example:

Html

```<code>  <li class="country active" data-country-code="ca"><div class="flag ca"></div><span class="country-name">Canada</span></li>
  <li class="country" data-country-code="us"><div class="flag us"></div><span class="country-name">United States</span></li>
   <li .........// many countries not active ></li>
</code>```

my jQuery:

```<code>  var country = 'us' ;
  $('li.country').data('country-code', country).attr('class', 'country active') ;
</code>```

what I want from my jQuery is to replace Canada which has country active  and change to to USA to be active because I have defined country as us, and not effect other countries.
I tried to check which country-code is us and make the class country active to it.

I want it will be like this because I have country = 'us'

```<code> <li class="country" data-country-code="ca"><div class="flag ca"></div><span class="country-name">Canada</span></li>
  <li class="country active" data-country-code="us"><div class="flag us"></div><span class="country-name">United States</span></li>
   <li .........// many countries not active ></li>
</code>```

答:
what i want from my jquery is to replace canada wich has country
  active and change to to usa to be active because i have defined
  country as us . and not effect other countries.

Try

```<code>var country = "us";
$('li.country').removeClass( "active" ).filter( "[data-country-code='" + country + "']" ).addClass( "active" );
</code>```

Title: Check data attribute and change class

Body:
How do I check if data attribute has special value and then change the class?

example:

Html

Canada

United States

my jQuery:

  var country = 'us' ;
  $('li.country').data('country-code', country).attr('class', 'country active') ;

what I want from my jQuery is to replace Canada which has country active  and change to to USA to be active because I have defined country as us, and not effect other countries.
I tried to check which country-code is us and make the class country active to it.

I want it will be like this because I have country = 'us'

Canada

United States

Body:
what i want from my jquery is to replace canada wich has country
  active and change to to usa to be active because i have defined
  country as us . and not effect other countries.

Try

var country = "us";
$('li.country').removeClass( "active" ).filter( "[data-country-code='" + country + "']" ).addClass( "active" );


问:
AWS: Copy all files matching a path to an S3 bucket?
I want to copy all CSV files in the current directory to my S3 bucket. I'm trying:

```<code>aws s3 cp s3://mybucket --include '*.CSV'
</code>```

But I get:

```<code>usage: aws [options] <command> <subcommand> [parameters]
aws: error: too few arguments
</code>```

I'm reading the docs but there's no example I can see of uploading a list of files.

If I try:

```<code>aws s3 cp *.CSV s3://openprescribing
</code>```

I get:

```<code>Unknown options: file1.CSV,file2.CSV
</code>```

Any ideas? The docs also talk about sync and include examples of lists of files, but it's not clear to me whether that means copying or syncing files. Same with mv which I suspect may mean deleting the files locally.

答:
You need to add double quotes around your source pattern:
aws s3 cp "*.CSV" s3://openprescribing

Then it should work. It happened to me before.

Body:
I want to copy all CSV files in the current directory to my S3 bucket. I'm trying:

aws s3 cp s3://mybucket --include '*.CSV'

But I get:

usage: aws [options] <command> <subcommand> [parameters]
aws: error: too few arguments

I'm reading the docs but there's no example I can see of uploading a list of files.

If I try:

aws s3 cp *.CSV s3://openprescribing

I get:

Unknown options: file1.CSV,file2.CSV

Any ideas? The docs also talk about sync and include examples of lists of files, but it's not clear to me whether that means copying or syncing files. Same with mv which I suspect may mean deleting the files locally.


问:
Make Realm Loop Generic and Reusable in Swift
Swift 4, Xcode 9.2

Here are a few Realm classes I have:

```<code>class Dog: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Cat: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Horse: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}
</code>```

Let's say I have some code like this where I compare two realms and create an object with a specific Dog class:

```<code>let remoteDogs = remoteRealm.objects(Dog.self)

for remoteDog in remoteDogs{
  if let localDog = realm.objects(Dog.self).filter("id = %@",remoteDog.id).first{
    // Update
    if localDog.updated < remoteDog.updated{
      //Remote is newer; replace local with it
      realm.create(Dog.self, value: remoteDog, update:true)
    }
  }
}
</code>```

This works great, but I need to do this same stuff on a whole bunch of Realm classes that I have. So I'm trying to make it more generic like this:

```<code>let animals = [Dog.self, Cat.self, Horse.self]

for animal in animals{
  let remoteAnimals = remoteRealm.objects(animal)

  for remoteAnimal in remoteAnimals{
    if let localAnimal = realm.objects(animal).filter("id = %@",remoteAnimal.id).first{
      // Update
      if localAnimal.updated < remoteAnimal.updated{
        //Remote is newer; replace local with it
        realm.create(animal, value: remoteAnimal, update:true)
      }
    }
  }
}
</code>```

This sort of works, but anytime I want to reference the property of an object (like with remoteAnimal.id and remoteAnimal.updated) then the compiler complains because it doesn't know what kind of object a remoteAnimal is.

Has anyone done something like this before? Any ideas how I can do this so that I don't have to write this same code over and over for each of my Realm classes? Thanks!

答:
Realm Object does not have id or updated.  You can have your Dog,
Cat and Horse classes inherit from an Animal class that is a subclass of Object and that does have id or updated. Since these properties are defined on Animal they will be usable in all of the subclasses (Dog, Cat, Horse).

```<code>class Animal: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Dog: Animal {
  //Other properties...
}
</code>```

EDIT you can also abuse Objective C's NSObject setValue:forKey: to set the property by name.  This is very sloppy typing and not good object oriented design but it does work.  Here is a playground:

```<code>import UIKit

class A: NSObject {
  @objc var customProperty = 0
}
let a = A()
a.setValue(5, forKey: "customProperty")
print(a.customProperty)
</code>```

Body:
Swift 4, Xcode 9.2

Here are a few Realm classes I have:

class Dog: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Cat: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Horse: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

Let's say I have some code like this where I compare two realms and create an object with a specific Dog class:

let remoteDogs = remoteRealm.objects(Dog.self)

for remoteDog in remoteDogs{
  if let localDog = realm.objects(Dog.self).filter("id = %@",remoteDog.id).first{
    // Update
    if localDog.updated < remoteDog.updated{
      //Remote is newer; replace local with it
      realm.create(Dog.self, value: remoteDog, update:true)
    }
  }
}

This works great, but I need to do this same stuff on a whole bunch of Realm classes that I have. So I'm trying to make it more generic like this:

let animals = [Dog.self, Cat.self, Horse.self]

for animal in animals{
  let remoteAnimals = remoteRealm.objects(animal)

  for remoteAnimal in remoteAnimals{
    if let localAnimal = realm.objects(animal).filter("id = %@",remoteAnimal.id).first{
      // Update
      if localAnimal.updated < remoteAnimal.updated{
        //Remote is newer; replace local with it
        realm.create(animal, value: remoteAnimal, update:true)
      }
    }
  }
}

This sort of works, but anytime I want to reference the property of an object (like with remoteAnimal.id and remoteAnimal.updated) then the compiler complains because it doesn't know what kind of object a remoteAnimal is.

Has anyone done something like this before? Any ideas how I can do this so that I don't have to write this same code over and over for each of my Realm classes? Thanks!

Body:
Realm Object does not have id or updated.  You can have your Dog,
Cat and Horse classes inherit from an Animal class that is a subclass of Object and that does have id or updated. Since these properties are defined on Animal they will be usable in all of the subclasses (Dog, Cat, Horse).

class Animal: Object {
  @objc dynamic var id = UUID().uuidString
  @objc dynamic var updated = Date()
  //Other properties...
}

class Dog: Animal {
  //Other properties...
}

EDIT you can also abuse Objective C's NSObject setValue:forKey: to set the property by name.  This is very sloppy typing and not good object oriented design but it does work.  Here is a playground:

import UIKit

class A: NSObject {
  @objc var customProperty = 0
}
let a = A()
a.setValue(5, forKey: "customProperty")
print(a.customProperty)


问:
How to change past commit to include a missed file?
I have committed a change and forgot to add a file to the change set. After other commits, I realized the file is now missing from a HEAD^4 commit.

How do I rewrite a previous commit to include the missing file?

答:
Although the accepted answer is correct, it lacks detailed instructions on how to perform editing a commit during a rebase process.

First, start a rebase process:

```<code>git rebase --interactive HEAD~4
</code>```

A list of commits will be presented, choose a commit you want to edit by changing the word pick to edit and save the file.

Make necessary modifications in your code (remember to invoke git add for new files)

After all modification are done, issue git commit --amend - this will amend a commit marked as edit

Invoke git rebase --continue that will finish the process (if there are more commits marked as edit, the above steps need to be repeated)

Important notes:

DO NOT remove lines marked as pick that you don't want to edit - leave them as is. Deleting these lines will result in deleting related commits

GIT forces you to stash before rebasing if your working directory is not clean; you can however git stash pop / git stash apply during rebase, in order to amend these changes (i.e. changes stashed before starting the rebase process) to a commit marked as edit

if something went wrong and you want to revert changes made during the rebase process before it finished (i.e. you want to revert to the point before starting the rebase), use git rebase --abort - also read: How to abort an interactive rebase if --abort doesn't work?

As said in the accepted answer:

Remember that you should not modify commits pushed to the remote repository this way. It's better to add a new commit with missing file in that case.

The answer why, is in the Git Book (paragraph entitled "The Perils of Rebasing"):

Do not rebase commits that exist outside your repository.

If you follow that guideline, you’ll be fine. If you don’t, people will hate you, and you’ll be scorned by friends and family.

When you rebase stuff, you’re abandoning existing commits and creating new ones that are similar but different. If you push commits somewhere and others pull them down and base work on them, and then you rewrite those commits with git rebase and push them up again, your collaborators will have to re-merge their work and things will get messy when you try to pull their work back into yours.

[...]

Body:
Although the accepted answer is correct, it lacks detailed instructions on how to perform editing a commit during a rebase process.

First, start a rebase process:

git rebase --interactive HEAD~4

A list of commits will be presented, choose a commit you want to edit by changing the word pick to edit and save the file.

Make necessary modifications in your code (remember to invoke git add for new files)

After all modification are done, issue git commit --amend - this will amend a commit marked as edit

Invoke git rebase --continue that will finish the process (if there are more commits marked as edit, the above steps need to be repeated)

Important notes:

DO NOT remove lines marked as pick that you don't want to edit - leave them as is. Deleting these lines will result in deleting related commits

GIT forces you to stash before rebasing if your working directory is not clean; you can however git stash pop / git stash apply during rebase, in order to amend these changes (i.e. changes stashed before starting the rebase process) to a commit marked as edit

if something went wrong and you want to revert changes made during the rebase process before it finished (i.e. you want to revert to the point before starting the rebase), use git rebase --abort - also read: How to abort an interactive rebase if --abort doesn't work?

As said in the accepted answer:

Remember that you should not modify commits pushed to the remote repository this way. It's better to add a new commit with missing file in that case.

The answer why, is in the Git Book (paragraph entitled "The Perils of Rebasing"):

Do not rebase commits that exist outside your repository.

If you follow that guideline, you’ll be fine. If you don’t, people will hate you, and you’ll be scorned by friends and family.

When you rebase stuff, you’re abandoning existing commits and creating new ones that are similar but different. If you push commits somewhere and others pull them down and base work on them, and then you rewrite those commits with git rebase and push them up again, your collaborators will have to re-merge their work and things will get messy when you try to pull their work back into yours.

[...]


问:
Spring Boot not able to read data at server startup with Postgres DB connection
I am having a very simple REST application based on Spring Boot that displays all the employees in the employee table when you hit the http://localhost:8080/api/employees endpoint.

The application gets the data from Postgres DB and displays it. Works fine with H2 but as soon as switched to Postgres DB I am getting this error at server startup.

Error (at server startup)

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at com.example.demo.EmployeeServiceApplication.main(EmployeeServiceApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [id] in table [employee]; found [int4 (Types#INTEGER)], but expecting [numeric(19,0) (Types#BIGINT)]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateColumnType(SchemaValidatorImpl.java:105) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:92) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        ... 23 common frames omitted

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.283 s
[INFO] Finished at: 2017-12-05T14:34:54-05:00
[INFO] Final Memory: 24M/437M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project employee-service-w-postgres: Could not exec java: Application finished with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
</code>```

pom.xml

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

application.properties

```<code>spring.datasource.url=jdbc:postgresql://192.168.99.100:5432/emp-db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate
</code>```

schema.sql

```<code>drop table if exists employee;
create table employee (
    id integer primary key not null,
    name varchar(20) not null
);
</code>```

data.sql

```<code>insert into employee(id, name) values(1, 'Jack');
insert into employee(id, name) values(2, 'Jill');
</code>```

domain/Employee.java

```<code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    public Employee(String name) {
        this.name = name;
    }

}
</code>```

controller/EmployeeRestController.java

```<code>@RestController
@RequestMapping("/api")
public class EmployeeRestController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

}
</code>```

答:
@Akli already gives the way to go on comments.

Seems to me that you defined employee.id as Long and are trying to map to a column with integer type. That’s the complain.

Just update your column to bigint or your id field to Integer.

Body:
I am having a very simple REST application based on Spring Boot that displays all the employees in the employee table when you hit the http://localhost:8080/api/employees endpoint.

The application gets the data from Postgres DB and displays it. Works fine with H2 but as soon as switched to Postgres DB I am getting this error at server startup.

Error (at server startup)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
        at com.example.demo.EmployeeServiceApplication.main(EmployeeServiceApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
        ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [id] in table [employee]; found [int4 (Types#INTEGER)], but expecting [numeric(19,0) (Types#BIGINT)]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateColumnType(SchemaValidatorImpl.java:105) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:92) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:50) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:91) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:475) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
        ... 23 common frames omitted

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.283 s
[INFO] Finished at: 2017-12-05T14:34:54-05:00
[INFO] Final Memory: 24M/437M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.9.RELEASE:run (default-cli) on project employee-service-w-postgres: Could not exec java: Application finished with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

application.properties

spring.datasource.url=jdbc:postgresql://192.168.99.100:5432/emp-db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate

schema.sql

drop table if exists employee;
create table employee (
    id integer primary key not null,
    name varchar(20) not null
);

data.sql

insert into employee(id, name) values(1, 'Jack');
insert into employee(id, name) values(2, 'Jill');

domain/Employee.java

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    public Employee(String name) {
        this.name = name;
    }

}

controller/EmployeeRestController.java

@RestController
@RequestMapping("/api")
public class EmployeeRestController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeService.getAllEmployees();
    }

}


问:
How would I make my buttons scrollable?
I have 3 buttons that I would like to make possible for it to scroll.

I've tried adding <ScrollView's to encapsulate each <LinearLayout that contains <Button's but that didn't work and just gave me more problems.

How can I use <ScrollView the correct way so that my buttons scroll?

Here's activity-maps.xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="something1"
        android:id="@+id/button2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="480dp"
            android:text="something2"
            android:id="@+id/button3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="440dp"
            android:text="something3"
            android:id="@+id/button4"/>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
A scrollview will just ensure that all buttons can be seen by scrolling if the buttons take up more space than the screen, which they do not; see:
https://developer.android.com/reference/android/widget/ScrollView.html

Perhaps you mean a bottom sheet, as seen in a similar way to what you have in google maps? A description of how to use and implement can be found at:

https://medium.com/android-bits/android-bottom-sheet-30284293f066

Title: How would I make my buttons scrollable?

Body:
I have 3 buttons that I would like to make possible for it to scroll.

I've tried adding <ScrollView's to encapsulate each <LinearLayout that contains <Button's but that didn't work and just gave me more problems.

How can I use <ScrollView the correct way so that my buttons scroll?

Here's activity-maps.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="something1"
        android:id="@+id/button2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="480dp"
            android:text="something2"
            android:id="@+id/button3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="440dp"
            android:text="something3"
            android:id="@+id/button4"/>
    </LinearLayout>

</RelativeLayout>


问:
asp.net dispose inside a class
Before return dt i want destroy sda

How destroy an Object with Dispose - inside the class dbConnect ?

```<code>  public class dbConnect
    {

    // othee code

    public DataTable SetQuery(string constr, DataTable dt, string sSql)
        {
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                //sda = null
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                    {
                        try
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            sda.Fill(dt);
                        }

                        finally
                        {
                            if (sda != null)
                                sda.Dispose();
                            //why the sda is not = null ?
                        }

                        return dt;
                    }
            }
        }
</code>```

What is the correct procedure for destroy object (not class) ?

答:
Using Dispose() doesn't mean your variable will become null, it's
you who chooses wheither your variable should stop referencing
something (so it's you who must set it to null).

You don't need to call Dispose() when you use using on a variable,
it will be called automatically at the end (see: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement).

Title: asp.net dispose inside a class

Body:
Before return dt i want destroy sda

How destroy an Object with Dispose - inside the class dbConnect ?

  public class dbConnect
    {

    // othee code

    public DataTable SetQuery(string constr, DataTable dt, string sSql)
        {
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                //sda = null
                using (MySqlDataAdapter sda = new MySqlDataAdapter())
                    {
                        try
                        {
                            cmd.Connection = con;
                            sda.SelectCommand = cmd;
                            sda.Fill(dt);
                        }

                        finally
                        {
                            if (sda != null)
                                sda.Dispose();
                            //why the sda is not = null ?
                        }

                        return dt;
                    }
            }
        }

What is the correct procedure for destroy object (not class) ?


问:
Cross platform 2D graphics/game library
I'm looking for suggestions for a 2d game engine or library. I'm not picky about the language used but more about the capabilities of the library and the platforms it works on.

I would like to write one code base that would work on iOS, OSX, Android, Win and *nix. I understand there would be some platform specific code but I would like the bulk to be useable on all platforms.

I have looked around and I have some ideas but I'm looking for other opinions. Anyone have any ideas?

答: Here's a link to a list of game engines that might suit your needs.</p>

Title: Cross platform 2D graphics/game library


问:
How to accept self-signed certificates with LWP::UserAgent
I am attempting to set up a node.js server that uses HTTPS. I will then write a scripts in Perl to make a HTTPS request to the server and measure latency of the round trip.

Here is my node.js:

```<code>var express = require('express');
var https = require('https');
var fs = require('fs');

var key = fs.readFileSync('encrypt/rootCA.key');
var cert = fs.readFileSync('encrypt/rootCA.pem');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: key,
  cert: cert
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("hello world - https\n");
}).listen(8088);
</code>```

Key/cert generation was done as follows:

```<code>openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
</code>```

This is my Perl script:

```<code>#!/usr/bin/perl
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => 'https://127.0.0.1:8080');
my $res = $ua->request($req);

if ($res->is_success) {
  print $res->as_string;
} else {
  print "Failed: ", $res->status_line, "\n";
}
</code>```

Returning the error:

```<code>Failed: 500 Can't verify SSL peers without knowing which Certificate Authorities to trust
</code>```

The node.js documentation describes how to set up an HTTPS server but it is vague about generating primary cert and intermediate cert.

https://medium.com/netscape/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e

答:
To make LWP::UserAgent ignore server certificate use the following configuration:</p>

```<code>my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
    SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
    verify_hostname => 0
);
</code>```

Body:
I am attempting to set up a node.js server that uses HTTPS. I will then write a scripts in Perl to make a HTTPS request to the server and measure latency of the round trip.

Here is my node.js:

var express = require('express');
var https = require('https');
var fs = require('fs');

var key = fs.readFileSync('encrypt/rootCA.key');
var cert = fs.readFileSync('encrypt/rootCA.pem');

// This line is from the Node.js HTTPS documentation.
var options = {
  key: key,
  cert: cert
};

https.createServer(options, function (req, res) {
    res.writeHead(200);
    res.end("hello world - https\n");
}).listen(8088);

Key/cert generation was done as follows:

openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

This is my Perl script:

#!/usr/bin/perl
use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => 'https://127.0.0.1:8080');
my $res = $ua->request($req);

if ($res->is_success) {
  print $res->as_string;
} else {
  print "Failed: ", $res->status_line, "\n";
}

Returning the error:

Failed: 500 Can't verify SSL peers without knowing which Certificate Authorities to trust

The node.js documentation describes how to set up an HTTPS server but it is vague about generating primary cert and intermediate cert.

https://medium.com/netscape/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e

Body:
To make LWP::UserAgent ignore server certificate use the following configuration:

my $ua = LWP::UserAgent->new;
$ua->ssl_opts(
    SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
    verify_hostname => 0
);


问:
wait.until(ExpectedConditions.visibilityOf(userName)) is not working
In the below code on 33rd line getting below error message near wait.until

Multiple markers at this line
    - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
    - The method until(Function) in the type FluentWait is not applicable for the
     arguments (ExpectedCondition)

```<code>   package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

 package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
</code>```

答:
The error which you are seeing is as follows :

```<code>Multiple markers at this line - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files - The method until(Function) in the type FluentWait is not applicable for the arguments (ExpectedCondition)
</code>```

Let us analyze what is happening in our code.

In the Page Object you have defined an WebElement as :

```<code>@FindBy(xpath = "//input[@ng-model='login.username']")
private WebElement userName;
</code>```

Moving ahead you have tried to use the WebElement within the method :

```<code>public void logIn(String uName, String Pswd) throws InterruptedException {
    WebDriverWait wait=new WebDriverWait(driver,7);
    wait.until(ExpectedConditions.visibilityOf(userName));
    //
}
</code>```

So basically here we were trying to wait for the visibility of an Indirectly Referenced Angular WebElement userName which is dependent on the attribute ng-model. In such circumstances we can never be sure that when the WebElement will be referenced within a method userName will mandatory reference to a not NULL value. It may be NULL as well.

Now let us have a look at the Method Defination of visibilityOf, it is defined as :

```<code>visibilityOf(WebElement element)
An expectation for checking that an element, known to be present on the DOM of a page, is visible.
</code>```

So clearly, visibilityOf method expects a Direct Reference of the WebElement. Hence in absence of a definite value (not NULL) of userName, WebDriverWait which is a variant of FluentWait shows the error.

Body:
In the below code on 33rd line getting below error message near wait.until

Multiple markers at this line
    - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
    - The method until(Function) in the type FluentWait is not applicable for the
     arguments (ExpectedCondition)

   package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

 package MPA;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginhelperClass {

    WebDriver driver;

    @FindBy(xpath = "//input[@ng-model='login.username']")
    private WebElement userName;

    @FindBy(xpath = "//input[@type='password']")
    private WebElement Password;

    @FindBy(xpath = "//input[@type='submit' and @value='Sign In']")
    private WebElement SignIn;

    @FindBy(xpath = "//span[@class='icon-avatar-round']")
    private WebElement Avatar;

    public LoginhelperClass(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void logIn(String uName, String Pswd) throws InterruptedException {
        WebDriverWait wait=new WebDriverWait(driver,7);
        wait.until(ExpectedConditions.visibilityOf(userName));
        userName.sendKeys(uName);
        Password.sendKeys(Pswd);
        SignIn.click();
        try {
            Thread.sleep(4000);
            if (Avatar.isDisplayed()) {
                System.out.println("Login Successfull: " + uName);
            } else {
                System.out.println("Login failure check the credentials: " + uName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}

Body:
The error which you are seeing is as follows :

Multiple markers at this line - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files - The method until(Function) in the type FluentWait is not applicable for the arguments (ExpectedCondition)

Let us analyze what is happening in our code.

In the Page Object you have defined an WebElement as :

@FindBy(xpath = "//input[@ng-model='login.username']")
private WebElement userName;

Moving ahead you have tried to use the WebElement within the method :

public void logIn(String uName, String Pswd) throws InterruptedException {
    WebDriverWait wait=new WebDriverWait(driver,7);
    wait.until(ExpectedConditions.visibilityOf(userName));
    //
}

So basically here we were trying to wait for the visibility of an Indirectly Referenced Angular WebElement userName which is dependent on the attribute ng-model. In such circumstances we can never be sure that when the WebElement will be referenced within a method userName will mandatory reference to a not NULL value. It may be NULL as well.

Now let us have a look at the Method Defination of visibilityOf, it is defined as :

visibilityOf(WebElement element)
An expectation for checking that an element, known to be present on the DOM of a page, is visible.

So clearly, visibilityOf method expects a Direct Reference of the WebElement. Hence in absence of a definite value (not NULL) of userName, WebDriverWait which is a variant of FluentWait shows the error.


问:
Symfony form setting default checkbox value in many-to-many entity collection
I am having an issue setting default values for checkboxes displayed for a many t many relationship.

I have a User entity and Options entity with a many-to-many relationship, mapped b a user_option table.

In a user form, I display the list of options in a checkbox.

The options entity contains a default field that indicated if the checkbox is set or unset for a new user. If the user has selected, then the user selection must be displayed.

```<code>class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="name", type="string", length=64, nullable=true)
     */
    protected $name;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Bundle\Entity\Option", inversedBy="users")
     * @ORM\JoinTable(name="user_options")
     */
    protected $userOptions;
}

class CommunicationOption {

   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50)
     */
    protected $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="default_state", type="boolean")
     */

}
</code>```

The form load the options

```<code>public function buildForm(FormBuilderInterface $builderInterface, array $options)
{
    $builderInterface
        ->add('userOptions', 'entity', array(
            'class' => 'Bundle\Entity\Option',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            'query_builder' => function (EntityRepository $repository) {
                return $repository->getFindAllQueryBuilder();
            },
            'by_reference' => true,
        ))
    ;
}
</code>```

This displays all options. However, all checkboxes are unchecked.
If a user saves data in the user_options table, then the checkbox is correctly displayed.

```<code>    {% for element in form.userOptions %}
       {{ form_widget(element, {'attr': {'class': 'col-xs-1' }}) }}
       {{ element.vars.label|raw }}
    {% endfor %}
</code>```

I require that for new entries, the default field is considered.
Setting the value in the constructor did not change the checkbox value, and in any case will set the default for all fields to true, which is not what I want.

I am using Symfony 2.6

答:
I work with symfony3. That's how it works

```<code>->add('aptitudes', EntityType::class, array( //change this line
      'class' => 'BackendBundle:Aptitudes', //change this line
      'expanded' => true,
      'multiple' => true,
      'required' => false,
      'query_builder' => null,
      'by_reference' => true,
))
</code>```

Body:
I am having an issue setting default values for checkboxes displayed for a many t many relationship.

I have a User entity and Options entity with a many-to-many relationship, mapped b a user_option table.

In a user form, I display the list of options in a checkbox.

The options entity contains a default field that indicated if the checkbox is set or unset for a new user. If the user has selected, then the user selection must be displayed.

class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="name", type="string", length=64, nullable=true)
     */
    protected $name;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Bundle\Entity\Option", inversedBy="users")
     * @ORM\JoinTable(name="user_options")
     */
    protected $userOptions;
}

class CommunicationOption {

   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50)
     */
    protected $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="default_state", type="boolean")
     */

}

The form load the options

public function buildForm(FormBuilderInterface $builderInterface, array $options)
{
    $builderInterface
        ->add('userOptions', 'entity', array(
            'class' => 'Bundle\Entity\Option',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            'query_builder' => function (EntityRepository $repository) {
                return $repository->getFindAllQueryBuilder();
            },
            'by_reference' => true,
        ))
    ;
}

This displays all options. However, all checkboxes are unchecked.
If a user saves data in the user_options table, then the checkbox is correctly displayed.

    {% for element in form.userOptions %}
       {{ form_widget(element, {'attr': {'class': 'col-xs-1' }}) }}
       {{ element.vars.label|raw }}
    {% endfor %}

I require that for new entries, the default field is considered.
Setting the value in the constructor did not change the checkbox value, and in any case will set the default for all fields to true, which is not what I want.

I am using Symfony 2.6

Body:
I work with symfony3. That's how it works

->add('aptitudes', EntityType::class, array( //change this line
      'class' => 'BackendBundle:Aptitudes', //change this line
      'expanded' => true,
      'multiple' => true,
      'required' => false,
      'query_builder' => null,
      'by_reference' => true,
))


问:
Is there any npm package to read Excel file which is in .xlsm format?
I am having a base template which is in the .xslm format and I want to read this file and preserve all those VBA and macros in it

I tried using npm's xslx package it preserves the VBA and macros but I am loosing all data validations and styles.I want a package that support writing .xlsm format without losing the VBA and macros.

Any other packages will do this job?

答:
You could try this library.
Here's an example, from their npm page:

```<code>var parseXlsx = require('excel');

parseXlsx('Spreadsheet.xlsx', function(err, data) {
  if(err) throw err;
    // data is an array of arrays
});
</code>```

Source.

There's also this library. Which supports more formats.

The GitHub page for the project seems to be gone, however.

As well as this library.
Example:

```<code>var excelParser = require('excel-parser');
excelParser.worksheets({
  inFile: 'my_file.in'
}, function(err, worksheets){
  if(err) console.error(err);
  console.log(worksheets);
});
</code>```

Source.

Body:
You could try this library.
Here's an example, from their npm page:

var parseXlsx = require('excel');

parseXlsx('Spreadsheet.xlsx', function(err, data) {
  if(err) throw err;
    // data is an array of arrays
});

Source.

There's also this library. Which supports more formats.

The GitHub page for the project seems to be gone, however.

As well as this library.
Example:

var excelParser = require('excel-parser');
excelParser.worksheets({
  inFile: 'my_file.in'
}, function(err, worksheets){
  if(err) console.error(err);
  console.log(worksheets);
});

Source.